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
cadbae6e7cedae99dcbba3969b13820a66a90e88
465943c5ffac075cd5a617c47fd25adfe496b8b4
/ATBEACON.CPP
2c4cb7465f45f91645e25418ced7fee8d200fdc6
[]
no_license
paulanthonywilson/airtrafficcontrol
7467f9eb577b24b77306709d7b2bad77f1b231b7
6c579362f30ed5f81cabda27033f06e219796427
refs/heads/master
2016-08-08T00:43:32.006519
2009-04-09T21:33:22
2009-04-09T21:33:22
172,292
1
0
null
null
null
null
UTF-8
C++
false
false
1,126
cpp
/* Function definitions for DelayATBeacon */ # include "atbeacon.h" /**********************************************************************/ void DelayAtBeacon::ProcessInput (char KeyHit_i) { int BeaconId; Beacon *AtBeacon; if (isdigit (KeyHit_i)) { BeaconId = int (KeyHit_i) - '0'; Landmarks_c->Beacons.Search (BeaconId); if (Landmarks_c->Beacons.Found()) { EchoChar (KeyHit_i); EchoChar (' '); AtBeacon = Landmarks_c->Beacons.FoundItem(); Next_c = new CompleteDelay (*this, AtBeacon); IsCompleted_c = True; } } } /**********************************************************************/ void DelayAtBeacon::PromptMsg () { char Msg[3] = " "; EifIterator BeaconIt = Landmarks_c->Beacons.Iterator(); Out_c->Prompt ("Select beacon number from :"); while (!BeaconIt.Finished()) { Msg[0] = '0' + Landmarks_c->Beacons.Item (BeaconIt)->ID(); Out_c->AddToPrompt (Msg); BeaconIt.Forth(); } } /**********************************************************************/ void DelayAtBeacon::Undo (){ CommonUndo(); }
[ [ [ 1, 46 ] ] ]
c7c1328a1d0f93aaaf394aaa9cd0dbbdcc2a1634
f69b9ae8d4c17d3bed264cefc5a82a0d64046b1c
/src/analyzers/WatershedAnalyzer.h
5f7ed2dff1968b33e269aa2dba93012d2dd2c9db
[]
no_license
lssgufeng/proteintracer
611501cf8001ff9d4bf5e7aa645c24069cce675f
055cc953d6bf62d17eb9435117f44b3f3d9b8f3f
refs/heads/master
2016-08-09T22:20:40.978584
2009-06-07T22:08:14
2009-06-07T22:08:14
55,025,270
0
0
null
null
null
null
UTF-8
C++
false
false
2,332
h
/*============================================================================== Copyright (c) 2009, André Homeyer All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ==============================================================================*/ #ifndef WatershedAnalyzer_h #define WatershedAnalyzer_h #include <memory> #include <string> #include <vector> #include <Analyzer.h> #include <analyzers/WatershedFilterPipeline.h> namespace PT { class WatershedAnalyzer : public Analyzer, public EventHandler<FilterProgressEvent> { public: WatershedAnalyzer( const Assay& assay, const Scan* scan, const std::string& analysisDirectory); virtual void process(); virtual void cancel() { filterPipeline_.cancel(); } static const std::string& getName(); static std::auto_ptr<Assay> createAssay(); virtual void handleEvent(const FilterProgressEvent &event); private: const Scan* scan_; WatershedFilterPipeline filterPipeline_; }; } #endif
[ "andre.homeyer@localhost" ]
[ [ [ 1, 69 ] ] ]
80db1b8aa106e4b44f4aae5be06afc3a87b933cc
38664d844d9fad34e88160f6ebf86c043db9f1c5
/branches/initialize/skin/src/controls/skinmenu/SkinBase.cpp
470a4c4e47d7fc6e0d4f5e6ffcb41f8088ba9ec0
[]
no_license
cnsuhao/jezzitest
84074b938b3e06ae820842dac62dae116d5fdaba
9b5f6cf40750511350e5456349ead8346cabb56e
refs/heads/master
2021-05-28T23:08:59.663581
2010-11-25T13:44:57
2010-11-25T13:44:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
35,384
cpp
// SkinBase.cpp: implementation of the CSkinBase class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "SkinBase.h" #include "../../base/wclassdefines.h" #include "winclasses.h" //#define ACTIVATE_VIEWER //#include "imageviewer.h" // for transparency typedef BOOL (WINAPI *LPSetLayeredWindowAttributes) ( HWND hwnd, // handle to the layered window COLORREF crKey, // specifies the color key BYTE bAlpha, // value for the blend function DWORD dwFlags // action ); #ifndef SPI_SETMENUFADE #define SPI_GETMENUFADE 0x1012 #define SPI_SETMENUFADE 0x1013 #endif #ifndef WS_EX_LAYERED #define WS_EX_LAYERED 0x00080000 // win 2000 layered windows support #define LWA_COLORKEY 0x00000001 #define LWA_ALPHA 0x00000002 #define ULW_COLORKEY 0x00000001 #define ULW_ALPHA 0x00000002 #define ULW_OPAQUE 0x00000004 #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// int CSkinBase::s_nOSVer = -1; PFNTRANSPARENTBLT CSkinBase::s_pfnFastTransparentBlt = NULL; PFNGRADIENTFILL CSkinBase::s_pfnFastGradientFill = NULL; BOOL CSkinBase::s_bThemingEnabled = (GetOS() >= SBOS_XP); // don't use fast trasparent blt on win95/98 because msimg32.dll has a resource leak BOOL CSkinBase::s_bSupportsFastTransparentBlt = (GetOS() < SBOS_ME) ? FALSE : -1; BOOL CSkinBase::s_bSupportsFastGradientFill = (GetOS() < SBOS_ME) ? FALSE : -1; CSkinBase::CSkinBase() { } CSkinBase::~CSkinBase() { } int CSkinBase::GetOS() { if (s_nOSVer == -1) // first time { OSVERSIONINFO vinfo; vinfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); BOOL rslt = GetVersionEx(&vinfo); if (rslt) { switch (vinfo.dwPlatformId) { case VER_PLATFORM_WIN32_NT: switch (vinfo.dwMajorVersion) { case 3: // nt351 ASSERT (0); // not supported break; case 4: // nt4 s_nOSVer = SBOS_NT4; break; case 5: // >= w2k switch (vinfo.dwMinorVersion) { case 0: // w2k s_nOSVer = SBOS_2K; break; case 1: // xp s_nOSVer = SBOS_XP; break; default: // > xp s_nOSVer = SBOS_XPP; break; } break; default: // > xp s_nOSVer = SBOS_XPP; break; } break; case VER_PLATFORM_WIN32_WINDOWS: ASSERT (vinfo.dwMajorVersion == 4); switch (vinfo.dwMinorVersion) { case 0: // nt4 s_nOSVer = SBOS_95; break; case 10: // xp s_nOSVer = SBOS_98; break; case 90: // > xp s_nOSVer = SBOS_ME; break; default: ASSERT (0); break; } break; default: ASSERT (0); break; } } } return s_nOSVer; } BOOL CSkinBase::SupportsFastTransparentBlt() { if (s_bSupportsFastTransparentBlt == -1) // first time { HINSTANCE hInst = LoadLibrary("msimg32.dll"); if (hInst) { s_pfnFastTransparentBlt = (PFNTRANSPARENTBLT)GetProcAddress(hInst, "TransparentBlt"); s_bSupportsFastTransparentBlt = (s_pfnFastTransparentBlt != NULL); } else s_bSupportsFastTransparentBlt = FALSE; } return s_bSupportsFastTransparentBlt; } BOOL CSkinBase::SupportsFastGradientFill() { if (s_bSupportsFastGradientFill == -1) // first time { HINSTANCE hInst = LoadLibrary("msimg32.dll"); if (hInst) { s_pfnFastGradientFill = (PFNGRADIENTFILL)GetProcAddress(hInst, "GradientFill"); s_bSupportsFastGradientFill = (s_pfnFastGradientFill != NULL); } else s_bSupportsFastGradientFill = FALSE; } return s_bSupportsFastGradientFill; } BOOL CSkinBase::GradientFill(CDC* pDCDest, LPRECT lpRect, COLORREF crFrom, COLORREF crTo, BOOL bHorz) { if (!lpRect) return FALSE; if (::IsRectEmpty(lpRect)) return FALSE; if (crFrom == crTo) { pDCDest->FillSolidRect(lpRect, crFrom); return TRUE; } if (GradientFillFast(pDCDest, lpRect, crFrom, crTo, bHorz)) return TRUE; // else return GradientFillSlow(pDCDest, lpRect, crFrom, crTo, bHorz); } BOOL CSkinBase::TransparentBlt(CDC* pDCDest, int nXOriginDest, int nYOriginDest, int nWidthDest, int nHeightDest, CDC* pDCSrc, int nXOriginSrc, int nYOriginSrc, int nWidthSrc, int nHeightSrc, UINT crTransparent) { if (nWidthDest < 1) return FALSE; if (nWidthSrc < 1) return FALSE; if (nHeightDest < 1) return FALSE; if (nHeightSrc < 1) return FALSE; if (TransparentBltFast(pDCDest, nXOriginDest, nYOriginDest, nWidthDest, nHeightDest, pDCSrc, nXOriginSrc, nYOriginSrc, nWidthSrc, nHeightSrc, crTransparent)) return TRUE; // else return TransparentBltSlow(pDCDest, nXOriginDest, nYOriginDest, nWidthDest, nHeightDest, pDCSrc, nXOriginSrc, nYOriginSrc, nWidthSrc, nHeightSrc, crTransparent); } BOOL CSkinBase::TransparentBltFast(CDC* pDCDest, int nXOriginDest, int nYOriginDest, int nWidthDest, int nHeightDest, CDC* pDCSrc, int nXOriginSrc, int nYOriginSrc, int nWidthSrc, int nHeightSrc, UINT crTransparent) { if (!SupportsFastTransparentBlt() || !s_pfnFastTransparentBlt) return FALSE; return s_pfnFastTransparentBlt(*pDCDest, nXOriginDest, nYOriginDest, nWidthDest, nHeightDest, *pDCSrc, nXOriginSrc, nYOriginSrc, nWidthSrc, nHeightSrc, crTransparent); } BOOL CSkinBase::TransparentBltSlow(CDC* pDCDest, int nXOriginDest, int nYOriginDest, int nWidthDest, int nHeightDest, CDC* pDCSrc, int nXOriginSrc, int nYOriginSrc, int nWidthSrc, int nHeightSrc, UINT crTransparent) { CDC dcMem, dcMask; dcMask.CreateCompatibleDC(pDCDest); dcMem.CreateCompatibleDC(pDCDest); CBitmap bmMask, bmMem; // copy src bitmap to mem dc bmMem.CreateCompatibleBitmap(pDCDest, nWidthSrc, nHeightSrc); CBitmap* pOldBMMem = dcMem.SelectObject(&bmMem); dcMem.BitBlt(0, 0, nWidthSrc, nHeightSrc, pDCSrc, nXOriginSrc, nYOriginSrc, SRCCOPY); // ShowDC(dcMem); // Create monochrome bitmap for the mask bmMask.CreateBitmap(nWidthSrc, nHeightSrc, 1, 1, NULL); CBitmap* pOldBMMask = dcMask.SelectObject(&bmMask); dcMem.SetBkColor(crTransparent); // Create the mask from the memory DC dcMask.BitBlt(0, 0, nWidthSrc, nHeightSrc, &dcMem, 0, 0, SRCCOPY); // ShowDC(dcMask); // Set the background in dcMem to black. Using SRCPAINT with black // and any other color results in the other color, thus making // black the transparent color dcMem.SetBkColor(RGB(0,0,0)); dcMem.SetTextColor(RGB(255,255,255)); dcMem.BitBlt(0, 0, nWidthSrc, nHeightSrc, &dcMask, 0, 0, SRCAND); // ShowDC(dcMem); // Set the foreground to black. See comment above. // pDCDest->SetStretchBltMode(COLORONCOLOR); pDCDest->SetStretchBltMode(HALFTONE); pDCDest->SetBkColor(RGB(255,255,255)); pDCDest->SetTextColor(RGB(0,0,0)); // CPoint ptOrg; // ::GetBrushOrgEx(*pDCDest, &ptOrg); // ::SetBrushOrgEx(*pDCDest, 0, 0, &ptOrg); if (nWidthDest == nWidthSrc && nHeightDest == nHeightSrc) { pDCDest->BitBlt(nXOriginDest, nYOriginDest, nWidthDest, nHeightDest, &dcMask, 0, 0, SRCAND); // ShowDC(*pDCDest); } else { pDCDest->StretchBlt(nXOriginDest, nYOriginDest, nWidthDest, nHeightDest, &dcMask, 0, 0, nWidthSrc, nHeightSrc, SRCAND); // ShowDC(*pDCDest); } // Combine the foreground with the background if (nWidthDest == nWidthSrc && nHeightDest == nHeightSrc) { pDCDest->BitBlt(nXOriginDest, nYOriginDest, nWidthDest, nHeightDest, &dcMem, 0, 0, SRCPAINT); // ShowDC(*pDCDest); } else { pDCDest->StretchBlt(nXOriginDest, nYOriginDest, nWidthDest, nHeightDest, &dcMem, 0, 0, nWidthSrc, nHeightSrc, SRCPAINT); // ShowDC(*pDCDest); } dcMask.SelectObject(pOldBMMask); dcMem.SelectObject(pOldBMMem); return TRUE; } /* BOOL CSkinBase::TransparentBltSlow(CDC* pDCDest, int nXOriginDest, int nYOriginDest, int nWidthDest, int nHeightDest, CDC* pDCSrc, int nXOriginSrc, int nYOriginSrc, int nWidthSrc, int nHeightSrc, UINT crTransparent) { CDC dcMem, dcMask; dcMask.CreateCompatibleDC(pDCDest); dcMem.CreateCompatibleDC(pDCDest); CBitmap bmMask, bmMem; // copy src bitmap to mem dc bmMem.CreateCompatibleBitmap(pDCDest, nWidthDest, nHeightDest); CBitmap* pOldBMMem = dcMem.SelectObject(&bmMem); dcMem.SetStretchBltMode(HALFTONE); CPoint ptOrg; ::GetBrushOrgEx(dcMem, &ptOrg); ::SetBrushOrgEx(dcMem, 0, 0, &ptOrg); dcMem.StretchBlt(0, 0, nWidthDest, nHeightDest, pDCSrc, nXOriginSrc, nYOriginSrc, nWidthSrc, nHeightSrc, SRCCOPY); // ShowDC(dcMem); // Create monochrome bitmap for the mask bmMask.CreateBitmap(nWidthDest, nHeightDest, 1, 1, NULL); CBitmap* pOldBMMask = dcMask.SelectObject(&bmMask); dcMem.SetBkColor(crTransparent); // Create the mask from the memory DC dcMask.BitBlt(0, 0, nWidthDest, nHeightDest, &dcMem, 0, 0, SRCCOPY); // ShowDC(dcMask); // Set the background in dcMem to black. Using SRCPAINT with black // and any other color results in the other color, thus making // black the transparent color dcMem.SetBkColor(RGB(0,0,0)); dcMem.SetTextColor(RGB(255,255,255)); dcMem.BitBlt(0, 0, nWidthDest, nHeightDest, &dcMask, 0, 0, SRCAND); // ShowDC(dcMem); // Set the foreground to black. See comment above. pDCDest->SetBkColor(RGB(255,255,255)); pDCDest->SetTextColor(RGB(0,0,0)); pDCDest->BitBlt(nXOriginDest, nYOriginDest, nWidthDest, nHeightDest, &dcMask, 0, 0, SRCAND); // ShowDC(*pDCDest); // Combine the foreground with the background pDCDest->BitBlt(nXOriginDest, nYOriginDest, nWidthDest, nHeightDest, &dcMem, 0, 0, SRCPAINT); // ShowDC(*pDCDest); dcMask.SelectObject(pOldBMMask); dcMem.SelectObject(pOldBMMem); return TRUE; } */ BOOL CSkinBase::GradientFillFast(CDC* pDCDest, LPRECT lpRect, COLORREF crFrom, COLORREF crTo, BOOL bHorz) { if (!SupportsFastGradientFill() || !s_pfnFastGradientFill) return FALSE; TRIVERTEX vert[2]; vert[0].x = lpRect->left; vert[0].y = lpRect->top; vert[0].Red = GetRValue(crFrom) << 8; vert[0].Green = GetGValue(crFrom) << 8; vert[0].Blue = GetBValue(crFrom) << 8; vert[0].Alpha = 0x0000; vert[1].x = lpRect->right; vert[1].y = lpRect->bottom; vert[1].Red = GetRValue(crTo) << 8; vert[1].Green = GetGValue(crTo) << 8; vert[1].Blue = GetBValue(crTo) << 8; vert[1].Alpha = 0x0000; GRADIENT_RECT gRect = { 0, 1 }; return s_pfnFastGradientFill(*pDCDest, vert, 2, &gRect, 1, bHorz ? GRADIENT_FILL_RECT_H : GRADIENT_FILL_RECT_V); } BOOL CSkinBase::GradientFillSlow(CDC* pDCDest, LPRECT lpRect, COLORREF crFrom, COLORREF crTo, BOOL bHorz) { if (!pDCDest || !lpRect) return FALSE; int nWidth = lpRect->right - lpRect->left; int nHeight = lpRect->bottom - lpRect->top; if (bHorz) { for (int nX = lpRect->left; nX < lpRect->right; nX++) pDCDest->FillSolidRect(nX, lpRect->top, 1, nHeight, BlendColors(crFrom, crTo, (lpRect->right - nX) / (float)nWidth)); } else { for (int nY = lpRect->top; nY < lpRect->bottom; nY++) pDCDest->FillSolidRect(lpRect->left, nY, nWidth, 1, BlendColors(crFrom, crTo, (lpRect->bottom - nY) / (float)nHeight)); } return TRUE; } COLORREF CSkinBase::BlendColors(COLORREF crA, COLORREF crB, float fAmountA) { BYTE btRed = (BYTE)min(255, (int)(GetRValue(crA) * fAmountA + GetRValue(crB) * (1.0f - fAmountA))); BYTE btGreen = (BYTE)min(255, (int)(GetGValue(crA) * fAmountA + GetGValue(crB) * (1.0f - fAmountA))); BYTE btBlue = (BYTE)min(255, (int)(GetBValue(crA) * fAmountA + GetBValue(crB) * (1.0f - fAmountA))); return RGB(btRed, btGreen, btBlue); } COLORREF CSkinBase::VaryColor(COLORREF crColor, float fFactor) { BYTE btRed = (BYTE)min(255, (int)(GetRValue(crColor) * fFactor)); BYTE btGreen = (BYTE)min(255, (int)(GetGValue(crColor) * fFactor)); BYTE btBlue = (BYTE)min(255, (int)(GetBValue(crColor) * fFactor)); return RGB(btRed, btGreen, btBlue); } HRGN CSkinBase::BitmapToRegion(CBitmap* pBmp, COLORREF color) { const DWORD RGNDATAHEADER_SIZE = sizeof(RGNDATAHEADER); const DWORD ADD_RECTS_COUNT = 40; // number of rects to be appended // get image properties BITMAP BM = { 0 }; pBmp->GetBitmap(&BM); // create temporary dc CBitmap bmpMem; CDC dc, dcMem1, dcMem2; CDC* pDC = CWnd::GetDesktopWindow()->GetDC(); dcMem1.CreateCompatibleDC(pDC); dcMem2.CreateCompatibleDC(pDC); bmpMem.CreateCompatibleBitmap(pDC, BM.bmWidth, BM.bmHeight); CWnd::GetDesktopWindow()->ReleaseDC(pDC); CBitmap* pOldBM1 = dcMem1.SelectObject(pBmp); CBitmap* pOldBM2 = dcMem2.SelectObject(&bmpMem); // verify that the mask color is correct for the current bit depth color = dcMem2.SetPixel(0, 0, color); dcMem2.BitBlt(0, 0, BM.bmWidth, BM.bmHeight, &dcMem1, 0, 0, SRCCOPY); dcMem1.SelectObject(pOldBM1); dcMem1.DeleteDC(); DWORD dwRectsCount = BM.bmHeight; // number of rects in allocated buffer int nY, nX; // current position in mask image // where mask was found bool bWasMask; // set when mask has been found in current scan line bool bIsMask; // set when current color is mask color CRect rLine; // allocate memory for region data // region data here is set of regions that are rectangles with height 1 pixel (scan line) // that's why nRgnStart allocation is <bm.biHeight> RECTs - number of scan lines in image RGNDATAHEADER* pRgnData = (RGNDATAHEADER*)new BYTE[ RGNDATAHEADER_SIZE + dwRectsCount * sizeof(RECT) ]; // get pointer to RECT table LPRECT pRects = (LPRECT)((LPBYTE)pRgnData + RGNDATAHEADER_SIZE); // zero region data header memory (header part only) memset( pRgnData, 0, RGNDATAHEADER_SIZE + dwRectsCount * sizeof(RECT) ); // fill it by default pRgnData->dwSize = RGNDATAHEADER_SIZE; pRgnData->iType = RDH_RECTANGLES; for ( nY = 0; nY < BM.bmHeight; nY++ ) { bWasMask = true; rLine.SetRect(0, nY, 0, nY + 1); for ( nX = 0; nX < BM.bmWidth; nX++ ) { // get color COLORREF crPixel = dcMem2.GetPixel(nX, nY); bIsMask = (crPixel == color); if (!bIsMask && bWasMask) // start of the rgn { rLine.left = nX; bWasMask = FALSE; } if (!bWasMask && (bIsMask || nX == BM.bmWidth - 1)) // end of rgn { bWasMask = true; rLine.right = bIsMask ? nX : nX + 1; // save current RECT // if this was a full line append to the last if it was full too BOOL bAdded = FALSE; if (pRgnData->nCount) { LPRECT pLastRect = &pRects[ pRgnData->nCount - 1]; if (!pLastRect->left && !rLine.left && pLastRect->right == BM.bmWidth - 1 && rLine.right == BM.bmWidth - 1) { pLastRect->bottom = rLine.bottom; bAdded = TRUE; } } // else add as a new line if (!bAdded) { pRects[ pRgnData->nCount++ ] = rLine; // if buffer full reallocate it with more room if ( pRgnData->nCount >= dwRectsCount ) { dwRectsCount += ADD_RECTS_COUNT; // allocate new buffer LPBYTE pRgnDataNew = new BYTE[ RGNDATAHEADER_SIZE + dwRectsCount * sizeof(RECT) ]; // copy current region data to it memcpy( pRgnDataNew, pRgnData, RGNDATAHEADER_SIZE + pRgnData->nCount * sizeof(RECT) ); // delte old region data buffer delete pRgnData; // set pointer to new regiondata buffer to current pRgnData = (RGNDATAHEADER*)pRgnDataNew; // correct pointer to RECT table pRects = (LPRECT)((LPBYTE)pRgnData + RGNDATAHEADER_SIZE); } } } } } // create region HRGN hRgn = ExtCreateRegion( NULL, RGNDATAHEADER_SIZE + pRgnData->nCount * sizeof(RECT), (LPRGNDATA)pRgnData ); CRect rBox; ::GetRgnBox(hRgn, rBox); // release region data delete pRgnData; dcMem2.SelectObject(pOldBM2); dcMem2.DeleteDC(); bmpMem.DeleteObject(); return hRgn; } HMENU CSkinBase::MakeMenuCopy(const HMENU hSrc) { if (!pSrc) return NULL; CMenu menu; VERIFY (menu.CreatePopupMenu()); ASSERT (::IsMenu(menu.m_hMenu)); int nNumItems = GetMenuItemCount( hSrc ); CString sLabel; MENUITEMINFO mii; ZeroMemory(&mii, sizeof(mii)); mii.cbSize = sizeof(mii); // must fill up this field mii.fMask = MIIM_STATE | MIIM_DATA; // get the state of the menu item for (int nItem = 0; nItem < nNumItems; nItem++) { UINT uIDItem = GetMenuItemID(hSrc, nItem); GetMenuString(hSrc, nItem, sLabel, MF_BYPOSITION); UINT uFlags = (uIDItem == 0) ? MF_SEPARATOR : (uIDItem == (UINT)-1) ? MF_POPUP : MF_STRING; // special case: if a popup menu we must copy it too if (uFlags == MF_POPUP) { HMENU hPopup = MakeMenuCopy(GetSubMenu(hSrc, nItem)); ASSERT (hPopup); uIDItem = (UINT)hPopup; } menu.AppendMenu(uFlags, uIDItem, sLabel); // make sure we copy the state too ::GetMenuItemInfo(hSrc, nItem, TRUE, &mii); ::SetMenuItemInfo(menu, nItem, TRUE, &mii); } return menu.Detach(); } // this one copies the menu without deleting the root BOOL CSkinBase::CopyMenu(const HMENU hScr, HMENU hDest) { ASSERT (::IsMenu(hDest)); if (!::IsMenu(hDest)) return FALSE; ASSERT (::IsMenu(hScr)); if (!::IsMenu(hScr)) return FALSE; // delete all the existing items while (GetMenuItemCount(hDest)) DeleteMenu(hDest, 0, MF_BYPOSITION); // copy across int nNumItems = GetMenuItemCount(hScr); CString sLabel; MENUITEMINFO mii; ZeroMemory(&mii, sizeof(mii)); mii.cbSize = sizeof(mii); // must fill up this field mii.fMask = MIIM_STATE | MIIM_DATA; // get the state of the menu item for (int nItem = 0; nItem < nNumItems; nItem++) { UINT uIDItem = GetMenuItemID(hScr, nItem); GetMenuString(hScr, nItem, sLabel, MF_BYPOSITION); UINT uFlags = (uIDItem == 0) ? MF_SEPARATOR : (uIDItem == (UINT)-1) ? MF_POPUP : MF_STRING; // special case: if a popup menu we must copy it too if (uFlags == MF_POPUP) { HMENU hPopup = MakeMenuCopy(GetSubMenu(hScr, nItem)); ASSERT (hPopup); uIDItem = (UINT)hPopup; } AppendMenu(hDest, uFlags, uIDItem, sLabel); // make sure we copy the state too ::GetMenuItemInfo(hSrc, nItem, TRUE, &mii); ::SetMenuItemInfo(hDest, nItem, TRUE, &mii); } return TRUE; } BOOL CSkinBase::CopyBitmap(const CBitmap* pSrc, CBitmap* pDest) { ASSERT (pDest); if (!pDest) return FALSE; pDest->DeleteObject(); if (!pSrc || !pSrc->GetSafeHandle()) return FALSE; CDC* pDC = CWnd::GetDesktopWindow()->GetDC(); CDC dcMem1, dcMem2; BOOL bRes = FALSE; if (dcMem1.CreateCompatibleDC(pDC) && dcMem2.CreateCompatibleDC(pDC)) { BITMAP bm; ((CBitmap*)pSrc)->GetBitmap(&bm); if (pDest->CreateCompatibleBitmap(pDC, bm.bmWidth, bm.bmHeight)) { ASSERT (CBitmap::FromHandle((HBITMAP)pDest->GetSafeHandle()) == pDest); CBitmap* pOldBM1 = dcMem1.SelectObject((CBitmap*)pSrc); CBitmap* pOldBM2 = dcMem2.SelectObject(pDest); dcMem2.BitBlt(0, 0, bm.bmWidth, bm.bmHeight, &dcMem1, 0, 0, SRCCOPY); bRes = TRUE; dcMem1.SelectObject(pOldBM1); dcMem2.SelectObject(pOldBM2); } } dcMem1.DeleteDC(); dcMem2.DeleteDC(); CWnd::GetDesktopWindow()->ReleaseDC(pDC); ASSERT (CBitmap::FromHandle((HBITMAP)pDest->GetSafeHandle()) == pDest); HANDLE* ph = (HANDLE*)((BYTE*)pDest + 4); // after CObject ASSERT (ph[0] == pDest->GetSafeHandle()); return bRes; } BOOL CSkinBase::ExtractResource(UINT nID, LPCTSTR szType, CString& sTempFilePath, HINSTANCE hInst) { if (!hInst) hInst = AfxFindResourceHandle(MAKEINTRESOURCE(nID), szType); if (!hInst) return FALSE; // compare time with that of module from which it was loaded CString sTempPath; CFileStatus fsRes, fsModule; CString sModulePath; ::GetModuleFileName(hInst, sModulePath.GetBuffer(MAX_PATH + 1), MAX_PATH); sModulePath.ReleaseBuffer(); if (!CFile::GetStatus(sModulePath, fsModule)) return FALSE; // create temp filename ::GetTempPath(MAX_PATH, sTempPath.GetBuffer(MAX_PATH)); sTempPath.ReleaseBuffer(); sTempFilePath.Format("%s%s_skin_%d.tmp", sTempPath, szType, nID); // see if the file has been created before if (!CFile::GetStatus(sTempFilePath, fsRes) || fsRes.m_mtime < fsModule.m_mtime) { // Load the resource into memory HRSRC hRes = FindResource(hInst, (LPCSTR)nID, szType); if (!hRes) { TRACE("Couldn't find %s resource %d!\n", szType, nID); return FALSE; } DWORD len = SizeofResource(hInst, hRes); BYTE* lpRes = (BYTE*)LoadResource(hInst, hRes); ASSERT(lpRes); CFile file; if (file.Open(sTempFilePath, CFile::modeCreate | CFile::modeWrite)) { file.Write(lpRes, len); file.Close(); FreeResource((HANDLE)lpRes); } else { FreeResource((HANDLE)lpRes); return FALSE; } } return TRUE; } HWND CSkinBase::GetChildWnd(HWND pParent, LPCTSTR szClass, int nID) { HWND hChild = ::GetWindow(hParent, GW_CHILD); while (hChild) { if (CWinClasses::IsClass(hChild, szClass)) { if (nID == -1 || GetDlgCtrlID(hChild) == nID) return hChild; } hChild = GetNextWindow(hChild, GW_HWNDNEXT); } return NULL; } BOOL CSkinBase::BitBlt(CDC* pDCDest, int nXOriginDest, int nYOriginDest, int nWidthDest, int nHeightDest, CDC* pDCSrc, int nXOriginSrc, int nYOriginSrc, UINT uROP, COLORREF crTransparent) { if (crTransparent != (COLORREF)-1) { return TransparentBlt(pDCDest, nXOriginDest, nYOriginDest, nWidthDest, nHeightDest, pDCSrc, nXOriginSrc, nYOriginSrc, nWidthDest, nHeightDest, crTransparent); } else { return pDCDest->BitBlt(nXOriginDest, nYOriginDest, nWidthDest, nHeightDest, pDCSrc, nXOriginSrc, nYOriginSrc, uROP); } return TRUE; } BOOL CSkinBase::StretchBlt(CDC* pDCDest, int nXOriginDest, int nYOriginDest, int nWidthDest, int nHeightDest, CDC* pDCSrc, int nXOriginSrc, int nYOriginSrc, int nWidthSrc, int nHeightSrc, UINT uROP, COLORREF crTransparent) { // check to see if this is really just a BitBlt if (nWidthDest == nWidthSrc && nHeightDest == nHeightSrc) { return BitBlt(pDCDest, nXOriginDest, nYOriginDest, nWidthDest, nHeightDest, pDCSrc, nXOriginSrc, nYOriginSrc, uROP, crTransparent); } // else pick whether its transparent or not if (crTransparent != (COLORREF)-1) { return TransparentBlt(pDCDest, nXOriginDest, nYOriginDest, nWidthDest, nHeightDest, pDCSrc, nXOriginSrc, nYOriginSrc, nWidthSrc, nHeightSrc, crTransparent); } else { return pDCDest->StretchBlt(nXOriginDest, nYOriginDest, nWidthDest, nHeightDest, pDCSrc, nXOriginSrc, nYOriginSrc, nWidthSrc, nHeightSrc, uROP); } return TRUE; } CString CSkinBase::GetTipText(LPCTSTR szText, BOOL bToolbar) { CString sText(szText), sTip; if (sText.IsEmpty()) return ""; // tip text starts at '\n' int nStartTip = bToolbar ? sText.Find('\n') : -1; if (bToolbar && nStartTip == -1) // no tip return ""; sText = sText.Right(sText.GetLength() - nStartTip - 1); // strip '&' and '...' if present int nLen = sText.GetLength(); sTip.Empty(); for (int nPos = 0; nPos < nLen; nPos++) { if (sText[nPos] != '&' && sText[nPos] != '.') sTip += sText[nPos]; } return sTip; } BOOL CSkinBase::ConvertToGrayScale(CBitmap* pBitmap, COLORREF crMask) { CDC dcTemp; dcTemp.CreateCompatibleDC(NULL); BITMAP BM; pBitmap->GetBitmap(&BM); CBitmap* pBMOld = dcTemp.SelectObject(pBitmap); // now iterate all the pixels, converting each to grayscale // a bit daggy, but.... int nXPixel = BM.bmWidth; COLORREF crPixel; while (nXPixel--) { int nYPixel = BM.bmHeight; while (nYPixel--) { crPixel = dcTemp.GetPixel(nXPixel, nYPixel); // leave the mask color as-is if (crPixel == crMask) continue; const BYTE btRed = GetRValue(crPixel); const BYTE btGreen = GetGValue(crPixel); const BYTE btBlue = GetBValue(crPixel); // if gray already goto next if (btRed == btGreen && btGreen == btBlue) continue; const BYTE btGray = (BYTE)((btRed / 3) + (btGreen / 2) + (btBlue / 4)); // note: SetPixelV() quicker than SetPixel() dcTemp.SetPixelV(nXPixel, nYPixel, RGB(btGray, btGray, btGray)); } } dcTemp.SelectObject(pBMOld); dcTemp.DeleteDC(); return TRUE; } BOOL CSkinBase::DoSysMenu(HWND hWnd, CPoint ptCursor, LPRECT prExclude, BOOL bCopy) { HMENU hMenu = GetSystemMenu(hWnd, FALSE); ASSERT ( hMenu ); if ( hMenu ) { TPMPARAMS tpmp; tpmp.cbSize = sizeof(tpmp); if (prExclude) tpmp.rcExclude = *prExclude; else SetRectEmpty(&tpmp.rcExclude); UINT uAlignFlags = TPM_LEFTALIGN | TPM_TOPALIGN | TPM_VERTICAL | TPM_RIGHTBUTTON | TPM_RETURNCMD; UINT uID = 0; if (bCopy) // skinning { HMENU hSysMenu = CSkinBase::MakeMenuCopy(hMenu); ASSERT (hSysMenu); if (hSysMenu) { InitSysMenu( hSysMenu, pWnd ); uID = ::TrackPopupMenuEx(hSysMenu, uAlignFlags, ptCursor.x, ptCursor.y, hWnd, &tpmp); ::DestroyMenu(hSysMenu); // cleanup } } else { InitSysMenu(hMenu, hWnd); uID = ::TrackPopupMenuEx(hMenu, uAlignFlags, ptCursor.x, ptCursor.y, hWnd, &tpmp); } if (uID & 0xf000) // syscommand { //MSG& curMsg = AfxGetThreadState()->m_lastSentMsg; // always post this command to allow this function to unwind // correctly before the command is handled //pWnd->PostMessage(WM_SYSCOMMAND, (uID & 0xfff0), MAKELPARAM(curMsg.pt.x, curMsg.pt.y)); PostMessage(hWnd, WM_SYSCOMMAND, (uID & 0xfff0), MAKELPARAM(ptCursor.x, ptCursor.y)); } } return TRUE; } void CSkinBase::InitSysMenu(HMENU hMenu, HWND hWnd) { // iterate all the menu items looking for something resembling a sys menu item int nItem = GetMenuItemCount(hMenu); CWindow cWnd; cWnd.Attach( hWnd ); while (nItem--) { UINT uID = GetMenuItemID(hMenu, nItem); if (uID >= 0xF000) { BOOL bEnable = TRUE; switch (uID & 0xFFF0) { case SC_MINIMIZE: bEnable = (cWnd.GetStyle() & WS_MINIMIZEBOX) && !cWnd.IsIconic(); break; case SC_MAXIMIZE: bEnable = (cWnd.GetStyle() & WS_MAXIMIZEBOX) && !cWnd.IsZoomed(); break; case SC_RESTORE: bEnable = cWnd.IsIconic() || cWnd.IsZoomed(); break; case SC_MOVE: case SC_SIZE: bEnable = !cWnd.IsIconic() && !cWnd.IsZoomed(); break; } EnableMenuItem(hMenu, uID, bEnable ? MF_ENABLED : MF_GRAYED); } } // set close as default item SetMenuDefaultItem(hMenu, SC_CLOSE, FALSE ); } CSize CSkinBase::GetTextExtent(CDC* pDC, LPCTSTR szText) { ASSERT (pDC && szText); if (pDC && szText) { CRect rText(0, 0, 0, SHRT_MAX); pDC->DrawText(szText, rText, DT_SINGLELINE | DT_CALCRECT); return rText.Size(); } // else return 0; } const LPCTSTR WORDBREAK = "_-+=,.:;\n"; const int CHUNK = 32; int CSkinBase::FormatText(CDC* pDC, CString& sText, CRect& rect, UINT uDTFlags) { CString sOrgText(sText); sText.Empty(); int nPos = 0, nLinePos = 0, nLen = sOrgText.GetLength(); int nLastWhiteSpace = -1; int nHeight = 0; const int LINEHEIGHT = pDC->GetTextExtent("W").cy; int nLongestLine = 0; // we always allow at least one line of text BOOL bSingleLine = (uDTFlags & DT_SINGLELINE); BOOL bCalcRect = (uDTFlags & DT_CALCRECT); BOOL bEllipsis = (uDTFlags & DT_END_ELLIPSIS); BOOL bModString = (uDTFlags & DT_MODIFYSTRING); BOOL bFinished = FALSE; const int CHUNK = 32; char* pBuffer = sOrgText.GetBuffer(sOrgText.GetLength() + 1); while (!bFinished) { int nChunk = CHUNK; BOOL bLonger = TRUE; int nLinePos = 0; int nPrevPos = 0; char* pLine = pBuffer + nPos; // add chunks till we go over BOOL bContinue = TRUE; int nWidth = 0; while (bContinue) { nChunk = min(nChunk, nLen - (nPos + nLinePos)); nLinePos += nChunk; nWidth = pDC->GetTextExtent(pLine, nLinePos).cx; bContinue = (nChunk == CHUNK && nWidth < rect.Width()); } // then iterate back and forth with sub chunks till we are just under for (int i = 0; i < 5; i++) { nChunk /= 2; if (nWidth == rect.Width()) break; else if (nWidth > rect.Width()) nLinePos -= nChunk; else nLinePos += nChunk; nWidth = pDC->GetTextExtent(pLine, nLinePos).cx; } // one final check to see we haven't ended up over if (nWidth > rect.Width()) nLinePos--; // then work back to the previous word break int nSavePos = nLinePos; while (nLinePos) { // we word break either if the current character is whitespace or // if the preceding character is a wordbreak character // or we've reached the end of the string BOOL bWordBreak = (nLinePos == nLen) || _istspace(pLine[nLinePos]) || (strchr(WORDBREAK, pLine[nLinePos - 1]) != NULL); if (bWordBreak) break; nLinePos--; } if (!nLinePos) nLinePos = nSavePos; // single word spans entire line nWidth = pDC->GetTextExtent(pLine, nLinePos).cx; // check for last line and add ellipsis if required nHeight += LINEHEIGHT; BOOL bAddEllipsis = FALSE; if (nHeight + LINEHEIGHT > rect.Height() || bSingleLine) { if (bEllipsis && nPos + nLinePos < nLen - 1) { const int LEN_ELLIPSIS = pDC->GetTextExtent("...", 3).cx; // modify the last line to add ellipsis while (nLinePos) { nWidth = pDC->GetTextExtent(pLine, nLinePos).cx + LEN_ELLIPSIS; if (nWidth > rect.Width()) nLinePos--; else break; } bAddEllipsis = TRUE; } sText += sOrgText.Mid(nPos, nLinePos); if (bAddEllipsis) sText += "..."; nLongestLine = max(nLongestLine, nWidth); break; } sText += sOrgText.Mid(nPos, nLinePos); sText += '\n'; nPos += nLinePos; bFinished = (nPos >= nLen - 1 || nHeight + LINEHEIGHT > rect.Height()); nLongestLine = max(nLongestLine, nWidth); // jump white space at the start of the next line if (!bFinished) { while (nPos < nLen - 1) { if (!_istspace(pBuffer[nPos])) break; // else nPos++; } } } sOrgText.ReleaseBuffer(); if (!bModString) sText = sOrgText; if (bCalcRect) { rect.right = rect.left + nLongestLine; rect.bottom = rect.top + nHeight; } return nHeight; } ////////////////////////////// ////////////////////////////// int CALLBACK CheckFontProc(ENUMLOGFONTEX *lpelfe, NEWTEXTMETRICEX *lpntme, DWORD FontType, LPARAM lParam) { BOOL* pPresent = (BOOL*)lParam; ASSERT (pPresent); if (pPresent && FontType == TRUETYPE_FONTTYPE) // only TT accepted for now *pPresent = TRUE; // at least one font found to match facename return 0; } BOOL CSkinBase::FontIsPresent(LPCTSTR szFaceName) { LOGFONT lf; HDC hdc = ::GetDC(NULL); lf.lfCharSet = DEFAULT_CHARSET; lf.lfPitchAndFamily = 0; lstrcpy(lf.lfFaceName, szFaceName); BOOL bPresent = FALSE; EnumFontFamiliesEx(hdc, &lf, (FONTENUMPROC)CheckFontProc, (LPARAM)&bPresent, 0); ::ReleaseDC(NULL, hdc); return bPresent; } ////////////////////////////////// // theming #ifndef STAP_ALLOW_NONCLIENT #define STAP_ALLOW_NONCLIENT (1 << 0) #define STAP_ALLOW_CONTROLS (1 << 1) #define STAP_ALLOW_WEBCONTENT (1 << 2) #endif typedef void (STDAPICALLTYPE* SETTHEMEAPPPROPERTIES)(DWORD); void CSkinBase::EnableTheming(BOOL bEnable) { if (GetOS() < SBOS_XP || bEnable == s_bThemingEnabled) return; static HMODULE hUXTheme = ::LoadLibrary("UXTheme.dll"); if (hUXTheme) { SETTHEMEAPPPROPERTIES SetThemeAppProperties = (SETTHEMEAPPPROPERTIES)GetProcAddress(hUXTheme, "SetThemeAppProperties"); if (SetThemeAppProperties) { SetThemeAppProperties(bEnable ? STAP_ALLOW_NONCLIENT | STAP_ALLOW_CONTROLS | STAP_ALLOW_WEBCONTENT : 0); s_bThemingEnabled = bEnable; } } } BOOL CSkinBase::CreateThemeManifest(LPCTSTR szName, LPCTSTR szDescription) { // if (GetOS() < SBOS_XP) // return FALSE; // create the manifest only if one does not exist CString sFilePath; ::GetModuleFileName(NULL, sFilePath.GetBuffer(MAX_PATH + 1), MAX_PATH); sFilePath.ReleaseBuffer(); sFilePath += ".Manifest"; CFileStatus fs; if (CFile::GetStatus(sFilePath, fs)) return TRUE; // already exists ASSERT (szName && strlen(szName) && szDescription && strlen(szDescription)); if (!(szName && strlen(szName) && szDescription && strlen(szDescription))) return FALSE; LPCTSTR szManifestFmt = " \ <?xml version='1.0' encoding='UTF-8' standalone='yes'?> \ <assembly \ xmlns='urn:schemas-microsoft-com:asm.v1' \ manifestVersion='1.0'> \ \ <assemblyIdentity \ version='1.0.0.0' \ processorArchitecture='X86' \ name='%s' \ type='win32' \ /> \ <description>%s</description> \ <dependency> \ <dependentAssembly> \ <assemblyIdentity \ type='win32' \ name='Microsoft.Windows.Common-Controls' \ version='6.0.0.0' \ processorArchitecture='X86' \ publicKeyToken='6595b64144ccf1df' \ language='*' \ /> \ </dependentAssembly> \ </dependency> \ </assembly> "; CString sManifest; sManifest.Format(szManifestFmt, szName, szDescription); CStdioFile file; if (!file.Open(sFilePath, CFile::modeCreate | CFile::modeWrite | CFile::typeText)) return FALSE; file.WriteString(sManifest); file.Close(); return TRUE; } ////////////////////////////////////////////////////////////////////////////////////////// HICON CSkinBase::GetWindowIcon(CWnd* pWnd) { ASSERT (pWnd); if (!pWnd) return NULL; HICON hIcon = pWnd->GetIcon(FALSE); // small icon if (!hIcon) hIcon = pWnd->GetIcon(TRUE); // large icon if (!hIcon) { WNDCLASS wndcls; CString sClass(CWinClasses::GetClass(*pWnd)); if (GetClassInfo(AfxGetInstanceHandle(), sClass, &wndcls)) hIcon = wndcls.hIcon; } return hIcon; }
[ "zhongzeng@ba8f1dc9-3c1c-0410-9eed-0f8a660c14bd" ]
[ [ [ 1, 1373 ] ] ]
1d5e6acfb3805751f49b913437709fd9a209a97a
12203ea9fe0801d613bbb2159d4f69cab3c84816
/Export/cpp/windows/obj/include/Grid.h
64ffd65b665bef8ca913d26a9dcac7ce069fccc4
[]
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
1,158
h
#ifndef INCLUDED_Grid #define INCLUDED_Grid #ifndef HXCPP_H #include <hxcpp.h> #endif HX_DECLARE_CLASS0(Grid) class Grid_obj : public hx::Object{ public: typedef hx::Object super; typedef Grid_obj OBJ_; Grid_obj(); Void __construct(int columns,int rows); public: static hx::ObjectPtr< Grid_obj > __new(int columns,int rows); static Dynamic __CreateEmpty(); static Dynamic __Create(hx::DynamicArray inArgs); ~Grid_obj(); HX_DO_RTTI; static void __boot(); static void __register(); void __Mark(HX_MARK_PARAMS); ::String __ToString() const { return HX_CSTRING("Grid"); } int _columns; /* REM */ int _rows; /* REM */ int _bitshift; /* REM */ Array< int > _grid; /* REM */ virtual bool get( int x,int y); Dynamic get_dyn(); virtual Void set( int x,int y,bool value); Dynamic set_dyn(); virtual int getLiveNeighbors( int x,int y); Dynamic getLiveNeighbors_dyn(); virtual int getCellValue( int x,int y); Dynamic getCellValue_dyn(); virtual int getCellReference( int x,int y); Dynamic getCellReference_dyn(); }; #endif /* INCLUDED_Grid */
[ [ [ 1, 52 ] ] ]
400dbdc5c4e807818a7e3e811df6e0bea06809af
28476e6f67b37670a87bfaed30fbeabaa5f773a2
/src/autumnframework/ValueWrapper.h
a7a3fc89ed1fb174e882c2b2ae3cbbca20907419
[]
no_license
rdmenezes/autumnframework
d1aeb657cd470b67616dfcf0aacdb173ac1e96e1
d082d8dc12cc00edae5f132b7f5f6e0b6406fe1d
refs/heads/master
2021-01-20T13:48:52.187425
2008-07-17T18:25:19
2008-07-17T18:25:19
32,969,073
1
1
null
null
null
null
UTF-8
C++
false
false
1,839
h
/* * Copyright 2006 the original author or authors. * * 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 AUTUMN_VALUEWRAPPER_H #define AUTUMN_VALUEWRAPPER_H #include <string> #include "Basic.h" #include "TypeManager.h" #include "IAutumnType.h" using namespace std; namespace Autumn{ /** * Parameter value for class constuctor or setter functions. * * @since 2006-11-22 * @version 0.1.0 */ class ValueWrapper{ private: /** Type of the argument */ string Type; /** Managed by Autumn framework or not */ bool Managed; /** Pointer to the argument */ void* PointerOfValue; /** Type Bean to create or delete value */ IAutumnType* TypeBean; public: /** * Constructor a new ValueWrapper with type and value * @param type Type of the argument * @param vl Value string list of the argument * @param managed This value is managed by Autumn or not * @param at TypeBean to create and delete value */ ValueWrapper(const string& type, StrValueList& vl, bool managed, IAutumnType* at); /** Destructor, delete pointer of value */ ~ValueWrapper(); /** * Return the address of pointer to the argument's value. */ void* getValuePointer() const { return this->PointerOfValue; } }; } // End namespace Autumn #endif
[ "sharplog@c16174ff-a625-0410-88e5-87db5789ed7d" ]
[ [ [ 1, 73 ] ] ]
12709c969795d23bafaf80798af432c493bede13
32b3bb0c3b24e5a660e23bc076d7d6630c6fa3d4
/trunk/soft/zebra-tester/mainwindow.cpp
97834facc496324eeab4817da013c3ef043e1dd2
[]
no_license
Quenii/ADCEVM-minor
19f49d96a0ede47bcf3cd149684ddd6b61811f8d
7aa5868bcc0cd903276714688663bb08f030031a
refs/heads/master
2016-09-06T04:25:08.767113
2011-06-26T13:18:54
2011-06-26T13:18:54
1,454,429
1
1
null
null
null
null
UTF-8
C++
false
false
2,274
cpp
#include "mainwindow.h" #include "qmdisubwindowex.h" #include "qdactypedialog.h" #include "qclockfreqdialog.h" #include "DacAnalyzerSettings.h" #include "qcentralwidget.h" #include "qpowermonitor.h" #include "RegAccess.hpp" #include <QPushButton> #include <QList> #include <QPointer> #include <QMessageBox> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { ui.setupUi(this); QCentralWidget* centralWidget = new QCentralWidget(this); setCentralWidget(centralWidget); /*bool ok = connect(ui.staticTestWidget, SIGNAL(modeChanged(TestMode)), centralWidget, SLOT(changeMode(TestMode))); Q_ASSERT(ok); */ ui.menuView->addAction(ui.dockWidgetConsole->toggleViewAction()); m_powerMonitorWidget = new QPowerMonitor(this); ui.menuView->addAction(m_powerMonitorWidget->toggleViewAction()); loadSettings(); } MainWindow::~MainWindow() { if (regAccess) regAccess->deleteLater(); } void MainWindow::closeEvent(QCloseEvent *event) { saveSettings(); } void MainWindow::loadSettings() { DacAnalyzerSettings s; m_powerMonitorWidget->move(s.powerMonitorWidgetPos()); m_powerMonitorWidget->setVisible(s.powerMonitorWidgetVisible()); } void MainWindow::saveSettings() { DacAnalyzerSettings s; s.setPowerMonitorWidgetPos(m_powerMonitorWidget->pos()); s.setPowerMonitorWidgetVisible(m_powerMonitorWidget->isVisible()); } void MainWindow::on_actionDacType_triggered(bool checked) { QDacTypeDialog dlg; if (QDialog::Accepted == dlg.exec()) { ui.dacTypeWidget->reloadSettings(); } } void MainWindow::on_actionClockFrequency_triggered(bool checked) { QClockFreqDialog dlg; if (QDialog::Accepted == dlg.exec()) { ui.clockFreqWidget->reloadSettings(); } } void MainWindow::on_action_Reset_GPIO_SPI_triggered(bool checked) { if (!regAccess) { regAccess = new RegAccess(0, 0); regAccess->setAttribute(Qt::WA_DeleteOnClose,true); } regAccess->show(); } void MainWindow::on_actionAboutCETC58DACAnalyzer_triggered(bool checked) { QMessageBox::about(this, tr("About CETC58 DAC Analyzer"), tr("<br><b>DAC Analyzer</b> is designed to work with the USB-DAC evaluation board.<br><br><div align=center>Copyright (c) CETC58, 2011</div><br> ")); }
[ "Administrator@.(none)", "[email protected]" ]
[ [ [ 1, 28 ], [ 30, 93 ] ], [ [ 29, 29 ] ] ]
5bfe88751df909178f93e6aba403d905ed76bb51
43626054205d6048ec98c76db5641ce8e42b8237
/SGP Sprint 2/SGP First Playable/SGP First Playable/SGP First Playable/source/CCreditsState.h
0bcd5a37a77a9eafb390fa9ce2826ab732f88129
[]
no_license
Wazoobi/whitewings
b700da98b855a64442ad7b7c4b0be23427b0ee23
a53fdb832cfb1ce8605209c9af47f36b01c44727
refs/heads/master
2021-01-10T19:33:22.924792
2009-08-05T18:30:07
2009-08-05T18:30:07
32,119,981
0
0
null
null
null
null
UTF-8
C++
false
false
2,382
h
////////////////////////////////////////////////////////////////////////// // File Name : "CCreditsState.h" // // Author : Juno Madden (JM) // // Purpose : To encapsulate all code for showing the credits. ////////////////////////////////////////////////////////////////////////// #pragma once #include "IGameState.h" #include "CGame.h" #include "SGD Wrappers/CSGD_Direct3D.h" #include "SGD Wrappers/CSGD_TextureManager.h" #include "SGD Wrappers/CSGD_DirectInput.h" #include "CFontManager.h" class CCreditsState : public IGameState { CSGD_Direct3D *m_pD3D; CSGD_TextureManager *m_pTM; CSGD_DirectInput *m_pDI; CFontManager *m_pFM; CGame *pGame; int m_nBackgroundID; CCreditsState(void); ~CCreditsState(void); CCreditsState(const CCreditsState& ); CCreditsState& operator=(const CCreditsState& ); public: ////////////////////////////////////////////////////////////////////////// // Function : Get Instance // // Purpose : Grants global access to the singleton. ////////////////////////////////////////////////////////////////////////// static CCreditsState* GetInstance(void); ////////////////////////////////////////////////////////////////////////// // Function : Enter // // Purpose : Enters into the state. ////////////////////////////////////////////////////////////////////////// void Enter(void); ////////////////////////////////////////////////////////////////////////// // Function : Exit // // Purpose : Leaves the state. ////////////////////////////////////////////////////////////////////////// void Exit(void); ////////////////////////////////////////////////////////////////////////// // Function : Input // // Purpose : Takes in input. ////////////////////////////////////////////////////////////////////////// bool Input(void); ////////////////////////////////////////////////////////////////////////// // Function : Updates // // Purpose : Updates data members based on time. ////////////////////////////////////////////////////////////////////////// void Update(float fElapsedTime); ////////////////////////////////////////////////////////////////////////// // Function : Render // // Purpose : Draws to the screen. ////////////////////////////////////////////////////////////////////////// void Render(void); };
[ "Juno05@1cfc0206-7002-11de-8585-3f51e31374b7" ]
[ [ [ 1, 77 ] ] ]
e540d770ce2bdcecfe195665a0b9d9bfc7c93f27
6e4f9952ef7a3a47330a707aa993247afde65597
/PROJECTS_ROOT/SmartWires/TI/json-value.h
023aaa74447c8b268111f0f0168522d8a2c9dc39
[]
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
19,284
h
/* * Terra Informatica Sciter Engine * http://terrainformatica.com/sciter * * JSON value class. * * The code and information provided "as-is" without * warranty of any kind, either expressed or implied. * * (C) 2003-2006, Andrew Fedoniouk ([email protected]) */ /**\file * \brief value, aka variant, aka discriminated union * * classes here: * * json::value - the value * json::string - wchar string with refcounted data * json::named_value - key/value pair * **/ #ifndef __json_value_h__ #define __json_value_h__ #pragma once #pragma pack(push,4) #ifdef __cplusplus #include "json-aux.h" /**json namespace.*/ namespace json { struct named_value; class string; /// \class value /// \brief The value type, can hold values of bool, int, double, string(wchar_t) and array(value) /// value is also known as JSON value, see: http://json.org/ struct value { friend struct array_data; friend struct string_data; friend class value_istream; friend class value_ostream; public: /// Type of the value. typedef enum VALUETYPE { V_UNDEFINED = 0, ///< empty V_BOOL = 1, ///< bool V_INT = 2, ///< int V_REAL = 3, ///< double V_STRING = 4, ///< string of wchar_t V_ARRAY = 5, ///< array of value elements V_MAP = 6 ///< map of name/value pairs - simple map }; value() :v_type(V_UNDEFINED) { data.l_val = 0; } value(const value& src) :v_type(V_UNDEFINED) { set(src); } /// constructor explicit value(bool v) :v_type(V_UNDEFINED) { set(v); } /// constructor explicit value(int v) :v_type(V_UNDEFINED) { set(v); } /// constructor explicit value(double v) :v_type(V_UNDEFINED) { set(v); } /// constructor explicit value(const byte* utf8, size_t length) :v_type(V_UNDEFINED) { set(utf8, length); } explicit value(const byte* utf8) :v_type(V_UNDEFINED) { if(utf8) set(utf8, strlen((const char*)utf8)); } /// constructor explicit value(const wchar_t* psz) :v_type(V_UNDEFINED) { set(psz); } explicit value(const wchar_t* ps, size_t length) :v_type(V_UNDEFINED) { set(ps, length); } /// constructor explicit value(const value* v, size_t n) :v_type(V_UNDEFINED) { set_array(v,n); } /// constructor explicit value(const string& s); explicit value(const value& k, const value& v) :v_type(V_UNDEFINED) { set(k,v); } /// current type VALUETYPE type() const { return v_type; } /// clear it and free resources inline void clear(); /// set new value inline void set(const value& src); /// assign utf8 encoded string void set(const byte* utf8, size_t length); /// assign string void set(const wchar_t* src); void set(const wchar_t* src, size_t length); void set(const string& src); /// assign int void set(int i) { clear(); data.i_val = i; v_type = V_INT; } /// assign bool void set(bool b) { clear(); data.i_val = (int)b; v_type = V_BOOL; } /// assign float void set(double r) { clear(); data.r_val = r; v_type = V_REAL; } /// assign vector of values void set_array(const value* v, size_t n); /// assign value to key, convert this value to map if needed. void set(const value& key, const value& val) { v2k(key, val); } void set(const wchar_t* key, const value& val) { value vk(key); v2k(vk, val); } ~value() { clear(); } /// indicator bool is_undefined() const { return (v_type == V_UNDEFINED); } /// indicator bool is_int() const { return (v_type == V_INT); } /// indicator bool is_real() const { return (v_type == V_REAL); } /// indicator bool is_bool() const { return (v_type == V_BOOL); } /// indicator bool is_string() const { return (v_type == V_STRING); } /// indicator bool is_array() const { return (v_type == V_ARRAY); } /// indicator bool is_map() const { return (v_type == V_MAP); } value& operator = (const wchar_t* ps) { set(ps); return *this; } value& operator = (int v) { set(v); return *this; } value& operator = (double v) { set(v); return *this; } value& operator = (bool v) { set(v); return *this; } value& operator = (const value& v) { set(v); return *this; } value& operator = (const string& s) { set(s); return *this; } //value& operator = (const std::vector<value>& a) { if(a.size() != 0) set(&a[0], a.size()); return *this; } //value& operator = (const std::wstring& s) { set(s.c_str()); return *this; } bool operator == ( const value& rs ) const; bool operator != ( const value& rs ) const { return !(operator==(rs)); } /// fetcher int get(int def_val) const { return (v_type == V_INT)? data.i_val: def_val; } /// fetcher double get(double def_val) const { return (v_type == V_REAL)? data.r_val: def_val; } /// fetcher bool get(bool def_val) const { return (v_type == V_BOOL)? (data.i_val != 0): def_val; } /// fetcher const wchar_t* get(const wchar_t* def_val) const; /// get array size and n-th element (if any) int length() const; /// get n-th element of the array value nth(int n) const; /// set n-th element of the array void nth(int n, const value& t); /// get value by key in the map value k2v(const value& k) const; /// set value to key in the map void v2k(const value& k, const value& v); /// set value to key in the map const named_value* get_first() const; // Joel's rewording of the gets above /// converter operator bool() { assert(v_type == V_BOOL); return get( false ); } /// converter operator int() { assert(v_type == V_INT); return get( 0 ); } /// converter operator double() { assert(v_type == V_REAL); return get( 0.0 ); } /// converter operator const wchar_t*() { assert(v_type == V_STRING); return get((const wchar_t*)0); } /// indexer value operator []( int index ) const { assert(v_type == V_ARRAY); if(v_type == V_ARRAY) return nth( index ); return value(); } /// map read access const value operator []( const value& key ) const { assert(v_type == V_MAP); if(v_type == V_MAP) return k2v( key ); return value(); } /// map read access const value operator []( const wchar_t* key ) const { assert(v_type == V_MAP); if(v_type == V_MAP) { value vkey(key); return k2v( vkey ); } return value(); } /// converter string to_string() const; void emit(utf8::ostream& os) const; /// converter static value from_string(const wchar_t* str) { if(str == 0 || str[0] == 0) return value(); // undefined //guessing conversion const wchar_t* endstr = str + wcslen(str); wchar_t* lastptr; int i = wcstol(str,&lastptr,10); if(lastptr == endstr) return value(i); double d = wcstod(str,&lastptr); if(lastptr == endstr) return value(d); if(wcsicmp(str,L"true")==0) return value(true); if(wcsicmp(str,L"false")==0) return value(false); return value(str); } //static void* mem_alloc(size_t sz) { return ::HeapAlloc( ::GetProcessHeap(), HEAP_ZERO_MEMORY, sz ); } //static void mem_free(void* mp) { ::HeapFree( ::GetProcessHeap(), 0, mp ); } typedef void (*wiper_t)( void * ); protected: VALUETYPE v_type; union data_slot { int i_val; double r_val; int64 l_val; string_data* s_val; array_data* a_val; // array data named_value* m_val; // simple map of name/value pairs. } data; void init( const value& v ) { data.l_val = v.data.l_val; v_type = v.v_type; } }; struct named_value { //friend class value_ostream; //friend class value_istream; value key; value val; named_value* next; value::wiper_t wipe; long n_refs; public: //named_value(named_value* n = 0): next(n), n_refs(1) {} //~named_value() { assert(n_refs == 0); if(next) next->release(); } void add_ref() { ++n_refs; } void release() { if (--n_refs <= 0) { if(next) next->release(); wipe(this); } } static named_value* find( named_value* root, const value& k ) { named_value* t = root; while(t) if( t->key == k ) return t; else t = t->next; return 0; } static bool get( const named_value* root, const value& k, value& v ) { named_value* t = find( const_cast<named_value*>(root),k); if( t ) { v = t->val; return true; } return false; } static void set( named_value* &root, const value& k, const value& v ) { named_value* t = find(root,k); if( !t ) { named_value* nt = (named_value*) malloc(sizeof(named_value)); nt->wipe = &free; nt->add_ref(); nt->next = t; nt->key = k; root = t = nt; // ccoder's fix } t->val = v; } static size_t length(const named_value* seq) { size_t sz = 0; while( seq ) { ++sz; seq = seq->next; } return sz; } }; struct array_data { volatile long ref_count; size_t length; value::wiper_t wipe; // value elements[] - go here value* elements() { return reinterpret_cast<value*>(this + 1); } static array_data* allocate( const value* values, size_t n ) { array_data* ad = (array_data*) malloc( sizeof(array_data) + n * sizeof(value) ); ad->wipe = &free; ad->ref_count = 1; ad->length = n; value* v = ad->elements(); for( size_t i = 0; i < n; ++i ) { v[i].init(values[i]); } return ad; } static array_data* allocate( size_t n ) { array_data* ad = (array_data*) malloc( sizeof(array_data) + n * sizeof(value) ); ad->wipe = &free; ad->ref_count = 1; ad->length = n; value* v = ad->elements(); value z; for( size_t i = 0; i < n; ++i ) { v[i].init(z); } return ad; } void release() { if( --ref_count == 0 ) { value* els = elements(); for( size_t i = 0; i < length; ++i ) els[i].~value(); wipe(this); } } void add_ref() { ++ref_count; } static bool equal( const array_data* v1, const array_data* v2 ) { if( v1->length != v2->length ) return false; value* a1 = const_cast<array_data*>(v1)->elements(); value* a2 = const_cast<array_data*>(v2)->elements(); for( size_t i = 0; i < v1->length; ++i ) if( a1[i] != a2[i] ) return false; return true; } }; struct string_data // ref_counted wchar buffer { long n_refs; size_t length; value::wiper_t wiper; void add_ref() { ++n_refs; } void release() { if (--n_refs <= 0) wiper(this); } static string_data* allocate(const wchar_t* lpsz) { string_data* pd = allocate(wcslen(lpsz)); wcscpy(pd->data(),lpsz); return pd; } static string_data* allocate(const wchar_t* lps, size_t n) { string_data* pd = allocate(n); wcscpy(pd->data(),lps); return pd; } static string_data* allocate(size_t n) { string_data* pd = (string_data*) malloc( sizeof(string_data) + sizeof(wchar_t) * (n + 1) ); pd->wiper = &free; pd->length = n; pd->data()[n] = 0; pd->n_refs = 1; return pd; } static string_data* allocate_from_utf8( const byte* utf8, size_t length) { pod::wchar_buffer buf; utf8::towcs(utf8,length,buf); return allocate(buf.data(), buf.length()); } static string_data* empty() { static string_data* _empty = 0; if(!_empty) _empty = allocate(size_t(0)); return _empty; } wchar_t* data() const { return (wchar_t *)(this + 1); } }; inline void value::clear() { switch(v_type) { case V_STRING: data.s_val->release(); break; case V_ARRAY: data.a_val->release(); break; case V_MAP: data.m_val->release(); break; } data.l_val = 0; v_type = V_UNDEFINED; } inline const wchar_t* value::get(const wchar_t* def_val) const { return (v_type == V_STRING)? data.s_val->data(): def_val; } inline void value::set(const byte* utf8, size_t length) { clear(); v_type = V_STRING; if( utf8 && utf8[0] && length ) data.s_val = string_data::allocate_from_utf8(utf8,length); else { data.s_val = string_data::empty(); data.s_val->add_ref(); } } inline void value::set(const wchar_t* src) { clear(); v_type = V_STRING; if( src && src[0] ) data.s_val = string_data::allocate(src); else { data.s_val = string_data::empty(); data.s_val->add_ref(); } } inline void value::set(const wchar_t* src, size_t length) { clear(); v_type = V_STRING; if( src && src[0] ) data.s_val = string_data::allocate(src, length); else { data.s_val = string_data::empty(); data.s_val->add_ref(); } } inline void value::set(const value& src) { if( this == &src ) return; clear(); v_type = src.v_type; data.l_val = src.data.l_val; switch(v_type) { case V_STRING: data.s_val->add_ref(); break; case V_ARRAY: data.a_val->add_ref(); break; case V_MAP: data.m_val->add_ref(); break; } } inline value value::k2v(const value& k) const { value v; named_value::get( data.m_val, k, v); return v; } inline const named_value* value::get_first() const { assert(v_type == V_MAP); return data.m_val; } inline void value::v2k(const value& k, const value& v) { if(!is_map()) { clear(); v_type = V_MAP; } named_value::set( data.m_val, k, v); } inline void value::set_array(const value* v, size_t n) { clear(); v_type = V_ARRAY; data.a_val = v? array_data::allocate(v,n): array_data::allocate(n); } inline int value::length() const { if(v_type == V_ARRAY) return int(data.a_val->length); if(v_type == V_STRING) return int(data.s_val->length); if(v_type == V_MAP) return int(named_value::length(data.m_val)); return 0; } inline bool value::operator == ( const value& rs ) const { if(v_type != rs.v_type ) return false; if(data.l_val == rs.data.l_val ) return true; if( v_type == V_STRING ) return wcscmp(data.s_val->data(), rs.data.s_val->data()) == 0; if( v_type == V_ARRAY ) return array_data::equal(data.a_val, rs.data.a_val); //if( v_type == V_MAP ) // return array_data::equal(data.a_val, rs.data.a_val); return false; } inline value value::nth(int n) const { return ( n >= 0 && n < length() )? data.a_val->elements()[n]: value(); } inline void value::nth(int n, const value& t) { if ( n >= 0 && n < length() ) data.a_val->elements()[n] = t; else assert(false); } inline void value::emit(utf8::ostream& os) const { switch(v_type) { case V_UNDEFINED: os << "null"; break; case V_BOOL: os << (get(false)? "true": "false"); break; case V_INT: { char buf[128]; sprintf(buf, "%d", get(0)); os << buf; } break; case V_REAL: { char buf[128]; sprintf(buf, "%f", get(0.0)); os << buf; } break; case V_STRING: { os << "\""; for(const wchar_t* pc = get(L""); *pc; ++pc) if( *pc == '"' ) os << "\\\""; else os << (char)*pc; os << "\""; } break; case V_ARRAY: { int total = length(); os << '['; nth(0).emit(os); for( int n = 1; n < total; ++n ) { os << ","; nth(n).emit(os); } os << ']'; } break; case V_MAP: { const json::named_value* pnv = get_first(); os << '{'; while(pnv) { pnv->key.emit(os); os << ':'; pnv->val.emit(os); if(pnv->next) os << ",\n"; else break; pnv = pnv->next; } os << '}'; } break; } } class string { friend struct value; string_data* psd; void init(string_data* ps) { psd = ps; if(psd) psd->add_ref(); } void clear() { if(psd) { psd->release(); psd = 0; } } public: string():psd(0) {} string(const wchar_t* s):psd(0) { if(s) init(string_data::allocate(s)); } string(const wchar_t* s, size_t sz):psd(0) { if(s && sz) init(string_data::allocate(s,sz)); } string(string_data* ps):psd(0) { init(ps); } string(const string& s):psd(0) { init(s.psd); } string(pod::wchar_buffer& wcb):psd(0) { if(wcb.length()) init(string_data::allocate(wcb.data(),wcb.length())); } string& operator = (const string& v) { clear(); init(v.psd); return *this; } string& operator = (const wchar_t* s) { clear(); if(s) init(string_data::allocate(s)); return *this; } ~string() { clear(); } const wchar_t* chars() const { return psd? psd->data():L""; } int length() const { return psd? int(psd->length):0; } operator const wchar_t*() const { return chars(); } }; inline value::value(const string& s) :v_type(V_UNDEFINED) { set(s); } inline void value::set(const string& s) { clear(); v_type = V_STRING; data.s_val = s.psd; data.s_val->add_ref(); } inline string value::to_string() const { switch(v_type) { case V_UNDEFINED: return L"{undefined}"; case V_BOOL: return get(false)? L"true": L"false"; case V_INT: { wchar_t buf[128]; swprintf(buf, L"%d", get(0)); return buf; } case V_REAL: { wchar_t buf[128]; swprintf(buf, L"%f", get(0.0)); return buf; } case V_STRING: return string( data.s_val ); } return string(); } } // ns sciter typedef struct json::value JSON_VALUE; #else // plain c typedef struct _JSON_VALUE { VALUETYPE v_type; union data_slot { int i_val; double r_val; __int64 l_val; void* s_val; void* a_val; // array data void* m_val; // simple map of name/value pairs. } data; } JSON_VALUE; #endif #pragma pack(pop) #endif
[ "wplabs@3fb49600-69e0-11de-a8c1-9da277d31688" ]
[ [ [ 1, 588 ] ] ]
ff4e312494b3bbec73ba5fcbe7adf53bae84b598
e47722025231d67c684f8072265cdb832487b4f3
/cpp/server/world.cpp
29571ba35fa3d73f3a7c96e0d1c15405786a02dd
[]
no_license
Gamer2k4/basinrogue
0950c049b9e7a9dd543c892b8b0d4f30b460faf7
0fac183e94ddb8d7b6a5b3333f137b11a2b72b58
refs/heads/master
2021-01-19T07:54:05.228849
2007-02-25T13:35:25
2007-02-25T13:35:25
40,727,740
0
0
null
null
null
null
UTF-8
C++
false
false
2,103
cpp
// // C++ Implementation: world // // Description: // // // Author: <>, (C) 2007 // // Copyright: See COPYING file that comes with this distribution // // #pragma warning(disable:4786) #include "world.h" #include "dungeon.h" #include "mobile.h" #include "player.h" World::World() {} World::~World() { for (DungeonDatabase::iterator iter = dungeon_list.begin(); iter != dungeon_list.end(); ++iter) { delete iter->second; } dungeon_list.clear(); } void World::AddDungeon(Dungeon& dungeon) { std::string name = dungeon.getName(); if (dungeon_list.find(name) != dungeon_list.end()) throw std::string("Inserting duplicate dungeon name."); dungeon_list[name] = &dungeon; } bool World::HasDungeon(Dungeon& dungeon) const { std::string name = dungeon.getName(); return (dungeon_list.find(name) != dungeon_list.end()); } void World::SetStartingDungeon(const std::string& dungeon_name) { std::cout << "Starting dungeon defined: " << dungeon_name << std::endl; if (dungeon_list.find(dungeon_name) == dungeon_list.end()) throw std::string("Invalid dungeon."); starting_dungeon = dungeon_name; } void World::AddPlayer(Mobile* mobile) { Level* level = dungeon_list[starting_dungeon]->GetLevel(0); std::pair < int, int > start_pos = level->GetSpawnPoint ( std::string("XXX") ); /* hack: start anywhere */ mobile->SetLevel( *level, start_pos.first, start_pos.second ); } void World::PlayerChangesDungeon(Player& player, const std::string& dungeon_name, int depth, const std::string& entrance_tag) { Level* old_level = player.mobile->GetLevel(); Level* next_level = dungeon_list[dungeon_name]->GetLevel(depth); int startx = 1; int starty = 1; std::pair < int, int > start_pos = next_level->GetSpawnPoint ( entrance_tag ); player.mobile->SetLevel( *next_level, start_pos.first, start_pos.second ); player.viewport.AttachToLevel( next_level, player.command_buffer ); player.SendMessage ( next_level->GetDungeon().GetEntryMessage() ); std::cout << "Player enters dungeon " << dungeon_name << " depth " << depth << "\n"; if (old_level->getMustKillOnLeave()) delete old_level; }
[ "christophe.cavalaria@712ddccb-0227-0410-9f85-29faccf8bd71", "antoine.from.rgrd@712ddccb-0227-0410-9f85-29faccf8bd71" ]
[ [ [ 1, 11 ], [ 13, 13 ], [ 15, 55 ], [ 57, 57 ], [ 60, 67 ], [ 70, 70 ], [ 72, 75 ] ], [ [ 12, 12 ], [ 14, 14 ], [ 56, 56 ], [ 58, 59 ], [ 68, 69 ], [ 71, 71 ] ] ]
b7c9f699743097bb7c4249a2ac1934c851e54a92
eb8a27a2cc7307f0bc9596faa4aa4a716676c5c5
/WinEdition/browser-lcc/jscc/src/v8/v8/src/.svn/text-base/regexp-macro-assembler.cc.svn-base
a7fa608c06c86ae7ddd4b1dee3b73f6f6c515f2b
[ "BSD-3-Clause", "bzip2-1.0.6", "LicenseRef-scancode-public-domain", "Artistic-2.0", "Artistic-1.0" ]
permissive
baxtree/OKBuzzer
c46c7f271a26be13adcf874d77a7a6762a8dc6be
a16e2baad145f5c65052cdc7c767e78cdfee1181
refs/heads/master
2021-01-02T22:17:34.168564
2011-06-15T02:29:56
2011-06-15T02:29:56
1,790,181
0
0
null
null
null
null
UTF-8
C++
false
false
9,807
// Copyright 2008 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "v8.h" #include "ast.h" #include "assembler.h" #include "regexp-stack.h" #include "regexp-macro-assembler.h" #include "simulator.h" namespace v8 { namespace internal { RegExpMacroAssembler::RegExpMacroAssembler() { } RegExpMacroAssembler::~RegExpMacroAssembler() { } bool RegExpMacroAssembler::CanReadUnaligned() { #ifdef V8_HOST_CAN_READ_UNALIGNED return true; #else return false; #endif } #ifndef V8_INTERPRETED_REGEXP // Avoid unused code, e.g., on ARM. NativeRegExpMacroAssembler::NativeRegExpMacroAssembler() { } NativeRegExpMacroAssembler::~NativeRegExpMacroAssembler() { } bool NativeRegExpMacroAssembler::CanReadUnaligned() { #ifdef V8_TARGET_CAN_READ_UNALIGNED return true; #else return false; #endif } const byte* NativeRegExpMacroAssembler::StringCharacterPosition( String* subject, int start_index) { // Not just flat, but ultra flat. ASSERT(subject->IsExternalString() || subject->IsSeqString()); ASSERT(start_index >= 0); ASSERT(start_index <= subject->length()); if (subject->IsAsciiRepresentation()) { const byte* address; if (StringShape(subject).IsExternal()) { const char* data = ExternalAsciiString::cast(subject)->resource()->data(); address = reinterpret_cast<const byte*>(data); } else { ASSERT(subject->IsSeqAsciiString()); char* data = SeqAsciiString::cast(subject)->GetChars(); address = reinterpret_cast<const byte*>(data); } return address + start_index; } const uc16* data; if (StringShape(subject).IsExternal()) { data = ExternalTwoByteString::cast(subject)->resource()->data(); } else { ASSERT(subject->IsSeqTwoByteString()); data = SeqTwoByteString::cast(subject)->GetChars(); } return reinterpret_cast<const byte*>(data + start_index); } NativeRegExpMacroAssembler::Result NativeRegExpMacroAssembler::Match( Handle<Code> regexp_code, Handle<String> subject, int* offsets_vector, int offsets_vector_length, int previous_index, Isolate* isolate) { ASSERT(subject->IsFlat()); ASSERT(previous_index >= 0); ASSERT(previous_index <= subject->length()); // No allocations before calling the regexp, but we can't use // AssertNoAllocation, since regexps might be preempted, and another thread // might do allocation anyway. String* subject_ptr = *subject; // Character offsets into string. int start_offset = previous_index; int end_offset = subject_ptr->length(); // The string has been flattened, so it it is a cons string it contains the // full string in the first part. if (StringShape(subject_ptr).IsCons()) { ASSERT_EQ(0, ConsString::cast(subject_ptr)->second()->length()); subject_ptr = ConsString::cast(subject_ptr)->first(); } // Ensure that an underlying string has the same ascii-ness. bool is_ascii = subject_ptr->IsAsciiRepresentation(); ASSERT(subject_ptr->IsExternalString() || subject_ptr->IsSeqString()); // String is now either Sequential or External int char_size_shift = is_ascii ? 0 : 1; int char_length = end_offset - start_offset; const byte* input_start = StringCharacterPosition(subject_ptr, start_offset); int byte_length = char_length << char_size_shift; const byte* input_end = input_start + byte_length; Result res = Execute(*regexp_code, subject_ptr, start_offset, input_start, input_end, offsets_vector, isolate); return res; } NativeRegExpMacroAssembler::Result NativeRegExpMacroAssembler::Execute( Code* code, String* input, int start_offset, const byte* input_start, const byte* input_end, int* output, Isolate* isolate) { ASSERT(isolate == Isolate::Current()); // Ensure that the minimum stack has been allocated. RegExpStackScope stack_scope(isolate); Address stack_base = stack_scope.stack()->stack_base(); int direct_call = 0; int result = CALL_GENERATED_REGEXP_CODE(code->entry(), input, start_offset, input_start, input_end, output, stack_base, direct_call, isolate); ASSERT(result <= SUCCESS); ASSERT(result >= RETRY); if (result == EXCEPTION && !isolate->has_pending_exception()) { // We detected a stack overflow (on the backtrack stack) in RegExp code, // but haven't created the exception yet. isolate->StackOverflow(); } return static_cast<Result>(result); } const byte NativeRegExpMacroAssembler::word_character_map[] = { 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0xffu, 0xffu, 0xffu, 0xffu, 0xffu, 0xffu, 0xffu, 0xffu, // '0' - '7' 0xffu, 0xffu, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, // '8' - '9' 0x00u, 0xffu, 0xffu, 0xffu, 0xffu, 0xffu, 0xffu, 0xffu, // 'A' - 'G' 0xffu, 0xffu, 0xffu, 0xffu, 0xffu, 0xffu, 0xffu, 0xffu, // 'H' - 'O' 0xffu, 0xffu, 0xffu, 0xffu, 0xffu, 0xffu, 0xffu, 0xffu, // 'P' - 'W' 0xffu, 0xffu, 0xffu, 0x00u, 0x00u, 0x00u, 0x00u, 0xffu, // 'X' - 'Z', '_' 0x00u, 0xffu, 0xffu, 0xffu, 0xffu, 0xffu, 0xffu, 0xffu, // 'a' - 'g' 0xffu, 0xffu, 0xffu, 0xffu, 0xffu, 0xffu, 0xffu, 0xffu, // 'h' - 'o' 0xffu, 0xffu, 0xffu, 0xffu, 0xffu, 0xffu, 0xffu, 0xffu, // 'p' - 'w' 0xffu, 0xffu, 0xffu, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, // 'x' - 'z' }; int NativeRegExpMacroAssembler::CaseInsensitiveCompareUC16( Address byte_offset1, Address byte_offset2, size_t byte_length, Isolate* isolate) { ASSERT(isolate == Isolate::Current()); unibrow::Mapping<unibrow::Ecma262Canonicalize>* canonicalize = isolate->regexp_macro_assembler_canonicalize(); // This function is not allowed to cause a garbage collection. // A GC might move the calling generated code and invalidate the // return address on the stack. ASSERT(byte_length % 2 == 0); uc16* substring1 = reinterpret_cast<uc16*>(byte_offset1); uc16* substring2 = reinterpret_cast<uc16*>(byte_offset2); size_t length = byte_length >> 1; for (size_t i = 0; i < length; i++) { unibrow::uchar c1 = substring1[i]; unibrow::uchar c2 = substring2[i]; if (c1 != c2) { unibrow::uchar s1[1] = { c1 }; canonicalize->get(c1, '\0', s1); if (s1[0] != c2) { unibrow::uchar s2[1] = { c2 }; canonicalize->get(c2, '\0', s2); if (s1[0] != s2[0]) { return 0; } } } } return 1; } Address NativeRegExpMacroAssembler::GrowStack(Address stack_pointer, Address* stack_base, Isolate* isolate) { ASSERT(isolate == Isolate::Current()); RegExpStack* regexp_stack = isolate->regexp_stack(); size_t size = regexp_stack->stack_capacity(); Address old_stack_base = regexp_stack->stack_base(); ASSERT(old_stack_base == *stack_base); ASSERT(stack_pointer <= old_stack_base); ASSERT(static_cast<size_t>(old_stack_base - stack_pointer) <= size); Address new_stack_base = regexp_stack->EnsureCapacity(size * 2); if (new_stack_base == NULL) { return NULL; } *stack_base = new_stack_base; intptr_t stack_content_size = old_stack_base - stack_pointer; return new_stack_base - stack_content_size; } #endif // V8_INTERPRETED_REGEXP } } // namespace v8::internal
[ [ [ 1, 266 ] ] ]
ac0dc6c151acc4619b2d5713dbf9911cb69fadaf
27bde5e083cf5a32f75de64421ba541b3a23dd29
/source/FileIO.h
98e2af8cb4ae00389bd2bec821cb8cd8e9056a6d
[]
no_license
jbsheblak/fatal-inflation
229fc6111039aff4fd00bb1609964cf37e4303af
5d6c0a99e8c4791336cf529ed8ce63911a297a23
refs/heads/master
2021-03-12T19:22:31.878561
2006-10-20T21:48:17
2006-10-20T21:48:17
32,184,096
0
0
null
null
null
null
UTF-8
C++
false
false
3,828
h
//--------------------------------------------------- // Name: Game : FileIO // Desc: handles reading / writing files // Author: John Sheblak // Contact: [email protected] //--------------------------------------------------- #ifndef _GAME_FILE_IO_H_ #define _GAME_FILE_IO_H_ #include "Types.h" #include <string> #include <vector> #include <map> #include "Arrow.h" namespace Game { class Arrow; namespace FileUtils { bool GetNextLine( std::string& line, FILE*& file ); }; // A file containing a set of timed entity placements namespace EntitySetFile { struct EntitySetEntry { std::string mEntityName; // name of entity (ie: RedArrow, BlueBeam) F32 mEntityTime; // spawn time for entity F32 mEntityRotation; // spawn rotation int32_t mStartX; // starting positions int32_t mStartY; Entity* mEntity; }; typedef std::vector<EntitySetEntry> EntitySetList; bool Export( const char* szFile, EntitySetList& entSet ); bool Import( const char* szFile, EntitySetList& entSet ); bool Import( uint8_t* stream, uint32_t streamSize, EntitySetList& entSet ); }; //end ArrowSetFile // entity description file that specifies properties for base entity variants namespace EntityDescFile { bool Export( const char* szFile, EntityDescMap* descMap ); bool Import( const char* szFile, EntityDescMap* descMap ); bool Import( uint8_t* stream, uint32_t streamSize, EntityDescMap* descMap ); bool Parse( const char* szFile, EntityDescMap* descMap ); }; // a level file containing an arrow set and other features namespace LevelFile { struct LevelEntry { std::string mName; std::string mBackground; std::string mMusic; std::string mEntitySet; F32 mTimeLength; }; bool Export( const char* szFile, const LevelEntry& entry ); bool Import( const char* szFile, LevelEntry& entry ); bool Import( uint8_t* stream, uint32_t streamSize, LevelEntry& entry ); bool Parse( const char* szFile, LevelEntry& entry ); }; // end LevelFile // a packed file containing multiple buffers of data namespace PackFile { struct PackElement { uint32_t mSignature; uint32_t mVersion; uint32_t mSize; void* mData; }; typedef std::vector<PackElement> PackElementList; bool Export( const char* szFile, PackElementList& list ); bool Import( const char* szFile, PackElementList& list ); bool Import( uint8_t* stream, uint32_t streamSize, PackElementList& list ); class PackFileManager { public: bool Import( const char* szFile ); bool GetPackElement( const char* signature, PackElement& elem ); bool GetPackElement( uint32_t sigHash, PackElement& elem ); void HardClearData(); static PackFileManager* GetPFM(); private: PackElementList mPackList; }; }; #define SPackFile (*PackFile::PackFileManager::GetPFM()) // a file for packing image files namespace ImageFile { struct ImageEntry { //std::string mImageName; uint32_t mImgNameHash; uint32_t mSize; void* mpData; }; typedef std::vector< ImageEntry > ImageEntryList; bool Export( const char* szFile, ImageEntryList& list ); bool Import( uint8_t* stream, uint32_t streamSize, ImageEntryList& list ); }; namespace GameSaveFile { // to be filled eventually. versioned in the read/write code struct SaveFile { uint32_t mCompletedLevels; }; bool Export( const char* szFile, const SaveFile& saveFile ); bool Import( const char* szFile, SaveFile& saveFile ); bool Import( uint8_t* stream, uint32_t streamSize, SaveFile& saveFile ); }; }; //end Game #endif // end _GAME_FILE_IO_H_
[ "jbsheblak@5660b91f-811d-0410-8070-91869aa11e15" ]
[ [ [ 1, 152 ] ] ]
bb6f6d2477ae9e6a5dd57bdd0a98cec764ea6e36
12ea67a9bd20cbeed3ed839e036187e3d5437504
/winxgui/Swc/swc/CHeaderCtrl.cpp
54295be656f5a908510fc6237cbec679c175b89d
[]
no_license
cnsuhao/winxgui
e0025edec44b9c93e13a6c2884692da3773f9103
348bb48994f56bf55e96e040d561ec25642d0e46
refs/heads/master
2021-05-28T21:33:54.407837
2008-09-13T19:43:38
2008-09-13T19:43:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,127
cpp
/* * CHeaderView.cpp 1.0 23/09/2003 * * Copyright 2003 Francisco Campos. All rights reserved. * BEYONDATA PROPRIETARY. Use is subject to license terms. * * \|||/ * |o_o| * ----o00o-------o00o--- * ---------------------- * * Windows Wrapper function * *****/ #include "stdafx.h" #include "CHeaderCtrl.h" #define UPDATEWIN Invalidate();\ UpdateWindow(); ///////////////////////////////////////////////////////////////////////////// // CHeaderView CHeaderView::CHeaderView() { m_clrFace= ::GetSysColor(COLOR_3DFACE); m_clrShadow= ::GetSysColor(COLOR_BTNSHADOW); m_clrLight= ::GetSysColor(COLOR_BTNHIGHLIGHT); m_nNumbottomSelect=-1; m_bSentido=TRUE; m_bMouserOver=FALSE; m_selected=-1; m_cfontNormal.CreateFont(14,0,0,0,400,0,0,0,0,1,2,1,34,"MS Sans Serif"); m_cfontBold.CreateFont(14,0,0,0,700,0,0,0,0,1,2,1,34,"MS Sans Serif"); } CHeaderView::~CHeaderView() { m_cfontNormal.m_hFont=NULL; m_cfontBold.m_hFont=NULL;} ///////////////////////////////////////////////////////////////////////////// // CHeaderView message handlers //*************************************************************************** BOOL CHeaderView::DrawItem(HDITEM hdi,CGDI* pDC) { CRect rcitem; CSize siImg=CSize(0,0); IMAGEINFO pImageInfo; int OldMode=pDC->SetBkMode(TRANSPARENT); GetItemRect(hdi.iOrder, rcitem); HFONT m_fontOldBold; HFONT m_fontOld; //--------------------------------------------------------- //se mueve la imagen para dar la sensacion //de seleccion del item //--------------------------------------------------------- if (m_nNumbottomSelect==hdi.iOrder) { DrawArrow(pDC,rcitem,m_bSentido); rcitem.right-=12; } if (hdi.iImage > -1) { m_img.GetImageInfo(hdi.iImage,&pImageInfo); CRect rcima =pImageInfo.rcImage; siImg=CSize(rcima.Width(),rcima.Height()); CPoint pti(rcitem.left+2,rcitem.top+1); m_img.Draw( hdi.iImage,pDC->m_hDC, pti, ILD_TRANSPARENT); } if (hdi.cchTextMax > 0) { CRect m_rctext=rcitem; m_rctext.left+=siImg.cx+4; m_rctext.bottom-=2; if (m_bMouserOver && m_selected==hdi.iOrder) m_fontOldBold=pDC->SelectFont(m_cfontBold); else m_fontOld=pDC->SelectFont(m_cfontNormal); DrawTextExt(hdi.pszText,pDC,&rcitem); } pDC->SetBkMode(OldMode); return TRUE; } //********************************************************************************** void CHeaderView::DrawTextExt(LPCSTR Cad,CGDI* pDC,CRect* rc) { TCHAR m_cadBreak[64]; memset(m_cadBreak,0x00,64); lstrcpy(m_cadBreak,Cad); int contt; int cont =contt=strlen(m_cadBreak); CSize coor=pDC->GetTextExtent(m_cadBreak,cont); if ( coor.cx > rc->Width()) { rc->left+=1; while(cont > 1 ) { TCHAR m_scadtemp[64]; memset(m_scadtemp,0x00,64); lstrcpy(m_scadtemp,m_cadBreak); lstrcat(m_scadtemp,_T("...")); CSize coor=pDC->GetTextExtent(m_scadtemp,lstrlen(m_scadtemp)); if(coor.cx > rc->Width()) *(m_cadBreak+cont)=NULL; else break; cont--; } lstrcat(m_cadBreak,_T("...")); rc->right+=3; } pDC->DrawText(m_cadBreak,rc,DT_SINGLELINE|DT_LEFT|DT_VCENTER); } void CHeaderView::PreSubClassWnd() { m_pParentWnd = GetParent(); ASSERT(m_pParentWnd); ClearImages(); ReDraw(); } //******************************************************************************** void CHeaderView::DrawArrow(CGDI* pDC,CRect rc,BOOL bUp) { CPen cp; CPen cps; CPen cpw; cp.CreatePen(PS_SOLID,1, m_clrFace); cps.CreatePen(PS_SOLID,1, m_clrShadow); cpw.CreatePen(PS_SOLID,1, m_clrLight); HPEN hPen; rc.left=rc.right-12; rc.right=rc.left+8; rc.bottom=rc.top+12; rc.top+=2; int m_mitad=rc.left+4; if (bUp == TRUE) { //linea izquierda hPen=pDC->SelectObject(&cps); pDC->MoveTo(rc.left,rc.bottom); pDC->LineTo(m_mitad,rc.top); //linea derecha pDC->SelectObject(&cpw); pDC->MoveTo(rc.right,rc.bottom); pDC->LineTo(m_mitad,rc.top); //linea de abajo pDC->MoveTo(rc.left,rc.bottom); pDC->LineTo(rc.right,rc.bottom); } else { rc.bottom=rc.top+12; rc.top+=4; //linea izquierda hPen=pDC->SelectObject(&cps); pDC->MoveTo(rc.left,rc.top); pDC->LineTo(m_mitad,rc.bottom); //linea superior pDC->MoveTo(rc.left,rc.top); pDC->LineTo(rc.right,rc.top); //linea derecha pDC->SelectObject(&cpw); pDC->MoveTo(rc.right,rc.top); pDC->LineTo(m_mitad,rc.bottom); } cp.DeleteObject(); cps.DeleteObject(); cpw.DeleteObject(); //pDC->SelectObject(pOld); } //******************************************************************* void CHeaderView::DelImageCol(int icol) { HDITEM hdi; GetItem(icol,&hdi); hdi.iImage=-1; hdi.fmt |= HDF_IMAGE; hdi.mask |= HDI_IMAGE | HDI_FORMAT; SetItem(icol,&hdi); } //********************************************************************* void CHeaderView::SetImageCol(int icol,int img) { HDITEM hdi; GetItem(icol,&hdi); hdi.iImage=img; hdi.fmt |= HDF_IMAGE; hdi.mask |= HDI_IMAGE | HDI_FORMAT; SetItem(icol,&hdi); } //******************************************************************** int CHeaderView::OnCreate(LPCREATESTRUCT lpCreateStruct) { ClearImages(); ReDraw(); return 0; } //******************************************************************** void CHeaderView::ReDraw() { int iNumItems=GetItemCount(); HDITEM m_hditems; m_hditems.fmt |= HDF_OWNERDRAW; for (int i =0; i < iNumItems; i++) SetItem(i,&m_hditems); } //********************************************************************* void CHeaderView::ClearImages() { HDITEM m_hditems; m_hditems.mask |=HDI_FORMAT|HDI_IMAGE; int iNumItems=GetItemCount(); for (int i =0; i < iNumItems; i++) { m_hditems.iImage=-1; SetItem(i,&m_hditems); } } //******************************************************************** void CHeaderView::OnPaint(HDC hDC) { CPaintDC dc(GetSafeHwnd()); // device context for painting CGDI MemDC; CBitmap m_BitmapMemDC; CRect rcClient; CRect rcWin; CBrush m_brush; //****************************************** GetWindowRect( &rcWin); GetClientRect( &rcClient ); MemDC.CreateCompatibleDC(dc.m_hDC); m_BitmapMemDC.CreateCompatibleBitmap(dc.m_hDC, rcClient.Width(),rcClient.Height()); CBitmap m_bitmapOld=MemDC.SelectObject(&m_BitmapMemDC); m_brush.CreateSysColorBrush(COLOR_3DFACE); MemDC.FillRect(rcClient,&m_brush); //evita el horrible color negro CGradient M(CSize(rcClient.Width(),rcClient.Height())); M.PrepareVertical(&MemDC); M.Draw(&MemDC,rcClient.left,rcClient.top,0,0,rcClient.Width(),rcClient.Height(),SRCCOPY); ScreenToClient(rcWin); BiselaBoton(rcWin,&MemDC); int iNumItems=GetItemCount(); int sizeOfBuffer = 256 ; LPSTR lpBuffer= new TCHAR[sizeOfBuffer]; for (int i =0; i < iNumItems; i++) { HDITEM hdi; memset(lpBuffer,0x00,sizeOfBuffer); memset(&hdi,0x00,sizeof(struct _HD_ITEMW)); GetItemFull(i,&hdi,lpBuffer,sizeOfBuffer); DrawItem(hdi,&MemDC); } delete[] lpBuffer; MemDC.Draw3dRect(rcClient,CDrawLayer::GetRGBSemiShadow(),CDrawLayer::GetRGBSemiShadow()); dc.BitBlt(0,0,rcClient.Width(),rcClient.Height(),MemDC.m_hDC, rcClient.left,rcClient.top,SRCCOPY); MemDC.SelectObject(&m_bitmapOld); m_BitmapMemDC.DeleteObject(); MemDC.DeleteDC(); } //************************************************************************ void CHeaderView::BiselaBoton(CRect rcWin,CGDI* pDC) { CPen cp; CPen cps; CPen cpw; cp.CreatePen(PS_SOLID,1, m_clrFace); cps.CreatePen(PS_SOLID,1, CDrawLayer::GetRGBSemiShadow()); cpw.CreatePen(PS_SOLID,1, m_clrLight); /*************************************************** pDC->Draw3dRect(rcWin,m_clrLight,m_clrShadow); rcWin.DeflateRect(1,1); pDC->Draw3dRect(rcWin,m_clrFace,m_clrFace); ***************************************************/ int iNumItems=GetItemCount(); int iContx=0; for (int i =0; i < iNumItems; i++) { CRect recItem; GetItemRect(i, recItem); iContx+=recItem.Width(); //quitamos todas las lineas recItem.DeflateRect(1,1); pDC->SelectObject(&cpw); pDC->MoveTo(iContx-2,rcWin.top+1); pDC->LineTo(iContx-2,rcWin.bottom-1); pDC->SelectObject(&cps); pDC->MoveTo(iContx-1,rcWin.top+1); pDC->LineTo(iContx-1,rcWin.bottom-1); pDC->SelectObject(&cpw); pDC->MoveTo(iContx,rcWin.top+1); pDC->LineTo(iContx,rcWin.bottom-1); } cp.DeleteObject(); cps.DeleteObject(); cpw.DeleteObject(); } //********************************************************************* void CHeaderView::OnWindowPosChanged(WINDOWPOS FAR* lpwndpos) { Default(); Invalidate(); UpdateWindow(); ReDraw(); } //********************************************************************************* BOOL CHeaderView::OnEraseBkgnd(HDC pDC) { return TRUE; } //********************************************************************************* void CHeaderView::SetImageList(UINT nBitmapID, int cx, int nGrow, COLORREF crMask) { CBitmap cbmp; BITMAP bmp; m_img.Create(nBitmapID,cx,nGrow,crMask); cbmp.LoadBitmap(theApp->GetInstance(),(LPCTSTR)nBitmapID); cbmp.GetBitmap(&bmp); m_img.Add(&cbmp,crMask); m_sizeImag=CSize(cx,bmp.bmHeight); } int CHeaderView::GetSortColumn(BOOL* bSortCol ) { *bSortCol =m_bSentido; return m_nNumbottomSelect; } void CHeaderView::SetSortColumn(int nCol,BOOL sentido) { m_nNumbottomSelect =nCol; m_bSentido=sentido; Invalidate(); UpdateWindow(); } BOOL CHeaderView::OnSetCursor(HWND hWnd, UINT nHitTest, UINT message) { Default(); if (m_bMouserOver) return 0; CRect rc; GetClientRect(rc); CPoint pt(GetMessagePos()); ScreenToClient(&pt); m_selected=-1; if (rc.PtInRect(pt)) { int iNumItems=GetItemCount(); for (int i =0; i < iNumItems; i++) { CRect recItem; GetItemRect(i, recItem); if (recItem.PtInRect(pt)) { m_selected=i; break; } } m_bMouserOver=TRUE; SetTimer(1,50,0); UPDATEWIN } return TRUE; } void CHeaderView::OnTimer(UINT nIDEvent) { // TODO: Add your message handler code here and/or call default if (!m_bMouserOver) return; CRect rc; CPoint pt(GetMessagePos()); ScreenToClient(&pt); GetClientRect(rc); CRect recItem; GetItemRect(m_selected, recItem); if (!rc.PtInRect(pt)||!recItem.PtInRect(pt)) { m_bMouserOver=FALSE; KillTimer(1); m_selected=-1; UPDATEWIN } } BOOL CHeaderView::OnLButtonDown(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default Default(); int iNumItems=GetItemCount(); for (int i =0; i < iNumItems; i++) { CRect recItem; GetItemRect(i, recItem); if (recItem.PtInRect(point)) { if (m_nNumbottomSelect==i) m_bSentido=!m_bSentido; else m_bSentido=TRUE; m_nNumbottomSelect=i; break; } } UPDATEWIN return TRUE; }
[ "xushiweizh@86f14454-5125-0410-a45d-e989635d7e98" ]
[ [ [ 1, 471 ] ] ]
a74b8aca517711329262337e3a044b1d63ef5703
cfcd2a448c91b249ea61d0d0d747129900e9e97f
/thirdparty/OpenCOLLADA/COLLADASaxFrameworkLoader/src/COLLADASaxFWLLibraryLightsLoader.cpp
a6499730519107a7740d2b4a8e6046bc6ff32dac
[]
no_license
fire-archive/OgreCollada
b1686b1b84b512ffee65baddb290503fb1ebac9c
49114208f176eb695b525dca4f79fc0cfd40e9de
refs/heads/master
2020-04-10T10:04:15.187350
2009-05-31T15:33:15
2009-05-31T15:33:15
268,046
0
0
null
null
null
null
UTF-8
C++
false
false
5,626
cpp
/* Copyright (c) 2008 NetAllied Systems GmbH This file is part of COLLADASaxFrameworkLoader. Licensed under the MIT Open Source License, for details please see LICENSE file or the website http://www.opensource.org/licenses/mit-license.php */ #include "COLLADASaxFWLStableHeaders.h" #include "COLLADASaxFWLLibraryLightsLoader.h" #include "COLLADAFWIWriter.h" #include "COLLADAFWLight.h" #include "COLLADAFWColor.h" namespace COLLADASaxFWL { //------------------------------ LibraryLightsLoader::LibraryLightsLoader( IFilePartLoader* callingFilePartLoader ) : FilePartLoader(callingFilePartLoader) , mCurrentColorValueIndex(0) { } //------------------------------ LibraryLightsLoader::~LibraryLightsLoader() { } //------------------------------ bool LibraryLightsLoader::dataColor( const double* data, size_t length ) { COLLADAFW::Color& color = mCurrentLight->getColor(); for ( size_t i = 0; i < length; ++i) { switch ( mCurrentColorValueIndex ) { case 0: color.setRed(data[i]); break; case 1: color.setGreen(data[i]); break; case 2: color.setBlue(data[i]); break; } mCurrentColorValueIndex++; } return true; } //------------------------------ bool LibraryLightsLoader::endColor( ) { // set alpha to a valid value, although it is not used by lights mCurrentLight->getColor().setAlpha(1); mCurrentColorValueIndex = 0; return true; } //------------------------------ bool LibraryLightsLoader::end__library_lights() { finish(); return true; } //------------------------------ bool LibraryLightsLoader::begin__light( const light__AttributeData& attributeData ) { mCurrentLight = FW_NEW COLLADAFW::Light( getUniqueIdFromId( attributeData.id, COLLADAFW::Light::ID()).getObjectId() ); if ( attributeData.name ) mCurrentLight->setName( (const char*) attributeData.name ); else if ( attributeData.id ) mCurrentLight->setName( (const char*) attributeData.id ); return true; } //------------------------------ bool LibraryLightsLoader::end__light() { bool success = writer()->writeLight(mCurrentLight); FW_DELETE mCurrentLight; mCurrentLight = 0; return true; } //------------------------------ bool LibraryLightsLoader::begin__technique_common__ambient() { mCurrentLight->setLightType(COLLADAFW::Light::AMBIENT_LIGHT); return true; } //------------------------------ bool LibraryLightsLoader::end__ambient__color() { return endColor(); } //------------------------------ bool LibraryLightsLoader::data__ambient__color( const double* data, size_t length ) { return dataColor(data, length); } //------------------------------ bool LibraryLightsLoader::begin__directional() { mCurrentLight->setLightType(COLLADAFW::Light::DIRECTIONAL_LIGHT); return true; } //------------------------------ bool LibraryLightsLoader::end__directional__color() { return endColor(); } //------------------------------ bool LibraryLightsLoader::data__directional__color( const double* data, size_t length ) { return dataColor(data, length); } //------------------------------ bool LibraryLightsLoader::begin__point() { mCurrentLight->setLightType(COLLADAFW::Light::POINT_LIGHT); return true; } //------------------------------ bool LibraryLightsLoader::end__point__color() { return endColor(); } //------------------------------ bool LibraryLightsLoader::data__point__color( const double* data, size_t length ) { return dataColor(data, length); } //------------------------------ bool LibraryLightsLoader::data__point__constant_attenuation( double value ) { mCurrentLight->setConstantAttenuation(value); return true; } //------------------------------ bool LibraryLightsLoader::data__point__linear_attenuation( double value ) { mCurrentLight->setLinearAttenuation(value); return true; } //------------------------------ bool LibraryLightsLoader::data__point__quadratic_attenuation( double value ) { mCurrentLight->setQuadraticAttenuation(value); return true; } //------------------------------ bool LibraryLightsLoader::begin__spot() { mCurrentLight->setLightType(COLLADAFW::Light::SPOT_LIGHT); return true; } //------------------------------ bool LibraryLightsLoader::end__spot__color() { return endColor(); } //------------------------------ bool LibraryLightsLoader::data__spot__color( const double* data, size_t length ) { return dataColor(data, length); } //------------------------------ bool LibraryLightsLoader::data__spot__constant_attenuation( double value ) { mCurrentLight->setConstantAttenuation(value); return true; } //------------------------------ bool LibraryLightsLoader::data__spot__linear_attenuation( double value ) { mCurrentLight->setLinearAttenuation(value); return true; } //------------------------------ bool LibraryLightsLoader::data__spot__quadratic_attenuation( double value ) { mCurrentLight->setQuadraticAttenuation(value); return true; } //------------------------------ bool LibraryLightsLoader::data__falloff_angle( double value ) { mCurrentLight->setFallOffAngle(value); return true; } //------------------------------ bool LibraryLightsLoader::data__falloff_exponent( double value ) { mCurrentLight->setFallOffExponent(value); return true; } } // namespace COLLADASaxFWL
[ [ [ 1, 225 ] ] ]
51f40bc9924fff7dcf40897598fe4cc9d0505862
54cacc105d6bacdcfc37b10d57016bdd67067383
/trunk/source/level/lighting/LightmapGenerator.h
14691b4fb3878a62cdadd5ad0483bd7743521b15
[]
no_license
galek/hesperus
4eb10e05945c6134901cc677c991b74ce6c8ac1e
dabe7ce1bb65ac5aaad144933d0b395556c1adc4
refs/heads/master
2020-12-31T05:40:04.121180
2009-12-06T17:38:49
2009-12-06T17:38:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,154
h
/*** * hesperus: LightmapGenerator.h * Copyright Stuart Golodetz, 2008. All rights reserved. ***/ #ifndef H_HESP_LIGHTMAPGENERATOR #define H_HESP_LIGHTMAPGENERATOR #include <vector> #include <source/level/vis/VisTable.h> #include <source/util/PolygonTypes.h> #include "Light.h" namespace hesp { //#################### FORWARD DECLARATIONS #################### typedef shared_ptr<class BSPTree> BSPTree_Ptr; typedef shared_ptr<class Lightmap> Lightmap_Ptr; typedef shared_ptr<class LightmapGrid> LightmapGrid_Ptr; class LightmapGenerator { //#################### TYPEDEFS #################### private: typedef std::vector<LightmapGrid_Ptr> LightmapGridVector; typedef std::vector<Lightmap_Ptr> LightmapVector; typedef shared_ptr<LightmapVector> LightmapVector_Ptr; typedef shared_ptr<const LightmapVector> LightmapVector_CPtr; typedef std::vector<TexturedPolygon_Ptr> TexPolyVector; typedef std::vector<TexturedLitPolygon_Ptr> TexLitPolyVector; typedef shared_ptr<TexLitPolyVector> TexLitPolyVector_Ptr; typedef shared_ptr<const TexLitPolyVector> TexLitPolyVector_CPtr; //#################### PRIVATE VARIABLES #################### private: // Input data TexPolyVector m_inputPolygons; std::vector<Light> m_lights; BSPTree_Ptr m_tree; LeafVisTable_Ptr m_leafVis; // Intermediate data LightmapGridVector m_grids; // Output data TexLitPolyVector_Ptr m_outputPolygons; LightmapVector_Ptr m_lightmaps; //#################### CONSTRUCTORS #################### public: LightmapGenerator(const TexPolyVector& inputPolygons, const std::vector<Light>& lights, const BSPTree_Ptr& tree, const LeafVisTable_Ptr& leafVis); //#################### PUBLIC METHODS #################### public: void generate_lightmaps(); LightmapVector_CPtr lightmaps() const; TexLitPolyVector_CPtr lit_polygons() const; //#################### PRIVATE METHODS #################### private: void clean_intermediate(); void construct_ambient_lightmaps(); void construct_grid(int n); void construct_grids(); void process_light(int n); void process_lights(); }; } #endif
[ [ [ 1, 72 ] ] ]
63ae48c594bc37c9352cd43837521b1132963c78
41efaed82e413e06f31b65633ed12adce4b7abc2
/projects/example/src/main.cpp
618ddea000a7e0453d351ebc437e71aac5b59bfc
[]
no_license
ivandro/AVT---project
e0494f2e505f76494feb0272d1f41f5d8f117ac5
ef6fe6ebfe4d01e4eef704fb9f6a919c9cddd97f
refs/heads/master
2016-09-06T03:45:35.997569
2011-10-27T15:00:14
2011-10-27T15:00:14
2,642,435
0
2
null
2016-04-08T14:24:40
2011-10-25T09:47:13
C
UTF-8
C++
false
false
950
cpp
// This file is an example for CGLib. // // CGLib 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. // // CGLib 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 CGLib; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // // Copyright 2007 Carlos Martinho #include "cg/cg.h" #include "MyApp.h" int main(int argc, char** argv) { cg::Manager::instance()->runApp(new example::MyApp(),60,argc,argv); return 0; }
[ "Moreira@Moreira-PC.(none)" ]
[ [ [ 1, 25 ] ] ]
461a8493fb21b181acec8991c16287dafdf4e1ce
7a6f06d37d3a1cf37532fb12935031e558b8a6ce
/patch/source/Irrlicht/CXMeshFileLoader.cpp
0331f5b8163029cc5f2dc14815eee62155d85a84
[]
no_license
pecc0/phx-irrlicht
8ab7192e2604f3d1f7f4dc45a86118d162574a69
d1009e6e46e2056fb1e046855c95ab39b2bb3fba
refs/heads/master
2016-09-05T19:00:20.648062
2011-01-19T22:02:51
2011-01-19T22:02:51
32,383,460
0
0
null
null
null
null
UTF-8
C++
false
false
56,997
cpp
// 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 #include "IrrCompileConfig.h" #ifdef _IRR_COMPILE_WITH_X_LOADER_ #include "CXMeshFileLoader.h" #include "os.h" #include "fast_atof.h" #include "coreutil.h" #include "ISceneManager.h" #include "IVideoDriver.h" #include "IFileSystem.h" #include "IReadFile.h" #ifdef _DEBUG #define _XREADER_DEBUG #endif //#define BETTER_MESHBUFFER_SPLITTING_FOR_X namespace irr { namespace scene { //! Constructor CXMeshFileLoader::CXMeshFileLoader(scene::ISceneManager* smgr, io::IFileSystem* fs) : SceneManager(smgr), FileSystem(fs), AnimatedMesh(0), MajorVersion(0), MinorVersion(0), BinaryFormat(false), BinaryNumCount(0), Buffer(0), P(0), End(0), FloatSize(0), CurFrame(0) { #ifdef _DEBUG setDebugName("CXMeshFileLoader"); #endif } //! returns true if the file maybe is able to be loaded by this class //! based on the file extension (e.g. ".bsp") bool CXMeshFileLoader::isALoadableFileExtension(const c8* filename) const { return strncmp(&filename[strlen(filename)-2], ".x", 2) == 0; } //! returns new instance of CSkinnedMesh. Used for overriding. CSkinnedMesh* irr::scene::CXMeshFileLoader::getNewMesh(void) { return new CSkinnedMesh(); } //! creates/loads an animated mesh from the file. //! \return Pointer to the created mesh. Returns 0 if loading failed. //! If you no longer need the mesh, you should call IAnimatedMesh::drop(). //! See IReferenceCounted::drop() for more information. IAnimatedMesh* CXMeshFileLoader::createMesh(io::IReadFile* f) { if (!f) return 0; #ifdef _XREADER_DEBUG u32 time = os::Timer::getRealTime(); #endif AnimatedMesh = getNewMesh(); if (load(f)) { AnimatedMesh->finalize(); } else { AnimatedMesh->drop(); AnimatedMesh = 0; } #ifdef _XREADER_DEBUG time = os::Timer::getRealTime() - time; core::stringc tmpString = "Time to load "; tmpString += BinaryFormat ? "binary" : "ascii"; tmpString += " X file: "; tmpString += time; tmpString += "ms"; os::Printer::log(tmpString.c_str()); #endif //Clear up MajorVersion=0; MinorVersion=0; BinaryFormat=0; BinaryNumCount=0; FloatSize=0; P=0; End=0; CurFrame=0; TemplateMaterials.clear(); delete [] Buffer; Buffer = 0; for (u32 i=0; i<Meshes.size(); ++i) delete Meshes[i]; Meshes.clear(); return AnimatedMesh; } bool CXMeshFileLoader::load(io::IReadFile* file) { if (!readFileIntoMemory(file)) return false; if (!parseFile()) return false; for (u32 n=0; n<Meshes.size(); ++n) { SXMesh *mesh=Meshes[n]; // default material if nothing loaded if (!mesh->Materials.size()) mesh->Materials.push_back(video::SMaterial()); u32 i; mesh->Buffers.reallocate(mesh->Materials.size()); #ifndef BETTER_MESHBUFFER_SPLITTING_FOR_X const u32 bufferOffset = AnimatedMesh->getMeshBufferCount(); #endif for (i=0; i<mesh->Materials.size(); ++i) { mesh->Buffers.push_back( AnimatedMesh->createBuffer() ); mesh->Buffers.getLast()->Material = mesh->Materials[i]; if (!mesh->HasSkinning) { //Set up rigid animation if (mesh->AttachedJointID!=-1) { AnimatedMesh->getAllJoints()[mesh->AttachedJointID]->AttachedMeshes.push_back( AnimatedMesh->getMeshBuffers().size()-1 ); } } } if (!mesh->HasVertexColors) { for (u32 j=0;j<mesh->FaceMaterialIndices.size();++j) { for (u32 id=j*3+0;id<=j*3+2;++id) { mesh->Vertices[ mesh->Indices[id] ].Color = mesh->Buffers[mesh->FaceMaterialIndices[j]]->Material.DiffuseColor; } } } #ifdef BETTER_MESHBUFFER_SPLITTING_FOR_X { //the same vertex can be used in many different meshbuffers, but it's slow to work out core::array< core::array< u32 > > verticesLinkIndex; verticesLinkIndex.reallocate(mesh->Vertices.size()); core::array< core::array< u16 > > verticesLinkBuffer; verticesLinkBuffer.reallocate(mesh->Vertices.size()); for (i=0;i<mesh->Vertices.size();++i) { verticesLinkIndex.push_back( core::array< u32 >() ); verticesLinkBuffer.push_back( core::array< u16 >() ); } for (i=0;i<mesh->FaceMaterialIndices.size();++i) { for (u32 id=i*3+0;id<=i*3+2;++id) { core::array< u16 > &Array=verticesLinkBuffer[ mesh->Indices[id] ]; bool found=false; for (u32 j=0; j < Array.size(); ++j) { if (Array[j]==mesh->FaceMaterialIndices[i]) { found=true; break; } } if (!found) Array.push_back( mesh->FaceMaterialIndices[i] ); } } for (i=0;i<verticesLinkBuffer.size();++i) { if (!verticesLinkBuffer[i].size()) verticesLinkBuffer[i].push_back(0); } for (i=0;i<mesh->Vertices.size();++i) { core::array< u16 > &Array = verticesLinkBuffer[i]; verticesLinkIndex[i].reallocate(Array.size()); for (u32 j=0; j < Array.size(); ++j) { scene::SSkinMeshBuffer *buffer = mesh->Buffers[ Array[j] ]; verticesLinkIndex[i].push_back( buffer->Vertices_Standard.size() ); buffer->Vertices_Standard.push_back( mesh->Vertices[i] ); } } for (i=0;i<mesh->FaceMaterialIndices.size();++i) { scene::SSkinMeshBuffer *buffer=mesh->Buffers[ mesh->FaceMaterialIndices[i] ]; for (u32 id=i*3+0;id<=i*3+2;++id) { core::array< u16 > &Array=verticesLinkBuffer[ mesh->Indices[id] ]; for (u32 j=0;j< Array.size() ;++j) { if ( Array[j]== mesh->FaceMaterialIndices[i] ) buffer->Indices.push_back( verticesLinkIndex[ mesh->Indices[id] ][j] ); } } } for (u32 j=0;j<mesh->WeightJoint.size();++j) { ISkinnedMesh::SJoint* joint = AnimatedMesh->getAllJoints()[mesh->WeightJoint[j]]; ISkinnedMesh::SWeight& weight = joint->Weights[mesh->WeightNum[j]]; u32 id = weight.vertex_id; if (id>=verticesLinkIndex.size()) { os::Printer::log("X loader: Weight id out of range", ELL_WARNING); id=0; weight.strength=0.f; } if (verticesLinkBuffer[id].size()==1) { weight.vertex_id=verticesLinkIndex[id][0]; weight.buffer_id=verticesLinkBuffer[id][0]; } else if (verticesLinkBuffer[id].size() != 0) { for (u32 k=1; k < verticesLinkBuffer[id].size(); ++k) { ISkinnedMesh::SWeight* WeightClone = AnimatedMesh->createWeight(joint); WeightClone->strength = weight.strength; WeightClone->vertex_id = verticesLinkIndex[id][k]; WeightClone->buffer_id = verticesLinkBuffer[id][k]; } } } } #else { core::array< u32 > verticesLinkIndex; core::array< s16 > verticesLinkBuffer; verticesLinkBuffer.set_used(mesh->Vertices.size()); // init with 0 for (i=0;i<mesh->Vertices.size();++i) { verticesLinkBuffer[i]=-1; } bool warned = false; // store meshbuffer number per vertex for (i=0;i<mesh->FaceMaterialIndices.size();++i) { for (u32 id=i*3+0;id<=i*3+2;++id) { if ((verticesLinkBuffer[mesh->Indices[id]] != -1) && (verticesLinkBuffer[mesh->Indices[id]] != (s16)mesh->FaceMaterialIndices[i])) { if (!warned) { os::Printer::log("X loader", "Duplicated vertex, animation might be corrupted.", ELL_WARNING); warned=true; } const u32 tmp = mesh->Vertices.size(); mesh->Vertices.push_back(mesh->Vertices[ mesh->Indices[id] ]); mesh->Indices[id] = tmp; verticesLinkBuffer.set_used(mesh->Vertices.size()); } verticesLinkBuffer[ mesh->Indices[id] ] = mesh->FaceMaterialIndices[i]; } } if (mesh->FaceMaterialIndices.size() != 0) { // store vertices in buffers and remember relation in verticesLinkIndex u32* vCountArray = new u32[mesh->Buffers.size()]; memset(vCountArray, 0, mesh->Buffers.size()*sizeof(u32)); // count vertices in each buffer and reallocate for (i=0; i<mesh->Vertices.size(); ++i) ++vCountArray[verticesLinkBuffer[i]]; for (i=0; i!=mesh->Buffers.size(); ++i) mesh->Buffers[i]->Vertices_Standard.reallocate(vCountArray[i]); verticesLinkIndex.set_used(mesh->Vertices.size()); // actually store vertices for (i=0; i<mesh->Vertices.size(); ++i) { scene::SSkinMeshBuffer *buffer = mesh->Buffers[ verticesLinkBuffer[i] ]; verticesLinkIndex[i] = buffer->Vertices_Standard.size(); buffer->Vertices_Standard.push_back( mesh->Vertices[i] ); } // count indices per buffer and reallocate memset(vCountArray, 0, mesh->Buffers.size()*sizeof(u32)); for (i=0; i<mesh->FaceMaterialIndices.size(); ++i) ++vCountArray[ mesh->FaceMaterialIndices[i] ]; for (i=0; i!=mesh->Buffers.size(); ++i) mesh->Buffers[i]->Indices.reallocate(vCountArray[i]); delete [] vCountArray; // create indices per buffer for (i=0; i<mesh->FaceMaterialIndices.size(); ++i) { scene::SSkinMeshBuffer *buffer = mesh->Buffers[ mesh->FaceMaterialIndices[i] ]; for (u32 id=i*3+0; id!=i*3+3; ++id) { buffer->Indices.push_back( verticesLinkIndex[ mesh->Indices[id] ] ); } } } for (u32 j=0; j<mesh->WeightJoint.size(); ++j) { ISkinnedMesh::SWeight& weight = (AnimatedMesh->getAllJoints()[mesh->WeightJoint[j]]->Weights[mesh->WeightNum[j]]); u32 id = weight.vertex_id; if (id>=verticesLinkIndex.size()) { os::Printer::log("X loader: Weight id out of range", ELL_WARNING); id=0; weight.strength=0.f; } weight.vertex_id=verticesLinkIndex[id]; weight.buffer_id=verticesLinkBuffer[id] + bufferOffset; } } #endif } return true; } //! Reads file into memory bool CXMeshFileLoader::readFileIntoMemory(io::IReadFile* file) { const long size = file->getSize(); if (size < 12) { os::Printer::log("X File is too small.", ELL_WARNING); return false; } Buffer = new c8[size]; //! read all into memory if (file->read(Buffer, size) != size) { os::Printer::log("Could not read from x file.", ELL_WARNING); return false; } Line = 1; End = Buffer + size; //! check header "xof " if (strncmp(Buffer, "xof ", 4)!=0) { os::Printer::log("Not an x file, wrong header.", ELL_WARNING); return false; } //! read minor and major version, e.g. 0302 or 0303 c8 tmp[3]; tmp[2] = 0x0; tmp[0] = Buffer[4]; tmp[1] = Buffer[5]; MajorVersion = core::strtol10(tmp); tmp[0] = Buffer[6]; tmp[1] = Buffer[7]; MinorVersion = core::strtol10(tmp); //! read format if (strncmp(&Buffer[8], "txt ", 4) ==0) BinaryFormat = false; else if (strncmp(&Buffer[8], "bin ", 4) ==0) BinaryFormat = true; else { os::Printer::log("Only uncompressed x files currently supported.", ELL_WARNING); return false; } BinaryNumCount=0; //! read float size if (strncmp(&Buffer[12], "0032", 4) ==0) FloatSize = 4; else if (strncmp(&Buffer[12], "0064", 4) ==0) FloatSize = 8; else { os::Printer::log("Float size not supported.", ELL_WARNING); return false; } P = &Buffer[16]; readUntilEndOfLine(); FilePath = stripPathFromString(file->getFileName(),true); return true; } //! Parses the file bool CXMeshFileLoader::parseFile() { while(parseDataObject()) { // loop } return true; } //! Parses the next Data object in the file bool CXMeshFileLoader::parseDataObject() { core::stringc objectName = getNextToken(); if (objectName.size() == 0) return false; // parse specific object #ifdef _XREADER_DEBUG os::Printer::log("debug DataObject:", objectName.c_str() ); #endif if (objectName == "template") return parseDataObjectTemplate(); else if (objectName == "Frame") { return parseDataObjectFrame( 0 ); } else if (objectName == "Mesh") { // some meshes have no frames at all //CurFrame = AnimatedMesh->createJoint(0); //CurFrame->Meshes.push_back(SXMesh()); //return parseDataObjectMesh(CurFrame->Meshes.getLast()); SXMesh *mesh=new SXMesh; //mesh->Buffer=AnimatedMesh->createBuffer(); Meshes.push_back(mesh); return parseDataObjectMesh(*mesh); } else if (objectName == "AnimationSet") { return parseDataObjectAnimationSet(); } else if (objectName == "Material") { // template materials now available thanks to joeWright TemplateMaterials.push_back(SXTemplateMaterial()); TemplateMaterials.getLast().Name = getNextToken(); return parseDataObjectMaterial(TemplateMaterials.getLast().Material); } else if (objectName == "}") { os::Printer::log("} found in dataObject", ELL_WARNING); return true; } os::Printer::log("Unknown data object in animation of .x file", objectName.c_str(), ELL_WARNING); return parseUnknownDataObject(); } bool CXMeshFileLoader::parseDataObjectTemplate() { #ifdef _XREADER_DEBUG os::Printer::log("CXFileReader: Reading template"); #endif // parse a template data object. Currently not stored. core::stringc name; if (!readHeadOfDataObject(&name)) { os::Printer::log("Left delimiter in template data object missing.", name.c_str(), ELL_ERROR); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } // read GUID getNextToken(); // read and ignore data members while(true) { core::stringc s = getNextToken(); if (s == "}") break; if (s.size() == 0) return false; } return true; } bool CXMeshFileLoader::parseDataObjectFrame( CSkinnedMesh::SJoint *Parent ) { #ifdef _XREADER_DEBUG os::Printer::log("CXFileReader: Reading frame"); #endif // A coordinate frame, or "frame of reference." The Frame template // is open and can contain any object. The Direct3D extensions (D3DX) // mesh-loading functions recognize Mesh, FrameTransformMatrix, and // Frame template instances as child objects when loading a Frame // instance. u32 JointID=0; core::stringc name; if (!readHeadOfDataObject(&name)) { os::Printer::log("No opening brace in Frame found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } CSkinnedMesh::SJoint *joint=0; if (name.size()) { for (u32 n=0; n < AnimatedMesh->getAllJoints().size(); ++n) { if (AnimatedMesh->getAllJoints()[n]->Name==name) { joint=AnimatedMesh->getAllJoints()[n]; JointID=n; break; } } } if (!joint) { #ifdef _XREADER_DEBUG os::Printer::log("creating joint ", name.c_str()); #endif joint=AnimatedMesh->createJoint(Parent); joint->Name=name; JointID=AnimatedMesh->getAllJoints().size()-1; } else { #ifdef _XREADER_DEBUG os::Printer::log("using joint ", name.c_str()); #endif if (Parent) Parent->Children.push_back(joint); } // Now inside a frame. // read tokens until closing brace is reached. while(true) { core::stringc objectName = getNextToken(); #ifdef _XREADER_DEBUG os::Printer::log("debug DataObject in frame:", objectName.c_str() ); #endif if (objectName.size() == 0) { os::Printer::log("Unexpected ending found in Frame in x file.", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } else if (objectName == "}") { break; // frame finished } else if (objectName == "Frame") { if (!parseDataObjectFrame(joint)) return false; } else if (objectName == "FrameTransformMatrix") { if (!parseDataObjectTransformationMatrix(joint->LocalMatrix)) return false; //joint->LocalAnimatedMatrix //joint->LocalAnimatedMatrix.makeInverse(); //joint->LocalMatrix=tmp*joint->LocalAnimatedMatrix; } else if (objectName == "Mesh") { /* frame.Meshes.push_back(SXMesh()); if (!parseDataObjectMesh(frame.Meshes.getLast())) return false; */ SXMesh *mesh=new SXMesh; mesh->AttachedJointID=JointID; Meshes.push_back(mesh); if (!parseDataObjectMesh(*mesh)) return false; } else { os::Printer::log("Unknown data object in frame in x file", objectName.c_str(), ELL_WARNING); if (!parseUnknownDataObject()) return false; } } return true; } bool CXMeshFileLoader::parseDataObjectTransformationMatrix(core::matrix4 &mat) { #ifdef _XREADER_DEBUG os::Printer::log("CXFileReader: Reading Transformation Matrix"); #endif if (!readHeadOfDataObject()) { os::Printer::log("No opening brace in Transformation Matrix found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } readMatrix(mat); if (!checkForOneFollowingSemicolons()) { os::Printer::log("No finishing semicolon in Transformation Matrix found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } if (!checkForClosingBrace()) { os::Printer::log("No closing brace in Transformation Matrix found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } return true; } bool CXMeshFileLoader::parseDataObjectMesh(SXMesh &mesh) { core::stringc name; if (!readHeadOfDataObject(&name)) { #ifdef _XREADER_DEBUG os::Printer::log("CXFileReader: Reading mesh"); #endif os::Printer::log("No opening brace in Mesh found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } #ifdef _XREADER_DEBUG os::Printer::log("CXFileReader: Reading mesh", name.c_str()); #endif // read vertex count const u32 nVertices = readInt(); // read vertices mesh.Vertices.set_used(nVertices); for (u32 n=0; n<nVertices; ++n) { readVector3(mesh.Vertices[n].Pos); mesh.Vertices[n].Color=0xFFFFFFFF; } if (!checkForTwoFollowingSemicolons()) { os::Printer::log("No finishing semicolon in Mesh Vertex Array found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } // read faces const u32 nFaces = readInt(); mesh.Indices.set_used(nFaces * 3); mesh.IndexCountPerFace.set_used(nFaces); core::array<u32> polygonfaces; u32 currentIndex = 0; for (u32 k=0; k<nFaces; ++k) { const u32 fcnt = readInt(); if (fcnt != 3) { if (fcnt < 3) { os::Printer::log("Invalid face count (<3) found in Mesh x file reader.", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } // read face indices polygonfaces.set_used(fcnt); u32 triangles = (fcnt-2); mesh.Indices.set_used(mesh.Indices.size() + ((triangles-1)*3)); mesh.IndexCountPerFace[k] = triangles * 3; for (u32 f=0; f<fcnt; ++f) polygonfaces[f] = readInt(); for (u32 jk=0; jk<triangles; ++jk) { mesh.Indices[currentIndex++] = polygonfaces[0]; mesh.Indices[currentIndex++] = polygonfaces[jk+1]; mesh.Indices[currentIndex++] = polygonfaces[jk+2]; } // TODO: change face indices in material list } else { mesh.Indices[currentIndex++] = readInt(); mesh.Indices[currentIndex++] = readInt(); mesh.Indices[currentIndex++] = readInt(); mesh.IndexCountPerFace[k] = 3; } } if (!checkForTwoFollowingSemicolons()) { os::Printer::log("No finishing semicolon in Mesh Face Array found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } // here, other data objects may follow while(true) { core::stringc objectName = getNextToken(); #ifdef _XREADER_DEBUG os::Printer::log("debug DataObject in mesh:", objectName.c_str() ); #endif if (objectName.size() == 0) { os::Printer::log("Unexpected ending found in Mesh in x file.", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } else if (objectName == "}") { break; // mesh finished } else if (objectName == "MeshNormals") { if (!parseDataObjectMeshNormals(mesh)) return false; } else if (objectName == "MeshTextureCoords") { if (!parseDataObjectMeshTextureCoords(mesh)) return false; } else if (objectName == "MeshVertexColors") { if (!parseDataObjectMeshVertexColors(mesh)) return false; } else if (objectName == "MeshMaterialList") { if (!parseDataObjectMeshMaterialList(mesh)) return false; } else if (objectName == "VertexDuplicationIndices") { // we'll ignore vertex duplication indices // TODO: read them if (!parseUnknownDataObject()) return false; } else if (objectName == "DeclData") { // arbitrary vertex attributes // first comes the number of element definitions // then the vertex element type definitions // with format type;tesselator;semantics;usageindex // we want to support 2;0;6;0 == tangent // 2;0;7;0 == binormal // 2;0;3;0 == normal // 1/2;0;5;0 == 1st uv coord // and 1/2;0;5;1 == 2nd uv coord // type==2 is 3xf32, type==1 is 2xf32 u32 j; const u32 dcnt = readInt(); u16 size = 0; s16 normalpos = -1; s16 uvpos = -1; s16 uv2pos = -1; s16 tangentpos = -1; s16 binormalpos = -1; s16 normaltype = -1; s16 uvtype = -1; s16 uv2type = -1; s16 tangenttype = -1; s16 binormaltype = -1; for (j=0; j<dcnt; ++j) { const u32 type = readInt(); //const u32 tesselator = readInt(); readInt(); const u32 semantics = readInt(); const u32 index = readInt(); switch (semantics) { case 3: normalpos = size; normaltype = type; break; case 5: if (index==0) { uvpos = size; uvtype = type; } else if (index==1) { uv2pos = size; uv2type = type; } break; case 6: tangentpos = size; tangenttype = type; break; case 7: binormalpos = size; binormaltype = type; break; default: break; } switch (type) { case 0: size += 4; break; case 1: size += 8; break; case 2: size += 12; break; case 3: size += 16; break; case 4: case 5: case 6: size += 4; break; case 7: size += 8; break; case 8: case 9: size += 4; break; case 10: size += 8; break; case 11: size += 4; break; case 12: size += 8; break; case 13: size += 4; break; case 14: size += 4; break; case 15: size += 4; break; case 16: size += 8; break; } } const u32 datasize = readInt(); u32* data = new u32[datasize]; for (j=0; j<datasize; ++j) data[j]=readInt(); if (!checkForOneFollowingSemicolons()) { os::Printer::log("No finishing semicolon in DeclData found.", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); delete [] data; return false; } if (!checkForClosingBrace()) { os::Printer::log("No closing brace in DeclData.", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); delete [] data; return false; } u8* dataptr = (u8*) data; for (j=0; j<mesh.Vertices.size(); ++j) { if ((normalpos != -1) && (normaltype == 2)) mesh.Vertices[j].Normal.set(*((core::vector3df*)(dataptr+normalpos))); if ((uvpos != -1) && (uvtype == 1)) mesh.Vertices[j].TCoords.set(*((core::vector2df*)(dataptr+uvpos))); dataptr += size; } delete [] data; } else if (objectName == "XSkinMeshHeader") { if (!parseDataObjectSkinMeshHeader(mesh)) return false; } else if (objectName == "SkinWeights") { //mesh.SkinWeights.push_back(SXSkinWeight()); //if (!parseDataObjectSkinWeights(mesh.SkinWeights.getLast())) if (!parseDataObjectSkinWeights(mesh)) return false; } else { os::Printer::log("Unknown data object in mesh in x file", objectName.c_str(), ELL_WARNING); if (!parseUnknownDataObject()) return false; } } return true; } bool CXMeshFileLoader::parseDataObjectSkinWeights(SXMesh &mesh) { #ifdef _XREADER_DEBUG os::Printer::log("CXFileReader: Reading mesh skin weights"); #endif if (!readHeadOfDataObject()) { os::Printer::log("No opening brace in Skin Weights found in .x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } core::stringc TransformNodeName; if (!getNextTokenAsString(TransformNodeName)) { os::Printer::log("Unknown syntax while reading transfrom node name string in .x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } mesh.HasSkinning=true; CSkinnedMesh::SJoint *joint=0; u32 n; for (n=0; n < AnimatedMesh->getAllJoints().size(); ++n) { if (AnimatedMesh->getAllJoints()[n]->Name==TransformNodeName) { joint=AnimatedMesh->getAllJoints()[n]; break; } } if (!joint) { #ifdef _XREADER_DEBUG os::Printer::log("creating joint for skinning ", TransformNodeName.c_str()); #endif n = AnimatedMesh->getAllJoints().size(); joint=AnimatedMesh->createJoint(0); joint->Name=TransformNodeName; } // read vertex weights const u32 nWeights = readInt(); // read vertex indices u32 i; const u32 jointStart = joint->Weights.size(); joint->Weights.reallocate(jointStart+nWeights); mesh.WeightJoint.reallocate( mesh.WeightJoint.size() + nWeights ); mesh.WeightNum.reallocate( mesh.WeightNum.size() + nWeights ); for (i=0; i<nWeights; ++i) { mesh.WeightJoint.push_back(n); mesh.WeightNum.push_back(joint->Weights.size()); CSkinnedMesh::SWeight *weight=AnimatedMesh->createWeight(joint); weight->buffer_id=0; weight->vertex_id=readInt(); } // read vertex weights for (i=jointStart; i<jointStart+nWeights; ++i) joint->Weights[i].strength = readFloat(); // read matrix offset // transforms the mesh vertices to the space of the bone // When concatenated to the bone's transform, this provides the // world space coordinates of the mesh as affected by the bone core::matrix4& MatrixOffset = joint->GlobalInversedMatrix; readMatrix(MatrixOffset); if (!checkForOneFollowingSemicolons()) { os::Printer::log("No finishing semicolon in Skin Weights found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } if (!checkForClosingBrace()) { os::Printer::log("No closing brace in Skin Weights found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } return true; } bool CXMeshFileLoader::parseDataObjectSkinMeshHeader(SXMesh& mesh) { #ifdef _XREADER_DEBUG os::Printer::log("CXFileReader: Reading skin mesh header"); #endif if (!readHeadOfDataObject()) { os::Printer::log("No opening brace in Skin Mesh header found in .x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } mesh.MaxSkinWeightsPerVertex = readInt(); mesh.MaxSkinWeightsPerFace = readInt(); mesh.BoneCount = readInt(); if (!BinaryFormat) getNextToken(); // skip semicolon if (!checkForClosingBrace()) { os::Printer::log("No closing brace in skin mesh header in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } return true; } bool CXMeshFileLoader::parseDataObjectMeshNormals(SXMesh &mesh) { #ifdef _XREADER_DEBUG os::Printer::log("CXFileReader: reading mesh normals"); #endif if (!readHeadOfDataObject()) { os::Printer::log("No opening brace in Mesh Normals found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } // read count const u32 nNormals = readInt(); core::array<core::vector3df> normals; normals.set_used(nNormals); // read normals for (u32 i=0; i<nNormals; ++i) readVector3(normals[i]); if (!checkForTwoFollowingSemicolons()) { os::Printer::log("No finishing semicolon in Mesh Normals Array found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } core::array<u32> normalIndices; normalIndices.set_used(mesh.Indices.size()); // read face normal indices const u32 nFNormals = readInt(); u32 normalidx = 0; core::array<u32> polygonfaces; for (u32 k=0; k<nFNormals; ++k) { const u32 fcnt = readInt(); u32 triangles = fcnt - 2; u32 indexcount = triangles * 3; if (indexcount != mesh.IndexCountPerFace[k]) { os::Printer::log("Not matching normal and face index count found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } if (indexcount == 3) { // default, only one triangle in this face for (u32 h=0; h<3; ++h) { const u32 normalnum = readInt(); mesh.Vertices[mesh.Indices[normalidx++]].Normal.set(normals[normalnum]); } } else { polygonfaces.set_used(fcnt); // multiple triangles in this face for (u32 h=0; h<fcnt; ++h) polygonfaces[h] = readInt(); for (u32 jk=0; jk<triangles; ++jk) { mesh.Vertices[mesh.Indices[normalidx++]].Normal.set(normals[polygonfaces[0]]); mesh.Vertices[mesh.Indices[normalidx++]].Normal.set(normals[polygonfaces[jk+1]]); mesh.Vertices[mesh.Indices[normalidx++]].Normal.set(normals[polygonfaces[jk+2]]); } } } if (!checkForTwoFollowingSemicolons()) { os::Printer::log("No finishing semicolon in Mesh Face Normals Array found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } if (!checkForClosingBrace()) { os::Printer::log("No closing brace in Mesh Normals found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } return true; } bool CXMeshFileLoader::parseDataObjectMeshTextureCoords(SXMesh &mesh) { #ifdef _XREADER_DEBUG os::Printer::log("CXFileReader: reading mesh texture coordinates"); #endif if (!readHeadOfDataObject()) { os::Printer::log("No opening brace in Mesh Texture Coordinates found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } const u32 nCoords = readInt(); for (u32 i=0; i<nCoords; ++i) readVector2(mesh.Vertices[i].TCoords); if (!checkForTwoFollowingSemicolons()) { os::Printer::log("No finishing semicolon in Mesh Texture Coordinates Array found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } if (!checkForClosingBrace()) { os::Printer::log("No closing brace in Mesh Texture Coordinates Array found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } return true; } bool CXMeshFileLoader::parseDataObjectMeshVertexColors(SXMesh &mesh) { #ifdef _XREADER_DEBUG os::Printer::log("CXFileReader: reading mesh vertex colors"); #endif if (!readHeadOfDataObject()) { os::Printer::log("No opening brace for Mesh Vertex Colors found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } mesh.HasVertexColors=true; const u32 nColors = readInt(); for (u32 i=0; i<nColors; ++i) { const u32 Index=readInt(); if (Index>=mesh.Vertices.size()) { os::Printer::log("index value in parseDataObjectMeshVertexColors out of bounds", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } readRGBA(mesh.Vertices[Index].Color); checkForOneFollowingSemicolons(); } if (!checkForOneFollowingSemicolons()) { os::Printer::log("No finishing semicolon in Mesh Vertex Colors Array found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } if (!checkForClosingBrace()) { os::Printer::log("No closing brace in Mesh Texture Coordinates Array found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } return true; } bool CXMeshFileLoader::parseDataObjectMeshMaterialList(SXMesh &mesh) { #ifdef _XREADER_DEBUG os::Printer::log("CXFileReader: Reading mesh material list"); #endif if (!readHeadOfDataObject()) { os::Printer::log("No opening brace in Mesh Material List found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } // read material count mesh.Materials.reallocate(readInt()); // read non triangulated face material index count const u32 nFaceIndices = readInt(); // There seems to be a compact representation of "all faces the same material" // being represented as 1;1;0;; which means 1 material, 1 face with first material // all the other faces have to obey then, so check is disabled //if (nFaceIndices != mesh.IndexCountPerFace.size()) // os::Printer::log("Index count per face not equal to face material index count in x file.", ELL_WARNING); // read non triangulated face indices and create triangulated ones mesh.FaceMaterialIndices.set_used( mesh.Indices.size() / 3); u32 triangulatedindex = 0; u32 ind = 0; for (u32 tfi=0; tfi<mesh.IndexCountPerFace.size(); ++tfi) { if (tfi<nFaceIndices) ind = readInt(); const u32 fc = mesh.IndexCountPerFace[tfi]/3; for (u32 k=0; k<fc; ++k) mesh.FaceMaterialIndices[triangulatedindex++] = ind; } // in version 03.02, the face indices end with two semicolons. // commented out version check, as version 03.03 exported from blender also has 2 semicolons if (!BinaryFormat) // && MajorVersion == 3 && MinorVersion <= 2) { if (P[0] == ';') ++P; } // read following data objects while(true) { core::stringc objectName = getNextToken(); if (objectName.size() == 0) { os::Printer::log("Unexpected ending found in Mesh Material list in .x file.", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } else if (objectName == "}") { break; // material list finished } else if (objectName == "{") { // template materials now available thanks to joeWright objectName = getNextToken(); for (u32 i=0; i<TemplateMaterials.size(); ++i) if (TemplateMaterials[i].Name == objectName) mesh.Materials.push_back(TemplateMaterials[i].Material); getNextToken(); // skip } } else if (objectName == "Material") { mesh.Materials.push_back(video::SMaterial()); if (!parseDataObjectMaterial(mesh.Materials.getLast())) return false; } else if (objectName == ";") { // ignore } else { os::Printer::log("Unknown data object in material list in x file", objectName.c_str(), ELL_WARNING); if (!parseUnknownDataObject()) return false; } } return true; } bool CXMeshFileLoader::parseDataObjectMaterial(video::SMaterial& material) { #ifdef _XREADER_DEBUG os::Printer::log("CXFileReader: Reading mesh material"); #endif if (!readHeadOfDataObject()) { os::Printer::log("No opening brace in Mesh Material found in .x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } // read RGBA readRGBA(material.DiffuseColor); checkForOneFollowingSemicolons(); // read power material.Shininess = readFloat(); // read specular readRGB(material.SpecularColor); checkForOneFollowingSemicolons(); // read emissive readRGB(material.EmissiveColor); checkForOneFollowingSemicolons(); // read other data objects while(true) { core::stringc objectName = getNextToken(); if (objectName.size() == 0) { os::Printer::log("Unexpected ending found in Mesh Material in .x file.", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } else if (objectName == "}") { break; // material finished } else if (objectName.equals_ignore_case("TextureFilename")) { // some exporters write "TextureFileName" instead. core::stringc TextureFileName; if (!parseDataObjectTextureFilename(TextureFileName)) return false; // original name if (FileSystem->existFile(TextureFileName.c_str())) material.setTexture(0, SceneManager->getVideoDriver()->getTexture (TextureFileName.c_str())); // mesh path else { TextureFileName=FilePath + stripPathFromString(TextureFileName,false); if (FileSystem->existFile(TextureFileName.c_str())) material.setTexture(0, SceneManager->getVideoDriver()->getTexture(TextureFileName.c_str())); // working directory else material.setTexture(0, SceneManager->getVideoDriver()->getTexture(stripPathFromString(TextureFileName,false).c_str())); } } else if (objectName.equals_ignore_case("NormalmapFilename")) { // some exporters write "NormalmapFileName" instead. core::stringc TextureFileName; if (!parseDataObjectTextureFilename(TextureFileName)) return false; // original name if (FileSystem->existFile(TextureFileName.c_str())) material.setTexture(1, SceneManager->getVideoDriver()->getTexture (TextureFileName.c_str())); // mesh path else { TextureFileName=FilePath + stripPathFromString(TextureFileName,false); if (FileSystem->existFile(TextureFileName.c_str())) material.setTexture(1, SceneManager->getVideoDriver()->getTexture(TextureFileName.c_str())); // working directory else material.setTexture(1, SceneManager->getVideoDriver()->getTexture(stripPathFromString(TextureFileName,false).c_str())); } } else { os::Printer::log("Unknown data object in material in .x file", objectName.c_str(), ELL_WARNING); if (!parseUnknownDataObject()) return false; } } return true; } bool CXMeshFileLoader::parseDataObjectAnimationSet() { #ifdef _XREADER_DEBUG os::Printer::log("CXFileReader: Reading animation set"); #endif core::stringc AnimationName; if (!readHeadOfDataObject(&AnimationName)) { os::Printer::log("No opening brace in Animation Set found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } while(true) { core::stringc objectName = getNextToken(); if (objectName.size() == 0) { os::Printer::log("Unexpected ending found in Animation set in x file.", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } else if (objectName == "}") { break; // animation set finished } else if (objectName == "Animation") { if (!parseDataObjectAnimation()) return false; } else { os::Printer::log("Unknown data object in animation set in x file", objectName.c_str(), ELL_WARNING); if (!parseUnknownDataObject()) return false; } } return true; } bool CXMeshFileLoader::parseDataObjectAnimation() { #ifdef _XREADER_DEBUG os::Printer::log("CXFileReader: reading animation"); #endif if (!readHeadOfDataObject()) { os::Printer::log("No opening brace in Animation found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } //anim.closed = true; //anim.linearPositionQuality = true; CSkinnedMesh::SJoint animationDump; core::stringc FrameName; while(true) { core::stringc objectName = getNextToken(); if (objectName.size() == 0) { os::Printer::log("Unexpected ending found in Animation in x file.", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } else if (objectName == "}") { break; // animation finished } else if (objectName == "AnimationKey") { if (!parseDataObjectAnimationKey(&animationDump)) return false; } else if (objectName == "AnimationOptions") { //TODO: parse options. if (!parseUnknownDataObject()) return false; } else if (objectName == "{") { // read frame name FrameName = getNextToken(); if (!checkForClosingBrace()) { os::Printer::log("Unexpected ending found in Animation in x file.", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } } else { os::Printer::log("Unknown data object in animation in x file", objectName.c_str(), ELL_WARNING); if (!parseUnknownDataObject()) return false; } } if (FrameName.size() != 0) { #ifdef _XREADER_DEBUG os::Printer::log("getting name: ", FrameName.c_str()); #endif CSkinnedMesh::SJoint *joint=0; u32 n; for (n=0; n < AnimatedMesh->getAllJoints().size(); ++n) { if (AnimatedMesh->getAllJoints()[n]->Name==FrameName) { joint=AnimatedMesh->getAllJoints()[n]; break; } } if (!joint) { #ifdef _XREADER_DEBUG os::Printer::log("creating joint for animation ", FrameName.c_str()); #endif joint=AnimatedMesh->createJoint(0); joint->Name=FrameName; } joint->PositionKeys.reallocate(joint->PositionKeys.size()+animationDump.PositionKeys.size()); for (n=0; n<animationDump.PositionKeys.size(); ++n) { joint->PositionKeys.push_back(animationDump.PositionKeys[n]); } joint->ScaleKeys.reallocate(joint->ScaleKeys.size()+animationDump.ScaleKeys.size()); for (n=0; n<animationDump.ScaleKeys.size(); ++n) { joint->ScaleKeys.push_back(animationDump.ScaleKeys[n]); } joint->RotationKeys.reallocate(joint->RotationKeys.size()+animationDump.RotationKeys.size()); for (n=0; n<animationDump.RotationKeys.size(); ++n) { joint->RotationKeys.push_back(animationDump.RotationKeys[n]); } } else os::Printer::log("joint name was never given", ELL_WARNING); return true; } bool CXMeshFileLoader::parseDataObjectAnimationKey(ISkinnedMesh::SJoint *joint) { #ifdef _XREADER_DEBUG os::Printer::log("CXFileReader: reading animation key"); #endif if (!readHeadOfDataObject()) { os::Printer::log("No opening brace in Animation Key found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } // read key type const u32 keyType = readInt(); if (keyType > 4) { os::Printer::log("Unknown key type found in Animation Key in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } // read number of keys const u32 numberOfKeys = readInt(); // eat the semicolon after the "0". if there are keys present, readInt() // does this for us. If there aren't, we need to do it explicitly if (numberOfKeys == 0) checkForOneFollowingSemicolons(); for (u32 i=0; i<numberOfKeys; ++i) { // read time const f32 time = (f32)readInt(); // read keys switch(keyType) { case 0: //rotation { //read quaternions // read count if (readInt() != 4) { os::Printer::log("Expected 4 numbers in animation key in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } f32 W = -readFloat(); f32 X = -readFloat(); f32 Y = -readFloat(); f32 Z = -readFloat(); if (!checkForTwoFollowingSemicolons()) { os::Printer::log("No finishing semicolon after quaternion animation key in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } ISkinnedMesh::SRotationKey *key=AnimatedMesh->createRotationKey(joint); key->frame=time; key->rotation.set(X,Y,Z,W); } break; case 1: //scale case 2: //position { // read vectors // read count if (readInt() != 3) { os::Printer::log("Expected 3 numbers in animation key in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } core::vector3df vector; readVector3(vector); if (!checkForTwoFollowingSemicolons()) { os::Printer::log("No finishing semicolon after vector animation key in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } if (keyType==2) { ISkinnedMesh::SPositionKey *key=AnimatedMesh->createPositionKey(joint); key->frame=time; key->position=vector; } else { ISkinnedMesh::SScaleKey *key=AnimatedMesh->createScaleKey(joint); key->frame=time; key->scale=vector; } } break; case 3: case 4: { // read matrix // read count if (readInt() != 16) { os::Printer::log("Expected 16 numbers in animation key in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } // read matrix core::matrix4 mat(core::matrix4::EM4CONST_NOTHING); readMatrix(mat); //mat=joint->LocalMatrix*mat; if (!checkForOneFollowingSemicolons()) { os::Printer::log("No finishing semicolon after matrix animation key in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } //core::vector3df rotation = mat.getRotationDegrees(); ISkinnedMesh::SRotationKey *keyR=AnimatedMesh->createRotationKey(joint); keyR->frame=time; keyR->rotation= core::quaternion(mat); ISkinnedMesh::SPositionKey *keyP=AnimatedMesh->createPositionKey(joint); keyP->frame=time; keyP->position=mat.getTranslation(); /* core::vector3df scale=mat.getScale(); if (scale.X==0) scale.X=1; if (scale.Y==0) scale.Y=1; if (scale.Z==0) scale.Z=1; ISkinnedMesh::SScaleKey *keyS=AnimatedMesh->createScaleKey(joint); keyS->frame=time; keyS->scale=scale; */ } break; } // end switch } if (!checkForOneFollowingSemicolons()) --P; if (!checkForClosingBrace()) { os::Printer::log("No closing brace in animation key in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } return true; } bool CXMeshFileLoader::parseDataObjectTextureFilename(core::stringc& texturename) { #ifdef _XREADER_DEBUG os::Printer::log("CXFileReader: reading texture filename"); #endif if (!readHeadOfDataObject()) { os::Printer::log("No opening brace in Texture filename found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } if (!getNextTokenAsString(texturename)) { os::Printer::log("Unknown syntax while reading texture filename string in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } if (!checkForClosingBrace()) { os::Printer::log("No closing brace in Texture filename found in x file", ELL_WARNING); os::Printer::log("Line", core::stringc(Line).c_str(), ELL_ERROR); return false; } return true; } bool CXMeshFileLoader::parseUnknownDataObject() { // find opening delimiter while(true) { core::stringc t = getNextToken(); if (t.size() == 0) return false; if (t == "{") break; } u32 counter = 1; // parse until closing delimiter while(counter) { core::stringc t = getNextToken(); if (t.size() == 0) return false; if (t == "{") ++counter; else if (t == "}") --counter; } return true; } //! checks for closing curly brace, returns false if not there bool CXMeshFileLoader::checkForClosingBrace() { return (getNextToken() == "}"); } //! checks for one following semicolon, returns false if not there bool CXMeshFileLoader::checkForOneFollowingSemicolons() { if (BinaryFormat) return true; return (getNextToken() == ";"); } //! checks for two following semicolons, returns false if they are not there bool CXMeshFileLoader::checkForTwoFollowingSemicolons() { if (BinaryFormat) return true; for (u32 k=0; k<2; ++k) { if (getNextToken() != ";") return false; } return true; } //! reads header of dataobject including the opening brace. //! returns false if error happened, and writes name of object //! if there is one bool CXMeshFileLoader::readHeadOfDataObject(core::stringc* outname) { core::stringc nameOrBrace = getNextToken(); if (nameOrBrace != "{") { if (outname) (*outname) = nameOrBrace; if (getNextToken() != "{") return false; } return true; } //! returns next parseable token. Returns empty string if no token there core::stringc CXMeshFileLoader::getNextToken() { core::stringc s; // process binary-formatted file if (BinaryFormat) { // in binary mode it will only return NAME and STRING token // and (correctly) skip over other tokens. s16 tok = readBinWord(); u32 len; // standalone tokens switch (tok) { case 1: // name token len = readBinDWord(); s = core::stringc(P, len); P += len; return s; case 2: // string token len = readBinDWord(); s = core::stringc(P, len); P += (len + 2); return s; case 3: // integer token //P += 4; //needed for the correct reading of an array template field return core::stringc(readBinDWord()); case 5: // GUID token P += 16; return "<guid>"; case 6: len = readBinDWord(); P += (len * 4); return "<int_list>"; case 7: len = readBinDWord(); P += (len * FloatSize); return "<flt_list>"; case 0x0a: return "{"; case 0x0b: return "}"; case 0x0c: return "("; case 0x0d: return ")"; case 0x0e: return "["; case 0x0f: return "]"; case 0x10: return "<"; case 0x11: return ">"; case 0x12: return "."; case 0x13: return ","; case 0x14: return ";"; case 0x1f: return "template"; case 0x28: return "WORD"; case 0x29: return "DWORD"; case 0x2a: return "FLOAT"; case 0x2b: return "DOUBLE"; case 0x2c: return "CHAR"; case 0x2d: return "UCHAR"; case 0x2e: return "SWORD"; case 0x2f: return "SDWORD"; case 0x30: return "void"; case 0x31: return "string"; case 0x32: return "unicode"; case 0x33: return "cstring"; case 0x34: return "array"; } } // process text-formatted file else { findNextNoneWhiteSpace(); if (P >= End) return s; while((P < End) && !core::isspace(P[0])) { // either keep token delimiters when already holding a token, or return if first valid char if (P[0]==';' || P[0]=='}' || P[0]=='{' || P[0]==',') { if (!s.size()) { s.append(P[0]); ++P; } break; // stop for delimiter } s.append(P[0]); ++P; } } return s; } //! places pointer to next begin of a token, which must be a number, // and ignores comments void CXMeshFileLoader::findNextNoneWhiteSpaceNumber() { if (BinaryFormat) return; while((P < End) && (P[0] != '-') && (P[0] != '.') && !( core::isdigit(P[0]))) { // check if this is a comment if ((P[0] == '/' && P[1] == '/') || P[0] == '#') readUntilEndOfLine(); else ++P; } } // places pointer to next begin of a token, and ignores comments void CXMeshFileLoader::findNextNoneWhiteSpace() { if (BinaryFormat) return; while(true) { while((P < End) && core::isspace(P[0])) { if (*P=='\n') ++Line; ++P; } if (P >= End) return; // check if this is a comment if ((P[0] == '/' && P[1] == '/') || P[0] == '#') readUntilEndOfLine(); else break; } } //! reads a x file style string bool CXMeshFileLoader::getNextTokenAsString(core::stringc& out) { if (BinaryFormat) { out=getNextToken(); return true; } findNextNoneWhiteSpace(); if (P >= End) return false; if (P[0] != '"') return false; ++P; while(P < End && P[0]!='"') { out.append(P[0]); ++P; } if ( P[1] != ';' || P[0] != '"') return false; P+=2; return true; } void CXMeshFileLoader::readUntilEndOfLine() { if (BinaryFormat) return; while(P < End) { if (P[0] == '\n' || P[0] == '\r') { ++P; ++Line; return; } ++P; } } u16 CXMeshFileLoader::readBinWord() { u8 *Q = (u8 *)P; u16 tmp = 0; tmp = Q[0] + (Q[1] << 8); P += 2; return tmp; } u32 CXMeshFileLoader::readBinDWord() { u8 *Q = (u8 *)P; u32 tmp = 0; tmp = Q[0] + (Q[1] << 8) + (Q[2] << 16) + (Q[3] << 24); P += 4; return tmp; } u32 CXMeshFileLoader::readInt() { if (BinaryFormat) { if (!BinaryNumCount) { u16 tmp = readBinWord(); // 0x06 or 0x03 if (tmp == 0x06) BinaryNumCount = readBinDWord(); else BinaryNumCount = 1; // single int } --BinaryNumCount; return readBinDWord(); } else { findNextNoneWhiteSpaceNumber(); return core::strtol10(P, &P); } } f32 CXMeshFileLoader::readFloat() { if (BinaryFormat) { if (!BinaryNumCount) { u16 tmp = readBinWord(); // 0x07 or 0x42 if (tmp == 0x07) BinaryNumCount = readBinDWord(); else BinaryNumCount = 1; // single int } --BinaryNumCount; if (FloatSize == 8) { char tmp[8]; memcpy(tmp, P, 8); P += 8; return (f32)(*(f64 *)tmp); } else { char tmp[4]; memcpy(tmp, P, 4); P += 4; return *(f32 *)tmp; } } findNextNoneWhiteSpaceNumber(); f32 ftmp; P = core::fast_atof_move(P, ftmp); return ftmp; } // read 2-dimensional vector. Stops at semicolon after second value for text file format bool CXMeshFileLoader::readVector2(core::vector2df& vec) { vec.X = readFloat(); vec.Y = readFloat(); return true; } // read 3-dimensional vector. Stops at semicolon after third value for text file format bool CXMeshFileLoader::readVector3(core::vector3df& vec) { vec.X = readFloat(); vec.Y = readFloat(); vec.Z = readFloat(); return true; } // read color without alpha value. Stops after second semicolon after blue value bool CXMeshFileLoader::readRGB(video::SColor& color) { video::SColorf tmpColor; tmpColor.r = readFloat(); tmpColor.g = readFloat(); tmpColor.b = readFloat(); color = tmpColor.toSColor(); return checkForOneFollowingSemicolons(); } // read color with alpha value. Stops after second semicolon after blue value bool CXMeshFileLoader::readRGBA(video::SColor& color) { video::SColorf tmpColor; tmpColor.r = readFloat(); tmpColor.g = readFloat(); tmpColor.b = readFloat(); tmpColor.a = readFloat(); color = tmpColor.toSColor(); return checkForOneFollowingSemicolons(); } // read matrix from list of floats bool CXMeshFileLoader::readMatrix(core::matrix4& mat) { for (u32 i=0; i<16; ++i) mat[i] = readFloat(); return checkForOneFollowingSemicolons(); } core::stringc CXMeshFileLoader::stripPathFromString(core::stringc string, bool returnPath) { s32 slashIndex=string.findLast('/'); // forward slash s32 backSlash=string.findLast('\\'); // back slash if (backSlash>slashIndex) slashIndex=backSlash; if (slashIndex==-1)//no slashes found { if (returnPath) return core::stringc(); //no path to return else return string; } if (returnPath) return string.subString(0, slashIndex + 1); else return string.subString(slashIndex+1, string.size() - (slashIndex+1)); } } // end namespace scene } // end namespace irr #endif // _IRR_COMPILE_WITH_X_LOADER_
[ "[email protected]@8db76cfa-2e72-11de-afe2-b5feb05456f9" ]
[ [ [ 1, 2348 ] ] ]
0695a1077fbeccc3927170a96381468c5d50654e
21868e763ab7ee92486a16164ccf907328123c00
/main.cpp
a53c086af0327f2565adc3d0e78210cbb89fec5c
[]
no_license
nodesman/flare
73aacd54b5b59480901164f83905cf6cc77fe2bb
ba95fbfdeec1d557056054cbf007bf485c8144a6
refs/heads/master
2020-05-09T11:17:15.929029
2011-11-26T16:54:07
2011-11-26T16:54:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
177
cpp
#include <QtGui/QApplication> #include "flare.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); flare w; w.show(); return a.exec(); }
[ [ [ 1, 10 ] ] ]
47ad0f3321cf26838aab12be0f5460dc41dc0ea5
ccaf260884a5b378a4b4178a5489d18f022eaac0
/AI3/src/main.cpp
a58d5941203407b9d6dca10a4ef3cd707fc56e90
[]
no_license
mmolignano/ai3
ac650a27434eeb74c5988217091dac458e72485a
0a2e9789ad268e06b7ceb0c627504d3e308e643d
refs/heads/master
2021-01-20T15:49:22.643334
2010-02-22T22:51:48
2010-02-22T22:51:48
33,311,395
0
0
null
null
null
null
UTF-8
C++
false
false
414
cpp
/* * main.cpp * * Created on: Feb 10, 2010 * Author: jsandbrook */ #include "main.h" int main(int argc, char** argv) { Model* model; // Read the command line arguments if(argc != 3) { std::cout << "Incorrect arguments.\nUsage: main.exe <testfilename> <trainfilename>"; } // Create the model model = new Model(argv[1], argv[2]); model->printModel(); return 0; }
[ "jsandbrook@c842427a-1736-11df-914e-2594af177612" ]
[ [ [ 1, 25 ] ] ]
de433bcba68899ca1dd01a21ffa42a211f743bce
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/branches/newton20/engine/ai/src/AgentDialogState.cpp
c22ada11e149590ca09dd93ef9fd8188be2ff6eb
[ "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
2,409
cpp
/* This source file is part of Rastullahs Lockenpracht. * Copyright (C) 2003-2008 Team Pantheon. http://www.team-pantheon.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the Clarified Artistic License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not you can get it here * http://www.jpaulmorrison.com/fbp/artistic2.htm. */ #include "stdinc.h" #include "AgentDialogState.h" #include "Agent.h" #include "AiMessages.h" #include "Creature.h" #include "CreatureController.h" #include "CreatureControllerManager.h" #include "MessagePump.h" using namespace Ogre; namespace rl { AgentDialogState::AgentDialogState(Agent* agent) : AgentState(agent), mPartner(NULL), mTalking(false) { } AgentDialogState::~AgentDialogState() { } void AgentDialogState::setDialogPartner(Agent* partner) { mPartner = partner; } void AgentDialogState::setDialog(Dialog* dialog) { mDialog = dialog; } void AgentDialogState::update(const Ogre::Real elapsedTime) { CreatureController* ctrl = CreatureControllerManager::getSingleton().getCreatureController( mAgent->getControlledCreature()); if (mAgent->getPosition().squaredDistance(mPartner->getPosition()) > 1.5 || !mAgent->isAhead(mPartner, 0.95)) { mAgent->addForce(mAgent->calcSeek(mPartner->getPosition())); mAgent->updateVehicle(0, elapsedTime); } else { if (!mTalking) { mAgent->reset(); ctrl->setMovement( CreatureController::MT_STEHEN, Vector3::ZERO, Vector3::ZERO); ctrl->setAnimation("reden"); mTalking = true; MessagePump::getSingleton().sendMessage<MessageType_DialogStarted>(mDialog); mAgent->popState(); } } } } // namespace rl
[ "melven@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 83 ] ] ]
06f57227abff3f77486ccb6c3026d1a3e092b27c
33f59b1ba6b12c2dd3080b24830331c37bba9fe2
/Depend/Foundation/Intersection/Wm4IntrSegment3Sphere3.h
fabcd1fca23f381e8740a0e08f493872152aa88f
[]
no_license
daleaddink/flagship3d
4835c223fe1b6429c12e325770c14679c42ae3c6
6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a
refs/heads/master
2021-01-15T16:29:12.196094
2009-11-01T10:18:11
2009-11-01T10:18:11
37,734,654
1
0
null
null
null
null
UTF-8
C++
false
false
2,336
h
// Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // The Wild Magic Version 4 Foundation Library source code is supplied // under the terms of the license agreement // http://www.geometrictools.com/License/Wm4FoundationLicense.pdf // and may not be copied or disclosed except in accordance with the terms // of that agreement. #ifndef WM4INTRSEGMENT3SPHERE3_H #define WM4INTRSEGMENT3SPHERE3_H #include "Wm4FoundationLIB.h" #include "Wm4Intersector.h" #include "Wm4Segment3.h" #include "Wm4Sphere3.h" namespace Wm4 { template <class Real> class WM4_FOUNDATION_ITEM IntrSegment3Sphere3 : public Intersector<Real,Vector3<Real> > { public: IntrSegment3Sphere3 (const Segment3<Real>& rkSegment, const Sphere3<Real>& rkSphere); // object access const Segment3<Real>& GetSegment () const; const Sphere3<Real>& GetSphere () const; // test-intersection query virtual bool Test (); // find-intersection query virtual bool Find (); int GetQuantity () const; const Vector3<Real>& GetPoint (int i) const; Real GetSegmentT (int i) const; // dynamic test-intersection query virtual bool Test (Real fTMax, const Vector3<Real>& rkVelocity0, const Vector3<Real>& rkVelocity1); // Dynamic find-intersection query. The first point of contact is // accessed by GetPoint(0). The first time of contact is accessed by // GetContactTime(). virtual bool Find (Real fTMax, const Vector3<Real>& rkVelocity0, const Vector3<Real>& rkVelocity1); Real ZeroThreshold; // default = Math<Real>::ZERO_TOLERANCE private: using Intersector<Real,Vector3<Real> >::IT_EMPTY; using Intersector<Real,Vector3<Real> >::IT_OTHER; using Intersector<Real,Vector3<Real> >::m_iIntersectionType; using Intersector<Real,Vector3<Real> >::m_fContactTime; // the objects to intersect const Segment3<Real>& m_rkSegment; const Sphere3<Real>& m_rkSphere; // information about the intersection set int m_iQuantity; Vector3<Real> m_akPoint[2]; Real m_afSegmentT[2]; }; typedef IntrSegment3Sphere3<float> IntrSegment3Sphere3f; typedef IntrSegment3Sphere3<double> IntrSegment3Sphere3d; } #endif
[ "yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa" ]
[ [ [ 1, 76 ] ] ]
63610352ff7d7f579f6feae922ee2f9671ecba4e
26706a661c23f5c2c1f97847ba09f44b7b425cf6
/TaskManager/PEEXE.H
be55b66ee814da0bef04c1cd7c460d495aa202b2
[]
no_license
124327288/nativetaskmanager
96a54dbe150f855422d7fd813d3631eaac76fadd
e75b3d9d27c902baddbb1bef975c746451b1b8bb
refs/heads/master
2021-05-29T05:18:26.779900
2009-02-10T13:23:28
2009-02-10T13:23:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,038
h
// From // //========================================== // Matt Pietrek // Microsoft Systems Journal, Feb 1997 // FILE: PEEXE.H //========================================== #ifndef __PEEXE_H__ #define __PEEXE_H__ #include "exefile.h" class PE_EXE : public EXE_FILE { public: PE_EXE(LPCTSTR pszFileName ); ~PE_EXE( ){ } BOOL IsValid(void) { return m_pNtHdr ? TRUE : FALSE; } // For those who want at the data directly PIMAGE_NT_HEADERS GetIMAGE_NT_HEADERS( void ) { return m_pNtHdr; } // IMAGE_FILE_HEADER fields WORD GetMachine( void ) { return m_pNtHdr->FileHeader.Machine; } WORD GetNumberOfSections( void ) { return m_pNtHdr->FileHeader.NumberOfSections; } DWORD GetTimeDateStamp(void) { return m_pNtHdr->FileHeader.TimeDateStamp; } DWORD GetCharacteristics( void ) { return m_pNtHdr->FileHeader.Characteristics; } // IMAGE_OPTIONAL_HEADER fields WORD GetLinkerVersion(void) { return(MAKEWORD( m_pNtHdr->OptionalHeader.MinorLinkerVersion, m_pNtHdr->OptionalHeader.MajorLinkerVersion ) ); } DWORD GetSizeOfCode( void ) { return m_pNtHdr->OptionalHeader.SizeOfCode; } DWORD GetSizeOfInitializedData( void ) { return m_pNtHdr->OptionalHeader.SizeOfInitializedData; } DWORD GetSizeOfUninitializedData( void ) { return m_pNtHdr->OptionalHeader.SizeOfUninitializedData; } DWORD GetAddressOfEntryPoint( void ) { return m_pNtHdr->OptionalHeader.AddressOfEntryPoint; } DWORD GetBaseOfCode( void ) { return m_pNtHdr->OptionalHeader.BaseOfCode; } DWORD GetBaseOfData( void ) { return m_pNtHdr->OptionalHeader.BaseOfData; } DWORD GetImageBase( void ) { return m_pNtHdr->OptionalHeader.ImageBase; } DWORD GetSectionAlignment( void ) { return m_pNtHdr->OptionalHeader.SectionAlignment; } DWORD GetFileAlignment( void ) { return m_pNtHdr->OptionalHeader.FileAlignment; } WORD GetMajorOperatingSystemVersion( void ) { return m_pNtHdr->OptionalHeader.MajorOperatingSystemVersion; } WORD GetMinorOperatingSystemVersion( void ) { return m_pNtHdr->OptionalHeader.MinorOperatingSystemVersion; } WORD GetMajorImageVersion( void ) { return m_pNtHdr->OptionalHeader.MajorImageVersion; } WORD GetMinorImageVersion( void ) { return m_pNtHdr->OptionalHeader.MinorImageVersion; } WORD GetMajorSubsystemVersion( void ) { return m_pNtHdr->OptionalHeader.MajorSubsystemVersion; } WORD GetMinorSubsystemVersion( void ) { return m_pNtHdr->OptionalHeader.MinorSubsystemVersion; } // DWORD GetWin32VersionValue( void ) // { return m_pNtHdr->OptionalHeader.Win32VersionValue; } DWORD GetSizeOfImage( void ) { return m_pNtHdr->OptionalHeader.SizeOfImage; } DWORD GetSizeOfHeaders( void ) { return m_pNtHdr->OptionalHeader.SizeOfHeaders; } WORD GetSubsystem( void ) { return m_pNtHdr->OptionalHeader.Subsystem; } DWORD GetSizeOfStackReserve( void ) { return m_pNtHdr->OptionalHeader.SizeOfStackReserve; } DWORD GetSizeOfStackCommit( void ) { return m_pNtHdr->OptionalHeader.SizeOfStackCommit; } DWORD GetSizeOfHeapReserve( void ) { return m_pNtHdr->OptionalHeader.SizeOfHeapReserve; } DWORD GetSizeOfHeapCommit( void ) { return m_pNtHdr->OptionalHeader.SizeOfHeapCommit; } DWORD GetDataDirectoryEntryRVA( DWORD id ); PVOID GetDataDirectoryEntryPointer( DWORD id ); DWORD GetDataDirectoryEntrySize( DWORD id ); PVOID GetReadablePointerFromRVA( DWORD rva ); protected: DWORD RVAToFileOffset( DWORD rva ); PIMAGE_NT_HEADERS m_pNtHdr; }; #endif
[ "[email protected]@97a26042-f463-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 160 ] ] ]
edde885464ee75a7e2c9b9851fad6c4b0ded7451
0e782c46fd93da70ce3bfc6ea7ff763225b31afd
/inc/View4.h
1ee09c124b17a0762742cc2a04cd18566d70a8c7
[]
no_license
dupesnduds/Mp
58940e12b42ce6169222ce863e6257f5d22726b9
4854ba197a8e4701d8fc3cdddbe45636225c555f
refs/heads/master
2021-05-26T20:09:00.285677
2011-09-19T00:50:36
2011-09-19T00:50:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,741
h
/* ============================================================================ Name : View4 from MpView4.h Author : Cleave Pokotea Version : Copyright : 2006 - 2007 Description : Declares view for application. ============================================================================ */ #ifndef MPView4_H #define MPView4_H // INCLUDES #include <aknview.h> // CONSTANTS // UID of view const TUid KView4Id = {4}; // FORWARD DECLARATIONS class CContainer4; // CLASS DECLARATION /** * CView4 view class. * */ class CView4 : public CAknView { public: // Constructors and destructor /** * EPOC default constructor. */ void ConstructL(); /** * Destructor. */ ~CView4(); public: // Functions from base classes /** * From CAknView returns Uid of View * @return TUid uid of the view */ TUid Id() const; /** * From MEikMenuObserver delegate commands from the menu * @param aCommand a command emitted by the menu * @return void */ void HandleCommandL(TInt aCommand); /** * From CAknView reaction if size change * @return void */ void HandleClientRectChange(); private: /** * From CAknView activate the view * @param aPrevViewId * @param aCustomMessageId * @param aCustomMessage * @return void */ void DoActivateL(const TVwsViewId& aPrevViewId,TUid aCustomMessageId, const TDesC8& aCustomMessage); /** * From CAknView deactivate the view (free resources) * @return void */ void DoDeactivate(); private: // Data CContainer4* iContainer; TRgb iTextForegroundColour; TRgb iTextBackgroundColour; TRgb iHighlightForegroundColour; TRgb iHighlightBackgroundColour; }; #endif
[ [ [ 1, 94 ] ] ]
1c1ecbeea0455fc3b985046a552c6a429c0ea2f1
2b32433353652d705e5558e7c2d5de8b9fbf8fc3
/Dm_new_idz/Mlita/GraphCtrl/GraphCtrlCtl.cpp
4ad2b70587840d8c2f5e33f173f55d7e397fcab8
[]
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,065
cpp
// GraphCtrlCtl.cpp : Implementation of the CGraphCtrlCtrl ActiveX Control class. #include "stdafx.h" #include "GraphCtrl.h" #include "GraphCtrlCtl.h" #include "GraphCtrlPpg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif IMPLEMENT_DYNCREATE(CGraphCtrlCtrl, COleControl) ///////////////////////////////////////////////////////////////////////////// // Message map BEGIN_MESSAGE_MAP(CGraphCtrlCtrl, COleControl) //{{AFX_MSG_MAP(CGraphCtrlCtrl) // NOTE - ClassWizard will add and remove message map entries // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG_MAP ON_OLEVERB(AFX_IDS_VERB_PROPERTIES, OnProperties) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // Dispatch map BEGIN_DISPATCH_MAP(CGraphCtrlCtrl, COleControl) //{{AFX_DISPATCH_MAP(CGraphCtrlCtrl) DISP_PROPERTY_EX(CGraphCtrlCtrl, "Tops", GetTops, SetTops, VT_I2) DISP_PROPERTY_EX(CGraphCtrlCtrl, "Oriented", GetOriented, SetOriented, VT_BOOL) DISP_FUNCTION(CGraphCtrlCtrl, "SetEdge", SetEdge, VT_EMPTY, VTS_I4 VTS_I4) DISP_FUNCTION(CGraphCtrlCtrl, "RemoveEdge", RemoveEdge, VT_EMPTY, VTS_I2 VTS_I2) //}}AFX_DISPATCH_MAP DISP_FUNCTION_ID(CGraphCtrlCtrl, "AboutBox", DISPID_ABOUTBOX, AboutBox, VT_EMPTY, VTS_NONE) END_DISPATCH_MAP() ///////////////////////////////////////////////////////////////////////////// // Event map BEGIN_EVENT_MAP(CGraphCtrlCtrl, COleControl) //{{AFX_EVENT_MAP(CGraphCtrlCtrl) // NOTE - ClassWizard will add and remove event map entries // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_EVENT_MAP END_EVENT_MAP() ///////////////////////////////////////////////////////////////////////////// // Property pages // TODO: Add more property pages as needed. Remember to increase the count! BEGIN_PROPPAGEIDS(CGraphCtrlCtrl, 1) PROPPAGEID(CGraphCtrlPropPage::guid) END_PROPPAGEIDS(CGraphCtrlCtrl) ///////////////////////////////////////////////////////////////////////////// // Initialize class factory and guid IMPLEMENT_OLECREATE_EX(CGraphCtrlCtrl, "GRAPHCTRL.GraphCtrlCtrl.1", 0x80b7cc80, 0xf4c3, 0x4eac, 0x81, 0x74, 0xfd, 0x1f, 0x64, 0xd5, 0x2, 0x27) ///////////////////////////////////////////////////////////////////////////// // Type library ID and version IMPLEMENT_OLETYPELIB(CGraphCtrlCtrl, _tlid, _wVerMajor, _wVerMinor) ///////////////////////////////////////////////////////////////////////////// // Interface IDs const IID BASED_CODE IID_DGraphCtrl = { 0x7c49fe05, 0x20a8, 0x42b0, { 0xbd, 0x79, 0x2c, 0xd7, 0xe2, 0x39, 0x71, 0xcc } }; const IID BASED_CODE IID_DGraphCtrlEvents = { 0xe2b53d75, 0x4ebb, 0x4fd9, { 0x87, 0x16, 0xcf, 0x1, 0xad, 0x8, 0x5, 0xcd } }; ///////////////////////////////////////////////////////////////////////////// // Control type information static const DWORD BASED_CODE _dwGraphCtrlOleMisc = OLEMISC_ACTIVATEWHENVISIBLE | OLEMISC_SETCLIENTSITEFIRST | OLEMISC_INSIDEOUT | OLEMISC_CANTLINKINSIDE | OLEMISC_RECOMPOSEONRESIZE; IMPLEMENT_OLECTLTYPE(CGraphCtrlCtrl, IDS_GRAPHCTRL, _dwGraphCtrlOleMisc) ///////////////////////////////////////////////////////////////////////////// // CGraphCtrlCtrl::CGraphCtrlCtrlFactory::UpdateRegistry - // Adds or removes system registry entries for CGraphCtrlCtrl BOOL CGraphCtrlCtrl::CGraphCtrlCtrlFactory::UpdateRegistry(BOOL bRegister) { // TODO: Verify that your control follows apartment-model threading rules. // Refer to MFC TechNote 64 for more information. // If your control does not conform to the apartment-model rules, then // you must modify the code below, changing the 6th parameter from // afxRegApartmentThreading to 0. if (bRegister) return AfxOleRegisterControlClass( AfxGetInstanceHandle(), m_clsid, m_lpszProgID, IDS_GRAPHCTRL, IDB_GRAPHCTRL, afxRegApartmentThreading, _dwGraphCtrlOleMisc, _tlid, _wVerMajor, _wVerMinor); else return AfxOleUnregisterClass(m_clsid, m_lpszProgID); } ///////////////////////////////////////////////////////////////////////////// // CGraphCtrlCtrl::CGraphCtrlCtrl - Constructor CPoint V[100][100]; CGraphCtrlCtrl::CGraphCtrlCtrl() { InitializeIIDs(&IID_DGraphCtrl, &IID_DGraphCtrlEvents); m_Tops=0; m_Oriented = 0; for (int i=0; i<100; i++) for (int j=0; j<100; j++) M[i][j] = 0; FILE *f=fopen("points.dat","rt"); int Count=0,x,y; fscanf(f,"%d\n",&Count); for (i=1; i<=Count; i++) { for (int j=0; j<=i; j++) { fscanf(f,"%d %d",&x,&y); V[i][j].x=x; V[i][j].y=y; } fscanf(f,"\n"); } fclose(f); } ///////////////////////////////////////////////////////////////////////////// // CGraphCtrlCtrl::~CGraphCtrlCtrl - Destructor CGraphCtrlCtrl::~CGraphCtrlCtrl() { // TODO: Cleanup your control's instance data here. } ///////////////////////////////////////////////////////////////////////////// // CGraphCtrlCtrl::OnDraw - Drawing function CPoint GetPoint(int r, int v,int W, int H) { CPoint Ret( (W*V[r][v].x) / V[r][0].x, (H*V[r][v].y)/V[r][0].y); return (Ret); } void Arraw(CDC* pdc, CPoint v1, CPoint v2, bool t) { pdc->MoveTo(v1); pdc->LineTo(v2); } void CGraphCtrlCtrl::OnDraw( CDC* pdc, const CRect& rcBounds, const CRect& rcInvalid) { pdc->FillRect(rcBounds, CBrush::FromHandle((HBRUSH)GetStockObject(WHITE_BRUSH))); for (int i=1; i<=m_Tops; i++) { pdc->Ellipse(GetPoint(m_Tops,i,rcBounds.Width(),rcBounds.Height()).x-2, GetPoint(m_Tops,i,rcBounds.Width(),rcBounds.Height()).y-2, GetPoint(m_Tops,i,rcBounds.Width(),rcBounds.Height()).x+2, GetPoint(m_Tops,i,rcBounds.Width(),rcBounds.Height()).y+2); } for (i=1; i<=m_Tops; i++) for (int j=1; j<=m_Tops; j++) { if (M[i][j]) Arraw(pdc, GetPoint(m_Tops,i,rcBounds.Width(),rcBounds.Height()), GetPoint(m_Tops,j,rcBounds.Width(),rcBounds.Height()),m_Oriented); } // pdc->LineTo( } ///////////////////////////////////////////////////////////////////////////// // CGraphCtrlCtrl::DoPropExchange - Persistence support void CGraphCtrlCtrl::DoPropExchange(CPropExchange* pPX) { ExchangeVersion(pPX, MAKELONG(_wVerMinor, _wVerMajor)); COleControl::DoPropExchange(pPX); // TODO: Call PX_ functions for each persistent custom property. } ///////////////////////////////////////////////////////////////////////////// // CGraphCtrlCtrl::OnResetState - Reset control to default state void CGraphCtrlCtrl::OnResetState() { COleControl::OnResetState(); // Resets defaults found in DoPropExchange // TODO: Reset any other control state here. } ///////////////////////////////////////////////////////////////////////////// // CGraphCtrlCtrl::AboutBox - Display an "About" box to the user void CGraphCtrlCtrl::AboutBox() { CDialog dlgAbout(IDD_ABOUTBOX_GRAPHCTRL); dlgAbout.DoModal(); } ///////////////////////////////////////////////////////////////////////////// // CGraphCtrlCtrl message handlers short CGraphCtrlCtrl::GetTops() { // TODO: Add your property handler here return m_Tops; } void CGraphCtrlCtrl::SetTops(short nNewValue) { // TODO: Add your property handler here m_Tops = nNewValue; RemoveAllEdges(); InvalidateControl(); SetModifiedFlag(); } void CGraphCtrlCtrl::SetEdge(long v1, long v2) { M[v1][v2] = 1; if (!m_Oriented) M[v2][v1]=1; InvalidateControl(); } void CGraphCtrlCtrl::RemoveEdge(short v1, short v2) { M[v1][v2] = 0; if (!m_Oriented) M[v2][v1]=0; InvalidateControl(); } BOOL CGraphCtrlCtrl::GetOriented() { // TODO: Add your property handler here return m_Oriented; } void CGraphCtrlCtrl::SetOriented(BOOL bNewValue) { // TODO: Add your property handler here m_Oriented = bNewValue; SetModifiedFlag(); } void CGraphCtrlCtrl::RemoveAllEdges() { for (int i=0; i<100; i++) for (int j=0; j<100; j++) M[i][j] = 0; }
[ [ [ 1, 287 ] ] ]
4429154bf259962682191fdbfdde805ad2cc598a
7b379862f58f587d9327db829ae4c6493b745bb1
/Source/Commands.h
51b1697d610ad99a70d1858b32bd829d149e304b
[]
no_license
owenvallis/Nomestate
75e844e8ab68933d481640c12019f0d734c62065
7fe7c06c2893421a3c77b5180e5f27ab61dd0ffd
refs/heads/master
2021-01-19T07:35:14.301832
2011-12-28T07:42:50
2011-12-28T07:42:50
2,950,072
2
0
null
null
null
null
UTF-8
C++
false
false
1,172
h
/* ============================================================================== Commands.h Created: 10 Oct 2011 10:17:05pm Author: Dimitri Diakopoulos TODO: Refactor this into a singleton ============================================================================== */ #ifndef __COMMANDS_H_BFE68D89__ #define __COMMANDS_H_BFE68D89__ #include "../JuceLibraryCode/JuceHeader.h" #include "Command.h" #include <map> #include <utility> class Commands { public: Commands(); ~Commands(); static const String SIGNAL_MOD; static const String SEND_OSC; static const String SEND_MIDI; static const String MIDI_KILL; static const String CLOCK_START; static const String CLOCK_STOP; static const String CLOCK_CHANGE_BPM; static const String CLOCK_CHANGE_QUANTIZE; static const String CLIENT_SPEAK; static const String CLIENT_READY; // We'll see how fast this is std::map<String, Command*> COMMAND_LIST; void registerCommand(String, Command *); }; #endif // __COMMANDS_H_BFE68D89__
[ "ow3nskip" ]
[ [ [ 1, 51 ] ] ]
b76d19854dafcba9c350a7057fe5f5d616ad79fc
d7b345a8a6b0473c325fab661342de295c33b9c8
/beta/src/polaris/auto_array.h
def5d58c42947aab71b229c721860a0c102e526a
[]
no_license
raould/Polaris-Open-Source
67ccd647bf40de51a3dae903ab70e8c271f3f448
10d0ca7e2db9e082e1d2ed2e43fa46875f1b07b2
refs/heads/master
2021-01-01T19:19:39.148016
2010-05-10T17:39:26
2010-05-10T17:39:26
631,953
3
2
null
null
null
null
UTF-8
C++
false
false
496
h
// Copyright 2010 Hewlett-Packard under the terms of the MIT X license // found at http://www.opensource.org/licenses/mit-license.html #pragma once template<class T> class auto_array { T* m_v; // Forbidden operations. auto_array& operator=(const auto_array& x); auto_array(const auto_array& x); public: auto_array() : m_v(0) {} auto_array(size_t n) : m_v(new T[n]) {} ~auto_array() { delete[] m_v; } T** operator&() { return &m_v; } T* get() { return m_v; } };
[ [ [ 1, 22 ] ] ]
7a351232511ad8a636376e62e790f0594f9b5200
374d23f6a603046a5299596fc59171dc1c6b09b4
/tensores/3DViewer/vtkFLTKObjectFactory.h
891443d084c70a7ba3460e091a2c7dd962342b9b
[]
no_license
mounyeh/tensorespablo
aa9b403ceef82094872e50f7ddd0cdd89b6b7421
f045a5c1e1decf7302de17f4448abbd284b3c2de
refs/heads/master
2021-01-10T06:09:53.357175
2010-09-19T22:57:16
2010-09-19T22:57:16
51,831,049
1
0
null
null
null
null
UTF-8
C++
false
false
1,824
h
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- * * $Id: vtkFLTKObjectFactory.h,v 1.12 2004/06/15 05:15:13 xpxqx Exp $ * * Copyright (c) 2002 - 2004 Sean McInerney * All rights reserved. * * See Copyright.txt or http://vtkfltk.sourceforge.net/Copyright.html * 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 notice for more information. * */ #ifndef VTK_FLTK_OBJECT_FACTORY_H_ # define VTK_FLTK_OBJECT_FACTORY_H_ # include "vtkFLTKConfigure.h" // VTK Common # include "vtkObjectFactory.h" /** \class vtkFLTKObjectFactory * \brief vtkFLTK object factory. * * Object Factory creating properly registered Interactor and RenderWindow * for implementing an event-driven interface with FLTK. * * \author Sean McInerney * \version $Revision: 1.12 $ * \date $Date: 2004/06/15 05:15:13 $ * * \sa * vtkObjectFactory */ class VTK_FLTK_EXPORT vtkFLTKObjectFactory : public vtkObjectFactory { public: static vtkFLTKObjectFactory* New (void); vtkTypeRevisionMacro(vtkFLTKObjectFactory, vtkObjectFactory); /** Return the version of VTK that the factory was built with. */ virtual const char* GetVTKSourceVersion (void); /** Return a text description of the factory. */ virtual const char* GetDescription (void); protected: vtkFLTKObjectFactory (void); private: vtkFLTKObjectFactory (const vtkFLTKObjectFactory&); // Not implemented. void operator= (const vtkFLTKObjectFactory&); // Not implemented. }; #endif /* VTK_FLTK_OBJECT_FACTORY_H_ */ /* * End of: $Id: vtkFLTKObjectFactory.h,v 1.12 2004/06/15 05:15:13 xpxqx Exp $. * */
[ "diodoledzeppelin@9de476db-11b3-a259-9df9-d52a56463d6f" ]
[ [ [ 1, 59 ] ] ]
174f7e93fb7e7f40ba34c1802d5f9bdfccc630a6
87ff03fd1b5a4642773a5a001165b595cfacd60d
/WinampRemoteMedia/winampplugin/Cajun/reader.h
80c4a35bb90ece67f360e41dc4ffc807d0ba5d46
[]
no_license
jubbynox/googlegadets
f7f16b2eb417871601a33d2f1f5615b3a007780a
79e94a0af754b0f3dfed59f73aeaa3bff39dafa5
refs/heads/master
2021-01-10T21:46:45.901272
2010-02-06T13:38:25
2010-02-06T13:38:25
32,803,954
0
0
null
null
null
null
UTF-8
C++
false
false
1,876
h
/********************************************** License: BSD Project Webpage: http://cajun-jsonapi.sourceforge.net/ Author: Terry Caton, tcaton(a)hotmail.com TODO: additional documentation. ***********************************************/ #pragma once #include "elements.h" namespace json { class Reader { public: struct Location { Location(); unsigned int m_nLine; // document line, zero-indexed unsigned int m_nLineOffset; // character offset from beginning of line, zero indexed unsigned int m_nDocOffset; // character offset from entire document, zero indexed }; static void Read(Element& elementRoot, std::istream& istr); private: class InputStream; enum TokenType; struct Token; typedef std::vector<Token> Tokens; class TokenStream; // scanning istream into token sequence void Scan(Tokens& tokens, InputStream& inputStream); void EatWhiteSpace(InputStream& inputStream); void MatchComment(std::string& sComment, InputStream& inputStream); void MatchString(std::string& sValue, InputStream& inputStream); void MatchNumber(std::string& sNumber, InputStream& inputStream); void MatchExpectedString(const std::string& sExpected, InputStream& inputStream); // parsing token sequence into element structure void Parse(Element& element, TokenStream& tokenStream); void Parse(Object& object, TokenStream& tokenStream); void Parse(Array& array, TokenStream& tokenStream); void Parse(String& string, TokenStream& tokenStream); void Parse(Number& number, TokenStream& tokenStream); void Parse(Boolean& boolean, TokenStream& tokenStream); void Parse(Null& null, TokenStream& tokenStream); const std::string& MatchExpectedToken(TokenType nExpected, TokenStream& tokenStream); }; } // End namespace
[ "jubbynox@9a519766-8835-0410-a643-67b8b61f6624" ]
[ [ [ 1, 62 ] ] ]
7a2ee781aff5cdb4206a3075b8abf7b32fc03291
138a353006eb1376668037fcdfbafc05450aa413
/source/ogre/OgreNewt/boost/mpl/aux_/config/static_constant.hpp
bb3cbeda48ed6fa04a54b8be92d77274f5d3c630
[]
no_license
sonicma7/choreopower
107ed0a5f2eb5fa9e47378702469b77554e44746
1480a8f9512531665695b46dcfdde3f689888053
refs/heads/master
2020-05-16T20:53:11.590126
2009-11-18T03:10:12
2009-11-18T03:10:12
32,246,184
0
0
null
null
null
null
UTF-8
C++
false
false
835
hpp
#ifndef BOOST_MPL_AUX_CONFIG_STATIC_CONSTANT_HPP_INCLUDED #define BOOST_MPL_AUX_CONFIG_STATIC_CONSTANT_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2000-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/mpl for documentation. // $Source: /cvsroot/ogre/ogreaddons/ogrenewt/OgreNewt_Main/inc/boost/mpl/aux_/config/static_constant.hpp,v $ // $Date: 2006/04/17 23:47:07 $ // $Revision: 1.1 $ #if !defined(BOOST_MPL_PREPROCESSING_MODE) // BOOST_STATIC_CONSTANT is defined here: # include <boost/config.hpp> #else // undef the macro for the preprocessing mode # undef BOOST_STATIC_CONSTANT #endif #endif // BOOST_MPL_AUX_CONFIG_STATIC_CONSTANT_HPP_INCLUDED
[ "Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e" ]
[ [ [ 1, 25 ] ] ]
bd0029931749fe1708984c3ce03cce3844810607
67b25fa154dc7dc5462214839e1e3d06fcb88ddc
/codebase/qe/qe.h
c2285c8de095cb05b6ab3a3adf41a93cb7cb638a
[]
no_license
pmeyyapp/Single-user-RDBMS
27485a19b672d29d3ebded2256584460f519f9ba
c797c265e199095d9a7efaaf44c1bf47ec2ab910
refs/heads/master
2020-12-24T16:06:12.295518
2011-10-21T03:41:44
2011-10-21T03:41:44
2,618,223
0
0
null
null
null
null
UTF-8
C++
false
false
11,205
h
#ifndef _qe_h_ #define _qe_h_ #include <vector> #include <iostream> #include <cstring> #include "../pf/pf.h" #include "../rm/rm.h" #include "../ix/ix.h" using namespace std; typedef enum{ MIN = 0, MAX, SUM, AVG, COUNT } AggregateOp; // The following functions are using the following // format for the passed data. // For int and real: use 4 bytes // For char and varchar: use 4 bytes for the length followed by // the characters struct Value { AttrType type; // type of value void *data; // value friend ostream &operator<<(ostream &s, const Value &v) { char buff[100],temp[100]; s<<"Value type :"<<v.type<<endl; if(v.type==TypeInt) { memset(buff,0,100); memcpy(buff,v.data,sizeof(buff)); s<<"Data :"<<*(int*)&buff<<endl; } else if(v.type==TypeReal) { memset(buff,0,100); memcpy(buff,v.data,sizeof(buff)); s<<"Data :"<<*(float*)&buff<<endl; } else { memset(buff,0,100); memcpy(buff,v.data,sizeof(buff)); memset(temp,0,100); memcpy(temp,buff,4); s<<"Length : "<<*(int*)&temp<<endl; s<<"Data :"<<buff<<endl; } } }; struct Condition { string lhsAttr; // left-hand side attribute CompOp op; // comparison operator bool bRhsIsAttr; // TRUE if right-hand side is an attribute and not a value string rhsAttr; // right-hand side attribute if bRhsIsAttr = TRUE Value rhsValue; // right-hand side value if bRhsIsAttr = FALSE friend ostream &operator<<(ostream &s, const Condition &c) { s<<"Left-hand side attribute :"<<c.lhsAttr<<endl; s<<"comparison operator :"<<c.op<<endl; s<<"Value or not :"<<c.bRhsIsAttr<<endl; s<<"Right-hand side attribute :"<<c.rhsAttr<<endl; s<<c.rhsValue<<endl; } }; class Iterator { // All the relational operators and access methods are iterators. public: virtual RC getNextTuple(void *data) = 0; virtual void getAttributes(vector<Attribute> &attrs) const = 0; virtual ~Iterator() {}; }; class TableScan : public Iterator { // A wrapper inheriting Iterator over RM_ScanIterator public: RM &rm; RM_ScanIterator *iter; string tablename; vector<Attribute> attrs; vector<char *> attrNames; TableScan(RM &rm, const char *tablename, const char *alias = NULL):rm(rm) { // Get Attributes from RM rm.getAttributes(tablename, attrs); // Get Attribute Names from RM unsigned i; for(i = 0; i < attrs.size(); ++i) { // convert to char * attrNames.push_back(const_cast<char *>(attrs[i].name.c_str())); } // Call rm scan to get iterator iter = new RM_ScanIterator(); rm.scan(tablename, attrNames, *iter); // Store tablename this->tablename = string(tablename); if(alias) this->tablename = string(alias); }; // Start a new iterator given the new compOp and value void setIterator() { iter->close(); delete iter; iter = new RM_ScanIterator(); rm.scan(tablename.c_str(), attrNames, *iter); }; RC getNextTuple(void *data) { RID rid; return iter->getNextTuple(rid, data); }; void getAttributes(vector<Attribute> &attrs) const { attrs.clear(); attrs = this->attrs; unsigned i; // For attribute in vector<Attribute>, name it as rel.attr for(i = 0; i < attrs.size(); ++i) { string tmp = tablename; tmp += "."; tmp += attrs[i].name; attrs[i].name = tmp; } }; ~TableScan() { iter->close(); }; }; class IndexScan : public Iterator { // A wrapper inheriting Iterator over IX_IndexScan public: RM &rm; IX_IndexScan *iter; IX_IndexHandle &handle; string tablename; vector<Attribute> attrs; IndexScan(RM &rm,IX_IndexHandle &indexHandle, const char *tablename, const char *alias = NULL):rm(rm),handle(indexHandle) { // Get Attributes from RM rm.getAttributes(tablename, attrs); // Store tablename this->tablename = string(tablename); if(alias) this->tablename = string(alias); // Store Index Handle iter = NULL; //this->handle = indexHandle; }; // Start a new iterator given the new compOp and value void setIterator(CompOp compOp, void *value) { if(iter != NULL) { iter->CloseScan(); delete iter; } iter = new IX_IndexScan(); iter->OpenScan(handle, compOp, value); }; RC getNextTuple(void *data) { RID rid; int rc = iter->GetNextEntry(rid); //cout<<"outside if"<<endl; if(rc == 0) { rc = rm.readTuple(tablename.c_str(), rid, data); // cout<<"innsidde if"<<endl; } return rc; }; void getAttributes(vector<Attribute> &attrs) const { attrs.clear(); attrs = this->attrs; unsigned i; // For attribute in vector<Attribute>, name it as rel.attr for(i = 0; i < attrs.size(); ++i) { string tmp = tablename; tmp += "."; tmp += attrs[i].name; attrs[i].name = tmp; } }; ~IndexScan() { iter->CloseScan(); }; }; class Filter : public Iterator { // Filter operator public: Iterator *it2; Condition filcond; vector<Attribute> filter_attr; Filter(Iterator *input, // Iterator of input R const Condition &condition // Selection condition ); ~Filter(); RC getNextTuple(void *data); // For attribute in vector<Attribute>, name it as rel.attr void getAttributes(vector<Attribute> &attrs) const; }; class Project : public Iterator { // Projection operator public: Iterator *it1; vector<string> att_name; vector<Attribute> proj_attr,curr_attr; int ipsize; Project(Iterator *input, // Iterator of input R const vector<string> &attrNames); // vector containing attribute names ~Project(); RC getNextTuple(void *data); // For attribute in vector<Attribute>, name it as rel.attr void getAttributes(vector<Attribute> &attrs) const; }; class NLJoin : public Iterator { // Nested-Loop join operator public: Iterator *left_it; TableScan *right_it; vector<Attribute> left_attr,right_attr; vector<Attribute>combined; AttrType atype; int flag; Condition joincd; char lbuff[100],rbuff[100],lval[100],rval[100]; int left_length,right_length; NLJoin(Iterator *leftIn, // Iterator of input R TableScan *rightIn, // TableScan Iterator of input S const Condition &condition // Join condition ); ~NLJoin(); RC getNextTuple(void *data); // For attribute in vector<Attribute>, name it as rel.attr void getAttributes(vector<Attribute> &attrs) const; }; class INLJoin : public Iterator { // Index Nested-Loop join operator public: Iterator *left_it2; IndexScan *right_it2; vector<Attribute> left_attr2,right_attr2; vector<Attribute>indexjoin; AttrType atype2; int flag2; Condition indexcd; char lbuff2[100],rbuff2[100],lval2[100],rval2[100]; int left_length2,right_length2; INLJoin(Iterator *leftIn, // Iterator of input R IndexScan *rightIn, // IndexScan Iterator of input S const Condition &condition // Join condition ); ~INLJoin(); RC getNextTuple(void *data); // For attribute in vector<Attribute>, name it as rel.attr void getAttributes(vector<Attribute> &attrs) const; }; class HashJoin : public Iterator { // Hash join operator public: HashJoin(Iterator *leftIn, // Iterator of input R Iterator *rightIn, // Iterator of input S const Condition &condition // Join condition ); ~HashJoin(); RC getNextTuple(void *data); // For attribute in vector<Attribute>, name it as rel.attr void getAttributes(vector<Attribute> &attrs) const; }; class Aggregate : public Iterator { // Aggregation operator public: Iterator *it5; Attribute ag; AggregateOp op1; vector<Attribute> agg_attr; char val[100],buff[100],mnac[100]; int num; float fnum; int imin,imax,isum,iavg,icount; float fmin,fmax,fsum,favg,fcount; Aggregate(Iterator *input, // Iterator of input R Attribute aggAttr, // The attribute over which we are computing an aggregate AggregateOp op // Aggregate operation ); // Extra Credit Aggregate(Iterator *input, // Iterator of input R Attribute aggAttr, // The attribute over which we are computing an aggregate Attribute gAttr, // The attribute over which we are grouping the tuples AggregateOp op // Aggregate operation ); ~Aggregate(); RC getNextTuple(void *data); // Please name the output attribute as aggregateOp(aggAttr) // E.g. Relation=rel, attribute=attr, aggregateOp=MAX // output attrname = "MAX(rel.attr)" void getAttributes(vector<Attribute> &attrs) const; }; #endif
[ [ [ 1, 370 ] ] ]
62af21bc9bcfab67d033854d16f1ff0a11f109cb
f177993b13e97f9fecfc0e751602153824dfef7e
/ImPro/ImProBaseClass/MyLib/LEADTOOL/Include/Filters/ILMNetSnk2.h
5bbfefc5e3d9166c91ae5c78dd858bd066055a14
[]
no_license
svn2github/imtophooksln
7bd7412947d6368ce394810f479ebab1557ef356
bacd7f29002135806d0f5047ae47cbad4c03f90e
refs/heads/master
2020-05-20T04:00:56.564124
2010-09-24T09:10:51
2010-09-24T09:10:51
11,787,598
1
0
null
null
null
null
UTF-8
C++
false
false
23,749
h
/* this ALWAYS GENERATED file contains the definitions for the interfaces */ /* File created by MIDL compiler version 7.00.0500 */ /* at Thu Nov 05 12:54:56 2009 */ /* Compiler settings for .\LMNetSnk.idl: Oicf, W1, Zp8, env=Win32 (32b run) protocol : dce , ms_ext, c_ext, robust error checks: allocation ref bounds_check enum stub_data VC __declspec() decoration level: __declspec(uuid()), __declspec(selectany), __declspec(novtable) DECLSPEC_UUID(), MIDL_INTERFACE() */ //@@MIDL_FILE_HEADING( ) #pragma warning( disable: 4049 ) /* more than 64k source lines */ /* verify that the <rpcndr.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCNDR_H_VERSION__ #define __REQUIRED_RPCNDR_H_VERSION__ 475 #endif #include "rpc.h" #include "rpcndr.h" #ifndef __RPCNDR_H_VERSION__ #error this stub requires an updated version of <rpcndr.h> #endif // __RPCNDR_H_VERSION__ #ifndef __ILMNetSnk2_h__ #define __ILMNetSnk2_h__ #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif /* Forward Declarations */ #ifndef __ILMNetSnkConnection_FWD_DEFINED__ #define __ILMNetSnkConnection_FWD_DEFINED__ typedef interface ILMNetSnkConnection ILMNetSnkConnection; #endif /* __ILMNetSnkConnection_FWD_DEFINED__ */ #ifndef __ILMNetSnk_FWD_DEFINED__ #define __ILMNetSnk_FWD_DEFINED__ typedef interface ILMNetSnk ILMNetSnk; #endif /* __ILMNetSnk_FWD_DEFINED__ */ #ifndef __LMNetSnk_FWD_DEFINED__ #define __LMNetSnk_FWD_DEFINED__ #ifdef __cplusplus typedef class LMNetSnk LMNetSnk; #else typedef struct LMNetSnk LMNetSnk; #endif /* __cplusplus */ #endif /* __LMNetSnk_FWD_DEFINED__ */ /* header files for imported files */ #include "oaidl.h" #include "ocidl.h" #ifdef __cplusplus extern "C"{ #endif #ifndef __LMNetSnkLib_LIBRARY_DEFINED__ #define __LMNetSnkLib_LIBRARY_DEFINED__ /* library LMNetSnkLib */ /* [helpstring][version][uuid] */ #ifndef __LMNetSnk2_GUID__ #define __LMNetSnk2_GUID__ static const IID LIBID_LMNetSnkLib = { 0xe2b7de04, 0x38c5, 0x11d5, { 0x91, 0xf6, 0x00, 0x10, 0x4b, 0xdb, 0x8f, 0xf9 } }; static const CLSID CLSID_LMNetSnk = { 0xe2b7de05, 0x38c5, 0x11d5, { 0x91, 0xf6, 0x00, 0x10, 0x4b, 0xdb, 0x8f, 0xf9 } }; static const IID IID_ILMNetSnk = { 0xe2b7de06, 0x38c5, 0x11d5, { 0x91, 0xf6, 0x00, 0x10, 0x4b, 0xdb, 0x8f, 0xf9 } }; static const IID IID_ILMNetSnkConnection = { 0xe2b7de07, 0x38c5, 0x11d5, { 0x91, 0xf6, 0x00, 0x10, 0x4b, 0xdb, 0x8f, 0xf9 } }; #endif DEFINE_GUID(LIBID_LMNetSnkLib,0xE2B7DE04,0x38C5,0x11D5,0x91,0xF6,0x00,0x10,0x4B,0xDB,0x8F,0xF9); #ifndef __ILMNetSnkConnection_INTERFACE_DEFINED__ #define __ILMNetSnkConnection_INTERFACE_DEFINED__ /* interface ILMNetSnkConnection */ /* [unique][helpstring][dual][uuid][object] */ DEFINE_GUID(IID_ILMNetSnkConnection,0xE2B7DE07,0x38C5,0x11D5,0x91,0xF6,0x00,0x10,0x4B,0xDB,0x8F,0xF9); #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("E2B7DE07-38C5-11D5-91F6-00104BDB8FF9") ILMNetSnkConnection : public IDispatch { public: virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_PrevConnection( /* [retval][out] */ ILMNetSnkConnection **pVal) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_NextConnection( /* [retval][out] */ ILMNetSnkConnection **pVal) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_ID( /* [retval][out] */ long *pVal) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Username( /* [retval][out] */ BSTR *pVal) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Address( /* [retval][out] */ BSTR *pVal) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Enabled( /* [retval][out] */ VARIANT_BOOL *pVal) = 0; virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_Enabled( /* [in] */ VARIANT_BOOL newVal) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Connected( /* [retval][out] */ VARIANT_BOOL *pVal) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Close( void) = 0; }; #else /* C style interface */ typedef struct ILMNetSnkConnectionVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( ILMNetSnkConnection * This, /* [in] */ REFIID riid, /* [iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( ILMNetSnkConnection * This); ULONG ( STDMETHODCALLTYPE *Release )( ILMNetSnkConnection * This); HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( ILMNetSnkConnection * This, /* [out] */ UINT *pctinfo); HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( ILMNetSnkConnection * This, /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo **ppTInfo); HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( ILMNetSnkConnection * This, /* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR *rgszNames, /* [range][in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID *rgDispId); /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( ILMNetSnkConnection * This, /* [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); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_PrevConnection )( ILMNetSnkConnection * This, /* [retval][out] */ ILMNetSnkConnection **pVal); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_NextConnection )( ILMNetSnkConnection * This, /* [retval][out] */ ILMNetSnkConnection **pVal); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ID )( ILMNetSnkConnection * This, /* [retval][out] */ long *pVal); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Username )( ILMNetSnkConnection * This, /* [retval][out] */ BSTR *pVal); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Address )( ILMNetSnkConnection * This, /* [retval][out] */ BSTR *pVal); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Enabled )( ILMNetSnkConnection * This, /* [retval][out] */ VARIANT_BOOL *pVal); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Enabled )( ILMNetSnkConnection * This, /* [in] */ VARIANT_BOOL newVal); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Connected )( ILMNetSnkConnection * This, /* [retval][out] */ VARIANT_BOOL *pVal); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Close )( ILMNetSnkConnection * This); END_INTERFACE } ILMNetSnkConnectionVtbl; interface ILMNetSnkConnection { CONST_VTBL struct ILMNetSnkConnectionVtbl *lpVtbl; }; #ifdef COBJMACROS #define ILMNetSnkConnection_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define ILMNetSnkConnection_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define ILMNetSnkConnection_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define ILMNetSnkConnection_GetTypeInfoCount(This,pctinfo) \ ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define ILMNetSnkConnection_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define ILMNetSnkConnection_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define ILMNetSnkConnection_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define ILMNetSnkConnection_get_PrevConnection(This,pVal) \ ( (This)->lpVtbl -> get_PrevConnection(This,pVal) ) #define ILMNetSnkConnection_get_NextConnection(This,pVal) \ ( (This)->lpVtbl -> get_NextConnection(This,pVal) ) #define ILMNetSnkConnection_get_ID(This,pVal) \ ( (This)->lpVtbl -> get_ID(This,pVal) ) #define ILMNetSnkConnection_get_Username(This,pVal) \ ( (This)->lpVtbl -> get_Username(This,pVal) ) #define ILMNetSnkConnection_get_Address(This,pVal) \ ( (This)->lpVtbl -> get_Address(This,pVal) ) #define ILMNetSnkConnection_get_Enabled(This,pVal) \ ( (This)->lpVtbl -> get_Enabled(This,pVal) ) #define ILMNetSnkConnection_put_Enabled(This,newVal) \ ( (This)->lpVtbl -> put_Enabled(This,newVal) ) #define ILMNetSnkConnection_get_Connected(This,pVal) \ ( (This)->lpVtbl -> get_Connected(This,pVal) ) #define ILMNetSnkConnection_Close(This) \ ( (This)->lpVtbl -> Close(This) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __ILMNetSnkConnection_INTERFACE_DEFINED__ */ #ifndef __ILMNetSnk_INTERFACE_DEFINED__ #define __ILMNetSnk_INTERFACE_DEFINED__ /* interface ILMNetSnk */ /* [unique][helpstring][dual][uuid][object] */ DEFINE_GUID(IID_ILMNetSnk,0xE2B7DE06,0x38C5,0x11D5,0x91,0xF6,0x00,0x10,0x4B,0xDB,0x8F,0xF9); #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("E2B7DE06-38C5-11D5-91F6-00104BDB8FF9") ILMNetSnk : public IDispatch { public: virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_ConnectionCount( /* [retval][out] */ long *pVal) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_FirstConnection( /* [retval][out] */ ILMNetSnkConnection **pVal) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_LastConnection( /* [retval][out] */ ILMNetSnkConnection **pVal) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE CloseAll( void) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE FindConnection( /* [in] */ long ID, /* [retval][out] */ ILMNetSnkConnection **pVal) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_ConnectionVersion( /* [retval][out] */ long *pVal) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_RestrictionCount( /* [retval][out] */ long *pVal) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE AddRestriction( /* [in] */ BSTR Address, /* [retval][out] */ long *pVal) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE RemoveRestriction( /* [in] */ long index) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetRestriction( /* [in] */ long Index, /* [retval][out] */ BSTR *pVal) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE FindRestriction( /* [in] */ BSTR Address, /* [retval][out] */ long *pVal) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE RemoveAllRestrictions( void) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_RequireLogin( /* [retval][out] */ VARIANT_BOOL *pVal) = 0; virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_RequireLogin( /* [in] */ VARIANT_BOOL newVal) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_UserCount( /* [retval][out] */ long *pVal) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE AddUser( /* [in] */ BSTR Username, /* [in] */ BSTR Password, /* [retval][out] */ long *pVal) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE RemoveUser( /* [in] */ long index) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetUsername( /* [in] */ long Index, /* [retval][out] */ BSTR *pVal) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetPassword( /* [in] */ long Index, /* [retval][out] */ BSTR *pVal) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetPassword( /* [in] */ long Index, /* [in] */ BSTR newVal) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE FindUser( /* [in] */ BSTR Username, /* [retval][out] */ long *pVal) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE RemoveAllUsers( void) = 0; }; #else /* C style interface */ typedef struct ILMNetSnkVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( ILMNetSnk * This, /* [in] */ REFIID riid, /* [iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( ILMNetSnk * This); ULONG ( STDMETHODCALLTYPE *Release )( ILMNetSnk * This); HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( ILMNetSnk * This, /* [out] */ UINT *pctinfo); HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( ILMNetSnk * This, /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo **ppTInfo); HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( ILMNetSnk * This, /* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR *rgszNames, /* [range][in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID *rgDispId); /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( ILMNetSnk * This, /* [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); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ConnectionCount )( ILMNetSnk * This, /* [retval][out] */ long *pVal); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_FirstConnection )( ILMNetSnk * This, /* [retval][out] */ ILMNetSnkConnection **pVal); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_LastConnection )( ILMNetSnk * This, /* [retval][out] */ ILMNetSnkConnection **pVal); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *CloseAll )( ILMNetSnk * This); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *FindConnection )( ILMNetSnk * This, /* [in] */ long ID, /* [retval][out] */ ILMNetSnkConnection **pVal); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ConnectionVersion )( ILMNetSnk * This, /* [retval][out] */ long *pVal); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_RestrictionCount )( ILMNetSnk * This, /* [retval][out] */ long *pVal); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *AddRestriction )( ILMNetSnk * This, /* [in] */ BSTR Address, /* [retval][out] */ long *pVal); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *RemoveRestriction )( ILMNetSnk * This, /* [in] */ long index); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetRestriction )( ILMNetSnk * This, /* [in] */ long Index, /* [retval][out] */ BSTR *pVal); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *FindRestriction )( ILMNetSnk * This, /* [in] */ BSTR Address, /* [retval][out] */ long *pVal); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *RemoveAllRestrictions )( ILMNetSnk * This); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_RequireLogin )( ILMNetSnk * This, /* [retval][out] */ VARIANT_BOOL *pVal); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_RequireLogin )( ILMNetSnk * This, /* [in] */ VARIANT_BOOL newVal); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_UserCount )( ILMNetSnk * This, /* [retval][out] */ long *pVal); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *AddUser )( ILMNetSnk * This, /* [in] */ BSTR Username, /* [in] */ BSTR Password, /* [retval][out] */ long *pVal); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *RemoveUser )( ILMNetSnk * This, /* [in] */ long index); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetUsername )( ILMNetSnk * This, /* [in] */ long Index, /* [retval][out] */ BSTR *pVal); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetPassword )( ILMNetSnk * This, /* [in] */ long Index, /* [retval][out] */ BSTR *pVal); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetPassword )( ILMNetSnk * This, /* [in] */ long Index, /* [in] */ BSTR newVal); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *FindUser )( ILMNetSnk * This, /* [in] */ BSTR Username, /* [retval][out] */ long *pVal); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *RemoveAllUsers )( ILMNetSnk * This); END_INTERFACE } ILMNetSnkVtbl; interface ILMNetSnk { CONST_VTBL struct ILMNetSnkVtbl *lpVtbl; }; #ifdef COBJMACROS #define ILMNetSnk_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define ILMNetSnk_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define ILMNetSnk_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define ILMNetSnk_GetTypeInfoCount(This,pctinfo) \ ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define ILMNetSnk_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define ILMNetSnk_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define ILMNetSnk_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define ILMNetSnk_get_ConnectionCount(This,pVal) \ ( (This)->lpVtbl -> get_ConnectionCount(This,pVal) ) #define ILMNetSnk_get_FirstConnection(This,pVal) \ ( (This)->lpVtbl -> get_FirstConnection(This,pVal) ) #define ILMNetSnk_get_LastConnection(This,pVal) \ ( (This)->lpVtbl -> get_LastConnection(This,pVal) ) #define ILMNetSnk_CloseAll(This) \ ( (This)->lpVtbl -> CloseAll(This) ) #define ILMNetSnk_FindConnection(This,ID,pVal) \ ( (This)->lpVtbl -> FindConnection(This,ID,pVal) ) #define ILMNetSnk_get_ConnectionVersion(This,pVal) \ ( (This)->lpVtbl -> get_ConnectionVersion(This,pVal) ) #define ILMNetSnk_get_RestrictionCount(This,pVal) \ ( (This)->lpVtbl -> get_RestrictionCount(This,pVal) ) #define ILMNetSnk_AddRestriction(This,Address,pVal) \ ( (This)->lpVtbl -> AddRestriction(This,Address,pVal) ) #define ILMNetSnk_RemoveRestriction(This,index) \ ( (This)->lpVtbl -> RemoveRestriction(This,index) ) #define ILMNetSnk_GetRestriction(This,Index,pVal) \ ( (This)->lpVtbl -> GetRestriction(This,Index,pVal) ) #define ILMNetSnk_FindRestriction(This,Address,pVal) \ ( (This)->lpVtbl -> FindRestriction(This,Address,pVal) ) #define ILMNetSnk_RemoveAllRestrictions(This) \ ( (This)->lpVtbl -> RemoveAllRestrictions(This) ) #define ILMNetSnk_get_RequireLogin(This,pVal) \ ( (This)->lpVtbl -> get_RequireLogin(This,pVal) ) #define ILMNetSnk_put_RequireLogin(This,newVal) \ ( (This)->lpVtbl -> put_RequireLogin(This,newVal) ) #define ILMNetSnk_get_UserCount(This,pVal) \ ( (This)->lpVtbl -> get_UserCount(This,pVal) ) #define ILMNetSnk_AddUser(This,Username,Password,pVal) \ ( (This)->lpVtbl -> AddUser(This,Username,Password,pVal) ) #define ILMNetSnk_RemoveUser(This,index) \ ( (This)->lpVtbl -> RemoveUser(This,index) ) #define ILMNetSnk_GetUsername(This,Index,pVal) \ ( (This)->lpVtbl -> GetUsername(This,Index,pVal) ) #define ILMNetSnk_GetPassword(This,Index,pVal) \ ( (This)->lpVtbl -> GetPassword(This,Index,pVal) ) #define ILMNetSnk_SetPassword(This,Index,newVal) \ ( (This)->lpVtbl -> SetPassword(This,Index,newVal) ) #define ILMNetSnk_FindUser(This,Username,pVal) \ ( (This)->lpVtbl -> FindUser(This,Username,pVal) ) #define ILMNetSnk_RemoveAllUsers(This) \ ( (This)->lpVtbl -> RemoveAllUsers(This) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __ILMNetSnk_INTERFACE_DEFINED__ */ DEFINE_GUID(CLSID_LMNetSnk,0xE2B7DE05,0x38C5,0x11D5,0x91,0xF6,0x00,0x10,0x4B,0xDB,0x8F,0xF9); #ifdef __cplusplus class DECLSPEC_UUID("E2B7DE05-38C5-11D5-91F6-00104BDB8FF9") LMNetSnk; #endif #endif /* __LMNetSnkLib_LIBRARY_DEFINED__ */ /* Additional Prototypes for ALL interfaces */ /* end of Additional Prototypes */ #ifdef __cplusplus } #endif #endif
[ "ndhumuscle@fa729b96-8d43-11de-b54f-137c5e29c83a" ]
[ [ [ 1, 657 ] ] ]
9f7bf2962b8359bd0743de15d6997ffd87e733f9
723202e673511cf9f243177d964dfeba51cb06a3
/09/oot/epa_labs/l2/src/SketcherDoc.h
52cd386e9f8fb51c73229e9e3d4c40faca8026d7
[]
no_license
aeremenok/a-team-777
c2ffe04b408a266f62c523fb8d68c87689f2a2e9
0945efbe00c3695c9cc3dbcdb9177ff6f1e9f50b
refs/heads/master
2020-12-24T16:50:12.178873
2009-06-16T14:55:41
2009-06-16T14:55:41
32,388,114
0
0
null
null
null
null
UTF-8
C++
false
false
3,185
h
// SketcherDoc.h : interface of the CSketcherDoc class // ///////////////////////////////////////////////////////////////////////////// #if !defined(AFX_SKETCHERDOC_H__623441AB_57EA_11D0_9257_00201834E2A3__INCLUDED_) #define AFX_SKETCHERDOC_H__623441AB_57EA_11D0_9257_00201834E2A3__INCLUDED_ #include "other\TStack.h" class CSketcherDoc : public CDocument { protected: // create from serialization only CSketcherDoc(); DECLARE_DYNCREATE(CSketcherDoc) // Attributes public: protected: COLORREF m_Color; // Current drawing color WORD m_Element; // Current element type TStack<CElement> m_ElementList; // Element list CSize m_DocSize; // Document size // Operations public: WORD GetElementType() // Get the element type { return m_Element; } COLORREF GetElementColor() // Get the element color { return m_Color; } void AddElement(CElement* pElement); // Add an element to the list IIterator<CElement>* getIterator(){return m_ElementList.getIterator();} //POSITION GetListHeadPosition() // Return list head POSITION value // { return m_ElementList.getFirst(); } //CElement* GetNext(POSITION& aPos) // Return current element pointer // { return m_ElementList.GetNext(aPos); } //POSITION GetListTailPosition() // Return list tail POSITION value // { return m_ElementList.GetTailPosition(); } //CElement* GetPrev(POSITION& aPos) // Return current element pointer // { return m_ElementList.GetPrev(aPos); } CSize GetDocSize() // Retrieve the document size { return m_DocSize; } void DeleteElement(CElement* pElement); // Delete an element void SendToBack(CElement* pElement); // Send element to start of list // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CSketcherDoc) public: virtual BOOL OnNewDocument(); virtual void Serialize(CArchive& ar); //}}AFX_VIRTUAL // Implementation public: virtual ~CSketcherDoc(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // Generated message map functions protected: //{{AFX_MSG(CSketcherDoc) afx_msg void OnColorBlack(); afx_msg void OnColorRed(); afx_msg void OnElementSquare(); afx_msg void OnElementText(); afx_msg void OnElementSquareText(); afx_msg void OnElementDiamond(); afx_msg void OnUpdateColorBlack(CCmdUI* pCmdUI); afx_msg void OnUpdateColorRed(CCmdUI* pCmdUI); afx_msg void OnUpdateElementSquare(CCmdUI* pCmdUI); afx_msg void OnUpdateElementText(CCmdUI* pCmdUI); afx_msg void OnUpdateElementSquareText(CCmdUI* pCmdUI); afx_msg void OnUpdateElementDiamond(CCmdUI* pCmdUI); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Developer Studio will insert additional declarations immediately before the previous line. #endif // !defined(AFX_SKETCHERDOC_H__623441AB_57EA_11D0_9257_00201834E2A3__INCLUDED_)
[ "emmanpavel@9273621a-9230-0410-b1c6-9ffd80c20a0c" ]
[ [ [ 1, 92 ] ] ]
c3de96ae62e1972001ca6c5c77d37722066e80a8
4ab40b7fa3d15e68457fd2b9100e0d331f013591
/mirrorworld/Objects/MWStaticObject.h
c010d167cdb4c9f396cf5028fea48d00a2f0500c
[]
no_license
yzhou61/mirrorworld
f5d2c221f3f8376cfb0bffd0a3accbe9bb1caa21
33653244e5599d7d04e8a9d8072d32ecc55355b3
refs/heads/master
2021-01-19T20:18:44.546599
2010-03-19T22:40:42
2010-03-19T22:40:42
32,120,779
0
0
null
null
null
null
UTF-8
C++
false
false
875
h
////////////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////////////// #ifndef _MW_STATIC_OBJECT_H_ #define _MW_STATIC_OBJECT_H_ #include "MWObject.h" namespace MirrorWorld { class StaticObject : public Object { public: StaticObject(unsigned int id, bool attachable = true, bool reflective = false):Object(id, attachable, reflective), m_pPhyMatID(NULL) {} virtual ~StaticObject() {} virtual Ogre::String name() const = 0; void setPhyMaterial(OgreNewt::MaterialID* matID) { m_pPhyMatID = matID; } virtual void setEntity(Ogre::SceneManager* sceneMgr, OgreNewt::World* world, Ogre::SceneNode* node, Ogre::Entity* entity); protected: OgreNewt::MaterialID* m_pPhyMatID; }; // End of StaticObject } //End of MirrorWorld #endif
[ "cxyzs7@2e672104-186a-11df-85bb-b9a83fee2cb1" ]
[ [ [ 1, 25 ] ] ]
4f4999c198b9c9b803dac59c2dfd36accfcce0b9
6327ac79f3294817895d5ef859509145bc0c28a9
/win/XFile/XfileEntity.cpp
2f65f9586995f0873b92dd975348faa1c1b3d169
[]
no_license
corpsofengineers/ffed3d
c8da1cb6e58f8b37b138d6f7d7ac0faa585e961b
8b6df7c081fd9ec4cf86220e8561439a8340d59b
refs/heads/master
2021-01-10T13:17:57.882726
2011-12-05T22:24:07
2011-12-05T22:24:07
49,797,267
2
1
null
null
null
null
WINDOWS-1251
C++
false
false
19,024
cpp
#include "XfileEntity.h" #include "Utility.h" #include "MeshHierarchy.h" #include "../Macros.h" #include "../Render/RenderSystem.h" // The time to change from one animation set to another // To see how the merging works - increase this time value to slow it down const float kMoveTransitionTime=1.0f; // Constructor CXFileEntity::CXFileEntity() : m_speedAdjust(1.0f),m_firstMesh(0), m_currentTrack(0),m_currentTime(0),m_numAnimationSets(0),m_currentAnimationSet(0),m_maxBones(0),m_sphereRadius(0), m_sphereCentre(0,0,0),m_boneMatrices(0) { m_d3dDevice = renderSystem->GetDevice(); effect=NULL; } // Destructor CXFileEntity::~CXFileEntity(void) { if (m_animController) { m_animController->Release(); m_animController=0; } if (m_frameRoot) { // Create a mesh heirarchy class to control the removal of memory for the frame heirarchy CMeshHierarchy memoryAllocator; D3DXFrameDestroy(m_frameRoot, &memoryAllocator); m_frameRoot=0; } if (m_boneMatrices) { delete []m_boneMatrices; m_boneMatrices=0; } } /* Load the x file The function D3DXLoadMeshHierarchyFromX requires a support object to handle memeory allocation etc. I have defined this in the class CMeshHierarchy */ bool CXFileEntity::LoadXFile(const std::string &filename,int startAnimation) { if (!Load(filename)) { return false; } SetAnimationSet(startAnimation); return true; } bool CXFileEntity::Load(const std::string &filename) { // Create our mesh hierarchy class to control the allocation of memory - only used temporarily CMeshHierarchy *memoryAllocator=new CMeshHierarchy; // To make it easier to find the textures change the current directory to the one containing the .x file // First though remember the current one to put it back afterwards std::string currentDirectory=CUtility::GetTheCurrentDirectory(); std::string xfilePath; CUtility::SplitPath(filename,&xfilePath,&m_filename); SetCurrentDirectory(xfilePath.c_str()); // This is the function that does all the .x file loading. We provide a pointer to an instance of our // memory allocator class to handle memory allocationm during the frame and mesh loading HRESULT hr = D3DXLoadMeshHierarchyFromX(filename.c_str(), D3DXMESH_MANAGED, m_d3dDevice, memoryAllocator, NULL, &m_frameRoot, &m_animController); delete memoryAllocator; memoryAllocator=0; SetCurrentDirectory(currentDirectory.c_str()); if (FAILED(hr)) return false; // if the x file contains any animation remember how many sets there are if(m_animController) m_numAnimationSets = m_animController->GetMaxNumAnimationSets(); // Bones for skining if(m_frameRoot) { // Set the bones up SetupBoneMatrices((D3DXFRAME_EXTENDED*)m_frameRoot, NULL); // Create the bone matrices array for use during FrameMove to hold the final transform m_boneMatrices = new D3DXMATRIX[m_maxBones]; ZeroMemory(m_boneMatrices, sizeof(D3DXMATRIX)*m_maxBones); // Calculate the Bounding Sphere for this model (used in CalculateInitialViewMatrix to position camera correctly) D3DXFrameCalculateBoundingSphere(m_frameRoot, &m_sphereCentre, &m_sphereRadius); } m_firstMesh->MeshData.pMesh->GetVertexBuffer(&vb.vb); m_firstMesh->MeshData.pMesh->GetIndexBuffer(&ib.ib); D3DVERTEXELEMENT9 pDecl[MAX_FVF_DECL_SIZE]; m_firstMesh->MeshData.pMesh->GetDeclaration(pDecl); renderSystem->CreateVertexDeclaration(&pDecl[0],&vb.declaration); // Получение данных о количестве вершин, индексов и полигонов dwNumVerticies = m_firstMesh->MeshData.pMesh->GetNumVertices(); dwNumIndecies = m_firstMesh->MeshData.pMesh->GetNumFaces()*3; dwNumFaces = m_firstMesh->MeshData.pMesh->GetNumFaces(); vb.vertexSize = (short)m_firstMesh->MeshData.pMesh->GetNumBytesPerVertex(); return true; } /* Since this demo can load many different sizes and shapes of 3d model setting the initial camera position so the model can be seen is a tricky task. This function uses the model's bounding sphere to come up with an initial position for the camera. */ D3DXVECTOR3 CXFileEntity::GetInitialCameraPosition() const { D3DXVECTOR3 cameraPos(0.0f,m_sphereCentre.y,-(m_sphereRadius*3)); return cameraPos; } /** * \brief we need to go through the hierarchy and set the combined matrices * calls itself recursively as it tareverses the hierarchy * \param device - the Direct3D device object * \param pFrame - current frame * \param pParentMatrix - the parent frame matrix * \author Keith Ditchburn \date 18 July 2005 */ void CXFileEntity::SetupBoneMatrices(D3DXFRAME_EXTENDED *pFrame, LPD3DXMATRIX pParentMatrix) { // Cast to our extended structure first D3DXMESHCONTAINER_EXTENDED* pMesh = (D3DXMESHCONTAINER_EXTENDED*)pFrame->pMeshContainer; // If this frame has a mesh if(pMesh) { // We need to remember which is the first mesh in the hierarchy for later when we // update (FrameMove) if(!m_firstMesh) m_firstMesh = pMesh; // if there is skin info, then setup the bone matrices if(pMesh->pSkinInfo && pMesh->MeshData.pMesh) { // Create a copy of the mesh to skin into later D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]; if (FAILED(pMesh->MeshData.pMesh->GetDeclaration(Declaration))) return; pMesh->MeshData.pMesh->CloneMesh(D3DXMESH_MANAGED, Declaration, m_d3dDevice, &pMesh->exSkinMesh); // Max bones is calculated for later use (to know how big to make the bone matrices array) m_maxBones=max(m_maxBones,(int)pMesh->pSkinInfo->GetNumBones()); // For each bone work out its matrix for (unsigned int i = 0; i < pMesh->pSkinInfo->GetNumBones(); i++) { // Find the frame containing the bone D3DXFRAME_EXTENDED* pTempFrame = (D3DXFRAME_EXTENDED*)D3DXFrameFind(m_frameRoot, pMesh->pSkinInfo->GetBoneName(i)); // set the bone part - point it at the transformation matrix pMesh->exFrameCombinedMatrixPointer[i] = &pTempFrame->exCombinedTransformationMatrix; } } } // Pass on to sibblings if(pFrame->pFrameSibling) SetupBoneMatrices((D3DXFRAME_EXTENDED*)pFrame->pFrameSibling, pParentMatrix); // Pass on to children if(pFrame->pFrameFirstChild) SetupBoneMatrices((D3DXFRAME_EXTENDED*)pFrame->pFrameFirstChild, &pFrame->exCombinedTransformationMatrix); } /** * \brief Called each frame update with the time and the current world matrix * \param elapsedTime - time passed * \param matWorld - current world matrix for the model * \author Keith Ditchburn \date 18 July 2005 */ void CXFileEntity::FrameMove(bool mode, float elapsedTime,const D3DXMATRIX *matWorld) { // Adjust animation speed //elapsedTime/=m_speedAdjust; // Advance the time and set in the controller //if (m_animController != NULL) //m_animController->AdvanceTime(elapsedTime, NULL); //m_animController->AdvanceTime(0.5f, NULL); if (mode==0) { m_animController->SetTrackPosition(0, elapsedTime); m_animController->AdvanceTime(0, NULL); } else { elapsedTime/=m_speedAdjust; m_animController->AdvanceTime(0.03f, NULL); m_currentTime+=0.01; } //m_currentTime+=0.01;//elapsedTime; //char cBuff[255]; //sprintf(cBuff,"FFED3D track position: %.2f", elapsedTime); //SetWindowText(hWnd,cBuff); // Now update the model matrices in the hierarchy UpdateFrameMatrices(m_frameRoot, matWorld); // If the model contains a skinned mesh update the vertices D3DXMESHCONTAINER_EXTENDED* pMesh = m_firstMesh; if(pMesh && pMesh->pSkinInfo) { unsigned int Bones = pMesh->pSkinInfo->GetNumBones(); // Create the bone matrices that transform each bone from bone space into character space // (via exFrameCombinedMatrixPointer) and also wraps the mesh around the bones using the bone offsets // in exBoneOffsetsArray for (unsigned int i = 0; i < Bones; ++i) D3DXMatrixMultiply(&m_boneMatrices[i],&pMesh->exBoneOffsets[i], pMesh->exFrameCombinedMatrixPointer[i]); // We need to modify the vertex positions based on the new bone matrices. This is achieved // by locking the vertex buffers and then calling UpdateSkinnedMesh. UpdateSkinnedMesh takes the // original vertex data (in pMesh->MeshData.pMesh), applies the matrices and writes the new vertices // out to skin mesh (pMesh->exSkinMesh). // UpdateSkinnedMesh uses software skinning which is the slowest way of carrying out skinning // but is easiest to describe and works on the majority of graphic devices. // Other methods exist that use hardware to do this skinning - see the notes and the // DirectX SDK skinned mesh sample for more details void *srcPtr=0; pMesh->MeshData.pMesh->LockVertexBuffer(D3DLOCK_READONLY, (void**)&srcPtr); void *destPtr=0; pMesh->exSkinMesh->LockVertexBuffer(0, (void**)&destPtr); // Update the skinned mesh pMesh->pSkinInfo->UpdateSkinnedMesh(m_boneMatrices, NULL, srcPtr, destPtr); // Unlock the meshes vertex buffers pMesh->exSkinMesh->UnlockVertexBuffer(); pMesh->MeshData.pMesh->UnlockVertexBuffer(); } } D3DXMATRIX CXFileEntity::GetMatrix() { D3DXFRAME_EXTENDED *currentFrame = (D3DXFRAME_EXTENDED*)m_frameRoot; //return currentFrame->TransformationMatrix; return currentFrame->exCombinedTransformationMatrix; } /** * \brief Called to update the frame matrices in the hierarchy to reflect current animation stage * \param frameBase - frame being looked at * \param parentMatrix - the matrix of our parent (if we have one) * \author Keith Ditchburn \date 18 July 2005 */ void CXFileEntity::UpdateFrameMatrices(const D3DXFRAME *frameBase, const D3DXMATRIX *parentMatrix) { D3DXFRAME_EXTENDED *currentFrame = (D3DXFRAME_EXTENDED*)frameBase; // If parent matrix exists multiply our frame matrix by it if (parentMatrix != NULL) D3DXMatrixMultiply(&currentFrame->exCombinedTransformationMatrix, &currentFrame->TransformationMatrix, parentMatrix); else currentFrame->exCombinedTransformationMatrix = currentFrame->TransformationMatrix; // If we have a sibling recurse if (currentFrame->pFrameSibling != NULL) UpdateFrameMatrices(currentFrame->pFrameSibling, parentMatrix); // If we have a child recurse if (currentFrame->pFrameFirstChild != NULL) UpdateFrameMatrices(currentFrame->pFrameFirstChild, &currentFrame->exCombinedTransformationMatrix); } /** * \brief Render our mesh. * Call the DrawFrame recursive fn on render with the root frame (see notes diagram) * \param device - the Direct3D device object * \author Keith Ditchburn \date 18 July 2005 */ void CXFileEntity::Render() { //D3DVERTEXELEMENT9 pDecl[MAX_FVF_DECL_SIZE]; if (m_frameRoot) { //m_frameRoot->pMeshContainer->MeshData.pMesh->GetDeclaration(pDecl); //renderSystem->CreateVertexDeclaration(&pDecl[0],&vb.declaration); renderSystem->SetVertexDeclaration(vb.declaration); DrawFrame(m_frameRoot); } } void CXFileEntity::RenderM() { renderSystem->DrawIndexedPrimitive(vb,0,dwNumVerticies,ib,0,dwNumFaces); } void CXFileEntity::Render(int vfrom, int vto, int ffrom, int fto) { renderSystem->DrawIndexedPrimitive(vb, vfrom, vto, ib, ffrom, fto); } /** * \brief Called to render a frame in the hierarchy * \param device - the Direct3D device object * \param frame - frame to render * \author Keith Ditchburn \date 18 July 2005 */ void CXFileEntity::DrawFrame(LPD3DXFRAME frame) { // Draw all mesh containers in this frame LPD3DXMESHCONTAINER meshContainer = frame->pMeshContainer; while (meshContainer) { DrawMeshContainer(meshContainer, frame); meshContainer = meshContainer->pNextMeshContainer; } // Recurse for sibblings if (frame->pFrameSibling != NULL) DrawFrame(frame->pFrameSibling); // Recurse for children if (frame->pFrameFirstChild != NULL) DrawFrame(frame->pFrameFirstChild); } /** * \brief Called to render a mesh * \param device - the Direct3D device object * \param meshContainerBase - the mesh container * \param frameBase - frame containing the mesh * \author Keith Ditchburn \date 18 July 2005 */ void CXFileEntity::DrawMeshContainer(LPD3DXMESHCONTAINER meshContainerBase, LPD3DXFRAME frameBase) { DWORD attrSize = 0; // Cast to our extended frame type D3DXFRAME_EXTENDED *frame = (D3DXFRAME_EXTENDED*)frameBase; // Cast to our extended mesh container D3DXMESHCONTAINER_EXTENDED *meshContainer = (D3DXMESHCONTAINER_EXTENDED*)meshContainerBase; // Set the world transform m_d3dDevice->SetTransform(D3DTS_WORLD, &frame->exCombinedTransformationMatrix); unsigned int pass; if (effect) { effect->SetMatrix("worldmat",&frame->exCombinedTransformationMatrix); effect->Begin(&pass,0); effect->BeginPass(0); } // Loop through all the materials in the mesh rendering each subset for (unsigned int iMaterial = 0; iMaterial < meshContainer->NumMaterials; iMaterial++) { // use the material in our extended data rather than the one in meshContainer->pMaterials[iMaterial].MatD3D //m_d3dDevice->SetMaterial( &meshContainer->exMaterials[iMaterial] ); //m_d3dDevice->SetTexture( 0, meshContainer->exTextures[iMaterial] ); // Select the mesh to draw, if there is skin then use the skinned mesh else the normal one LPD3DXMESH pDrawMesh = (meshContainer->pSkinInfo) ? meshContainer->exSkinMesh: meshContainer->MeshData.pMesh; // Finally Call the mesh draw function //pDrawMesh->DrawSubset(iMaterial); pDrawMesh->GetVertexBuffer(&vb.vb); pDrawMesh->GetIndexBuffer(&ib.ib); //D3DVERTEXELEMENT9 pDecl[MAX_FVF_DECL_SIZE]; //pDrawMesh->GetDeclaration(pDecl); //renderSystem->CreateVertexDeclaration(&pDecl[0],&vb.declaration); // Получение данных о количестве вершин, индексов и полигонов dwNumVerticies = pDrawMesh->GetNumVertices(); dwNumIndecies = pDrawMesh->GetNumFaces()*3; dwNumFaces = pDrawMesh->GetNumFaces(); vb.vertexSize = (short)pDrawMesh->GetNumBytesPerVertex(); renderSystem->DrawIndexedPrimitive(vb,0,dwNumVerticies,ib,0,dwNumFaces); } if (effect) { effect->EndPass(); effect->End(); } } /** * \brief Change to a different animation set * Handles transitions between animations to make it smooth and not a sudden jerk to a new position * \param index - new animation set index * \author Keith Ditchburn \date 18 July 2005 */ void CXFileEntity::SetAnimationSet(unsigned int index) { if (index==m_currentAnimationSet) return; if (index>=m_numAnimationSets) index=0; // Remember current animation m_currentAnimationSet=index; // Get the animation set from the controller LPD3DXANIMATIONSET set; m_animController->GetAnimationSet(m_currentAnimationSet, &set ); // Note: for a smooth transition between animation sets we can use two tracks and assign the new set to the track // not currently playing then insert Keys into the KeyTrack to do the transition between the tracks // tracks can be mixed together so we can gradually change into the new animation // Alternate tracks DWORD newTrack = ( m_currentTrack == 0 ? 1 : 0 ); // Assign to our track m_animController->SetTrackAnimationSet( newTrack, set ); set->Release(); // Clear any track events currently assigned to our two tracks m_animController->UnkeyAllTrackEvents( m_currentTrack ); m_animController->UnkeyAllTrackEvents( newTrack ); // Add an event key to disable the currently playing track kMoveTransitionTime seconds in the future m_animController->KeyTrackEnable( m_currentTrack, FALSE, m_currentTime + kMoveTransitionTime ); // Add an event key to change the speed right away so the animation completes in kMoveTransitionTime seconds m_animController->KeyTrackSpeed( m_currentTrack, 0.0f, m_currentTime, kMoveTransitionTime, D3DXTRANSITION_LINEAR ); // Add an event to change the weighting of the current track (the effect it has blended with the secon track) m_animController->KeyTrackWeight( m_currentTrack, 0.0f, m_currentTime, kMoveTransitionTime, D3DXTRANSITION_LINEAR ); // Enable the new track m_animController->SetTrackEnable( newTrack, TRUE ); // Add an event key to set the speed of the track m_animController->KeyTrackSpeed( newTrack, 1.0f, m_currentTime, kMoveTransitionTime, D3DXTRANSITION_LINEAR ); // Add an event to change the weighting of the current track (the effect it has blended with the first track) // As you can see this will go from 0 effect to total effect(1.0f) in kMoveTransitionTime seconds and the first track goes from // total to 0.0f in the same time. m_animController->KeyTrackWeight( newTrack, 1.0f, m_currentTime, kMoveTransitionTime, D3DXTRANSITION_LINEAR ); // Remember current track m_currentTrack = newTrack; } /** * \brief Go to the next animation * \author Keith Ditchburn \date 18 July 2005 */ void CXFileEntity::NextAnimation() { unsigned int newAnimationSet=m_currentAnimationSet+1; if (newAnimationSet>=m_numAnimationSets) newAnimationSet=0; SetAnimationSet(newAnimationSet); } /** * \brief Get the name of the animation * Note: altered 24/09/07 to solve a D3DX memory leak caused because I was not releasing the set after getting it * \param index - the animation set index * \return the name * \author Keith Ditchburn \date 18 July 2005 */ std::string CXFileEntity::GetAnimationSetName(unsigned int index) { if (index>=m_numAnimationSets) return "Error: No set exists"; // Get the animation set LPD3DXANIMATIONSET set; m_animController->GetAnimationSet(m_currentAnimationSet, &set ); std::string nameString(set->GetName()); set->Release(); return nameString; } double CXFileEntity::GetAnimationSetLength(unsigned int index) { if (index>=m_numAnimationSets) return 0; // Get the animation set LPD3DXANIMATIONSET set; m_animController->GetAnimationSet(m_currentAnimationSet, &set ); double pr = set->GetPeriod(); set->Release(); return pr; } int CXFileEntity::GetNumAnimationSets() { return m_numAnimationSets; } /** * \brief Slow down animation * \author Keith Ditchburn \date 18 July 2005 */ void CXFileEntity::AnimateSlower() { m_speedAdjust+=0.1f; } /** * \brief Speed up animation * \author Keith Ditchburn \date 18 July 2005 */ void CXFileEntity::AnimateFaster() { if (m_speedAdjust>0.1f) m_speedAdjust-=0.1f; } void CXFileEntity::ExportX(int exp) { char buf[200]; sprintf(buf,"models\\%i\\model_e.x",exp); int hr=D3DXSaveMeshToX(buf, m_firstMesh->MeshData.pMesh, NULL, NULL, NULL, 0, D3DXF_FILEFORMAT_TEXT); } void CXFileEntity::SetEffect(ID3DXEffect* effectF) { effect = effectF; }
[ "dreamonzzz@a43015ce-51b6-2c96-052f-f15b0ecaca65" ]
[ [ [ 1, 551 ] ] ]
31699b8b759082e3273553f8d6b0a092e5fc72ff
854ee643a4e4d0b7a202fce237ee76b6930315ec
/arcemu_svn/src/sun/src/QuestScripts/Tanaris.cpp
a5aa36199565a7db0705e09af4c932436dff2bf6
[]
no_license
miklasiak/projekt
df37fa82cf2d4a91c2073f41609bec8b2f23cf66
064402da950555bf88609e98b7256d4dc0af248a
refs/heads/master
2021-01-01T19:29:49.778109
2008-11-10T17:14:14
2008-11-10T17:14:14
34,016,391
2
0
null
null
null
null
UTF-8
C++
false
false
3,697
cpp
/* * WEmu Scripts for WEmu MMORPG Server * Copyright (C) 2008 WEmu Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "StdAfx.h" #include "Setup.h" #include "EAS/EasyFunctions.h" #define SendQuickMenu(textid) objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), textid, plr); \ Menu->SendTo(plr); class SpiritScreeches : public GossipScript { public: void GossipHello(Object* pObject, Player* plr, bool AutoSend) { if(!plr) return; GossipMenu *Menu; Creature *spirit = (Creature*)(pObject); if (spirit == NULL) return; if(plr->GetQuestLogForEntry(3520)) { objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 2039, plr); Menu->AddItem( 0, "Goodbye", 1); if(AutoSend) Menu->SendTo(plr); } } void GossipSelectOption(Object* pObject, Player* plr, uint32 Id, uint32 IntId, const char * EnteredCode) { if(!plr) return; Creature *spirit = (Creature*)(pObject); if (spirit == NULL) return; switch (IntId) { case 0: GossipHello(pObject, plr, true); break; case 1: { QuestLogEntry *en = plr->GetQuestLogForEntry(3520); if(en && en->GetMobCount(0) < en->GetQuest()->required_mobcount[0]) { en->SetMobCount(0, en->GetMobCount(0) + 1); en->SendUpdateAddKill(0); en->UpdatePlayerFields(); } if(!spirit) return; spirit->Despawn(1, 0); return; } } } void Destroy() { delete this; } }; class ScreecherSpirit : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(ScreecherSpirit); ScreecherSpirit(Creature* pCreature) : CreatureAIScript(pCreature) {} void OnLoad() { if(!_unit) return _unit->Despawn(60*1000, 0); Creature *cialo = _unit->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(_unit->GetPositionX(), _unit->GetPositionY(), _unit->GetPositionZ(), 5307); if(!cialo) return; if(!cialo->isAlive()) cialo->Despawn(1, 6*60*1000); } }; class StewardOfTime : public GossipScript { public: void GossipHello(Object* pObject, Player* Plr, bool AutoSend) { GossipMenu *Menu; if(Plr->GetQuestLogForEntry(10279) || Plr->HasFinishedQuest(10279)) { objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 9978, Plr); Menu->AddItem( 0, "Please take me to the master's lair", 1); Menu->SendTo(Plr); } } void GossipSelectOption(Object * pObject, Player* Plr, uint32 Id, uint32 IntId, const char * Code) { Creature* creat = static_cast<Creature*>(pObject); switch(IntId) { case 1: creat->CastSpell(Plr, dbcSpell.LookupEntry(34891), true); break; } } }; void SetupTanaris(ScriptMgr * mgr) { GossipScript * Screeches = (GossipScript*) new SpiritScreeches(); mgr->register_gossip_script(8612, Screeches); mgr->register_creature_script(8612, &ScreecherSpirit::Create); GossipScript * StewardOfTimeGossip = (GossipScript*) new StewardOfTime(); mgr->register_gossip_script(20142, StewardOfTimeGossip); }
[ "[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef" ]
[ [ [ 1, 150 ] ] ]
dc5897dec8c30b5e9dabfa5d3f02b539129cdc96
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Common/Models/MATHAND1/BELTCNV2.H
51cbdbd3fab337953eeadb70f3e68fdbe43b7307
[]
no_license
abcweizhuo/Test3
0f3379e528a543c0d43aad09489b2444a2e0f86d
128a4edcf9a93d36a45e5585b70dee75e4502db4
refs/heads/master
2021-01-17T01:59:39.357645
2008-08-20T00:00:29
2008-08-20T00:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,658
h
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // $Nokeywords: $ //=========================================================================== // SysCAD Copyright Kenwalt (Pty) Ltd 1992 #ifndef __BELTCNV2_H #define __BELTCNV2_H #ifndef __SC_DEFS_H #include "sc_defs.h" #endif #ifndef __M_BASE_H #include "m_base.h" #endif #ifndef __MTRLOGIC_H #include "mtrlogic.h" #endif #ifndef __SP_QUEUE_H #include "sp_queue.h" #endif #ifdef __BELTCNV2_CPP #define DllImportExport DllExport #elif !defined(MDLLIB) #define DllImportExport DllImport #else #define DllImportExport #endif //=========================================================================== //=========================================================================== // // // //=========================================================================== DEFINE_TAGOBJ(BeltCnv2); class CBeltFdPrDrive { friend class BeltCnv2; public: enum { BPC_None, BPC_FwdRev, BPC_Full}; CBeltFdPrDrive(BeltCnv2 * pBelt);//, bool AsFeed); void Advance(double TimeStep); double Speed(FlwNode*pNd) { const double SpdFrac = m_IOPtSB.Speed(pNd); return m_dMaxSpeed*Range(-1.0, SpdFrac, 1.0); } protected: BeltCnv2 * m_pBelt; long m_lCtrl; double m_dPosnReqd; double m_dPosnActual; double m_dPosnStart; double m_dMaxSpeed; double m_dPosnMin; double m_dPosnMax; CIO_MtrSpdBlk m_IOPtSB; CPwrUser m_Pwr; }; class BeltCnv2 : public MdlNode { friend class CBeltFdPrDrive; protected: typedef CArray < double, double > CWtMtrPosArray; public: CArray <CBeltFdPrDrive*, CBeltFdPrDrive*> m_FeedDrives; CArray <CBeltFdPrDrive*, CBeltFdPrDrive*> m_ProdDrives; BeltCnv2(pTagObjClass pClass_, pchar TagIn, pTaggedObject pAttach, TagObjAttachment eAttach); virtual ~BeltCnv2(); virtual void BuildDataDefn(DataDefnBlk & DDB); virtual flag DataXchg(DataChangeBlk & DCB); virtual flag ValidateData(ValidateDataBlk & VDB); virtual void CollectElectrics(CNodeElectricsArray & TSCA); virtual void ConnectElectrics(); virtual flag GetOtherData(FilingControlBlock &FCB); virtual flag PutOtherData(FilingControlBlock &FCB); virtual void SetState(eScdMdlStateActs RqdState); virtual void StartSolution(); virtual void PostConnect(int IONo); virtual void PreDisConnect(int IONo); virtual void ConfigureJoins(); virtual void StartStep(); virtual void EvalJoinPressures(long JoinMask); virtual flag EvalFlowEquations(eScdFlwEqnTasks Task, CSpPropInfo *pProps, int IONo, int FE, int LnkNo); virtual void EvalProducts(CNodeEvalIndex & NEI); virtual void EvalPowerRequired(); virtual void EvalCtrlActions(eScdCtrlTasks Tasks=CO_All); virtual void EvalDiscrete(); virtual void ClosureInfo(); virtual dword ModelStatus(); virtual flag GetModelAction(CMdlActionArray & Acts); virtual flag SetModelAction(CMdlAction & Act); virtual flag GetModelGraphic(CMdlGraphicArray & Grfs); virtual flag OperateModelGraphic(CMdlGraphicWnd & Wnd, CMdlGraphic & Grf); // ConditionBlk Override DEFINE_CI(BeltCnv2, MdlNode, 4); protected: SpQueue m_Q; CWtMtrPosArray &m_WtMtrPos; //CDVector FdPos, PrPos; CIO_MtrSpdBlk m_BeltSB; CPwrUser m_BeltPwr; CDirectFlwIO m_Spill; CDirectFlwIO m_Vent; CDirectFlwIO m_AccIn; CDirectFlwIO m_AccOut; CDirectAccCalc m_AccCalc; double m_MaxVelocity; double m_MaxSpillLoading; double m_MaxStallLoading; double m_MinLoading; long m_MaxTurnDown; long m_ProfPts; long m_ProfDispType; flag m_fShowProfile; flag m_fStartIfStalled; flag m_fWasRunning; flag m_TripperOn; double m_NLPower; double m_FLPower; double m_Power; //Strng m_SpillName; double m_TotMassPrev; double m_SpillMassPrev; double m_VentMassPrev; bool m_LBtnDn; bool m_RBtnDn; CPoint m_MousePt; }; //=========================================================================== #undef DllImportExport #endif
[ [ [ 1, 101 ], [ 103, 104 ], [ 106, 111 ], [ 118, 150 ], [ 152, 152 ], [ 157, 163 ] ], [ [ 102, 102 ], [ 105, 105 ], [ 112, 117 ], [ 151, 151 ], [ 153, 156 ] ] ]
c441cfc294ef38abaa90c7ead999208b14a13b4d
f77f105963cd6447d0f392b9ee7d923315a82ac6
/Box2DandOgre/include/GameObject/LedgeSensor.h
0eb202c10002e843228d62ab550354069b344e75
[]
no_license
GKimGames/parkerandholt
8bb2b481aff14cf70a7a769974bc2bb683d74783
544f7afa462c5a25c044445ca9ead49244c95d3c
refs/heads/master
2016-08-07T21:03:32.167272
2010-08-26T03:01:35
2010-08-26T03:01:35
32,834,451
0
0
null
null
null
null
UTF-8
C++
false
false
792
h
/*============================================================================= LedgeSensor.h Author: Matt King =============================================================================*/ #ifndef LEDGESENSOR_H #define LEDGESENSOR_H #include "GameObjectSensor.h" /// LedgeSensor is used to tell the player that there is a ledge right there /// that they can climb. class LedgeSensor : public GameObjectSensor { public: LedgeSensor(); ~LedgeSensor(){}; bool Update(double timeSinceLastFrame){ return true;}; /// Called when two fixtures begin to touch. /// Sends out the signal OnTouch to its subscribers virtual void BeginContact(ContactPoint* contact, b2Fixture* contactFixture, b2Fixture* collidedFixture); protected: }; #endif
[ "mapeki@34afb35a-be5b-11de-bb5c-85734917f5ce" ]
[ [ [ 1, 34 ] ] ]
fcea1599d8fa385a8c66ed22115927152040e2e6
6c8c4728e608a4badd88de181910a294be56953a
/UiModule/Ether/Data/OpenSimWorld.h
e354cb6c08a2661b5914588edc907248865ba77a
[ "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
995
h
// For conditions of distribution and use, see copyright notice in license.txt #ifndef incl_UiModule_OpenSimWorld_h #define incl_UiModule_OpenSimWorld_h #include "WorldInfo.h" namespace Ether { namespace Data { class OpenSimWorld : public WorldInfo { Q_OBJECT public: OpenSimWorld(QUrl login_url, QMap<QString, QVariant> grid_info, QString path_to_pixmap = QString(), QUuid id = 0) : WorldInfo(WorldTypes::OpenSim, login_url, grid_info, path_to_pixmap, id) { } public slots: void Print() { qDebug() << "<OpenSimWorld>"; qDebug() << " id: " << id(); qDebug() << " login url: " << loginUrl(); qDebug() << " image path: " << pixmapPath(); qDebug() << " grid info: " << gridInfo(); } }; } } #endif // OPENSIMWORLD_H
[ "[email protected]@5b2332b8-efa3-11de-8684-7d64432d61a3" ]
[ [ [ 1, 36 ] ] ]
c0590e7287ae137fe168e279a7ecdc2e77edb472
6caf1a340711c6c818efc7075cc953b2f1387c04
/client/DlgDeleteProject.h
883a9fbd9a244fb66ce7041ef0a29a2790bb7849
[]
no_license
lbrucher/timelis
35c68061bea68cc31ce1c68e3adbc23cb7f930b1
0fa9f8f5ef28fe02ca620c441783a1ff3fc17bde
refs/heads/master
2021-01-01T18:18:37.988944
2011-08-18T19:39:19
2011-08-18T19:39:19
2,229,915
2
1
null
null
null
null
UTF-8
C++
false
false
1,390
h
// $Id: DlgDeleteProject.h,v 1.1 2005/01/11 14:42:25 lbrucher Exp $ // #if !defined(AFX_DLGDELETEPROJECT_H__F22436B4_D63A_4CCC_96AF_B9F7FDAB38C3__INCLUDED_) #define AFX_DLGDELETEPROJECT_H__F22436B4_D63A_4CCC_96AF_B9F7FDAB38C3__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // DlgDeleteProject.h : header file // ///////////////////////////////////////////////////////////////////////////// // CDlgDeleteProject dialog class CDlgDeleteProject : public CDialog { // Construction public: CDlgDeleteProject(CWnd* pParent = NULL); // standard constructor long m_nSelectedProjectID; // Dialog Data //{{AFX_DATA(CDlgDeleteProject) enum { IDD = IDD_DELPROJECT }; CComboBox m_Projects; //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CDlgDeleteProject) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CDlgDeleteProject) virtual BOOL OnInitDialog(); virtual void OnOK(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_DLGDELETEPROJECT_H__F22436B4_D63A_4CCC_96AF_B9F7FDAB38C3__INCLUDED_)
[ [ [ 1, 51 ] ] ]
c38458f0cb47398741a01a5f7c043d56eee04c4a
dc4b6ab7b120262779e29d8b2d96109517f35551
/Dialog/TypeCStringDlg.h
162582d477c340f12bd07c4250c7e6b5676aef80
[]
no_license
cnsuhao/wtlhelper9
92daef29b61f95f44a10e3277d8835c2dd620616
681df3a014fc71597e9380b0a60bd3cd23e22efe
refs/heads/master
2021-07-17T19:59:07.143192
2009-05-18T14:24:48
2009-05-18T14:24:48
108,361,858
0
1
null
null
null
null
UTF-8
C++
false
false
2,938
h
//////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2004 Sergey Solozhentsev // Author: Sergey Solozhentsev e-mail: [email protected] // Product: WTL Helper // File: TypeCStringDlg.h // Created: 01.12.2004 9:48 // // Using this software in commercial applications requires an author // permission. The permission will be granted to everyone excluding the cases // when someone simply tries to resell the code. // This file may be redistributed by any means PROVIDING it is not sold for // profit without the authors written consent, and providing that this notice // and the authors name is included. // This file is provided "as is" with no expressed or implied warranty. The // author accepts no liability if it causes any damage to you or your computer // whatsoever. // //////////////////////////////////////////////////////////////////////////////// // TypeCStringDlg.h : Declaration of the CTypeCStringDlg #pragma once #include "../resource.h" // CTypeCStringDlg #define STYPE_ANOTHER 0 #define STYPE_WTL 1 #define STYPE_ATL 2 #define SPLACE_WHOLE 0 #define SPLACE_H 1 class CTypeCStringDlg : public CDialogImpl<CTypeCStringDlg>, public CWinDataExchange<CTypeCStringDlg> { public: CTypeCStringDlg(); ~CTypeCStringDlg(); enum { IDD = IDD_TYPECSTRINGDLG }; BEGIN_MSG_MAP(CTypeCStringDlg) MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog) COMMAND_HANDLER(IDOK, BN_CLICKED, OnClickedOK) COMMAND_HANDLER(IDCANCEL, BN_CLICKED, OnClickedCancel) COMMAND_HANDLER(IDC_RADIO_TYPE_ANOTHER, BN_CLICKED, OnBnClickRadioTypeAnother) COMMAND_HANDLER(IDC_RADIO_TYPE_WTL, BN_CLICKED, OnBnClickRadioTypeWtl) COMMAND_HANDLER(IDC_RADIO_TYPE_ATL, BN_CLICKED, OnBnClickRadioTypeAtl) END_MSG_MAP() BEGIN_DDX_MAP(CTypeCStringDlg) DDX_RADIO(IDC_RADIO_TYPE_ANOTHER, m_Type) DDX_RADIO(IDC_RADIO_PLACE_WHOLE, m_Place) DDX_CHECK(IDC_CHECK1, m_bAskAgain) END_DDX_MAP() int m_Type; int m_Place; bool m_bAskAgain; //true if stdafx.h exists bool m_bStdAfx; // Handler prototypes: // 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 OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); LRESULT OnClickedOK(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled); LRESULT OnClickedCancel(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled); LRESULT OnBnClickRadioTypeAnother(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled); LRESULT OnBnClickRadioTypeWtl(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled); LRESULT OnBnClickRadioTypeAtl(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled); };
[ "free2000fly@eea8f18a-16fd-41b0-b60a-c1204a6b73d1" ]
[ [ [ 1, 79 ] ] ]
d69ec306ff6da12c13366cdc2492c28e66329cc0
ed9ecdcba4932c1adacac9218c83e19f71695658
/n8asm/n8asm/n8asm.cpp
7f5beda865a5b4bb3ebbfe3d1ad5299a1b35e37a
[]
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
278
cpp
#include <stdio.h> #include <stdlib.h> #include "n8asm_compiler.h" int main(int argc, char ** argv) { printf("N8 Assembler - Clement JACOB - 2010\n"); N8Compiler * compiler = N8Compiler::Instance(); compiler->Compile("src.asm","src.hex"); system("PAUSE"); }
[ "clems71@52ecbd26-af3e-11de-a2ab-0da4ed5138bb" ]
[ [ [ 1, 13 ] ] ]
dd622c4b4cd19e624372fb4868e24987dca73650
99d3989754840d95b316a36759097646916a15ea
/trunk/2011_09_07_to_baoxin_gpd/ferrylibs/src/ferry/cv_geometry/OpenCV_FMC.h
2f6d2b5ba5e26ef0db1b225fea0332d6b166aa58
[]
no_license
svn2github/ferryzhouprojects
5d75b3421a9cb8065a2de424c6c45d194aeee09c
482ef1e6070c75f7b2c230617afe8a8df6936f30
refs/heads/master
2021-01-02T09:20:01.983370
2011-10-20T11:39:38
2011-10-20T11:39:38
11,786,263
1
0
null
null
null
null
UTF-8
C++
false
false
1,190
h
#pragma once #include "FundamentalMatrixCalculator.h" #include "CvMatUtil.h" using namespace ferry::cv_mat; namespace ferry { namespace cv_geometry { class OpenCV_FMC : public FundamentalMatrixCalculator { public: OpenCV_FMC(int method = CV_FM_RANSAC, double param1 = 0.5, double param2 = 0.99, CvMat* status = NULL) { this->method = method; this->param1 = param1; this->param2 = param2; this->status = status; } public: FundamentalMatrix compute(const vector<CvPoint2D32f>& x1s, const vector<CvPoint2D32f>& x2s) { CvMat* F = cvCreateMat(3, 3, CV_64FC1); int N = (int)x1s.size(); CvMat* points1 = cvCreateMat(N, 2, CV_64FC1); CvMat* points2 = cvCreateMat(N, 2, CV_64FC1); for (int i = 0; i < N; i++) { cvmSet(points1, i, 0, x1s[i].x); cvmSet(points1, i, 1, x1s[i].y); cvmSet(points2, i, 0, x2s[i].x); cvmSet(points2, i, 1, x2s[i].y); } cvFindFundamentalMat(points1, points2, F, method, param1, param2, status); cout<<"F: "<<F<<endl; cvReleaseMat(&points1); cvReleaseMat(&points2); return FundamentalMatrix(F); } private: int method; double param1; double param2; CvMat* status; }; } }
[ "ferryzhou@b6adba56-547e-11de-b413-c5e99dc0a8e2" ]
[ [ [ 1, 48 ] ] ]
e2ffc9dab6ae3daa97ab7402c4e83676d9dc70e9
5a9924aff39460fa52f1f55ff387d9ab82c3470f
/tibia76/evrebot76/tibiapacket.h
5c0438b5b815a62202a7cb732a2090556347e5dd
[]
no_license
PimentelM/evremonde
170e4f1916b0a1007c6dbe52b578db53bc6e70de
6b56e8461a602ea56f0eae47a96d340487ba987d
refs/heads/master
2021-01-10T16:03:38.410644
2010-12-04T17:31:01
2010-12-04T17:31:01
48,460,569
0
1
null
null
null
null
UTF-8
C++
false
false
1,410
h
#ifndef TIBIAPACKET_H #define TIBIAPACKET_H #include "winsock2.h" #include "tibia.h" /* Tibia Packet by Evremonde for protocol version 7.6 */ class CTibiaPacket { public: CTibiaPacket(); ~CTibiaPacket(); // -> tibia CTibia Tibia; // original winsock functions int (WINAPI *sendNext) (SOCKET s, char *buf, int len, int flags); int (WINAPI *recvNext) (SOCKET s, char *buf, int len, int flags); // -> get char *getSay(char *buf, int len); // -> send void sendPing(SOCKET socket); void sendAttack(SOCKET socket, int targetId, Attack_t attackId); void sendStop(SOCKET socket); void sendLogout(SOCKET socket); void sendMove(SOCKET socket, Direction_t direction); void sendTurn(SOCKET socket, Direction_t direction); void sendDragToSlot(SOCKET socket, int itemId, char *fromContainerName, int toSlot); void sendStack(SOCKET socket, int itemId); void sendSelectOutfit(SOCKET socket); void sendSetOutfit(SOCKET socket, Outfit_t outfitId); void sendSetOutfitColors(SOCKET socket, OutfitColor_t head, OutfitColor_t body, OutfitColor_t legs, OutfitColor_t feet); void sendShootSelf(SOCKET socket, int itemId, int itemCount); void sendShootTarget(SOCKET socket, int itemId, int itemCount); void sendUse(SOCKET socket, int itemId); void sendSay(SOCKET socket, Speak_t speak, char *message); }; #endif // #ifndef TIBIAPACKET_H
[ "evretibia@cc901e99-3b3f-0410-afbc-77a0fa429cc7" ]
[ [ [ 1, 56 ] ] ]
fe31cb8468aa7c89fe643248ef568531a9d44c45
f4a966283e1923f3160349d1090c972920aea200
/Flood/TrainingAlgorithm/GradientDescent.cpp
e82b22ff107751fd3a3e26acf177eff49f3f2ee3
[]
no_license
sachinsurendran/neural-network-classes
326bce86546d96b5ddc6b10ca000beb6337a0c20
bee9cb92da5b69878194f8f1547bc15d69e68627
refs/heads/master
2021-01-18T23:47:28.294669
2011-11-03T22:11:10
2011-11-03T22:11:10
32,112,281
0
0
null
null
null
null
UTF-8
C++
false
false
68,904
cpp
/****************************************************************************************************************/ /* */ /* Flood: An Open Source Neural Networks C++ Library */ /* www.cimne.com/flood */ /* */ /* G R A D I E N T D E S C E N T C L A S S */ /* */ /* Roberto Lopez */ /* International Center for Numerical Methods in Engineering (CIMNE) */ /* Technical University of Catalonia (UPC) */ /* Barcelona, Spain */ /* E-mail: [email protected] */ /* */ /****************************************************************************************************************/ #include "GradientDescent.h" #include <iostream> #include <fstream> #include <algorithm> #include <functional> #include <limits> #include <math.h> #include <time.h> namespace Flood { // GENERAL CONSTRUCTOR // /// General constructor. It creates a gradient descent training algorithm object associated to an objective /// functional object. /// It also initializes the class members to their default values: /// /// Training operators: /// <ul> /// <li> Train rate method = Brent; /// </ul> /// /// Training parameters: /// <ul> /// <li> First train rate: 1.0. /// <li> Bracketing factor: 2.0. /// <li> Tolerance in train rate: 1.0e-3. /// </ul> /// /// Stopping criteria: /// <ul> /// <li> Evaluation goal: -1.0e99. /// <li> Gradient norm goal: 0.0. /// <li> Maximum training time: 1.0e6. /// <li> Maximum number of epochs: 100. /// </ul> /// /// User stuff: /// <ul> /// <li> Warning train rate: 1.0e6. /// <li> Error train rate: 1.0e12. /// <li> Display: true. /// <li> Display period: 25. /// </ul> /// /// @param newObjectiveFunctional Pointer to an objective functional object. /// /// @see TrainingAlgorithm. GradientDescent::GradientDescent(ObjectiveFunctional* newObjectiveFunctional) : TrainingAlgorithm(newObjectiveFunctional) { // Training operators trainRateMethod = BrentMethod; // Training parameters firstTrainRate = 1.0e-6; bracketingFactor = 2.0; trainRateTolerance = 1.0e-6; // Stopping criteria evaluationGoal = -1.0e99; gradientNormGoal = 0.0; maximumTime = 1.0e6; maximumNumberOfEpochs = 100; // User stuff warningTrainRate = 1.0e6; errorTrainRate = 1.0e12; displayPeriod = 25; reserveTrainingDirectionHistory = false; reserveTrainingDirectionNormHistory = false; reserveTrainingRateHistory = false; } // DEFAULT CONSTRUCTOR // /// Default constructor. It creates a gradient descent training algorithm object not associated to any objective /// functional object. /// It also initializes the class members to their default values: /// /// Training operators: /// <ul> /// <li> Train rate method = Brent; /// </ul> /// /// Training parameters: /// <ul> /// <li> First train rate: 1.0. /// <li> Bracketing factor: 2.0. /// <li> Tolerance in train rate: 1.0e-3. /// </ul> /// /// Stopping criteria: /// <ul> /// <li> Evaluation goal: -1.0e99. /// <li> Gradient norm goal: 0.0. /// <li> Maximum training time: 1.0e6. /// <li> Maximum number of epochs: 100. /// </ul> /// /// User stuff: /// <ul> /// <li> Warning train rate: 1.0e6. /// <li> Error train rate: 1.0e12. /// <li> Display: true. /// <li> Display period: 25. /// </ul> /// /// @see TrainingAlgorithm. GradientDescent::GradientDescent(void) : TrainingAlgorithm() { // Training operators trainRateMethod = BrentMethod; // Training parameters firstTrainRate = 1.0; bracketingFactor = 2.0; trainRateTolerance = 1.0e-3; // Stopping criteria evaluationGoal = -1.0e99; gradientNormGoal = 0.0; maximumTime = 1.0e6; maximumNumberOfEpochs = 100; // User stuff warningTrainRate = 1.0e6; errorTrainRate = 1.0e12; displayPeriod = 25; reserveTrainingDirectionHistory = false; reserveTrainingDirectionNormHistory = false; reserveTrainingRateHistory = false; } // DESTRUCTOR /// Destructor. GradientDescent::~GradientDescent(void) { } // METHODS // TrainRateMethod getTrainRateMethod(void) method /// This method returns the train rate method used for training. /// /// @see calculateGoldenSectionTrainRate(double, double, Vector<double>, Vector<double>). /// @see calculateBrentMethodTrainRate(double, double, Vector<double>, Vector<double>). /// @see train(void). GradientDescent::TrainRateMethod GradientDescent::getTrainRateMethod(void) { return(trainRateMethod); } // double getFirstTrainRate(void) method /// This method returns the initial train rate value in line minimization. /// /// @see calculateGoldenSectionTrainRate(double, double, Vector<double>, Vector<double>). /// @see calculateBrentMethodTrainRate(double, double, Vector<double>, Vector<double>). /// @see train(void). double GradientDescent::getFirstTrainRate(void) { return(firstTrainRate); } // double getBracketingFactor(void) method /// This method returns the increase factor when bracketing a minimum in line minimization. /// /// @see calculateGoldenSectionTrainRate(double, double, Vector<double>, Vector<double>). /// @see calculateBrentMethodTrainRate(double, double, Vector<double>, Vector<double>). /// @see train(void). double GradientDescent::getBracketingFactor(void) { return(bracketingFactor); } // double getTrainRateTolerance(void) method /// This method returns the tolerance value in line minimization. /// /// @see calculateGoldenSectionTrainRate(double, double, Vector<double>, Vector<double>). /// @see calculateBrentMethodTrainRate(double, double, Vector<double>, Vector<double>). /// @see train(void). double GradientDescent::getTrainRateTolerance(void) { return(trainRateTolerance); } // double getWarningTrainRate(void) method /// This method returns the train rate value at wich a warning message is written to the screen during line /// minimization. /// /// @see calculateGoldenSectionTrainRate(double, double, Vector<double>, Vector<double>). /// @see calculateBrentMethodTrainRate(double, double, Vector<double>, Vector<double>). /// @see train(void). double GradientDescent::getWarningTrainRate(void) { return(warningTrainRate); } // double getErrorTrainRate(void) method /// This method returns the train rate value at wich the line minimization algorithm is assumed to fail when /// bracketing a minimum. /// /// @see calculateGoldenSectionTrainRate(double, double, Vector<double>, Vector<double>). /// @see calculateBrentMethodTrainRate(double, double, Vector<double>, Vector<double>). /// @see train(void). double GradientDescent::getErrorTrainRate(void) { return(errorTrainRate); } // bool getReserveTrainingDirectionHistory(void) method /// This method returns true if the training direction history matrix is to be reserved, and false otherwise. bool GradientDescent::getReserveTrainingDirectionHistory(void) { return(reserveTrainingDirectionHistory); } // bool getReserveTrainingDirectionNormHistory(void) method /// This method returns true if the training direction norm history vector is to be reserved, and false otherwise. bool GradientDescent::getReserveTrainingDirectionNormHistory(void) { return(reserveTrainingDirectionHistory); } // bool getReserveTrainingRateHistory(void) method /// This method returns true if the training rate history vector is to be reserved, and false otherwise. bool GradientDescent::getReserveTrainingRateHistory(void) { return(reserveTrainingRateHistory); } // Matrix<double> getTrainingDirectionHistory(void) method /// This method returns the training direction history matrix. Matrix<double> GradientDescent::getTrainingDirectionHistory(void) { return(trainingDirectionHistory); } // Vector<double> getTrainingDirectionNormHistory(void) method /// This method returns the training direction norm history vector. Vector<double> GradientDescent::getTrainingDirectionNormHistory(void) { return(trainingDirectionNormHistory); } // Vector<double> getTrainingRateHistory(void) method /// This method returns the training rate history vector. Vector<double> GradientDescent::getTrainingRateHistory(void) { return(trainingRateHistory); } // void setTrainRateMethod(TrainRateMethod) method /// This method sets a new train rate method to be used for training. /// /// @param newTrainRateMethod Train rate method. /// /// @see calculateGoldenSectionTrainRate(double, double, Vector<double>, Vector<double>). /// @see calculateBrentMethodTrainRate(double, double, Vector<double>, Vector<double>). /// @see train(void). void GradientDescent::setTrainRateMethod(GradientDescent::TrainRateMethod newTrainRateMethod) { trainRateMethod = newTrainRateMethod; } // void setFirstTrainRate(double) method /// This method sets a new value to be used as an initial train rate in line minimization. /// /// @param newFirstTrainRate Initial train rate value. /// /// @see calculateGoldenSectionTrainRate(double, double, Vector<double>, Vector<double>). /// @see calculateBrentMethodTrainRate(double, double, Vector<double>, Vector<double>). /// @see train(void). void GradientDescent::setFirstTrainRate(double newFirstTrainRate) { // Control sentence (if debug) #ifndef NDEBUG if(newFirstTrainRate <= 0.0) { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "void setFirstTrainRate(double) method." << std::endl << "First train rate must be greater than 0." << std::endl << std::endl; exit(1); } #endif // Set first train rate firstTrainRate = newFirstTrainRate; } // void setBracketingFactor(double) method /// This method sets a new increase factor value to be used for line minimization when bracketing a minimum. /// /// @param newBracketingFactor Bracketing factor value. /// /// @see calculateGoldenSectionTrainRate(double, double, Vector<double>, Vector<double>). /// @see calculateBrentMethodTrainRate(double, double, Vector<double>, Vector<double>). /// @see train(void). void GradientDescent::setBracketingFactor(double newBracketingFactor) { // Control sentence (if debug) #ifndef NDEBUG if(newBracketingFactor <= 0.0) { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "void setBracketingFactor(double) method." << std::endl << "Bracketing factor must be greater than 0." << std::endl << std::endl; exit(1); } #endif bracketingFactor = newBracketingFactor; } // void setTrainRateTolerance(double) method /// This method sets a new tolerance value to be used in line minimization. /// /// @param newTrainRateTolerance Tolerance value in line minimization. /// /// @see calculateGoldenSectionTrainRate(double, double, Vector<double>, Vector<double>). /// @see calculateBrentMethodTrainRate(double, double, Vector<double>, Vector<double>). /// @see train(void). void GradientDescent::setTrainRateTolerance(double newTrainRateTolerance) { // Control sentence (if debug) #ifndef NDEBUG if(newTrainRateTolerance <= 0.0) { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "void setTrainRateTolerance(double) method." << std::endl << "Tolerance must be greater than 0." << std::endl << std::endl; exit(1); } #endif // Set train rate tolerance trainRateTolerance = newTrainRateTolerance; } // void setWarningTrainRate(double) method /// This method sets a new train rate value at wich a warning message is written to the screen during line /// minimization. /// /// @param newWarningTrainRate Warning train rate value. /// /// @see calculateGoldenSectionTrainRate(double, double, Vector<double>, Vector<double>). /// @see calculateBrentMethodTrainRate(double, double, Vector<double>, Vector<double>). /// @see train(void). void GradientDescent::setWarningTrainRate(double newWarningTrainRate) { // Control sentence (if debug) #ifndef NDEBUG if(newWarningTrainRate <= 0.0) { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "void setWarningTrainRate(double) method." << std::endl << "Warning train rate must be greater than 0." << std::endl << std::endl; exit(1); } #endif warningTrainRate = newWarningTrainRate; } // void setErrorTrainRate(double) method /// This method sets a new train rate value at wich a the line minimization algorithm is assumed to fail when /// bracketing a minimum. /// /// @param newErrorTrainRate Error train rate value. /// /// @see calculateGoldenSectionTrainRate(double, double, Vector<double>, Vector<double>). /// @see calculateBrentMethodTrainRate(double, double, Vector<double>, Vector<double>). /// @see train(void). void GradientDescent::setErrorTrainRate(double newErrorTrainRate) { // Control sentence (if debug) #ifndef NDEBUG if(newErrorTrainRate <= 0.0) { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "void setErrorTrainRate(double) method." << std::endl << "Error train rate must be greater than 0." << std::endl << std::endl; exit(1); } #endif // Set error train rate errorTrainRate = newErrorTrainRate; } // void setReserveTrainingDirectionHistory(bool) method /// This method makes the training direction history matrix to be reseved or not in memory. /// /// @param newReserveTrainingDirectionHistory True if the training direction history matrix is to be reserved, /// false otherwise. void GradientDescent::setReserveTrainingDirectionHistory(bool newReserveTrainingDirectionHistory) { reserveTrainingDirectionHistory = newReserveTrainingDirectionHistory; } // void setReserveTrainingDirectionNormHistory(bool) method /// This method makes the history vector of training direction norms to be reseved or not in memory. /// /// @param newReserveTrainingDirectionNormHistory True if the training direction norm history to be reserved, /// false otherwise. void GradientDescent::setReserveTrainingDirectionNormHistory(bool newReserveTrainingDirectionNormHistory) { reserveTrainingDirectionNormHistory = newReserveTrainingDirectionNormHistory; } // void setReserveTrainingRateHistory(bool) method /// This method makes the training rate history vector to be reseved or not in memory. /// /// @param newReserveTrainingRateHistory True if the training rate history vector is to be reserved, false /// otherwise. void GradientDescent::setReserveTrainingRateHistory(bool newReserveTrainingRateHistory) { reserveTrainingRateHistory = newReserveTrainingRateHistory; } // void setReserveAllTrainingHistory(bool) method /// This method makes the training history of all variables to reseved or not in memory. /// /// @param newReserveAllTrainingHistory True if the training history of all variables is to be reserved, /// false otherwise. void GradientDescent::setReserveAllTrainingHistory(bool newReserveAllTrainingHistory) { reserveElapsedTimeHistory = newReserveAllTrainingHistory; reserveFreeParametersHistory = newReserveAllTrainingHistory; reserveFreeParametersNormHistory = newReserveAllTrainingHistory; reserveEvaluationHistory = newReserveAllTrainingHistory; reserveGradientHistory = newReserveAllTrainingHistory; reserveGradientNormHistory = newReserveAllTrainingHistory; reserveTrainingDirectionHistory = newReserveAllTrainingHistory; reserveTrainingDirectionNormHistory = newReserveAllTrainingHistory; reserveTrainingRateHistory = newReserveAllTrainingHistory; } // void setTrainingDirectionHistory(Matrix<double>) method /// This method sets a new matrix containing the training direction history over the training epochs. /// Each row in the matrix contains the training direction vector of one single epoch. /// /// @param newTrainingDirectionHistory Training direction history matrix. void GradientDescent::setTrainingDirectionHistory(Matrix<double> newTrainingDirectionHistory) { trainingDirectionHistory = newTrainingDirectionHistory; } // void setTrainingDirectionNormHistory(Vector<double>) method /// This method sets a new vector containing the training direction norm history over the training epochs. /// Each element in the vector contains the training direction norm of one single epoch. /// /// @param newTrainingDirectionNormHistory Training direction norm history vector. void GradientDescent::setTrainingDirectionNormHistory(Vector<double> newTrainingDirectionNormHistory) { trainingDirectionNormHistory = newTrainingDirectionNormHistory; } // void setTrainingRateHistory(Vector<double>) method /// This method sets a new vector containing the training rate history over the training epochs. /// Each element in the vector contains the training rate of one single epoch. /// /// @param newTrainingRateHistory Training rate history vector. void GradientDescent::setTrainingRateHistory(Vector<double> newTrainingRateHistory) { trainingRateHistory = newTrainingRateHistory; } // double calculateGoldenSectionTrainRate(double, double, Vector<double>, Vector<double>) // method /// This method returns the train rate by searching in a given direction to locate the minimum of the objective /// function in that direction. It uses the golden section method. /// /// @param initialTrainRate Initial train rate in line minimization. /// @param evaluation Network's evaluation value. /// @param freeParameters Network's free parameters vector. /// @param trainDirection Train direction vector. /// /// @see calculateBrentMethodTrainRate(double, double, Vector<double>, Vector<double>). /// @see train(void). double GradientDescent::calculateGoldenSectionTrainRate (double initialTrainRate, double evaluation, Vector<double> freeParameters, Vector<double> trainDirection) { double trainRate = 0.0; // Multilayer perceptron MultilayerPerceptron* multilayerPerceptron = objectiveFunctional->getMultilayerPerceptron(); int numberOfFreeParameters = multilayerPerceptron->getNumberOfFreeParameters(); Vector<double> potentialFreeParameters(numberOfFreeParameters); double a = 0.0; double evaluationA = 0.0; double b = 0.0; double evaluationB = 0.0; double c = 0.0; double evaluationC = 0.0; double d = 0.0; double evaluationD = 0.0; double tau = (3.0-sqrt(5.0))/2.0; // 0.382 // Start golden section search // Set initial a point a = 0.0; // Calculate evaluation for a evaluationA = evaluation; // Set initial b point b = initialTrainRate; // Calculate evaluation for b potentialFreeParameters = freeParameters + trainDirection*b; evaluationB = objectiveFunctional->calculatePotentialEvaluation(potentialFreeParameters); // Find initial interval where minimum evaluation occurs while(evaluationA > evaluationB) { // Set new b b *= bracketingFactor; if(b >= errorTrainRate) { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "double calculateGoldenSectionTrainRate" << "(double, double, Vector<double>, Vector<double>) method." << std::endl << "Unable to bracket a minimum." << std::endl; exit(1); } else if(display && b >= warningTrainRate) { std::cout << std::endl << "Flood Warning: Train rate is " << b << std::endl; } // Calculate evaluation for new b potentialFreeParameters = freeParameters + trainDirection*b; evaluationB = objectiveFunctional->calculatePotentialEvaluation(potentialFreeParameters); } // Initialize c and d (interior points for line minimization) // Initialize c point c = a + tau*(b-a); // Calculate evaluation for c potentialFreeParameters = freeParameters + trainDirection*c; evaluationC = objectiveFunctional->calculatePotentialEvaluation(potentialFreeParameters); // Initialize d point d = b - tau*(b-a); // Calculate evaluation for d potentialFreeParameters = freeParameters + trainDirection*d; evaluationD = objectiveFunctional->calculatePotentialEvaluation(potentialFreeParameters); // Reduce the interval with the golden section algorithm while(b-a > trainRateTolerance) { Vector<double> evaluationVectorLeft(3); evaluationVectorLeft[0] = evaluationA; evaluationVectorLeft[1] = evaluationC; evaluationVectorLeft[2] = evaluationD; double minimumEvaluationLeft = evaluationVectorLeft.calculateMinimum(); Vector<double> evaluationVectorRight(3); evaluationVectorRight[0] = evaluationB; evaluationVectorRight[1] = evaluationC; evaluationVectorRight[2] = evaluationD; double minimumEvaluationRight = evaluationVectorRight.calculateMinimum(); if((evaluationC <= evaluationD && evaluationB >= minimumEvaluationLeft) || (evaluationA <= minimumEvaluationRight)) // There is a minimum between a and b { b=d; d=c; evaluationB = evaluationD; evaluationD = evaluationC; // Set new c point c = a + tau*(b-a); // Calculate evaluation for new c potentialFreeParameters = freeParameters + trainDirection*c; evaluationC = objectiveFunctional->calculatePotentialEvaluation(potentialFreeParameters); } else if((evaluationD <= evaluationC && evaluationA >= minimumEvaluationRight) || (evaluationB <= minimumEvaluationLeft)) // There is a minimum between c and b { a = c; c = d; evaluationA = evaluationC; evaluationC = evaluationD; // Set new d point d = b - tau*(b-a); // Calculate evaluation for new d potentialFreeParameters = freeParameters + trainDirection*d; evaluationD = objectiveFunctional->calculatePotentialEvaluation(potentialFreeParameters); } else { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "double calculateGoldenSectionTrainRate" << "(double, double, Vector<double>, Vector<double>) method." << std::endl << "Unable to find were the minimum is." << std::endl; exit(1); } } // Get minimum evaluation and train rate among points A, B, C and D double minimumEvaluation = evaluation; trainRate = 0.0; if(evaluationA < minimumEvaluation) { minimumEvaluation = evaluationA; trainRate = a; } else if(evaluationB < minimumEvaluation) { minimumEvaluation = evaluationB; trainRate = b; } else if(evaluationC < minimumEvaluation) { minimumEvaluation = evaluationC; trainRate = c; } else if(evaluationD < minimumEvaluation) { minimumEvaluation = evaluationD; trainRate = d; } return(trainRate); } // double calculateBrentMethodTrainRate(double, double, Vector<double>, Vector<double>) // method /// This method returns the train rate by searching in a given direction to locate the minimum of the evaluation /// function in that direction. It uses the Brent's method. /// /// @param initialTrainRate Initial train rate in line minimization. /// @param evaluation Network's evaluation value. /// @param freeParameters Network's free parameters vector. /// @param trainDirection Train direction vector. /// /// @see calculateGoldenSectionTrainRate(double, double, Vector<double>, Vector<double>). /// @see train(void). double GradientDescent::calculateBrentMethodTrainRate(double initialTrainRate, double evaluation, Vector<double> freeParameters, Vector<double> trainDirection) { double trainRate = 0.0; MultilayerPerceptron* multilayerPerceptron = objectiveFunctional->getMultilayerPerceptron(); int numberOfFreeParameters = multilayerPerceptron->getNumberOfFreeParameters(); Vector<double> potentialFreeParameters(numberOfFreeParameters); double a = 0.0; double evaluationA = evaluation; double b = 0.0; double evaluationB = evaluation; double u = 0.0; double evaluationU = evaluation; double v = 0.0; double evaluationV = evaluation; double w = 0.0; double evaluationW = evaluation; double x = 0.0; double evaluationX = evaluation; // Golden number double tau = (3.0-sqrt(5.0))/2.0; // 0.382 // Start Brent search // Set initial a point a = 0.0; // Calculate evaluation for a evaluationA = evaluation; // Set initial b point b = initialTrainRate; // Calculate evaluation for b potentialFreeParameters = freeParameters + trainDirection*b; evaluationB = objectiveFunctional->calculatePotentialEvaluation(potentialFreeParameters); // Find initial interval where minimum evaluation occurs while(evaluationA > evaluationB) { // Reset a point and corresponding evaluation a = b; evaluationA = evaluationB; // Set new b b *= bracketingFactor; if(b >= errorTrainRate) { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "double calculateGoldenSectionTrainRate" << "(double, double, Vector<double>, Vector<double>) method." << std::endl << "Unable to bracket a minimum." << std::endl; exit(1); } else if(display && b >= warningTrainRate) { std::cout << std::endl << "Flood Warning: Train rate is " << b << std::endl; } // Calculate evaluation for new b potentialFreeParameters = freeParameters + trainDirection*b; evaluationB = objectiveFunctional->calculatePotentialEvaluation(potentialFreeParameters); } // Get inediate point V v = a + tau*(b-a); // Calculate evaluation for V potentialFreeParameters = freeParameters + trainDirection*v; evaluationV = objectiveFunctional->calculatePotentialEvaluation(potentialFreeParameters); // Set initial W and X points w = v; evaluationW = evaluationV; x = v; evaluationX = evaluationV; // Maximum and minimum intervals ??? bool goldenSection = false; // Reduce the interval while(b-a > trainRateTolerance) { // Quadratic interpolation if(w != x && w != v && x != v) // Can construct parabola { // zz vector Vector<double> trainRateVector(3); trainRateVector[0] = v; trainRateVector[1] = w; trainRateVector[2] = x; std::sort(trainRateVector.begin(), trainRateVector.end(), std::less<double>()); // pp vector Vector<double> evaluationVector(3); for(int i = 0; i < 3; i++) { if(trainRateVector[i] == v) { evaluationVector[i] = evaluationV; } else if(trainRateVector[i] == w) { trainRateVector[i] = evaluationW; } else if(trainRateVector[i] == x) { trainRateVector[i] = evaluationX; } else { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "double calculateBrentMethodTrainRate" << std::endl << "(double, double, Vector<double>, Vector<double>) method." << std::endl << "Unable to construct train rate and evaluation vectors right." << std::endl << std::endl; exit(1); } } // xStar is the minimum of the parabola through the three train rate points double numerator = (pow(trainRateVector[2],2) - pow(trainRateVector[1],2))*evaluationVector[0] + (pow(trainRateVector[1],2) - pow(trainRateVector[0],2))*evaluationVector[2] + (pow(trainRateVector[0],2) - pow(trainRateVector[2],2))*evaluationVector[1]; double denominator = (trainRateVector[2] - trainRateVector[1])*evaluationVector[0] + (trainRateVector[1] - trainRateVector[0])*evaluationVector[2] + (trainRateVector[0] - trainRateVector[2])*evaluationVector[1]; double xStar = 0.5*numerator/denominator; if(xStar < b && a < xStar) // xStar is in [a,b] { u = xStar; // Good, no need to perform golden section goldenSection = false; } else // xStar is not in [a,b] { // Bad, need to perform golden section goldenSection = true; } } else // Cannot construct parabola { // Bad, need to perform golden section goldenSection = true; } // // Golden section // if(goldenSection == true) { if(x >= (a+b)/2.0) { u = x-tau*(x-a); } else { u = x+tau*(b-x); } } // Calculate evaluation for U potentialFreeParameters = freeParameters + trainDirection*u; evaluationU = objectiveFunctional->calculatePotentialEvaluation(potentialFreeParameters); // Update points if(evaluationU <= evaluationX) { if(u < x) { b = x; evaluationB = evaluationX; } else { a = x; evaluationA = evaluationX; } v = w; evaluationV = evaluationW; w = x; evaluationW = evaluationX; x = u; evaluationX = evaluationU; } else { if(u < x) { a = u; evaluationA = evaluationU; } else { b = u; evaluationB = evaluationU; } if((evaluationU <= evaluationW) || (w == x)) { v = w; evaluationV = evaluationW; w = u; evaluationW = evaluationU; } else if((evaluationU <= evaluationV) || (v == x) || (v == w)) { v = u; evaluationV = evaluationU; } } } // while loop // Get minimum evaluation and train rate among points A, B, V, W and X double minimumEvaluation = evaluation; trainRate = 0.0; if(evaluationA < minimumEvaluation) { minimumEvaluation = evaluationA; trainRate = a; } else if(evaluationB < minimumEvaluation) { minimumEvaluation = evaluationB; trainRate = b; } else if(evaluationU < minimumEvaluation) { minimumEvaluation = evaluationU; trainRate = u; } else if(evaluationV < minimumEvaluation) { minimumEvaluation = evaluationV; trainRate = v; } else if(evaluationW < minimumEvaluation) { minimumEvaluation = evaluationW; trainRate = w; } else if(evaluationX < minimumEvaluation) { minimumEvaluation = evaluationX; trainRate = x; } return(trainRate); } // void train(void) method /// This method trains a multilayer perceptron with an associated objective functional according to the gradient /// descent algorithm. /// Training occurs according to the training parameters. /// /// @see TrainRateMethod. void GradientDescent::train(void) { // Control sentence (if debug) #ifndef NDEBUG if(objectiveFunctional == NULL) { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "void train(void) method." << std::endl << "Pointer to objective functional object cannot be NULL." << std::endl << std::endl; exit(1); } #endif // Multilayer perceptron stuff MultilayerPerceptron* multilayerPerceptron = objectiveFunctional->getMultilayerPerceptron(); int numberOfFreeParameters = multilayerPerceptron->getNumberOfFreeParameters(); resizeTrainingHistory(maximumNumberOfEpochs+1); // Free parameters Vector<double> freeParameters = multilayerPerceptron->getFreeParameters(); if(reserveFreeParametersHistory) { freeParametersHistory.setRow(0, freeParameters); } // Free parameters norm double freeParametersNorm = freeParameters.calculateNorm(); if(reserveFreeParametersNormHistory) { freeParametersNormHistory[0] = freeParametersNorm; } if(display && (freeParametersNorm >= warningFreeParametersNorm)) { std::cout << "Flood Warning: Initial free parameters norm is " << freeParametersNorm << "." << std::endl; } // Training time stuff time_t beginningTime, currentTime; double elapsedTime = 0.0; // Start training time(&beginningTime); if(display) { std::cout << std::endl << "Training with gradient descent..." << std::endl; } // Initial evaluation double evaluation = objectiveFunctional->calculateEvaluation(); if(reserveEvaluationHistory) { evaluationHistory[0] = evaluation; } // Initial objective function gradient Vector<double> gradient = objectiveFunctional->calculateGradient(); if(reserveGradientHistory) { gradientHistory.setRow(0, gradient); } // Initial gradient norm double gradientNorm = gradient.calculateNorm(); if(display && (gradientNorm >= warningGradientNorm)) { std::cout << "Flood Warning: Initial gradient norm is " << gradientNorm << "." << std::endl; } // Free parameters history if(reserveFreeParametersHistory) { freeParametersHistory.setRow(0, freeParameters); } // Evaluation history if(reserveEvaluationHistory) { evaluationHistory[0] = evaluation; } // Gradient norm history if(reserveGradientNormHistory) { gradientNormHistory[0] = gradientNorm; } if(display && (gradientNorm >= warningGradientNorm)) { std::cout << "Flood Warning: Initial gradient norm is " << gradientNorm << "." << std::endl; } // Elapsed time time(&currentTime); elapsedTime = difftime(currentTime, beginningTime); if(reserveElapsedTimeHistory) { elapsedTimeHistory[0] = elapsedTime; } // Stopping criteria if(evaluation <= evaluationGoal) { if(display) { std::cout << std::endl << "Initial evaluation is less than goal." << std::endl; std::cout << "Elapsed time: " << elapsedTime << ";" << std::endl; std::cout << "Initial parameters norm: " << freeParametersNorm << std::endl; std::cout << "Initial evaluation: " << evaluation << std::endl; std::cout << "Initial gradient norm: " << gradientNorm << std::endl; objectiveFunctional->print(); } resizeTrainingHistory(1); return; } else if(gradientNorm <= gradientNormGoal) { if(display) { std::cout << std::endl << "Initial gradient norm is less than goal." << std::endl; std::cout << "Elapsed time: " << elapsedTime << ";" << std::endl; std::cout << "Initial parameters norm: " << freeParametersNorm << std::endl; std::cout << "Initial evaluation: " << evaluation << std::endl; std::cout << "Initial gradient norm: " << gradientNorm << std::endl; objectiveFunctional->print(); } resizeTrainingHistory(1); return; } else { if(display) { std::cout << "Elapsed time: " << elapsedTime << ";" << std::endl; std::cout << "Initial parameters norm: " << freeParametersNorm << std::endl; std::cout << "Initial evaluation: " << evaluation << std::endl; std::cout << "Initial gradient norm: " << gradientNorm << std::endl; objectiveFunctional->print(); } } // Initialize tain direction vector Vector<double> trainDirection(numberOfFreeParameters); double trainDirectionNorm = 0.0; // Initialize train rate stuff double initialTrainRate = 0.0; double trainRate = 0.0; double oldTrainRate = 0.0; // Main loop for(int epoch = 1; epoch <= maximumNumberOfEpochs; epoch++) { // Get train direction trainDirection = gradient*(-1.0); if(reserveTrainingDirectionHistory) { trainingDirectionHistory.setRow(epoch-1, trainDirection); } // Train direction norm trainDirectionNorm = trainDirection.calculateNorm(); if(reserveTrainingDirectionNormHistory) { trainingDirectionNormHistory[epoch-1] = trainDirectionNorm; } // Get initial train rate if(epoch == 1) { initialTrainRate = firstTrainRate; } else { initialTrainRate = oldTrainRate; } // Get train rate switch(trainRateMethod) { case Fixed: trainRate = firstTrainRate; break; case GoldenSection: trainRate = calculateGoldenSectionTrainRate (initialTrainRate, evaluation, freeParameters, trainDirection); break; case BrentMethod: trainRate = calculateBrentMethodTrainRate (initialTrainRate, evaluation, freeParameters, trainDirection); break; } if(reserveTrainingRateHistory) { trainingRateHistory[epoch-1] = trainRate; } // Train rate stopping criteria if(trainRate == 0.0) { if(display) { std::cout << std::endl << "Epoch " << epoch << ": " << "Train rate is zero." << std::endl; std::cout << "Elapsed time: " << elapsedTime << ";" << std::endl; std::cout << "Final parameters norm: " << freeParametersNorm << std::endl; std::cout << "Final evaluation: " << evaluation << std::endl; std::cout << "Final gradient norm: " << gradientNorm << std::endl; objectiveFunctional->print(); } resizeTrainingHistory(epoch); break; } // Get new free parameters freeParameters = freeParameters + trainDirection*trainRate; // Set new free parameters multilayerPerceptron->setFreeParameters(freeParameters); // Free parameters history if(reserveFreeParametersHistory) { freeParametersHistory.setRow(epoch, freeParameters); } freeParametersNorm = freeParameters.calculateNorm(); if(display && (freeParametersNorm >= warningFreeParametersNorm)) { std::cout << "Flood Warning: Free parameters norm is " << freeParametersNorm << "." << std::endl; } if(reserveFreeParametersNormHistory) { freeParametersNormHistory[epoch] = freeParametersNorm; } // Objective function evaluation double oldEvaluation = evaluation; evaluation = objectiveFunctional->calculateEvaluation(); if(reserveEvaluationHistory) { evaluationHistory[epoch] = evaluation; } // Objective function gradient gradient = objectiveFunctional->calculateGradient(); if(reserveGradientHistory) { gradientHistory.setRow(epoch, gradient); } // Gradient norm gradientNorm = gradient.calculateNorm(); if(display && (gradientNorm >= warningGradientNorm)) { std::cout << "Flood Warning: Gradient norm is " << gradientNorm << "." << std::endl; } if(reserveGradientNormHistory) { gradientNormHistory[epoch] = gradientNorm; } // Elapsed time time(&currentTime); elapsedTime = difftime(currentTime, beginningTime); if(reserveElapsedTimeHistory) { elapsedTimeHistory[epoch] = elapsedTime; } // Stopping Criteria // Evaluation goal if(evaluation <= evaluationGoal) { if(display) { std::cout << std::endl << "Epoch " << epoch << ": " << "Evaluation goal reached." << std::endl; std::cout << "Elapsed time: " << elapsedTime << ";" << std::endl; std::cout << "Final parameters norm: " << freeParametersNorm << std::endl; std::cout << "Final evaluation: " << evaluation << std::endl; std::cout << "Final gradient norm: " << gradientNorm << std::endl; objectiveFunctional->print(); } resizeTrainingHistory(1+epoch); break; } // Gradient norm goal if(gradientNorm <= gradientNormGoal) { if(display) { std::cout << std::endl << "Epoch " << epoch << ": " << "Gradient norm goal reached." << std::endl; std::cout << "Elapsed time: " << elapsedTime << ";" << std::endl; std::cout << "Final parameters norm: " << freeParametersNorm << std::endl; std::cout << "Final evaluation: " << evaluation << std::endl; std::cout << "Final gradient norm: " << gradientNorm << std::endl; objectiveFunctional->print(); } resizeTrainingHistory(1+epoch); break; } // Minimum evaluation improvement double improvement = fabs(evaluation - oldEvaluation); if(improvement <= minimumImprovement) { if(display) { std::cout << std::endl << "Epoch " << epoch << ": " << "Minimum evaluation improvement reached." << std::endl; std::cout << "Elapsed time: " << elapsedTime << ";" << std::endl; std::cout << "Final parameters norm: " << freeParametersNorm << std::endl; std::cout << "Final evaluation: " << evaluation << std::endl; std::cout << "Final gradient norm: " << gradientNorm << std::endl; objectiveFunctional->print(); } resizeTrainingHistory(1+epoch); break; } // Maximum optimization time time(&currentTime); elapsedTime = difftime(currentTime, beginningTime); if(elapsedTime >= maximumTime) { if(display) { std::cout << std::endl << "Epoch " << epoch << ": " << "Maximum training time reached." << std::endl; std::cout << "Elapsed time: " << elapsedTime << ";" << std::endl; std::cout << "Final parameters norm: " << freeParametersNorm << std::endl; std::cout << "Final evaluation: " << evaluation << std::endl; std::cout << "Final gradient norm: " << gradientNorm << std::endl; objectiveFunctional->print(); } resizeTrainingHistory(1+epoch); break; } // Maximum number of epochs if(epoch == maximumNumberOfEpochs) { if(display) { std::cout << std::endl << "Epoch " << epoch << ": " << "Maximum number of epochs reached." << std::endl; std::cout << "Elapsed time: " << elapsedTime << ";" << std::endl; std::cout << "Final parameters norm: " << freeParametersNorm << std::endl; std::cout << "Final evaluation: " << evaluation << std::endl; std::cout << "Final gradient norm: " << gradientNorm << std::endl; objectiveFunctional->print(); } break; } // Progress if(display && epoch % displayPeriod == 0) { std::cout << std::endl << "Epoch " << epoch << ";" << std::endl; std::cout << "Elapsed time: " << elapsedTime << ";" << std::endl; std::cout << "Free parameters norm: " << freeParametersNorm << std::endl; std::cout << "Evaluation: " << evaluation << std::endl; std::cout << "Gradient norm: " << gradientNorm << std::endl; objectiveFunctional->print(); } // Update oldTrainRate = trainRate; } } // void print(void) method /// This method prints to the screen the training parameters, the stopping criteria and other user stuff /// concerning the gradient descent object: /// /// Training operators: /// <ul> /// <li> Train rate method. /// </ul> /// /// Training parameters: /// <ul> /// <li> Initial train rate. /// <li> Train rate tolerance. /// </ul> /// /// Stopping criteria: /// <ul> /// <li> Evaluation goal. /// <li> Gradient norm goal. /// <li> Maximum time. /// <li> Maximum number of epochs. /// </ul> /// /// User stuff: /// <ul> /// <li> Warning train rate. /// <li> Error train rate. /// <li> Display. /// <li> Display period. /// <li> Reserve elapsed time history. /// <li> Reserve free parameters history. /// <li> Reserve free parameters norm history. /// <li> Reserve evaluation history. /// <li> Reserve gradient history. /// <li> Reserve gradient norm history. /// <li> Reserve training direction history. /// <li> Reserve training direction norm history. /// <li> Reserve training rate history. /// </ul> void GradientDescent::print(void) { std::cout << std::endl << "Gradient Descent Object." << std::endl; // Training operators // Train rate method std::cout << "Train rate method:" << std::endl; switch(trainRateMethod) { case Fixed: std::cout << "Fixed" << std::endl; break; case GoldenSection: std::cout << "Golden section" << std::endl; break; case BrentMethod: std::cout << "Brent Method" << std::endl; break; } // Training parameters std::cout << "First train rate: " << std::endl << firstTrainRate << std::endl << "Train rate tolerance: " << std::endl << trainRateTolerance << std::endl; // Stopping criteria std::cout << "Evaluation goal:" << std::endl << evaluationGoal << std::endl << "Gradient norm goal:" << std::endl << gradientNormGoal << std::endl << "Maximum time:" << std::endl << maximumTime << std::endl << "Maximum number of epochs:" << std::endl << maximumNumberOfEpochs << std::endl; // User stuff std::cout << "Warning train rate:" << std::endl << warningTrainRate << std::endl << "Error train rate:" << std::endl << errorTrainRate << std::endl << "Display:" << std::endl << display << std::endl << "Display period:" << std::endl << displayPeriod << std::endl; std::cout << "Reserve elapsed time history:" << std::endl << reserveElapsedTimeHistory << std::endl << "Reserve free parameters history:" << std::endl << reserveFreeParametersHistory << std::endl << "Reserve free parameters norm history:" << std::endl << reserveFreeParametersNormHistory << std::endl << "Reserve evaluation history:" << std::endl << reserveEvaluationHistory << std::endl << "Reserve gradient history:" << std::endl << reserveGradientHistory << std::endl << "Reserve gradient norm history:" << std::endl << reserveGradientNormHistory << std::endl << "Reserve training direction history:" << std::endl << reserveTrainingDirectionHistory << std::endl << "Reserve training direction norm history:" << std::endl << reserveTrainingDirectionNormHistory << std::endl << "Reserve training rate history:" << std::endl << reserveTrainingRateHistory << std::endl; } // void save(char*) method /// This method saves the gradient descent object to a data file. /// /// Training operators: /// <ul> /// <li> Train rate method. /// </ul> /// /// Training parameters: /// <ul> /// <li> First train rate. /// <li> Train rate tolerance. /// </ul> /// /// Stopping criteria: /// <ul> /// <li> Evaluation goal. /// <li> Gradient norm goal. /// <li> Maximum time. /// <li> Maximum number of epochs. /// </ul> /// /// User stuff: /// <ul> /// <li> Warning train rate. /// <li> Error train rate. /// <li> Display. /// <li> Display period. /// <li> Reserve elapsed time history. /// <li> Reserve free parameters history. /// <li> Reserve free parameters norm history. /// <li> Reserve evaluation history. /// <li> Reserve gradient history. /// <li> Reserve gradient norm history. /// <li> Reserve training direction history. /// <li> Reserve training direction norm history. /// <li> Reserve training rate history. /// </ul> /// /// @param filename Filename. /// /// @see load(char*). void GradientDescent::save(char* filename) { // File std::fstream file; file.open(filename, std::ios::out); if(!file.is_open()) { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "void save(char*) method." << std::endl << "Cannot open gradient descent object data file." << std::endl << std::endl; exit(1); } else { if(display) { std::cout << std::endl << "Saving gradient descent object to data file..." << std::endl; } } // Write file header file << "% Flood Neural Network. Gradient Descent Object." << std::endl; // Training operators // Train direction method // Train rate method file << "TrainRateMethod:" << std::endl; switch(trainRateMethod) { case Fixed: file << "Fixed" << std::endl; break; case GoldenSection: file << "GoldenSection" << std::endl; break; case BrentMethod: file << "BrentMethod" << std::endl; break; } // Training parameters file << "FirstTrainRate:" << std::endl << firstTrainRate << std::endl << "TrainRateTolerance:" << std::endl << trainRateTolerance << std::endl; // Stopping criteria file << "EvaluationGoal:" << std::endl << evaluationGoal << std::endl << "GradientNormGoal:" << std::endl << gradientNormGoal << std::endl << "MaximumTime: " << std::endl << maximumTime << std::endl << "MaximumNumberOfEpochs: " << std::endl << maximumNumberOfEpochs << std::endl; // User stuff file << "WarningTrainRate:" << std::endl << warningTrainRate << std::endl << "ErrorTrainRate:" << std::endl << errorTrainRate << std::endl << "Display:" << std::endl << display << std::endl << "DisplayPeriod:" << std::endl << displayPeriod << std::endl; file << "ReserveElapsedTimeHistory:" << std::endl << reserveElapsedTimeHistory << std::endl << "ReserveFreeParametersHistory:" << std::endl << reserveFreeParametersHistory << std::endl << "ReserveFreeParametersNormHistory:" << std::endl << reserveFreeParametersNormHistory << std::endl << "ReserveEvaluationHistory:" << std::endl << reserveEvaluationHistory << std::endl << "ReserveGradientHistory:" << std::endl << reserveGradientHistory << std::endl << "ReserveGradientNormHistory:" << std::endl << reserveGradientNormHistory << std::endl << "ReserveTrainingDirectionHistory:" << std::endl << reserveTrainingDirectionHistory << std::endl << "ReserveTrainingDirectionNormHistory:" << std::endl << reserveTrainingDirectionNormHistory << std::endl << "ReserveTrainingRateHistory:" << std::endl << reserveTrainingRateHistory << std::endl; file.close(); } // void load(char*) method /// This method loads a gradient descent object from a data file. /// Please mind about the file format, wich is specified in the User's Guide. /// /// Training operators: /// <ul> /// <li> Train rate method. /// </ul> /// /// Training parameters: /// <ul> /// <li> Initial train rate. /// <li> Train rate tolerance. /// </ul> /// /// Stopping criteria: /// <ul> /// <li> Evaluation goal. /// <li> Gradient norm goal. /// <li> Maximum time. /// <li> Maximum number of epochs. /// </ul> /// /// User stuff: /// <ul> /// <li> Warning train rate. /// <li> Error train rate. /// <li> Display. /// <li> Display period. /// <li> Reserve elapsed time history. /// <li> Reserve free parameters history. /// <li> Reserve free parameters norm history. /// <li> Reserve evaluation history. /// <li> Reserve gradient history. /// <li> Reserve gradient norm history. /// <li> Reserve training direction history. /// <li> Reserve training direction norm history. /// <li> Reserve training rate history. /// </ul> /// /// @param filename Filename. /// /// @see save(char*). void GradientDescent::load(char* filename) { std::string word; // File std::fstream file; file.open(filename, std::ios::in); if(!file.is_open()) { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "void load(char*) method." << std::endl << "Cannot open gradient descent object data file." << std::endl; exit(1); } else { if(display) { std::cout << std::endl << "Loading gradient descent object from data file..." << std::endl; } } // Train rate method file >> word; file >> word; if(word == "Fixed") { trainRateMethod = Fixed; } else if(word == "GoldenSection") { trainRateMethod = GoldenSection; } else if(word == "BrentMethod") { trainRateMethod = BrentMethod; } else { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "void load(char*) method." << std::endl << "Unknown file format." << std::endl; exit(1); } // Training parameters // First train rate file >> word; if(word != "FirstTrainRate:") { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "void load(char*) method." << std::endl << "Unknown file format." << std::endl; exit(1); } file >> firstTrainRate; // Tolerance file >> word; if(word != "TrainRateTolerance:") { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "void load(char*) method." << std::endl << "Unknown file format." << std::endl; exit(1); } file >> trainRateTolerance; // Stopping criteria: // Evaluation goal file >> word; if(word != "EvaluationGoal:") { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "void load(char*) method." << std::endl << "Unknown file format." << std::endl; exit(1); } file >> evaluationGoal; // Gradient norm goal file >> word; if(word != "GradientNormGoal:") { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "void load(char*) method." << std::endl << "Unknown file format." << std::endl; exit(1); } file >> gradientNormGoal; // Maximum time file >> word; if(word != "MaximumTime:") { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "void load(char*) method." << std::endl << "Unknown file format." << std::endl; exit(1); } file >> maximumTime; // Maximum number of epochs file >> word; if(word != "MaximumNumberOfEpochs:") { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "void load(char*) method." << std::endl << "Unknown file format." << std::endl; exit(1); } file >> maximumNumberOfEpochs; // User stuff: // Warning train rate file >> word; if(word != "WarningTrainRate:") { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "void load(char*) method." << std::endl << "Unknown file format." << std::endl; exit(1); } file >> warningTrainRate; // Error train rate file >> word; if(word != "ErrorTrainRate:") { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "void load(char*) method." << std::endl << "Unknown file format." << std::endl; exit(1); } file >> errorTrainRate; // Display file >> word; if(word != "Display:") { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "void load(char*) method." << std::endl << "Unknown file format." << std::endl; exit(1); } file >> display; // Display period file >> word; if(word != "DisplayPeriod:") { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "void load(char*) method." << std::endl << "Unknown file format." << std::endl; exit(1); } file >> displayPeriod; // Reserve elapsed time history file >> word; if(word != "ReserveElapsedTimeHistory:") { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "void load(char*) method." << std::endl << "Unknown file format." << std::endl; exit(1); } file >> reserveElapsedTimeHistory; // Reserve free parameters history file >> word; if(word != "ReserveFreeParametersHistory:") { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "void load(char*) method." << std::endl << "Unknown file format." << std::endl; exit(1); } file >> reserveFreeParametersHistory; // Reserve free parameters norm history file >> word; if(word != "ReserveFreeParametersNormHistory:") { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "void load(char*) method." << std::endl << "Unknown file format." << std::endl; exit(1); } file >> reserveFreeParametersNormHistory; // Reserve evaluation history file >> word; if(word != "ReserveEvaluationHistory:") { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "void load(char*) method." << std::endl << "Unknown file format." << std::endl; exit(1); } file >> reserveEvaluationHistory; // Reserve gradient history file >> word; if(word != "ReserveGradientHistory:") { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "void load(char*) method." << std::endl << "Unknown file format." << std::endl; exit(1); } file >> reserveGradientHistory; // Reserve gradient norm history file >> word; if(word != "ReserveGradientNormHistory:") { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "void load(char*) method." << std::endl << "Unknown file format." << std::endl; exit(1); } file >> reserveGradientNormHistory; // Reserve training direction history file >> word; if(word != "ReserveTrainingDirectionHistory:") { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "void load(char*) method." << std::endl << "Unknown file format." << std::endl; exit(1); } file >> reserveTrainingDirectionHistory; // Reserve training direction norm history file >> word; if(word != "ReserveTrainingDirectionNormHistory:") { std::cout << std::endl << "Flood Error: GradientDescent class." << std::endl << "void load(char*) method." << std::endl << "Unknown file format." << std::endl; exit(1); } file >> reserveTrainingDirectionNormHistory; // Reserve training rate history file >> word; if(word != "ReserveTrainingRateHistory:") { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "void load(char*) method." << std::endl << "Unknown file format." << std::endl; exit(1); } file >> reserveTrainingRateHistory; // Close file file.close(); } // void resizeTrainingHistory(int) method /// This method resizes the vectors or matrices containing training history information to a new size: /// /// <ul> /// <li> Elapsed time history vector. /// <li> Free parameters history matrix. /// <li> Free parameters norm history vector. /// <li> Evaluation history vector. /// <li> Gradient history matrix. /// <li> Gradient norm history vector. /// <li> Training direction history matrix. /// <li> Training direction norm history vector /// <li> Training rate history vector. /// </ul> /// /// @param newSize Size of training history. void GradientDescent::resizeTrainingHistory(int newSize) { // Elapsed time history vector if(reserveElapsedTimeHistory) { elapsedTimeHistory.resize(newSize); } // Free parameters history matrix if(reserveFreeParametersHistory) { MultilayerPerceptron* multilayerPerceptron = objectiveFunctional->getMultilayerPerceptron(); int numberOfFreeParameters = multilayerPerceptron->getNumberOfFreeParameters(); freeParametersHistory.resize(newSize, numberOfFreeParameters); } // Free parameters norm history vector if(reserveFreeParametersNormHistory) { freeParametersNormHistory.resize(newSize); } // Evaluation history vector if(reserveEvaluationHistory) { evaluationHistory.resize(newSize); } // Gradient history matrix if(reserveGradientHistory) { MultilayerPerceptron* multilayerPerceptron = objectiveFunctional->getMultilayerPerceptron(); int numberOfFreeParameters = multilayerPerceptron->getNumberOfFreeParameters(); gradientHistory.resize(newSize, numberOfFreeParameters); } // Gradient norm history vector if(reserveGradientNormHistory) { gradientNormHistory.resize(newSize); } // Training direction history matrix if(reserveTrainingDirectionHistory) { MultilayerPerceptron* multilayerPerceptron = objectiveFunctional->getMultilayerPerceptron(); int numberOfFreeParameters = multilayerPerceptron->getNumberOfFreeParameters(); trainingDirectionHistory.resize(newSize, numberOfFreeParameters); } // Training direction norm history vector if(reserveTrainingDirectionNormHistory) { trainingDirectionNormHistory.resize(newSize); } // Training rate history vector if(reserveTrainingRateHistory) { trainingRateHistory.resize(newSize); } } // void saveTrainingHistory(char*) method /// This method saves the training history to a data file. /// /// @param filename Training history filename. void GradientDescent::saveTrainingHistory(char* filename) { std::fstream file; file.open(filename, std::ios::out); // Write file header if(!file.is_open()) { std::cerr << std::endl << "Flood Error: GradientDescent class." << std::endl << "void saveTrainingHistory(char*) method." << std::endl << "Cannot open training history data file." << std::endl << std::endl; exit(1); } else { if(display) { std::cout << std::endl << "Saving training history to data file..." << std::endl; } } // Write file header file << "% Flood Neural Network. Gradient Descent Training History." << std::endl; // Write file data if(reserveElapsedTimeHistory) { file << "ElapsedTimeHistory:" << std::endl; file << elapsedTimeHistory << std::endl; } if(reserveFreeParametersHistory) { file << "FreeParametersHistory:" << std::endl; file << freeParametersHistory << std::endl; } if(reserveFreeParametersNormHistory) { file << "FreeParametersNormHistory:" << std::endl; file << freeParametersHistory << std::endl; } if(reserveEvaluationHistory) { file << "EvaluationHistory:" << std::endl; file << evaluationHistory << std::endl; } if(reserveGradientHistory) { file << "GradientHistory:" << std::endl; file << gradientHistory << std::endl; } if(reserveGradientNormHistory) { file << "GradientNormHistory:" << std::endl; file << gradientNormHistory << std::endl; } if(reserveTrainingDirectionHistory) { file << "TrainingDirectionHistory:" << std::endl; file << trainingDirectionHistory << std::endl; } if(reserveTrainingDirectionNormHistory) { file << "TrainingDirectionNormHistory:" << std::endl; file << trainingDirectionNormHistory << std::endl; } if(reserveTrainingRateHistory) { file << "TrainingRateHistory:" << std::endl; file << trainingRateHistory << std::endl; } file.close(); } } // Flood: An Open Source Neural Networks C++ Library. // Copyright (C) 2005-2008 Roberto Lopez // // This library is free software; you can redistribute it and/or // modify it under the s of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
[ "[email protected]@676a24c8-2324-11df-bcc3-9d5e0fc24faa" ]
[ [ [ 1, 2555 ] ] ]
5493880a6aecf1f41726397d1d7e6820fbebefb4
d37a1d5e50105d82427e8bf3642ba6f3e56e06b8
/DVR/HaohanITPlayer/HWNDDLL/CWndContainer.h
561cc1ffc2406b7e5a85e3e12d7b3e07d8d01ca7
[]
no_license
080278/dvrmd-filter
176f4406dbb437fb5e67159b6cdce8c0f48fe0ca
b9461f3bf4a07b4c16e337e9c1d5683193498227
refs/heads/master
2016-09-10T21:14:44.669128
2011-10-17T09:18:09
2011-10-17T09:18:09
32,274,136
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
2,102
h
// HwndManager.h: interface for the CWndContainer class. // ////////////////////////////////////////////////////////////////////// #ifndef __CWNDCONTAINER_H #define __CWNDCONTAINER_H #include "Display.h" #include "HWndDllExport.h" class CWndContainer : public CWnd { public: CWndContainer(); virtual ~CWndContainer(); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CDisplay) public: virtual BOOL Create(LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CCreateContext* pContext = NULL); //}}AFX_VIRTUAL // Generated message map functions protected: //{{AFX_MSG(CWndContainer) afx_msg void OnPaint(); afx_msg BOOL OnEraseBkgnd(CDC* pDC); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnRButtonDown(UINT nFlags, CPoint point); afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point); //}}AFX_MSG DECLARE_MESSAGE_MAP() public: BOOL CreateWnd ( ); bool Init(HWND hParent); void Clear(); HWND GetHWnd(int index ); int GetIndex(HWND hWnd ); int GetFocus(); bool SetSplitMode(int nPlayer,int num, int order = 0); void OnUpdateFocus( POINT pt ) ; bool SetFocus( int index ); void ResizeWindow(); void SetPaintBG(int index, BOOL bPaitBG ); BOOL GetVisible(int index); //2008-08-11 void SetOsdText(int index, int line, char* text,COLORREF crColor); private: void UpdateSplitRect( int num /* 0,1,2,3,4*/ , HWND hWnd, int order = 0); void CreateWndByRect(); void UpdatePanelByRect( int order = 0); bool DrawWindow( int index ); void VisibleAll(bool bVisible); void DrawFocus( CDisplay* pDisplay, BOOL bFocus ); private: CDisplay* m_pDisplays[MAX_CLIENT_WINDOW]; RECT m_ClientRect[MAX_CLIENT_WINDOW]; int m_DisplayMode; HWND m_hParentWnd; int m_CurrentClient; int m_ClientNum; int m_SPLIT_4_order; //µÚ¼¸¸ö4·Ö¸î 0,1,2,3 }; #endif //
[ "[email protected]@27769579-7047-b306-4d6f-d36f87483bb3" ]
[ [ [ 1, 69 ] ] ]
d8cb387631523fc5f86e35cc667c63e3f50d99b6
46885801c2459416e82517f93b7d452d78b33aff
/source/world/camera.h
9f8e11390ed5c4bb351ddab73cf7d1fd659d3088
[]
no_license
libercv/smallengine
aabe92d4743789e8eab4a65d86d5a838ddc2aded
c1645fb99db213b419a81d4815a6645e1be89fe9
refs/heads/master
2021-01-10T08:09:05.991405
2009-04-01T14:52:59
2009-04-01T14:52:59
36,439,082
0
0
null
null
null
null
UTF-8
C++
false
false
394
h
#ifndef CAMERA_H #define CAMERA_H #include "entity.h" #include "../graphics/drawing3d.h" #include "../math/vector3d.h" namespace Small { class Camera : public Entity { public: void Render(void); void RotateView(int dx, int dy); void RotateView(float angle, float x, float y, float z); void Apply(void); }; // class Camera } // namespace Small #endif //CAMERA_H
[ "daviddq@3342a6a6-5e2d-0410-95e1-bf50fdd259a6", "libercv@3342a6a6-5e2d-0410-95e1-bf50fdd259a6" ]
[ [ [ 1, 22 ] ], [ [ 23, 23 ] ] ]
3283793eb6dc95afe9757176ffe1e9224c799b03
5e6ff9e6e8427078135a7b4d3b194bcbf631e9cd
/EngineSource/dpslim/dpslim/Database/Source/DBProductTree.cpp
67bf1b9d987c7e423b5a56c027913c8752929c7b
[]
no_license
karakots/dpresurrection
1a6f3fca00edd24455f1c8ae50764142bb4106e7
46725077006571cec1511f31d314ccd7f5a5eeef
refs/heads/master
2016-09-05T09:26:26.091623
2010-02-01T11:24:41
2010-02-01T11:24:41
32,189,181
0
0
null
null
null
null
UTF-8
C++
false
false
2,617
cpp
// ---------------------- // // Created 9/2/2004 // Steve Noble, DecisionPower, Inc. // // ---------------------- #include "DBProductTree.h" #include "DBModel.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // IMPLEMENT_DYNAMIC(ProductTreeRecordset, CRecordset) ProductTreeRecordset::ProductTreeRecordset(CDatabase* pdb) : CRecordset(pdb) { //{{AFX_FIELD_INIT(BrandProductRecordset) parentID = 0; childID = 0; m_nFields = 2; //m_nDefaultType = snapshot; m_nDefaultType = CRecordset::snapshot; // Using bound parameters in place of MFC filter string modification. //m_nParams = 1; } CString ProductTreeRecordset::GetDefaultConnect() { // We don't allow the record set to connect on it's own. Dynamic // creation from the view passes the document's database to // the record set. //return _T("ODBC;DSN=Test"); return _T(""); } CString ProductTreeRecordset::GetDefaultSQL() { CString tmp("SELECT parent_id, child_id FROM product_tree "); tmp += ModelRecordset::ModelQuery; return tmp; } void ProductTreeRecordset::DoFieldExchange(CFieldExchange* pFX) { // Create our own field exchange mechanism. We must do this for two // reasons. First, MFC's class wizard cannot currently determine the data // types of procedure columns. Second, we must create our own parameter // data exchange lines to take advantage of a bound ODBC input parameter. //{{AFX_FIELD_MAP(BrandProductRecordset) pFX->SetFieldType(CFieldExchange::outputColumn); RFX_Long(pFX, _T("[parent_id]"), parentID); RFX_Long(pFX, _T("[child_id]"), childID); } ///////////////////////////////////////////////////////////////////////////// #ifdef _DEBUG void ProductTreeRecordset::AssertValid() const { CRecordset::AssertValid(); } void ProductTreeRecordset::Dump(CDumpContext& dc) const { CRecordset::Dump(dc); } #endif //_DEBUG int ProductTreeRecordset::Open(unsigned int nOpenType, LPCTSTR lpszSql, DWORD dwOptions) { // Override the default behavior of the Open member function. We want to // ensure that the record set executes on the SQL Server default // (blocking) statement type. nOpenType = CRecordset::snapshot; //forwardOnly; dwOptions = CRecordset::readOnly; try { CRecordset::Open(nOpenType, GetDefaultSQL(), dwOptions); } catch (CException* e) { e->Delete(); return FALSE; } return TRUE; }
[ "Isaac.Noble@fd82578e-0ebe-11df-96d9-85c6b80b8d9c" ]
[ [ [ 1, 101 ] ] ]
b8097ad3e2967cddc9aa00763b5aac9d75286187
12732dc8a5dd518f35c8af3f2a805806f5e91e28
/trunk/CodeLite/db_record.h
a7270c7825b464e62ebd7f3f93420f3b9ebae624
[]
no_license
BackupTheBerlios/codelite-svn
5acd9ac51fdd0663742f69084fc91a213b24ae5c
c9efd7873960706a8ce23cde31a701520bad8861
refs/heads/master
2020-05-20T13:22:34.635394
2007-08-02T21:35:35
2007-08-02T21:35:35
40,669,327
0
0
null
null
null
null
UTF-8
C++
false
false
1,691
h
#ifndef CODELITE_DB_RECORD_H #define CODELITE_DB_RECORD_H #include <wx/wxsqlite3.h> #include "smart_ptr.h" #ifdef WXMAKINGDLL_CODELITE # define WXDLLIMPEXP_CL WXEXPORT #elif defined(WXUSINGDLL_CODELITE) # define WXDLLIMPEXP_CL WXIMPORT #else /* not making nor using FNB as DLL */ # define WXDLLIMPEXP_CL #endif // WXMAKINGDLL_CODELITE enum { TagOk = 0, TagExist, TagError }; /** * \ingroup CodeLite * \version 1.0 * first version * * \date 09-21-2006 * * \author Eran * Base class for any database record */ class WXDLLIMPEXP_CL DbRecord { public: DbRecord(){} virtual ~DbRecord(){} public: /** * Save this record into db. * \param insertPreparedStmnt Prepared statement for insert operation * \return TagOk, TagExist, TagError */ virtual int Store(wxSQLite3Statement& insertPreparedStmnt) = 0; /** * Update this record into db. * \param insertPreparedStmnt Prepared statement for insert operation * \return TagOk, TagError */ virtual int Update(wxSQLite3Statement& updatePreparedStmnt) = 0; /** * Delete this record from db. * \param deletePreparedStmnt Prepared statement for delete operation * \return TagOk, TagError */ virtual int Delete(wxSQLite3Statement& deletePreparedStmnt) = 0; /** * \return delete preapred statement */ virtual wxString GetDeleteOneStatement() = 0; /** * \return update preapred statement */ virtual wxString GetUpdateOneStatement() = 0; /** * \return insert preapred statement */ virtual wxString GetInsertOneStatement() = 0; }; typedef SmartPtr<DbRecord> DbRecordPtr; #endif // CODELITE_DB_RECORD_H
[ "eranif@b1f272c1-3a1e-0410-8d64-bdc0ffbdec4b" ]
[ [ [ 1, 78 ] ] ]
a5205f5e97754ae7de06b2651838e91fbb5a7705
9324000ac1cb567bd4862547cbdccf0923446095
/foliage/memory.hpp
f31d24b35ef49335a0b3d120998eb78244d56545
[]
no_license
mguillemot/kamaku.foliage
cf63d49e1e5ddd7c30b75acfc1841028d109cba4
18c225346916e240bc19bf5570a8c414bbb4153b
refs/heads/master
2016-08-03T20:09:17.929309
2007-09-04T18:15:17
2007-09-04T18:15:17
2,226,835
0
0
null
null
null
null
UTF-8
C++
false
false
3,925
hpp
#ifndef _FOLIAGE__MEMORY #define _FOLIAGE__MEMORY #include <memory> #include "basic_types.hpp" namespace Foliage { #ifdef __PPC__ class EternalPool // (64 MB) { public: static const Uint32 start = 0x08000000; static const Uint32 end = 0x0bffffff; static Uint32 current; }; class LevelPool // (64 MB) { public: static const Uint32 start = 0x0c000000; static const Uint32 end = 0x0fffffff; static Uint32 current; }; // Pool memory allocator. Memory can be cleared only for the whole pool at // one time. // WARNING: Pool overflow checks aren't made automatically for speed purposes. template <typename T, typename Pool> class PoolAllocator { public: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef T *pointer; typedef const T *const_pointer; typedef T &reference; typedef const T &const_reference; typedef T value_type; template <typename U> struct rebind { typedef PoolAllocator<U, Pool> other; }; PoolAllocator() throw() {} PoolAllocator(const PoolAllocator &) throw() {} template <typename U, typename P> PoolAllocator(const PoolAllocator<U, P> &) throw() {} ~PoolAllocator() throw() {} template <typename U, typename P> PoolAllocator& operator=(const PoolAllocator<U, P>&) throw() { return *this; } pointer address(reference value) { return &value; } const_pointer address(const_reference value) const { return &value; } pointer allocate(size_type n, const void *hint = 0) { pointer mem = (T*)Pool::current; Pool::current += n * sizeof(T); if ((Pool::current & 0x7) != 0) { // Align "Pool::current" to a multiple of 8 Pool::current = (Pool::current + 8) & 0xfffffff8; } return mem; } void deallocate(pointer addr, size_type n) { // Does nothing on purpose } size_type max_size() const throw() { return ((Pool::end - Pool::start + 1) / sizeof(T)); } void construct(pointer addr, const T &value) { new((T*)addr) T(value); } void destroy(pointer addr) { addr->~T(); } bool outOfMemory() const { return (Pool::current >= Pool::end); } void clear() { Pool::current = Pool::start; } }; template <typename T1, typename T2, typename P1, typename P2> inline bool operator==(const PoolAllocator<T1, P1>&, const PoolAllocator<T2, P2>&) throw() { return (P1::start == P2::start); } template <typename T1, typename T2, typename P1, typename P2> inline bool operator!=(const PoolAllocator<T1, P1>&, const PoolAllocator<T2, P2>&) throw() { return (P1::start != P2::start); } // Partial template specialization for "void" type template <typename Pool> class PoolAllocator<void, Pool> { public: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef void *pointer; typedef const void *const_pointer; typedef void value_type; template <typename U> struct rebind { typedef PoolAllocator<U, Pool> other; }; }; #endif void printMemoryUsage(); enum MemoryPersistance { Eternal, LevelOnly }; } void* operator new(std::size_t sz, const Foliage::MemoryPersistance pool) throw (); void operator delete(void* m, const Foliage::MemoryPersistance pool) throw (); void* operator new[](std::size_t sz, const Foliage::MemoryPersistance pool) throw (); void operator delete[](void* m, const Foliage::MemoryPersistance pool) throw (); #endif // _FOLIAGE__MEMORY
[ "erhune@1bdb3d1c-df69-384c-996e-f7b9c3edbfcf", "Erhune@1bdb3d1c-df69-384c-996e-f7b9c3edbfcf" ]
[ [ [ 1, 9 ], [ 12, 19 ], [ 21, 147 ], [ 153, 164 ] ], [ [ 10, 11 ], [ 20, 20 ], [ 148, 152 ] ] ]
af0337d20662315a393eb3b4bd3de4acb5166225
9310fd7bac6871c98b216a2e081b19e9232c14ed
/lib/agr/src/Clustering.cpp
d22a30c3ddcb79e26ddc7f39be483376bc777e76
[]
no_license
baloo/wiidrums
1345525c759a2325274ddbfe182a9549c6c4e325
ed3832d4f91cd9932bfeb321b8aa57340a502d48
refs/heads/master
2016-09-09T18:19:06.403352
2009-05-21T02:04:09
2009-05-21T02:04:09
179,309
2
0
null
null
null
null
UTF-8
C++
false
false
3,771
cpp
/** * \file Clustering.cpp * \brief Implementation for the cClustering class * \date 09/02/08 */ #include <vector> #include "Movement.h" #include "Clustering.h" namespace AGR { /*! Constructor */ cClustering::cClustering() : m_size( 0 ), m_buffer( NULL ) { } /*! Destructor */ cClustering::~cClustering() { clear(); } /*! Clear the values */ void cClustering::clear( ) { m_size = 0; m_buffer = NULL; } /*! Initialise the necessary values * \return Success */ bool cClustering::initialise( const unsigned int size, /**< Size of the buffer (Number of clusters) */ cVector3int* ptBuffer ) /**< Pointer to the buffer to be manipulated */ { if( NULL == ptBuffer || 0 == size ) { return false; } m_size = size; m_buffer = ptBuffer; return true; } /*! Create normalised vectors and their average vectors * \return Success */ bool cClustering::createNormalisedVectors( const cMovement* movementArray, /**< Array containing the movement to be processed */ const unsigned int nbMovement, /**< Number of movement in the array */ cMovement** ptNormalisedMovementArray, /**< Array used to store the normalised movement */ cMovement* ptAverageMovement, /**< Average movement */ cMovement* ptAllMovementsPoints, /**< Store all the points of all the previous movements */ unsigned int *ptMovementNormalisedSize) /**< Size used for normalised vectors, two time the average observation size (used if the pointer is not NULL) */ { // Check inputs if( NULL == movementArray || 0 == nbMovement || NULL == ptNormalisedMovementArray || NULL == ptAverageMovement || NULL == ptAllMovementsPoints ) { return false; } // calculate average size, multiply by 2 for normalised size unsigned int nbPoints = 0; unsigned int normalisedMovementSize = 0; for( unsigned int i=0; i<nbMovement; i++ ) { nbPoints += movementArray[i].getSize(); } normalisedMovementSize = (int)(nbPoints*1.5f) ; normalisedMovementSize /= nbMovement; if( NULL != ptMovementNormalisedSize ){ *ptMovementNormalisedSize = normalisedMovementSize; } ptAllMovementsPoints->initialise( nbPoints + normalisedMovementSize*(nbMovement+1) ); ptAverageMovement->initialise( normalisedMovementSize ); // Normalise vectors for( unsigned int i=0; i<nbMovement; i++ ) { cMovement::changeVectorSize( movementArray[i], normalisedMovementSize, &(*ptNormalisedMovementArray)[i] ); } // Create average vector of normalised vectors for( unsigned int i=0; i<normalisedMovementSize; i++ ) { cVector3int* ptPoint = &( ptAverageMovement->modifyBuffer()[i] ); *ptPoint = cVector3int(0, 0, 0); for( unsigned int j=0; j<nbMovement; j++ ) { *ptPoint += (*ptNormalisedMovementArray)[j].getData( i ); } *ptPoint /= nbMovement; } //---------------- // fill the allObservations buffer cVector3int* bigBuffer = ptAllMovementsPoints->modifyBuffer(); // the movements vectors points for( unsigned int i=0; i<nbMovement; i++ ) { for( unsigned int j=0; j < movementArray[i].getSize() ; j++ ) { *bigBuffer = movementArray[i].getData( j ); bigBuffer ++; } } // the normalised vectors points for( unsigned int i=0; i<nbMovement; i++ ) { for( unsigned int j=0; j<normalisedMovementSize; j++ ) { *bigBuffer = (*ptNormalisedMovementArray)[i].getData( j ); bigBuffer ++; } } // the average vector for( unsigned int j=0; j<normalisedMovementSize; j++ ) { *bigBuffer = ptAverageMovement->getData( j ); bigBuffer ++; } return true; } } // namespace AGR
[ [ [ 1, 156 ] ] ]
edb8c8d9bdd31169311102883f01493203af48e5
2d22825193eacf3669ac8bd7a857791745a9ead4
/hw2/player.cxx
f03af5c00eaf9da8924d105b3854908f9e1d3085
[]
no_license
dtbinh/com-animation-classprojects
557ba550b575c3d4efc248f7984a3faac8f052fd
37dc800a6f2bac13f5aa4fc7e0e96aa8e9cec29e
refs/heads/master
2021-01-06T20:45:42.613604
2009-01-20T00:23:11
2009-01-20T00:23:11
41,496,905
0
0
null
null
null
null
UTF-8
C++
false
false
26,315
cxx
#ifdef WIN32 #include <FL/gl.h> #endif #include <stdio.h> #include <stdlib.h> #include <string.h> // Add string functionality #include <fstream> #include <assert.h> #include <math.h> #include <process.h> #include <vector> #include <iostream> #include <GL/gl.h> // Header so that you can use GL routines (MESA) #include <GL/glu.h> // some OpenGL extensions #include <FL/glut.H> // GLUT for use with FLTK #include <FL/fl_file_chooser.H> // Allow a file chooser for save. #include "player.h" #include "interface.h" // UI framework built by FLTK (using fluid) #include "transform.h" // utility functions for vector and matrix transformation #include "display.h" #include "interpolator.h" #include "MotionGraph.h" using namespace std; /*************** Types *********************/ enum {OFF, ON}; /*************** Static Variables *********/ static Display displayer; static Skeleton *pActor = NULL; // Actor info as read from ASF file static bool bActorExist = false; // Set to true if actor exists static Motion *pSampledMotion = NULL; // Motion information as read from AMC file static Motion *pInterpMotion = NULL; // Interpolated Motion static int nFrameNum, nFrameInc=1; // Current frame and frame increment static Fl_Window *form=NULL; // Global form static MouseT mouse; // Keeping track of mouse input static CameraT camera; // Structure about camera setting static int Play=OFF, Rewind=OFF; // Some Flags for player static int Repeat=OFF, Record=OFF; static int PlayInterpMotion=ON; // Flag which desides which motion to play (pSampledMotion or pInterpMotion) static int Background=ON, Light=OFF; // Flags indicating if the object exists static char *Record_filename; // Recording file name static int recmode = 0; static int piccount=0; static char * argv2; static int maxFrames=0; std::vector <double*> line; bool path_draw = true; static MotionGraph *pMotionGraph = NULL; int CurrentFrame = -1; // Variables for FPS calculation int Frames = 0; const int UpdateTime = 1000; int LastTime = 0, CurrentTime = 0; double FPS = 0.0f; /*************** Functions *******************/ static void draw_triad() { glBegin(GL_LINES); /* draw x axis in red, y axis in green, z axis in blue */ glColor3f(1., .2, .2); glVertex3f(0., 0., 0.); glVertex3f(1., 0., 0.); glColor3f(.2, 1., .2); glVertex3f(0., 0., 0.); glVertex3f(0., 1., 0.); glColor3f(.2, .2, 1.); glVertex3f(0., 0., 0.); glVertex3f(0., 0., 1.); glEnd(); } //Draw checker board ground plane static void draw_ground() { float i, j; int count = 0; GLfloat white4[] = {.4, .4, .4, 1.}; GLfloat white1[] = {.1, .1, .1, 1.}; GLfloat green5[] = {0., .5, 0., 1.}; GLfloat green2[] = {0., .2, 0., 1.}; GLfloat black[] = {0., 0., 0., 1.}; GLfloat mat_shininess[] = {7.}; /* Phong exponent */ glBegin(GL_QUADS); for(i=-15.;i<=15.;i+=1) { for(j=-15.;j<=15.;j+=1) { if((count%2) == 0) { glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, black); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, white4); // glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, white1); // glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess); glColor3f(.6, .6, .6); } else { glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, black); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, green5); // glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, green2); // glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess); glColor3f(.8, .8, .8); } glNormal3f(0.,0.,1.); glVertex3f(j, 0, i); glVertex3f(j, 0, i+1); glVertex3f(j+1,0, i+1); glVertex3f(j+1,0, i); count++; } } glEnd(); } double* GetOGLPos(int x, int y) { GLint viewport[4]; GLdouble modelview[16]; GLdouble projection[16]; GLfloat winX, winY, winZ; GLdouble posX, posY, posZ; glGetDoublev( GL_MODELVIEW_MATRIX, modelview ); glGetDoublev( GL_PROJECTION_MATRIX, projection ); glGetIntegerv( GL_VIEWPORT, viewport ); winX = (float)x; winY = (float)viewport[3] - (float)y; glReadPixels( x, int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ ); gluUnProject( winX, winY, winZ, modelview, projection, viewport, &posX, &posY, &posZ); double* pos = new double[3]; pos[0] = posX; pos[1] = posY; pos[2] = posZ; return pos; } void cameraView(void) { glTranslated(camera.tx, camera.ty, camera.tz); glTranslated(camera.atx, camera.aty, camera.atz); glRotated(-camera.tw, 0.0, 1.0, 0.0); glRotated(-camera.el, 1.0, 0.0, 0.0); glRotated(camera.az, 0.0, 1.0, 0.0); glTranslated(-camera.atx, -camera.aty, -camera.atz); glScaled(camera.zoom, camera.zoom, camera.zoom); } /* * redisplay() is called by Player_Gl_Window::draw(). * * The display is double buffered, and FLTK swap buffers when * Player_Gl_Window::draw() returns. The GL context associated with this * instance of Player_Gl_Window is set to be the current context by FLTK * when it calls draw(). */ static void redisplay() { if(Light) glEnable(GL_LIGHTING); else glDisable(GL_LIGHTING); /* clear image buffer to black */ glClearColor(0, 0, 0, 0); glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); /* clear image, zbuf */ glPushMatrix(); /* save current transform matrix */ cameraView(); glLineWidth(2.); /* we'll draw background with thick lines */ if (Background) draw_ground(); if(mouse.button==1 && path_draw) { double* temp = GetOGLPos(mouse.x, mouse.y); if(line.size()) { double* temp2 = line[line.size()-1]; if(temp[0]!=temp2[0] || temp[2]!=temp2[2]) line.push_back(temp); } else line.push_back(temp); } for(int i=1;i<line.size();i++) { glBegin(GL_LINES); glColor3f(1., 0.0f, 0.0f); double* temp1 = line[i-1]; double* temp2 = line[i]; glVertex3f(line[i-1][0], 0.002f, line[i-1][2]); glVertex3f(line[i ][0], 0.002f, line[i ][2]); glEnd(); } if(Background) draw_triad(); /* draw a triad in the origin of the world coord */ if (bActorExist) displayer.show(); glPopMatrix(); /* restore current transform matrix */ } /* Callbacks from form. */ void redisplay_proc(Fl_Light_Button *obj, long val) { Light = light_button->value(); Background = background_button->value(); glwindow->redraw(); } void switchmode_proc(Fl_Light_Button *obj, long val) { path_draw = !path_draw; } //Interpolate loaded motion using linear interpolation void interpolate_callback(Fl_Button *button, void *) { if (pMotionGraph) if (line.size() > 1) { pMotionGraph->doPathSynthesis(line); } else { CurrentFrame = pMotionGraph->m_MaxSCCRoot->m_FrameIndex; displayer.m_pActor[0]->setPosture(pMotionGraph->m_pPostures[CurrentFrame]); } } void load_callback(Fl_Button *button, void *) { char *filename; if(button==loadActor_button) { filename = fl_file_chooser("Select filename","*.ASF",""); if(filename != NULL) { //Remove old actor //if(pActor != NULL) // delete pActor; //Read skeleton from asf file pActor = new Skeleton(filename, MOCAP_SCALE); //Set the rotations for all bones in their local coordinate system to 0 //Set root position to (0, 0, 0) pActor->setBasePosture(); displayer.loadActor(pActor); bActorExist = true; glwindow->redraw(); } } if(button==loadMotion_button) { if (bActorExist == true) { filename = fl_file_chooser("Select filename","*.AMC",""); if(filename != NULL) { //delete old motion if any //if (pSampledMotion != NULL) //{ // delete pSampledMotion; // pSampledMotion = NULL; //} //if (pInterpMotion != NULL) //{ // delete pInterpMotion; // pInterpMotion = NULL; //} //Read motion (.amc) file and create a motion pSampledMotion = new Motion(filename, MOCAP_SCALE,pActor); //set sampled motion for display displayer.loadMotion(pSampledMotion); //Tell actor to perform the first pose ( first posture ) // pActor->setPosture(displayer.m_pMotion->m_pPostures[0]); maxFrames = 0; if ( (displayer.m_pMotion[displayer.numActors-1]->m_NumFrames - 1) > maxFrames) { maxFrames = (displayer.m_pMotion[displayer.numActors-1]->m_NumFrames - 1); frame_slider->maximum((double)maxFrames+1); } nFrameNum=(int) frame_slider->value() -1; // display for (int i = 0; i < displayer.numActors; i++) displayer.m_pActor[i]->setPosture(displayer.m_pMotion[i]->m_pPostures[displayer.m_pMotion[i]->GetPostureNum(nFrameNum)]); Fl::flush(); glwindow->redraw(); } } } glwindow->redraw(); } void save_callback(Fl_Button *button, void *) { //char *filename; if(button==save_button) glwindow->save(fl_file_chooser("Save to Jpeg File", "*.jpg", "")); } void play_callback(Fl_Button *button, void *) { if(displayer.m_pMotion[0] != NULL) { if(button==play_button) { Play=ON; Rewind=OFF; } if(button==pause_button){ Play=OFF; Repeat=OFF; } if(button==repeat_button) { Rewind=OFF; Play=ON; Repeat=ON; } if(button==rewind_button) { Rewind=ON; Play=OFF; Repeat=OFF; } } } void record_callback(Fl_Light_Button *button, void *) { int current_state = (int) button->value(); if(Play == OFF) { if(Record == OFF && current_state == ON) { Record_filename = fl_file_chooser("Save Animation to Jpeg Files", "", ""); if(Record_filename != NULL) Record = ON; } if(Record == ON && current_state == OFF) Record = OFF; } button->value(Record); } void idle(void*) { bool flag = true; if (line.size() && pMotionGraph->buffer.size()) { displayer.m_pActor[0]->setPosture(pMotionGraph->buffer[pMotionGraph->m_BufferIndex]); if (pMotionGraph->m_BufferIndex+1 < pMotionGraph->buffer.size()) pMotionGraph->m_BufferIndex++; } if(CurrentFrame != -1) { printf("CurrentFrame = %d\n", CurrentFrame); printf("buffer size = %d\n", pMotionGraph->buffer.size()); CurrentFrame = pMotionGraph->Traverse1(CurrentFrame, flag); if (pMotionGraph->buffer.size() > 0) { displayer.m_pActor[0]->setPosture(pMotionGraph->buffer[pMotionGraph->m_BufferIndex]); if (pMotionGraph->m_BufferIndex+1 < pMotionGraph->buffer.size()) pMotionGraph->m_BufferIndex++; if (pMotionGraph->buffer.size() > 1000) { pMotionGraph->GenerateMotion(1000, 0, "OutputMotion.amc"); exit(0); } } } /*else if (displayer.m_pMotion[0] != NULL) { if(Rewind==ON) { nFrameNum=0; for (int i = 0; i < displayer.numActors; i++) displayer.m_pActor[i]->setPosture(displayer.m_pMotion[i]->m_pPostures[displayer.m_pMotion[i]->GetPostureNum(nFrameNum)]); Rewind=OFF; } if(Play==ON) { if(nFrameNum >= maxFrames) { if(Repeat == ON) { nFrameNum=0; for (int i = 0; i < displayer.numActors; i++) displayer.m_pActor[i]->setPosture(displayer.m_pMotion[i]->m_pPostures[displayer.m_pMotion[i]->GetPostureNum(nFrameNum)]); } else { for (int i = 0; i < displayer.numActors; i++) displayer.m_pActor[i]->setPosture(displayer.m_pMotion[i]->m_pPostures[displayer.m_pMotion[i]->GetPostureNum(nFrameNum)]); } } else for (int i = 0; i < displayer.numActors; i++) displayer.m_pActor[i]->setPosture(displayer.m_pMotion[i]->m_pPostures[displayer.m_pMotion[i]->GetPostureNum(nFrameNum)]); if(Record==ON) glwindow->save(Record_filename); if (nFrameNum < maxFrames) nFrameNum += nFrameInc; } }*/ frame_slider->value((double)nFrameNum+1); glwindow->redraw(); // Calculate FPS Frames++; if ( (GetTickCount() - LastTime) > UpdateTime ) { FPS = ((double)Frames/(double)(GetTickCount()-LastTime)) * 1000.0f; LastTime = GetTickCount(); Frames = 0; } // Adjust to 30 fps while ( (GetTickCount() - CurrentTime) < 30) {} CurrentTime = GetTickCount(); //printf("FPS:%f\n", FPS); } void fslider_callback(Fl_Value_Slider *slider, long val) { if (displayer.m_pMotion[0] != NULL) { if(displayer.m_pMotion[0]->m_NumFrames > 0) { nFrameNum=(int) frame_slider->value()-1; for (int i = 0; i < displayer.numActors; i++) // if(displayer.m_pMotion[i]->m_NumFrames > 0) displayer.m_pActor[i]->setPosture(displayer.m_pMotion[i]->m_pPostures[displayer.m_pMotion[i]->GetPostureNum(nFrameNum)]); Fl::flush(); glwindow->redraw(); } } } // locate rotation center at the (root.x, 0, root.z) void locate_callback(Fl_Button *obj, void *) { if(bActorExist && displayer.m_pMotion[0] != NULL) { camera.zoom = 1; camera.atx = pActor->m_RootPos[0]; camera.aty = 0; camera.atz = pActor->m_RootPos[2]; } glwindow->redraw(); } void valueIn_callback(Fl_Value_Input *obj, void *) { displayer.m_SpotJoint = (int) joint_idx->value(); nFrameInc = (int) fsteps->value(); glwindow->redraw(); } void sub_callback(Fl_Value_Input *obj, void*) { int subnum; subnum = (int)sub_input->value(); if (subnum < 0) sub_input->value(0); else if (subnum > displayer.numActors-1) sub_input->value(displayer.numActors-1); else { // Change values of other inputs to match subj num dt_input->value(displayer.m_pMotion[subnum]->offset); tx_input->value(displayer.m_pActor[subnum]->tx); ty_input->value(displayer.m_pActor[subnum]->ty); tz_input->value(displayer.m_pActor[subnum]->tz); rx_input->value(displayer.m_pActor[subnum]->rx); ry_input->value(displayer.m_pActor[subnum]->ry); rz_input->value(displayer.m_pActor[subnum]->rz); } glwindow->redraw(); } void dt_callback(Fl_Value_Input *obj, void*) { int subnum,max = 0; subnum = (int)sub_input->value(); if (subnum < displayer.numActors && subnum >= 0) { displayer.m_pMotion[subnum]->SetTimeOffset((int)dt_input->value()); printf("Shifting subject %d by %d\n",subnum,(int)dt_input->value()); for (int i = 0; i < displayer.numActors; i++) { if ((displayer.m_pMotion[i]->m_NumFrames - 1 - displayer.m_pMotion[i]->offset) > max) max = (displayer.m_pMotion[i]->m_NumFrames - 1 - displayer.m_pMotion[i]->offset); } maxFrames = max; frame_slider->maximum((double)maxFrames+1); displayer.m_pActor[subnum]->setPosture(displayer.m_pMotion[subnum]->m_pPostures[displayer.m_pMotion[subnum]->GetPostureNum(nFrameNum)]); } glwindow->redraw(); } void tx_callback(Fl_Value_Input *obj, void*) { int subnum = 0; subnum = (int)sub_input->value(); if (subnum < displayer.numActors && subnum >= 0) { displayer.m_pActor[subnum]->tx = (int)tx_input->value(); } glwindow->redraw(); } void ty_callback(Fl_Value_Input *obj, void*) { int subnum = 0; subnum = (int)sub_input->value(); if (subnum < displayer.numActors && subnum >= 0) { displayer.m_pActor[subnum]->ty = (int)ty_input->value(); } glwindow->redraw(); } void tz_callback(Fl_Value_Input *obj, void*) { int subnum = 0; subnum = (int)sub_input->value(); if (subnum < displayer.numActors && subnum >= 0) { displayer.m_pActor[subnum]->tz = (int)tz_input->value(); } glwindow->redraw(); } void rx_callback(Fl_Value_Input *obj, void*) { int subnum = 0; subnum = (int)sub_input->value(); if (subnum < displayer.numActors && subnum >= 0) { displayer.m_pActor[subnum]->rx = (int)rx_input->value(); } glwindow->redraw(); } void ry_callback(Fl_Value_Input *obj, void*) { int subnum = 0; subnum = (int)sub_input->value(); if (subnum < displayer.numActors && subnum >= 0) { displayer.m_pActor[subnum]->ry = (int)ry_input->value(); } glwindow->redraw(); } void rz_callback(Fl_Value_Input *obj, void*) { int subnum = 0; subnum = (int)sub_input->value(); if (subnum < displayer.numActors && subnum >= 0) { displayer.m_pActor[subnum]->rz = (int)rz_input->value(); } glwindow->redraw(); } void exit_callback(Fl_Button *obj, long val) { //DEBUG: uncomment exit(1); } void light_init() { /* set up OpenGL to do lighting * we've set up three lights */ /* set material properties */ GLfloat white8[] = {.8, .8, .8, 1.}; GLfloat white2[] = {.2, .2, .2, 1.}; GLfloat black[] = {0., 0., 0., 1.}; GLfloat mat_shininess[] = {50.}; /* Phong exponent */ GLfloat light0_position[] = {-25., 25., 25., 0.}; /* directional light (w=0) */ GLfloat white[] = {11., 11., 11., 5.}; GLfloat light1_position[] = {-25., 25., -25., 0.}; GLfloat red[] = {1., .3, .3, 5.}; GLfloat light2_position[] = {25., 25., -5., 0.}; GLfloat blue[] = {.3, .4, 1., 25.}; glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, white2); /* no ambient */ glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, white8); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, white2); glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess); /* set up several lights */ /* one white light for the front, red and blue lights for the left & top */ glLightfv(GL_LIGHT0, GL_POSITION, light0_position); glLightfv(GL_LIGHT0, GL_DIFFUSE, white); glLightfv(GL_LIGHT0, GL_SPECULAR, white); glEnable(GL_LIGHT0); glLightfv(GL_LIGHT1, GL_POSITION, light1_position); glLightfv(GL_LIGHT1, GL_DIFFUSE, red); glLightfv(GL_LIGHT1, GL_SPECULAR, red); glEnable(GL_LIGHT1); glLightfv(GL_LIGHT2, GL_POSITION, light2_position); glLightfv(GL_LIGHT2, GL_DIFFUSE, blue); glLightfv(GL_LIGHT2, GL_SPECULAR, blue); glEnable(GL_LIGHT2); //mstevens GLfloat light3_position[] = {0., -25., 0., 0.6}; glLightfv(GL_LIGHT3, GL_POSITION, light3_position); glLightfv(GL_LIGHT3, GL_DIFFUSE, white); glLightfv(GL_LIGHT3, GL_SPECULAR, white); glEnable(GL_LIGHT3); glEnable(GL_NORMALIZE); /* normalize normal vectors */ glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE); /* two-sided lighting*/ /* do the following when you want to turn on lighting */ if(Light) glEnable(GL_LIGHTING); else glDisable(GL_LIGHTING); } static void error_check(int loc) { /* this routine checks to see if OpenGL errors have occurred recently */ GLenum e; while ((e = glGetError()) != GL_NO_ERROR) fprintf(stderr, "Error: %s before location %d\n", gluErrorString(e), loc); } void gl_init() { int red_bits, green_bits, blue_bits; struct {GLint x, y, width, height;} viewport; glEnable(GL_DEPTH_TEST); /* turn on z-buffer */ glGetIntegerv(GL_RED_BITS, &red_bits); glGetIntegerv(GL_GREEN_BITS, &green_bits); glGetIntegerv(GL_BLUE_BITS, &blue_bits); glGetIntegerv(GL_VIEWPORT, &viewport.x); printf("OpenGL window has %d bits red, %d green, %d blue; viewport is %dx%d\n", red_bits, green_bits, blue_bits, viewport.width, viewport.height); /* setup perspective camera with OpenGL */ glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(/*vertical field of view*/ 45., /*aspect ratio*/ (double) viewport.width/viewport.height, /*znear*/ .1, /*zfar*/ 50.); /* from here on we're setting modeling transformations */ glMatrixMode(GL_MODELVIEW); //Move away from center glTranslatef(0., 0., -5.); camera.zoom = 1; camera.tw = 0; camera.el = -15; camera.az = -25; camera.atx = 0; camera.aty = 0; camera.atz = 0; } /******************* * Define the methods for glwindow, a subset of Fl_Gl_Window. *******************/ /* * Handle keyboard and mouse events. Don't make any OpenGL calls here; * the GL Context is not set! Make the calls in redisplay() and call * the redraw() method to cause FLTK to set up the context and call draw(). * See the FLTK documentation under "Using OpenGL in FLTK" for additional * tricks and tips. */ int Player_Gl_Window::handle(int event) { int handled = 1; static int prev_x, prev_y; int delta_x=0, delta_y=0; float ev_x, ev_y; switch(event) { case FL_RELEASE: mouse.x = (Fl::event_x()); mouse.y = (Fl::event_y()); mouse.button = 0; break; case FL_PUSH: mouse.x = (Fl::event_x()); mouse.y = (Fl::event_y()); mouse.button = (Fl::event_button()); break; case FL_DRAG: mouse.x = (Fl::event_x()); mouse.y = (Fl::event_y()); delta_x=mouse.x-prev_x; delta_y=mouse.y-prev_y; if(mouse.button == 1 && !path_draw) { if(abs(delta_x) > abs(delta_y)) camera.az += (GLdouble) (delta_x); else camera.el -= (GLdouble) (delta_y); } else if(mouse.button==2) { if(abs(delta_y) > abs(delta_x)) { glScalef(1+delta_y/100.,1+delta_y/100.,1+delta_y/100.); // camera.zoom -= (GLdouble) delta_y/100.0; // if(camera.zoom < 0.) camera.zoom = 0; } } else if(mouse.button==3){ //camera.tx += (GLdouble) delta_x/10.0; //camera.tz -= (GLdouble) delta_y/10.0; //FLTK's origin is at the left_top corner camera.tx += (GLdouble) cos(camera.az/180.0*3.141)*delta_x/10.0; camera.tz += (GLdouble) sin(camera.az/180.0*3.141)*delta_x/10.0; camera.ty -= (GLdouble) delta_y/10.0; //FLTK's origin is at the left_top corner camera.atx = -camera.tx; camera.aty = -camera.ty; camera.atz = -camera.tz; } break; case FL_KEYBOARD: switch (Fl::event_key()) { case 'q': case 'Q': case 65307: exit(0); } break; default: // pass other events to the base class... handled= Fl_Gl_Window::handle(event); } prev_x=mouse.x; prev_y=mouse.y; glwindow->redraw(); return (handled); // Returning one acknowledges that we handled this event } /* Prewritten Save Function */ void Player_Gl_Window::save (char *filename) { /*int i; int j; static char anim_filename[512]; static Pic *in = NULL; sprintf(anim_filename, "%05d.jpg", piccount++); if (filename == NULL) return; //Allocate a picture buffer. if(in == NULL) in = pic_alloc(640,480,3,NULL); printf("File to save to: %s\n", anim_filename); for (i=479; i>=0; i--) { glReadPixels(0,479-i,640,1,GL_RGB, GL_UNSIGNED_BYTE, &in->pix[i*in->nx*in->bpp]); } if (jpeg_write(anim_filename, in)) printf("%s saved Successfully\n", anim_filename); else printf("Error in Saving\n");*/ } /* Prewritten Draw Function. */ void Player_Gl_Window::draw () { //Upon setup of the window (or when Fl_Gl_Window->invalidate is called), //the set of functions inside the if block are executed. if (!valid()) { /* if (fopen("Skeleton.ASF", "r") == NULL) { printf("Program can't run without 'Skeleton.ASF'!.\n" "Please make sure you place a 'Skeleton.ASF' file to working directory.\n"); exit(1); }*/ gl_init(); light_init(); } //Redisplay the screen then put the proper buffer on the screen. redisplay(); } int main(int argc, char **argv) { /* initialize form, sliders and buttons*/ form = make_window(); light_button->value(Light); background_button->value(Background); record_button->value(Record); frame_slider->value(1); /*show form, and do initial draw of model */ form->show(); glwindow->show(); /* glwindow is initialized when the form is built */ if (argc > 2) { char *filename; if(1==1) { filename = argv[1]; if(filename != NULL) { //Remove old actor if(pActor != NULL) delete pActor; //Read skeleton from asf file pActor = new Skeleton(filename, MOCAP_SCALE); //Set the rotations for all bones in their local coordinate system to 0 //Set root position to (0, 0, 0) pActor->setBasePosture(); displayer.loadActor(pActor); bActorExist = true; } } if(1==1) { if (bActorExist == true) { argv2 = filename = argv[2]; if(filename != NULL) { //delete old motion if any if (pSampledMotion != NULL) { delete pSampledMotion; pSampledMotion = NULL; } if (pInterpMotion != NULL) { delete pInterpMotion; pInterpMotion = NULL; } //--- Create a motion graph from a batch of parameters --- if (argc > 3) { pMotionGraph = new MotionGraph(); pMotionGraph->setActor(pActor); for (int i = 2; i < argc; i++) { pSampledMotion = new Motion(argv[i], MOCAP_SCALE, pActor); pMotionGraph->Concatenate(*pSampledMotion); delete pSampledMotion; } cout << "NumMotions in MotionGraph = " << pMotionGraph->m_NumMotions << endl; pMotionGraph->Construct(); } //Read motion (.amc) file and create a motion pSampledMotion = new Motion(filename, MOCAP_SCALE,pActor); //set sampled motion for display displayer.loadMotion(pSampledMotion); maxFrames = (displayer.m_pMotion[displayer.numActors-1]->m_NumFrames - 1); frame_slider->maximum((double)maxFrames+1); //Tell actor to perform the first pose ( first posture ) pActor->setPosture(displayer.m_pMotion[0]->m_pPostures[0]); //frame_slider->maximum((double)displayer.m_pMotion[0]->m_NumFrames ); nFrameNum=0; } } else printf("Load Actor first.\n"); nFrameInc=4; // Current frame and frame increment Play=ON; // Some Flags for player Repeat=OFF; Record=ON; //Background=OFF; Light=OFF; // Flags indicating if the object exists Record_filename = ""; // Recording file name recmode=1; } glwindow->redraw(); } Fl::add_idle(idle); return Fl::run(); }
[ "grahamhuang@73147322-a748-11dd-a8c6-677c70d10fe4" ]
[ [ [ 1, 992 ] ] ]
f7974d6702bbe23cb44bdc648c89e19ee3bc5053
7e1e3e63b025cee308855ff92ed07748f28d3044
/code/ElectronicElections/src/BPlusTreeTests/SequenceTreeBlockTests.h
cd710e8c4a5d5804f94898bb2f11eaa9a2f213a6
[]
no_license
dschenkelman/datos11
d4829bd1cf60e1f7ca8d0c84e8c89911c15a87d8
616289c49bb66ebac16b7bcb5cf414b9c4e1d6db
refs/heads/master
2021-01-13T01:59:55.736042
2011-11-26T17:22:11
2011-11-26T17:22:11
32,222,112
0
0
null
null
null
null
UTF-8
C++
false
false
613
h
/* * SequenceTreeBlockTests.h * * Created on: 08/10/2011 * Author: JuanMa */ #ifndef SEQUENCETREEBLOCKTESTS_H_ #define SEQUENCETREEBLOCKTESTS_H_ #include "../BPlusTree/SequenceTreeBlock.h" #include "../Entities/DistrictMethods.h" #include <string> class SequenceTreeBlockTests { void printResult(std::string testName, bool result); DistrictMethods districtMethods; SequenceTreeBlock* block1; public: SequenceTreeBlockTests(); bool testPopFirstWorksCorrectly(); void print(); void run(); virtual ~SequenceTreeBlockTests(); }; #endif /* SEQUENCETREEBLOCKTESTS_H_ */
[ "[email protected]@f9f0a831-8b36-b70b-cf23-ca8cda4a889e" ]
[ [ [ 1, 26 ] ] ]
8781e9502939e715bcb95bfb34a01f949d139935
b6e4ffc4a7ffd9c74284bfde80b4a23577991039
/ofMarFader/src/testApp.cpp
d9c9cda544aeb8af238e95af959b9b76f198820b
[]
no_license
UIKit0/ofxMarsyasApps
e88e7376995d93361d8fdd93bc7cac0f14e6c9ba
0f639341c465a5f9f7c672e6dbee084ea450f386
refs/heads/master
2021-01-18T10:45:19.567100
2011-03-13T23:15:21
2011-03-13T23:15:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,235
cpp
#include "testApp.h" #ifdef USE_CVD #include <cvd/gl_helpers.h> #endif #define VIDEO_WIDTH 640 #define VIDEO_HEIGHT 480 #define VIDEO_SIZE VIDEO_WIDTH,VIDEO_HEIGHT //-------------------------------------------------------------- void testApp::setup() { // ofSoundStreamListDevices(); ofSetBackgroundAuto(true); ofBackground(0,0,0); ofSetFrameRate(1000/(10)); glutSetWindowTitle("PhaseVocoder"); font.loadFont("fonts/HelveticaBold.ttf", 12); font_sm.loadFont("fonts/Helvetica.ttf", 9); cvGrabber.listDevices(); cvGrabber.initGrabber(VIDEO_SIZE); videoSize.set(VIDEO_SIZE); cameraGrabber.initGrabber(640,480); cameraImage.allocate(640,480, OF_IMAGE_COLOR); #ifdef USE_FIDUCIAL_TRACKER fiducials.pixels = cvGrabber.getPixels(); fiducials.videoSize.x = videoSize.x; fiducials.videoSize.y = videoSize.y; fiducials.width = 200; fiducials.height = 200 * VIDEO_HEIGHT/VIDEO_WIDTH; fiducials.setup(); fiducialImages.resize(12); for (int i=0; i<fiducialImages.size(); i++) fiducialImages[i].loadImage(string("fiducials/")+ofToString(i)+".png"); mixer.fiducials = &fiducials.tracker.fiducialsList; #endif /* mixer.addChannel(9, ofToDataPath("flute.wav")); mixer.addChannel(2, ofToDataPath("flute2.wav")); mixer.addChannel(6, ofToDataPath("pluck.wav")); */ mixer.addChannel(9, ofToDataPath("gravity.wav")); mixer.addChannel(2, ofToDataPath("jazz.wav")); mixer.addChannel(6, ofToDataPath("prodigy.wav")); #ifdef USE_SKIN_DETECTOR skin.pixels = cvGrabber.getPixels(); skin.videoSize.x = videoSize.x; skin.videoSize.y = videoSize.y; skin.width = 200; skin.height = 200 * VIDEO_HEIGHT/VIDEO_WIDTH; skin.setup(); #endif } //-------------------------------------------------------------- void testApp::update() { cvGrabber.grabFrame(); cameraGrabber.grabFrame(); if (cvGrabber.isFrameNew()) { CVD::BasicImage<CVD::Rgb<CVD::byte> > grabRGB((CVD::Rgb<CVD::byte>*)cvGrabber.getPixels(), CVD::ImageRef(videoSize.x, videoSize.y)); imRGB.copy_from(grabRGB); #ifdef USE_FIDUCIAL_TRACKER fiducials.update(); #endif #ifdef USE_SKIN_DETECTOR skin.update(); #endif } if (cameraGrabber.isFrameNew()) cameraImage.setFromPixels(cameraGrabber.getPixels(), 640,480, OF_IMAGE_COLOR); } //-------------------------------------------------------------- void testApp::draw() { #ifdef USE_FIDUCIAL_TRACKER ofPoint drawVideoSize(fiducials.width,fiducials.height); ofPoint scale = drawVideoSize / videoSize; #endif glPushMatrix(); glPixelZoom(scale.x, -scale.y); glRasterPos2f(10 + 0*(drawVideoSize.x+10), 10 + 0*(drawVideoSize.y+10)); glDrawPixels(imRGB); #ifdef USE_FIDUCIAL_TRACKER glRasterPos2f(10 + 1*(drawVideoSize.x+10), 10 + 0*(drawVideoSize.y+10)); glDrawPixels(fiducials.imBW); glRasterPos2f(10 + 2*(drawVideoSize.x+10), 10 + 0*(drawVideoSize.y+10)); glDrawPixels(fiducials.imThreshold); #endif #ifdef USE_SKIN_DETECTOR glRasterPos2f(10 + 0*(drawVideoSize.x+10), 10 + 1*(drawVideoSize.y+10)); glDrawPixels(skin.imBlur); glRasterPos2f(10 + 1*(drawVideoSize.x+10), 10 + 1*(drawVideoSize.y+10)); glDrawPixels(skin.imSkin); glRasterPos2f(10 + 2*(drawVideoSize.x+10), 10 + 1*(drawVideoSize.y+10)); glDrawPixels(skin.imMedian); glRasterPos2f(10 + 3*(drawVideoSize.x+10), 10 + 1*(drawVideoSize.y+10)); glDrawPixels(skin.imEroded); #endif glRasterPos2f(0.,0.); glPopMatrix(); #ifdef USE_FIDUCIAL_TRACKER if (mixer.fiducials==NULL) return; list<ofxFiducial>& fiducials = *mixer.fiducials; list<ofxFiducial>::iterator fiducial; Marsyas::MarSystem* channel; string query; ofRectangle channelFrame(10,drawVideoSize.y+20, 100,100); ofRectangle sliderFrame(0,0, 100,12); string fiducialStr, channelNameStr; ofPoint textOffset; double pitch, gain; /* string pitchStr = ofToString(net.pitch, 2); float w = font.stringWidth(pitchStr); float h = font.stringHeight(pitchStr); font.drawString(pitchStr, ((float)ofGetWidth() - w) / 2, ((float)ofGetHeight()/2) + (h/2) + drawVideoSize.y + 20); */ cameraImage.draw(ofGetWidth() - (640/1.5) - 10, ofGetHeight() - (480/1.5) - 10, (640/1.5), (480/1.5)); for (fiducial = fiducials.begin(); fiducial != fiducials.end(); fiducial++) { if (fiducial->getId() == 1) continue; // Start searching for SoundFileChannel query = "SoundFileChannel/"+ofToString(fiducial->getId()); channel = mixer.channels->getChildMarSystem(query); // Try searching for MicrophoneChannel if (channel == NULL) { query = "MicrophoneChannel/"+ofToString(fiducial->getId()); channel = mixer.channels->getChildMarSystem(query); channelNameStr = "Microphone"; } else { channelNameStr = channel->getctrl("mrs_string/filename")->to<Marsyas::mrs_string>(); } if (channel!=NULL) { textOffset.set(0,10); fiducialStr = "fiducial " + ofToString(fiducial->getId()); gain = channel->getctrl("mrs_real/gain")->to<Marsyas::mrs_real>(); pitch = channel->getctrl("mrs_real/pitch")->to<Marsyas::mrs_real>(); fiducialImages[fiducial->getId()].draw(channelFrame.x, channelFrame.y, channelFrame.height, channelFrame.height); font_sm.drawString(fiducialStr, channelFrame.x, channelFrame.y + channelFrame.height + 10); textOffset.x = channelFrame.x + channelFrame.height + 10; textOffset.y += 6; sliderFrame.x = textOffset.x; sliderFrame.y = channelFrame.y + textOffset.y + font.stringHeight(fiducialStr) - 10; ofSetColor(0x555555); ofRect(sliderFrame.x-1, sliderFrame.y-1, sliderFrame.width+2, sliderFrame.height+2); ofFill(); ofSetColor(0x222222); ofRect(sliderFrame.x, sliderFrame.y, sliderFrame.width, sliderFrame.height); ofSetColor(0xdddddd); ofRect(sliderFrame.x, sliderFrame.y, sliderFrame.width * gain, sliderFrame.height); ofSetColor(0xffffff); font.drawString(channelNameStr, textOffset.x, channelFrame.y + textOffset.y); textOffset.y += font.stringHeight(channelNameStr); textOffset.x += sliderFrame.width; font.drawString(", " + ofToString(pitch, 3) + "x", textOffset.x, channelFrame.y + textOffset.y); channelFrame.y += channelFrame.height + 20; } } #endif } //-------------------------------------------------------------- void testApp::keyPressed(int key) {} //-------------------------------------------------------------- void testApp::keyReleased(int key) {} //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y) {} //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button) {} //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button) {} //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button) {} //-------------------------------------------------------------- void testApp::windowResized(int w, int h) {}
[ [ [ 1, 262 ] ] ]
c0cf86092095493cb21c287af8d762a00b7cefd3
bc4919e48aa47e9f8866dcfc368a14e8bbabbfe2
/Open GL Basic Engine/source/glutFramework/glutFramework/GameStateManager.cpp
5b5caa34673dddb731ffdc59aa40768c1cf834ae
[]
no_license
CorwinJV/rvbgame
0f2723ed3a4c1a368fc3bac69052091d2d87de77
a4fc13ed95bd3e5a03e3c6ecff633fe37718314b
refs/heads/master
2021-01-01T06:49:33.445550
2009-11-03T23:14:39
2009-11-03T23:14:39
32,131,378
0
0
null
null
null
null
UTF-8
C++
false
false
6,822
cpp
#include "GameStateManager.h" #include <iostream> GameStateManager::GameStateManager()//(Game game) : base(game) { Initialize(); } bool GameStateManager::Initialize() { // TODO: Add your initialization code here stateCount = -1; numStates = 0; //why is this here? - so the gamestate knows who its parent gamestate manager is GameState* tempGS = new GameState(*this, stateCount); return true; // if something bad happens, return false } bool GameStateManager::removeGameStateAt(int index) { if (index < 0) // make sure we have an index that's at least position 0 return false; // erase the item at this index vector<GameState*>::iterator itr = stateList.begin(); for(int i = 0; i < index; i++) { itr++; if(itr >= stateList.end()) // lets also make sure that we're working within the confines of the vector { return false; } } delete (*itr); stateList.erase(itr); numStates--; return true; // if something bad happens, return false } bool GameStateManager::removeGameStateID(int nukeID) { if (nukeID < 0) // make sure we have an index that's at least position 0 return false; // erase the item at this index vector<GameState*>::iterator itr = stateList.begin(); for (; itr != stateList.end(); itr++) { if((*itr)->getID() == nukeID) { delete (*itr); stateList.erase(itr); numStates--; return true; // item is found and erased } } return false; // item wasn't found } bool GameStateManager::removeTopGameState() { stateList.pop_back(); return true; // if something bad happens, return false } bool GameStateManager::Update() { //======================================= // Update Game States //======================================= vector<GameState*>::iterator itr = stateList.begin(); if(!stateList.empty()) if((stateList.back()->getStatus() != Active) && (stateList.back()->getStatus() != DeleteMe)) { //std::cout << "top state was not active, setting it to active" << endl; stateList.back()->setStatus(Active); } // update statelist for (; itr != stateList.end(); itr++) { #ifdef GSMStatus std::cout << "GSM - State ID : " << (*itr)->getID() << " status is "; switch((*itr)->getStatus()) { case 0: std::cout << " Active "; break; case 1: std::cout << " Passive "; break; case 2: std::cout << " Hidden "; break; case 3: std::cout << " DeleteMe "; break; default: std::cout << " INVALID STATE "; break; } std::cout << endl; #endif if((*itr)->getStatus() == Active) { (*itr)->Update(); #ifdef GSMStatus std::cout << "GSM - State ID : " << (*itr)->getID() << " has been updated" << endl; #endif } } //======================================= // Delete Pending Game States //======================================= // Instead of using the same iterator to delete, let's use a reverse_iterator vector<GameState*>::reverse_iterator rItr = stateList.rbegin(); for(; rItr != stateList.rend(); rItr++) { if((*rItr)->getStatus() == DeleteMe) { #ifdef GSMWork std::cout << "GSM - State ID : " << (*rItr)->getID() << " is about to be deleted" << endl; #endif delete(*rItr); stateList.erase(rItr.base() - 1); numStates--; break; } } //itr = stateList.end(); //if(stateList.empty() == false) // itr--; //// delete any states flagged for deletion //for (; itr != stateList.begin(); itr--) // { // if((*itr)->getStatus() == DeleteMe) // { // std::cout << "GSM - State ID : " << (*itr)->getID() << " is about to be deleted" << endl; // delete (*itr); // stateList.erase(itr); // numStates--; // break; // } // } //======================================= // Add Pending Game States //======================================= itr = statesToAdd.begin(); for(; itr != statesToAdd.end(); itr++) { stateList.push_back((*itr)); numStates++; } statesToAdd.clear(); return true; // if something bad happens, return false } bool GameStateManager::Draw()//(GameTime gameTime) { // TODO: Add your update code here vector<GameState*>::iterator itr = stateList.begin(); for (; itr != stateList.end(); itr++) { if((*itr)->getStatus() <= Passive) { (*itr)->Draw(); #ifdef GSMStatus std::cout << "GSM - State ID : " << (*itr)->getID() << " has been drawn" << endl; #endif } } return true; // if something bad happens, return false } bool GameStateManager::setState(int stateID, State newStatus = Active) { if (stateID < 0) // make sure we have an index that's at least position 0 return false; vector<GameState*>::iterator itr = stateList.begin(); for (; itr != stateList.end(); itr++) { if((*itr)->getID() == stateID) { (*itr)->setStatus(newStatus); return true; } } return false; // item wasn't found } int GameStateManager::getStateCount() { return stateCount; } int GameStateManager::getNumStates() { return numStates; } bool GameStateManager::setList(vector<GameState*> newlist) { // delete stateList; // ?? not sure if this is needed or not stateList = newlist; return true; } void GameStateManager::processMouse(int x, int y) { //======================================= // Update Mouse States //======================================= vector<GameState*>::iterator itr = stateList.begin(); // update statelist for (; itr != stateList.end(); itr++) { if((*itr)->getStatus() == Active) (*itr)->processMouse(x, y); } } void GameStateManager::processMouseClick(int button, int state, int x, int y) { //======================================= // Update Mouse States //======================================= vector<GameState*>::iterator itr = stateList.begin(); // update statelist for (; itr != stateList.end(); itr++) { if((*itr)->getStatus() == Active) (*itr)->processMouseClick(button, state, x, y); } } void GameStateManager::keyboardInput(unsigned char c, int x, int y) { vector<GameState*>::iterator itr = stateList.begin(); // update statelist for (; itr != stateList.end(); itr++) { if((*itr)->getStatus() == Active) (*itr)->keyboardInput( c, x, y); } } GameStateManager::~GameStateManager() { vector<GameState*>::iterator itr = stateList.begin(); // delete buttonlist contents for (; itr != stateList.end(); itr++) { (*itr)->~GameState(); } stateList.clear(); } void GameStateManager::setAllButTopPassive() { vector<GameState*>::iterator itr = stateList.begin(); // update statelist for (; itr != stateList.end()-1; itr++) { (*itr)->setStatus(Passive); } }
[ "corwin.j@5457d560-9b84-11de-b17c-2fd642447241" ]
[ [ [ 1, 284 ] ] ]
c04fde5e99bbb3ce9f3633413f8c57b7f12c6aa7
e970f96d7981c206e5fc79d3a2ec22bac88c1af1
/oscSender/src/testApp.cpp
99e76c20d71a94b96d5b3ea8bbb7f26168a6752c
[]
no_license
zenwerk/ofOscScreenSync
a9772438fbc2f4c5ec8cec889d95428df713fedc
b7d36ff197dbd0d3c2891254ef152d296608a714
refs/heads/master
2020-05-18T05:48:34.189019
2011-09-19T06:48:15
2011-09-19T06:48:15
2,413,630
0
0
null
null
null
null
UTF-8
C++
false
false
5,223
cpp
#include "testApp.h" #include "beatDetect.h" // 送信先ホスト #define HOST "localhost" #define PORT1 12345 #define PORT2 23456 // 自身がメッセージを受取るときに使用するポート #define RECEIVE_PORT1 3333 int testApp_buffer_size = 1024, testApp_fft_size = 512; int counter = 0; bool bSendFFTValue = false; bool bKickDetected = false; bool bSnareDetected = false; bool bHihatDetected = false; // スクリーン描画制御フラグ bool bScreen1 = false; bool bScreen2 = false; void testApp::setup(){ // フレームレートを60Hzにセット ofSetFrameRate(60); // オーディオインプットを指定 この値は固定すること // Output->0 Input->mono sampleRate->44100 bufSize->1024 ofSoundStreamSetup(0, 1, this, 44100, testApp_buffer_size, 4); // 二つのクライアントに対して2つのsender sender.setup( HOST, PORT1 ); sender2.setup(HOST, PORT2); // 二つのクライアントから送られてくるフラグ受取るreceiver receiver.setup(RECEIVE_PORT1); //fbook.loadFont("frabk.ttf", 32, true, false); ofBackground(20,20,20); printf("testApp setup() OK!\n"); } //------------------------------------------------------------------------ void testApp::audioReceived(float* input, int bufferSize, int nChannels) { bd.audioReceived(input, bufferSize); } //------------------------------------------------------------------------ void testApp::keyPressed(int key){ if(key == '\\'){ bSendFFTValue = !bSendFFTValue; } // 押されたkeyをOSCで送信 ofxOscMessage m; m.setAddress( "/testApp/keyPressed" ); m.addIntArg( key ); sender.sendMessage( m ); sender2.sendMessage(m); pressedKey = key; } //------------------------------------------------------------------------ void testApp::update() { bKickDetected = false; bSnareDetected = false; bHihatDetected = false; bd.updateFFT(); if(bSendFFTValue){ ofxOscMessage fftVal; fftVal.setAddress("/testApp/fftVal"); for(int i=0; i<testApp_fft_size; i++){ fftVal.addFloatArg(bd.magnitude[i]); } sender.sendMessage(fftVal); sender2.sendMessage(fftVal); } // ビート検出を行い結果をOSCで送信 ofxOscMessage oscbd; oscbd.setAddress("/testApp/BeatDetect"); // ドラム音の検出 if(bd.isBeatRange(0,2,2)){ oscbd.addStringArg("KickDetected"); bKickDetected = true; } // スネア音の検出 if(bd.isBeatRange(12,18,4)){ oscbd.addStringArg("SnareDetected"); bSnareDetected = true; } // ハイハット音の検出 if(bd.isBeatRange(27,31,3)){ oscbd.addStringArg("HihatDetected"); bHihatDetected = true; } oscbd.addStringArg("end"); sender.sendMessage(oscbd); sender2.sendMessage(oscbd); // check for waiting messages // スクリーン描画フラグを設定 while( receiver.hasWaitingMessages() ) { // get the next message ofxOscMessage m; receiver.getNextMessage( &m ); if(m.getAddress() == "/testApp/DrawComplete"){ for ( int i=0; i<m.getNumArgs(); i++ ) { //if(m.getArgAsString( i ) == "end") break; if(m.getArgAsString(i) == "Screen1") bScreen1 = true; else if(m.getArgAsString(i) == "Screen2") bScreen2 = true; else; } } } // 二つのクライアントから描画完了フラグを受け取ったら // 次のフレームの描画を指示する if(bScreen1 && bScreen2){ ofxOscMessage m; m.setAddress( "/testApp/bDrawFlag" ); m.addStringArg( "DrawScreen" ); sender.sendMessage( m ); sender2.sendMessage(m); bScreen1 = bScreen2 = false; counter++; cout << "DrawScreen!!: " << counter << endl; } } //------------------------------------------------------------------------ void testApp::draw() { // display instructions string buf; buf = "sending osc messages to" + string( HOST ) + ofToString( PORT1 ); ofDrawBitmapString( buf, 10, 20 ); ofDrawBitmapString( "Sending the pressed Key to the Client", 10, 50 ); //ofDrawBitmapString( "click to send osc message [/mouse/button <button> <\"up\"|\"down\">]", 10, 65 ); if(bSendFFTValue) ofDrawBitmapString( "Sending the FFT Value!!", 10, 80 ); ofDrawBitmapString("Pressed Key = " + ofToString(pressedKey), 10, 100); if(bKickDetected) ofDrawBitmapString("Kick Detected!!", 10, 120); if(bSnareDetected) ofDrawBitmapString("Snare Detected!!", 10, 140); if(bHihatDetected) ofDrawBitmapString("Hihat Detected!!", 10, 160); } void testApp::keyReleased(int key){ } void testApp::mouseMoved(int x, int y){ } void testApp::mouseDragged(int x, int y, int button){ } void testApp::mousePressed(int x, int y, int button){ } void testApp::mouseReleased(int x, int y, int button){ } void testApp::windowResized(int w, int h){ }
[ [ [ 1, 178 ] ] ]
852d894f04835bd068663e267abfb72e9d9bb3ec
fc4946d917dc2ea50798a03981b0274e403eb9b7
/gentleman/gentleman/WindowsAPICodePack/WindowsAPICodePack/DirectX/DirectX/Direct3D10/D3D10ShaderReflectionConstantBuffer.cpp
23ec02b8a69aa0aa37ea18b262def854237aa298
[]
no_license
midnite8177/phever
f9a55a545322c9aff0c7d0c45be3d3ddd6088c97
45529e80ebf707e7299887165821ca360aa1907d
refs/heads/master
2020-05-16T21:59:24.201346
2010-07-12T23:51:53
2010-07-12T23:51:53
34,965,829
3
2
null
null
null
null
UTF-8
C++
false
false
1,399
cpp
// Copyright (c) Microsoft Corporation. All rights reserved. #include "stdafx.h" #include "D3D10ShaderReflectionConstantBuffer.h" #include "D3D10ShaderReflectionVariable.h" using namespace Microsoft::WindowsAPICodePack::DirectX::Direct3D10; using namespace msclr::interop; ShaderBufferDescription ShaderReflectionConstantBuffer::Description::get() { D3D10_SHADER_BUFFER_DESC desc = {0}; CommonUtils::VerifyResult(GetInterface<ID3D10ShaderReflectionConstantBuffer>()->GetDesc(&desc)); return ShaderBufferDescription(desc); } ShaderReflectionVariable^ ShaderReflectionConstantBuffer::GetVariableByIndex(UInt32 index) { ID3D10ShaderReflectionVariable* returnValue = GetInterface<ID3D10ShaderReflectionConstantBuffer>()->GetVariableByIndex(static_cast<UINT>(index)); return returnValue == NULL ? nullptr : gcnew ShaderReflectionVariable(returnValue); } ShaderReflectionVariable^ ShaderReflectionConstantBuffer::GetVariableByName(String^ name) { IntPtr ptr = Marshal::StringToHGlobalAnsi(name); try { ID3D10ShaderReflectionVariable * returnValue = GetInterface<ID3D10ShaderReflectionConstantBuffer>()->GetVariableByName(static_cast<char*>(ptr.ToPointer())); return returnValue ? gcnew ShaderReflectionVariable(returnValue) : nullptr; } finally { Marshal::FreeHGlobal(ptr); } }
[ "lucemia@9e708c16-f4dd-11de-aa3c-59de0406b4f5" ]
[ [ [ 1, 40 ] ] ]
a8752f15189f56ba27cc5265684367d7e1be7b6c
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ClientShellDLL/ClientShellShared/HUDDamage.h
135f65acefe10bf3f981bb968ab9b7670132c9bb
[]
no_license
rickyharis39/nolf2
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
refs/heads/master
2021-01-01T17:21:00.678517
2011-07-23T12:11:19
2011-07-23T12:11:19
38,495,312
1
0
null
null
null
null
UTF-8
C++
false
false
744
h
// ----------------------------------------------------------------------- // // // MODULE : HUDDamage.h // // PURPOSE : HUDItem to display player damage icons // // (c) 2001 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #ifndef __HUD_DAMAGE_H #define __HUD_DAMAGE_H #include "HUDItem.h" class CHUDDamage : public CHUDItem { public: CHUDDamage(); ~CHUDDamage(); LTBOOL Init(); void Render(); void Update(); void UpdateLayout(); private: LTIntPt m_BasePos; uint16 m_nIconHt; LTBOOL m_bDraw; LTPoly_GT4 *m_Poly; HTEXTURE *m_hIcon; // icon }; #endif
[ [ [ 1, 42 ] ] ]
d9dd45d7b4020c081f131ecc711dfb9d906bb1b3
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/Modules/Parameter/ParameterPublic.cpp
f15a6024cac803e5b15aee29c8878b023fb3ba75
[ "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
14,582
cpp
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Buffer.h" #include "MsgBuffer.h" #include "MsgBufferEnums.h" #include "Module.h" #include "ParameterEnums.h" #include "Parameter.h" namespace isab { MsgBuffer * ParameterProviderDecoder::dispatch(MsgBuffer *buf, ParameterProviderInterface *m ) { int length; length=buf->getLength(); switch (buf->getMsgType()) { case MsgBufferEnums::PARAM_CLEAR: { uint32 paramId=buf->readNext32bit(); m->decodedClearParam(paramId, buf->getSource()); delete buf; return NULL; } case MsgBufferEnums::PARAM_SET_INT32: { uint32 paramId=buf->readNext32bit(); int32 numEntries=buf->readNext32bit(); int32 *data = new int32[numEntries]; int32 *tmpptr = data; int i; for (i=numEntries; i>0 ; --i) { *tmpptr++ = buf->readNext32bit(); } m->decodedSetParam(paramId, data, numEntries, buf->getSource()); delete[] data; delete buf; return NULL; } case MsgBufferEnums::PARAM_SET_FLOAT: { uint32 paramId=buf->readNext32bit(); int32 numEntries=buf->readNext32bit(); float *data = new float[numEntries]; float *tmpptr = data; int i; for (i=numEntries; i>0 ; --i) { *tmpptr++ = buf->readNextFloat(); } m->decodedSetParam(paramId, data, numEntries, buf->getSource()); delete[] data; delete buf; return NULL; } case MsgBufferEnums::PARAM_SET_STRING: { /* Read out the data and store both the strings themselvs * and an array of pointers to the strings */ uint32 paramId=buf->readNext32bit(); int32 numEntries=buf->readNext32bit(); int readPos = buf->getReadPos(); int remainingChars = buf->getLength() - readPos; m->decodedSetParam(paramId, remainingChars, reinterpret_cast<const char *>(buf->accessRawData(readPos)), numEntries, buf->getSource()); delete buf; return NULL; } case MsgBufferEnums::PARAM_SET_BINARY_BLOCK: { uint32 paramId = buf->readNext32bit(); int size = buf->readNext32bit(); const uint8* data = buf->accessRawData(); m->decodedSetParam(paramId, data, size, buf->getSource()); delete buf; return NULL; } case MsgBufferEnums::PARAM_GET: { uint32 paramId=buf->readNext32bit(); m->decodedGetParam(paramId, buf->getSource()); delete(buf); return NULL; } case MsgBufferEnums::PARAM_REWRITE_ORIG_FILE: { m->decodedRewriteOrigFile(buf->getSource()); delete(buf); return NULL; } default: return buf; } } MsgBuffer * ParameterConsumerDecoder::dispatch(MsgBuffer *buf, ParameterConsumerInterface *m ) { int length; length=buf->getLength(); switch (buf->getMsgType()) { case MsgBufferEnums::PARAM_VAL_NONE: { uint32 paramId=buf->readNext32bit(); m->decodedParamNoValue(paramId, buf->getSource(), buf->getDestination()); delete buf; return NULL; } case MsgBufferEnums::PARAM_VAL_INT32: { uint32 paramId=buf->readNext32bit(); int32 numEntries=buf->readNext32bit(); int32 *data = new int32[numEntries]; int32 *tmpptr = data; int i; for (i=numEntries; i>0 ; --i) { *tmpptr++ = buf->readNext32bit(); } m->decodedParamValue(paramId, data, numEntries, buf->getSource(), buf->getDestination()); delete[] data; delete buf; return NULL; } case MsgBufferEnums::PARAM_VAL_FLOAT: { uint32 paramId=buf->readNext32bit(); int32 numEntries=buf->readNext32bit(); float *data = new float[numEntries]; float *tmpptr = data; int i; for (i=numEntries; i>0 ; --i) { *tmpptr++ = buf->readNextFloat(); } m->decodedParamValue(paramId, data, numEntries, buf->getSource(), buf->getDestination()); delete[] data; delete buf; return NULL; } case MsgBufferEnums::PARAM_VAL_STRING: { /* Read out the data and stor both the strings themselvs * and an array of pointers to the strings */ uint32 paramId=buf->readNext32bit(); int32 numEntries=buf->readNext32bit(); const char **indexarray = new const char *[numEntries]; const char **indexptr = indexarray; const char *rawdata = reinterpret_cast<const char *>(buf->accessRawData(buf->getReadPos())); int i; for (i=numEntries; i>0 ; --i) { *indexptr++ = rawdata; rawdata += strlen(rawdata) + 1; } m->decodedParamValue(paramId, indexarray, numEntries, buf->getSource(), buf->getDestination()); delete[] indexarray; delete buf; return NULL; } case MsgBufferEnums::PARAM_VAL_BINARY_BLOCK: { uint32 paramId = buf->readNext32bit(); int size = buf->readNext32bit(); const uint8* data = buf->accessRawData(); m->decodedParamValue(paramId, data, size, buf->getSource(), buf->getDestination()); delete buf; return NULL; } default: return buf; } } uint32 ParameterConsumerPublic::paramNoValue(uint32 paramId, uint32 dst) { if (dst == MsgBufferEnums::ADDR_DEFAULT) { dst = m_defaultDst; } uint32 src = m_owner->getRequestId(); MsgBuffer *buf=new MsgBuffer(dst, src, MsgBufferEnums::PARAM_VAL_NONE, 4 ); buf->writeNext32bit(paramId); m_queue->insert(buf); return src; } uint32 ParameterConsumerPublic::paramValue(uint32 paramId, const int32 * data, int32 numEntries, uint32 dst) { if (dst == MsgBufferEnums::ADDR_DEFAULT) { dst = m_defaultDst; } uint32 src = m_owner->getRequestId(); MsgBuffer *buf=new MsgBuffer(dst, src, MsgBufferEnums::PARAM_VAL_INT32, 8 + numEntries*4 ); buf->writeNext32bit(paramId); buf->writeNext32bit(numEntries); while (numEntries) { buf->writeNext32bit(*data++); --numEntries; } m_queue->insert(buf); return src; } uint32 ParameterConsumerPublic::paramValue(uint32 paramId, const float * data, int32 numEntries, uint32 dst) { if (dst == MsgBufferEnums::ADDR_DEFAULT) { dst = m_defaultDst; } uint32 src = m_owner->getRequestId(); MsgBuffer *buf=new MsgBuffer(dst, src, MsgBufferEnums::PARAM_VAL_FLOAT, 8 + numEntries*4 ); buf->writeNext32bit(paramId); buf->writeNext32bit(numEntries); while (numEntries) { buf->writeNextFloat(*data++); --numEntries; } m_queue->insert(buf); return src; } uint32 ParameterConsumerPublic::paramValue(uint32 paramId, int length, const char * data, int32 numEntries, uint32 dst) { if (dst == MsgBufferEnums::ADDR_DEFAULT) { dst = m_defaultDst; } uint32 src = m_owner->getRequestId(); MsgBuffer *buf=new MsgBuffer(dst, src, MsgBufferEnums::PARAM_VAL_STRING, 8 ); buf->writeNext32bit(paramId); buf->writeNext32bit(numEntries); buf->writeNextByteArray(reinterpret_cast<const uint8 *>(data), length); m_queue->insert(buf); return src; } uint32 ParameterConsumerPublic::paramValue(uint32 paramId, const uint8* data, int size, uint32 dst) { if (dst == MsgBufferEnums::ADDR_DEFAULT) { dst = m_defaultDst; } uint32 src = m_owner->getRequestId(); MsgBuffer *buf = new MsgBuffer(dst, src, MsgBufferEnums::PARAM_VAL_BINARY_BLOCK, size + 8); buf->writeNext32bit(paramId); buf->writeNext32bit(size); buf->writeNextByteArray(data, size); m_queue->insert(buf); return src; } uint32 ParameterProviderPublic::clearParam(uint32 paramId, uint32 dst) { if (dst == MsgBufferEnums::ADDR_DEFAULT) { dst = m_defaultDst; } uint32 src = m_owner->getRequestId(); MsgBuffer *buf=new MsgBuffer(dst, src, MsgBufferEnums::PARAM_CLEAR, 4 ); buf->writeNext32bit(paramId); m_queue->insert(buf); return src; } uint32 ParameterProviderPublic::setParam(uint32 paramId, const int32 * data, int32 numEntries, uint32 dst) { if (dst == MsgBufferEnums::ADDR_DEFAULT) { dst = m_defaultDst; } uint32 src = m_owner->getRequestId(); MsgBuffer *buf=new MsgBuffer(dst, src, MsgBufferEnums::PARAM_SET_INT32, 8 + numEntries*4 ); buf->writeNext32bit(paramId); buf->writeNext32bit(numEntries); while (numEntries) { buf->writeNext32bit(*data++); --numEntries; } m_queue->insert(buf); return src; } uint32 ParameterProviderPublic::setParam(uint32 paramId, const float * data, int32 numEntries, uint32 dst) { if (dst == MsgBufferEnums::ADDR_DEFAULT) { dst = m_defaultDst; } uint32 src = m_owner->getRequestId(); MsgBuffer *buf=new MsgBuffer(dst, src, MsgBufferEnums::PARAM_SET_FLOAT, 8 + numEntries*4 ); buf->writeNext32bit(paramId); buf->writeNext32bit(numEntries); while (numEntries) { buf->writeNextFloat(*data++); --numEntries; } m_queue->insert(buf); return src; } uint32 ParameterProviderPublic::setParam(uint32 paramId, const char * const * data, int32 numEntries, uint32 dst) { if (dst == MsgBufferEnums::ADDR_DEFAULT) { dst = m_defaultDst; } uint32 src = m_owner->getRequestId(); MsgBuffer *buf=new MsgBuffer(dst, src, MsgBufferEnums::PARAM_SET_STRING, 8 ); buf->writeNext32bit(paramId); buf->writeNext32bit(numEntries); while (numEntries) { buf->writeNextCharString(*data++); --numEntries; } m_queue->insert(buf); return src; } uint32 ParameterProviderPublic::setParam(uint32 paramId, const uint8* data, int size, uint32 dst) { if (dst == MsgBufferEnums::ADDR_DEFAULT) { dst = m_defaultDst; } uint32 src = m_owner->getRequestId(); MsgBuffer *buf = new MsgBuffer(dst, src, MsgBufferEnums::PARAM_SET_BINARY_BLOCK, size + 8); buf->writeNext32bit(paramId); buf->writeNext32bit(size); buf->writeNextByteArray(data, size); m_queue->insert(buf); return src; } uint32 ParameterProviderPublic::getParam(uint32 paramId, uint32 dst) { if (dst == MsgBufferEnums::ADDR_DEFAULT) { dst = m_defaultDst; } uint32 src = m_owner->getRequestId(); MsgBuffer *buf=new MsgBuffer(dst, src, MsgBufferEnums::PARAM_GET,4); buf->writeNext32bit(paramId); m_queue->insert(buf); return src; } uint32 ParameterProviderPublic::rewriteOrigFile(uint32 dst) { if (dst == MsgBufferEnums::ADDR_DEFAULT) { dst = m_defaultDst; } uint32 src = m_owner->getRequestId(); MsgBuffer *buf=new MsgBuffer(dst, src, MsgBufferEnums::PARAM_REWRITE_ORIG_FILE,0); m_queue->insert(buf); return src; } } /* namespace isab */
[ [ [ 1, 382 ] ] ]
a033238f3bbdcd90eebdb8d4f99b5a6af3739f14
f838c6ad5dd7ffa6d9687b0eb49d5381e6f2e776
/branches/unix_develop/imgs/rgb2yuv.cpp
5cd4a397262404a3e3beaf69d56be222aaeb71fe
[]
no_license
BackupTheBerlios/wiccoder-svn
e773acb186aa9966eaf7848cda454ab0b5d948c5
c329182382f53d7a427caec4b86b11968d516af9
refs/heads/master
2021-01-11T11:09:56.248990
2009-08-19T11:28:23
2009-08-19T11:28:23
40,806,440
0
0
null
null
null
null
UTF-8
C++
false
false
4,035
cpp
/******************************************************************************* * file: rgb2yuv.cpp * * version: 0.0.1 * * author: mice (mailto:[email protected], ICQ:332-292-380) * * description: not available * * tests: none * *******************************************************************************/ //////////////////////////////////////////////////////////////////////////////// // headers #include "rgb2yuv.h" //////////////////////////////////////////////////////////////////////////////// // imgs namespace namespace imgs { //////////////////////////////////////////////////////////////////////////////// // rgb2yuv protected declaration int _byte_clip(const int val); //////////////////////////////////////////////////////////////////////////////// // rgb2yuv public definition int rgb2yuv(const img_rgb &rgb, img_yuv &yuv, const int frmt) { if (24 != rgb.bpp()) return -1; if (img_yuv::YUV_FRMT_444 != frmt) return -1; if (0 != yuv.reset(rgb.w(), rgb.h(), frmt)) return -1; img_rgb::rgb24_t *const rgb_bits = (img_rgb::rgb24_t *)rgb.bits(); img_yuv::sample_t *const &y_bits = yuv.y(); img_yuv::sample_t *const &u_bits = yuv.u(); img_yuv::sample_t *const &v_bits = yuv.v(); // unsigned int *const line_buf = (unsigned int *)malloc(rgb.w() * sizeof(unsigned int)); // if (NULL == line_buf) return -1; const int dline = rgb.w(); const int dline_uv = rgb.w() / yuv.dy(); img_rgb::rgb24_t *rgbl_bits = rgb_bits; img_yuv::sample_t *yl_bits = yuv.y(); img_yuv::sample_t *ul_bits = yuv.u(); img_yuv::sample_t *vl_bits = yuv.v(); for (int cy = rgb.h() - 1; 0 <= cy; --cy) { for (int cx = rgb.w() - 1; 0 <= cx; --cx) { const img_rgb::rgb24_t &rgb_pxl = rgbl_bits[cx]; yl_bits[cx] = (( 66*rgb_pxl.r + 129*rgb_pxl.g + 25*rgb_pxl.b + 128) >> 8) + 16; ul_bits[cx] = ((-38*rgb_pxl.r - 74*rgb_pxl.g + 112*rgb_pxl.b + 128) >> 8) + 128; vl_bits[cx] = ((112*rgb_pxl.r - 94*rgb_pxl.g - 18*rgb_pxl.b + 128) >> 8) + 128; } rgbl_bits += dline; yl_bits += dline; ul_bits += dline_uv; vl_bits += dline_uv; } return 0; } int yuv2rgb(const img_yuv &yuv, img_rgb &rgb, const int bpp) { if (24 != bpp) return -1; if (img_yuv::YUV_FRMT_444 != yuv.frmt()) return -1; if (0 != rgb.reset(yuv.w(), yuv.h(), bpp)) return -1; img_yuv::sample_t *const &y_bits = yuv.y(); img_yuv::sample_t *const &u_bits = yuv.u(); img_yuv::sample_t *const &v_bits = yuv.v(); img_rgb::rgb24_t *const rgb_bits = (img_rgb::rgb24_t *)rgb.bits(); // unsigned int *const line_buf = (unsigned int *)malloc(rgb.w() * sizeof(unsigned int)); // if (NULL == line_buf) return -1; const int dline = yuv.w(); const int dline_uv = yuv.w() / yuv.dy(); img_yuv::sample_t *yl_bits = yuv.y(); img_yuv::sample_t *ul_bits = yuv.u(); img_yuv::sample_t *vl_bits = yuv.v(); img_rgb::rgb24_t *rgbl_bits = rgb_bits; for (int cy = rgb.h() - 1; 0 <= cy; --cy) { for (int cx = rgb.w() - 1; 0 <= cx; --cx) { img_rgb::rgb24_t &rgb_pxl = rgbl_bits[cx]; const int kc = int(yl_bits[cx]) - 16; const int kd = int(ul_bits[cx]) - 128; const int ke = int(vl_bits[cx]) - 128; rgb_pxl.r = _byte_clip((298*kc + 409*ke + 128) >> 8); rgb_pxl.g = _byte_clip((298*kc - 100*kd - 208*ke + 128) >> 8); rgb_pxl.b = _byte_clip((298*kc + 516*kd + 128) >> 8); } yl_bits += dline; ul_bits += dline_uv; vl_bits += dline_uv; rgbl_bits += dline; } return 0; } //////////////////////////////////////////////////////////////////////////////// // rgb2yuv protected definitions int _byte_clip(const int val) { if (0 > val) return 0; if (0xFF < val) return 0xFF; return val; } } // namespace imgs
[ "kulikov@b1028fda-012f-0410-8370-c1301273da9f" ]
[ [ [ 1, 124 ] ] ]
9d85cd96e3508497582ab809481d1aabbce8e177
89d2197ed4531892f005d7ee3804774202b1cb8d
/GWEN/include/Gwen/Controls/RichLabel.h
f3b0b034815e2d318b8aa66bc51638cc91df7e03
[ "MIT", "Zlib" ]
permissive
hpidcock/gbsfml
ef8172b6c62b1c17d71d59aec9a7ff2da0131d23
e3aa990dff8c6b95aef92bab3e94affb978409f2
refs/heads/master
2020-05-30T15:01:19.182234
2010-09-29T06:53:53
2010-09-29T06:53:53
35,650,825
0
0
null
null
null
null
UTF-8
C++
false
false
1,345
h
/* GWEN Copyright (c) 2010 Facepunch Studios See license in Gwen.h */ #pragma once #include "Base.h" #include "Gwen/BaseRender.h" #include "Text.h" namespace Gwen { namespace Controls { class GWEN_EXPORT RichLabel : public Controls::Base { public: GWEN_CONTROL( RichLabel, Gwen::Controls::Base ); void AddLineBreak(); void AddText( const Gwen::TextObject& text, Gwen::Color color, Gwen::Font* font = NULL ); virtual bool SizeToChildren( bool w = true, bool h = true ); protected: struct DividedText { typedef std::list<DividedText> List; DividedText() { type = 0; font = NULL; } unsigned char type; Gwen::UnicodeString text; Gwen::Color color; Gwen::Font* font; }; void Layout( Gwen::Skin::Base* skin ); void SplitLabel( const Gwen::UnicodeString& text, Gwen::Font* pFont, const DividedText& txt, int& x, int& y, int& lineheight ); void CreateNewline( int& x, int& y, int& lineheight ); void CreateLabel( const Gwen::UnicodeString& text, const DividedText& txt, int& x, int& y, int& lineheight, bool NoSplit ); void Rebuild(); void OnBoundsChanged( Gwen::Rect oldBounds ); DividedText::List m_TextBlocks; bool m_bNeedsRebuild; }; } }
[ "haza55@5bf3a77f-ad06-ad18-b9fb-7d0f6dabd793" ]
[ [ [ 1, 56 ] ] ]
3be4991cf673f40b76a3e19bafe75621af1758af
48ab31a0a6a8605d57b5e140309c910f46eb5b35
/Root/Support/LifeCycleObservable.h
f10de15d6aa1455d5558a0601ecb7a74e244b564
[]
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
3,441
h
/**********************************************************\ Copyright Brandon Haynes http://code.google.com/p/indexeddb GNU Lesser General Public License \**********************************************************/ #ifndef BRANDONHAYNES_INDEXEDDB_SUPPORT_LIFECYCLEOBSERVABLE_H #define BRANDONHAYNES_INDEXEDDB_SUPPORT_LIFECYCLEOBSERVABLE_H #include <list> #include <boost/enable_shared_from_this.hpp> #include "LifeCycleObserver.h" #include "Container.h" namespace BrandonHaynes { namespace IndexedDB { namespace API { class Transaction; typedef boost::shared_ptr<Transaction> TransactionPtr; namespace Support { ///<summary> /// This class represents an entity that implements the observer pattern; other classes may observe /// it to determine if it contains a transaction that has been committed or aborted. Observers /// are also notified when this object is closed. /// TODO: Pretty sure we can refactor out the transactional methods here; there's no need to chain these ///</summary> template<class T> class LifeCycleObservable : public boost::enable_shared_from_this<LifeCycleObservable<T> > { public: typedef boost::shared_ptr<LifeCycleObservable<T> > LifeCycleObservablePtr; typedef boost::shared_ptr<LifeCycleObserver<T> > LifeCycleObserverPtr; typedef boost::weak_ptr<LifeCycleObserver<T> > LifeCycleObserverWeakPtr; // Add a new observer to this observable class void addLifeCycleObserver(const LifeCycleObserverPtr& observer) { observers.push_back(observer); } struct removeWeakPtr : public std::unary_function<boost::weak_ptr<T>, bool> { removeWeakPtr(const LifeCycleObserverWeakPtr& ptr) : inner(ptr) { } LifeCycleObserverWeakPtr inner; bool operator()(const LifeCycleObserverWeakPtr& b) { return inner.lock() == b.lock(); } }; virtual boost::shared_ptr<T> get_object() { return FB::ptr_cast<T>(shared_from_this()); } // Remove an observer from this observable class void removeLifeCycleObserver(const LifeCycleObserverPtr& observer) { observers.remove_if(removeWeakPtr(observer));} public: // These methods are executed when the derived class wishes to fire the transaction event virtual void onTransactionCommitted(const TransactionPtr& transaction) = 0; virtual void onTransactionAborted(const TransactionPtr& transaction) = 0; // This method is called when the derived class is about to close; it notifies all // observers of this fact void raiseOnCloseEvent() { for_each(observers.begin(), observers.end(), ExecuteCloseFunctor(FB::ptr_cast<T>(shared_from_this()))); observers.clear(); } private: // A list of our current observers std::list<LifeCycleObserverWeakPtr> observers; // Functor that calls the onClose event on a given observer struct ExecuteCloseFunctor { const boost::shared_ptr<T> observable; ExecuteCloseFunctor(const boost::shared_ptr<T>& observable) : observable(observable) { } void operator ()(const LifeCycleObserverWeakPtr& observer) { LifeCycleObserverPtr p(observer.lock()); if (p) { p->onClose(observable); } } }; friend class Support::Container<T>; }; } } } } #endif
[ [ [ 1, 10 ], [ 12, 19 ], [ 21, 30 ], [ 32, 33 ], [ 37, 37 ], [ 39, 40 ], [ 53, 53 ], [ 56, 56 ], [ 58, 58 ], [ 61, 65 ], [ 67, 71 ], [ 73, 76 ], [ 79, 80 ], [ 89, 99 ] ], [ [ 11, 11 ], [ 20, 20 ], [ 31, 31 ], [ 34, 36 ], [ 38, 38 ], [ 41, 52 ], [ 54, 55 ], [ 57, 57 ], [ 59, 60 ], [ 66, 66 ], [ 72, 72 ], [ 77, 78 ], [ 81, 88 ] ] ]
29a0de9a24558dafebb2becda81ca9509dfd0044
138a353006eb1376668037fcdfbafc05450aa413
/source/ogre/OgreNewt/boost/mpl/greater_equal.hpp
828a6323d3aba70b5fa532f1fab74fff72b5c9ad
[]
no_license
sonicma7/choreopower
107ed0a5f2eb5fa9e47378702469b77554e44746
1480a8f9512531665695b46dcfdde3f689888053
refs/heads/master
2020-05-16T20:53:11.590126
2009-11-18T03:10:12
2009-11-18T03:10:12
32,246,184
0
0
null
null
null
null
UTF-8
C++
false
false
685
hpp
#ifndef BOOST_MPL_GREATER_EQUAL_HPP_INCLUDED #define BOOST_MPL_GREATER_EQUAL_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2000-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/mpl for documentation. // $Source: /cvsroot/ogre/ogreaddons/ogrenewt/OgreNewt_Main/inc/boost/mpl/greater_equal.hpp,v $ // $Date: 2006/04/17 23:48:05 $ // $Revision: 1.1 $ #define AUX778076_OP_NAME greater_equal #define AUX778076_OP_TOKEN >= #include <boost/mpl/aux_/comparison_op.hpp> #endif // BOOST_MPL_GREATER_EQUAL_HPP_INCLUDED
[ "Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e" ]
[ [ [ 1, 21 ] ] ]
240c161c0c41ae0ca609add55d273b7f268c143f
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/ContentTools/Common/Filters/FilterScene/PlatformWriter/hctPlatformWriterOptions.h
6ad13ce550a0896b8d436e85a8686235c8e2000f
[]
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
3,638
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 HKFILTERSCENE_HKFILTERSCENEPLATFORMWRITEROPTIONS_HKCLASS_H #define HKFILTERSCENE_HKFILTERSCENEPLATFORMWRITEROPTIONS_HKCLASS_H /// hctPlatformWriterOptions meta information extern const class hkClass hctPlatformWriterOptionsClass; /// Describes the platform writer options. class hctPlatformWriterOptions { public: HK_DECLARE_REFLECTION(); HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR(HK_MEMORY_CLASS_EXPORT, hctPlatformWriterOptions); /// enum Preset { /// CUSTOM, /// MSVC_WIN32, /// MSVC_XBOX, /// MSVC_AMD64, /// CW_PS2, /// CW_GAMECUBE, /// CW_PSP, /// CW_WII, /// GCC33_PS2, /// GCC32_PS2, /// GCC295_PS2, /// SN31_PS2, /// SN393_GAMECUBE, /// SNC_PSP, /// GCC151_PSP, /// X360, /// GCC_PS3, /// MAC_PPC, /// MAC_386, /// XML }; /// Default constructor hctPlatformWriterOptions() : m_filename(HK_NULL), m_tagfile(true), m_preset(hctPlatformWriterOptions::MSVC_WIN32), m_bytesInPointer(4), m_littleEndian(1), m_reusePaddingOptimized(0), m_emptyBaseClassOptimized(1), m_removeMetadata(false), m_userTag(0), m_saveEnvironmentData(false) { } /// Finish constructor hctPlatformWriterOptions(hkFinishLoadedObjectFlag f) { } // // Members // public: /// The filename to export as. It is the name less the 'common path' between what /// was entered / selected and what the current asset is called. char* m_filename; /// Use tagfile format hkBool m_tagfile; //+default(true) /// Chosen layout preset hkEnum<Preset, hkInt8> m_preset; //+default(hctPlatformWriterOptions::MSVC_WIN32) /// Number of bytes in a pointer hkInt8 m_bytesInPointer; //+default(4) /// Is the platform little endian. Eg: pc, xbox and PlayStation(R)2 are 1, and 0 for powerpc /// based. hkInt8 m_littleEndian; //+default(1) /// Does the reuse padding optimization. hkInt8 m_reusePaddingOptimized; //+default(0) /// Does the empty base class optimization. hkInt8 m_emptyBaseClassOptimized; //+default(1) /// Should we remove hkClass(es) hkBool m_removeMetadata; //+default(true) /// An optional tag to the file hkUint32 m_userTag; //+default(0) /// Whether environment data is saved hkBool m_saveEnvironmentData; //+default(false) }; #endif // HKFILTERSCENE_HKFILTERSCENEPLATFORMWRITEROPTIONS_HKCLASS_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, 136 ] ] ]
90ee4004f8c6d5fe99657e3bdf0668eca9341310
a4fe7601a92c7b4d236eecdcd055a8cf2bf2d5a7
/Asteroids/starfield.cpp
f8235870a18353673b1f883963a25b18f7f5de5b
[]
no_license
AnthIste/Asteroids
390f3e501a1ff7ca7a9d70e44dc7a231388c65a0
5cfdf02bb0909096820bffe4cce9548932d13767
refs/heads/master
2021-01-10T20:00:33.632072
2011-07-10T14:51:54
2011-07-10T14:51:54
2,025,904
3
1
null
null
null
null
UTF-8
C++
false
false
3,329
cpp
#include "starfield.h" #include <cstdlib> #include <time.h> Starfield::Starfield(int cellWidth, int cellHeight) { srand(time(0)); pRoot = new Cell(rand()%666); pRoot->pDown = new Cell(rand()%666); pRoot->pRight = new Cell(rand()%666); pRoot->pRight->pDown = new Cell(rand()%666); pRoot->pDown->pRight = pRoot->pRight->pDown; pRoot->pRight->pRight = 0; pRoot->pDown->pDown = 0; pRoot->pRight->pDown->pRight = 0; pRoot->pRight->pDown->pDown = 0; this->cellWidth = cellWidth; this->cellHeight = cellHeight; scrollX = 0.0; scrollY = 0.0; } Starfield::~Starfield() { delete pRoot->pRight->pDown; delete pRoot->pRight; delete pRoot->pDown; delete pRoot; } void Starfield::scroll(double dx, double dy) { scrollX += dx; scrollY += dy; if (scrollX < 0) { scrollX += cellWidth; overflowHorizontal(); } else if (scrollX > cellWidth) { scrollX -= cellWidth; overflowHorizontal(); } if (scrollY < 0) { scrollY += cellHeight; overflowVertical(); } else if (scrollY > cellHeight) { scrollY -= cellHeight; overflowVertical(); } } void Starfield::render(LPDIRECT3DDEVICE9 d3ddev) { unmarkCells(pRoot); renderCell(d3ddev, pRoot, 0, 0); } void Starfield::renderCell(LPDIRECT3DDEVICE9 d3ddev, Starfield::Cell* cell, int xOffset, int yOffset) { if (cell == 0 || cell->bRendered == true) return; srand(cell->seed); for (int k = 0; k < 100; k++) { int x = rand() % cellWidth - static_cast<int>(scrollX) + xOffset; int y = rand() % cellHeight - static_cast<int>(scrollY) + yOffset; int sizeSeed = rand() % 100; int size = 1; if (sizeSeed > 90) { size = 3; } else if (sizeSeed > 70) { size = 2; } if (size == 3) { D3DRECT starPos = {x, y, x+3, y+3}; d3ddev->Clear(1, &starPos, D3DCLEAR_TARGET, D3DCOLOR_XRGB(255, 255, 255), 1.0f, 0); } else if (size == 2) { D3DRECT starPos = {x, y, x+2, y+2}; d3ddev->Clear(1, &starPos, D3DCLEAR_TARGET, D3DCOLOR_XRGB(255, 255, 255), 1.0f, 0); } else { D3DRECT starPos = {x, y, x+1, y+1}; d3ddev->Clear(1, &starPos, D3DCLEAR_TARGET, D3DCOLOR_XRGB(255, 255, 255), 1.0f, 0); } } cell->bRendered = true; renderCell(d3ddev, cell->pRight, xOffset + cellWidth, yOffset); renderCell(d3ddev, cell->pDown, xOffset, yOffset + cellHeight); } void Starfield::unmarkCells(Cell* pCell) { if (pCell == 0 || pCell->bRendered == false) return; pCell->bRendered = false; unmarkCells(pCell->pRight); unmarkCells(pCell->pDown); } void Starfield::overflowVertical() { Cell* pTmp = pRoot; pRoot = pRoot->pDown; pRoot->pDown = pTmp; pRoot->pDown->pDown = 0; pRoot->pRight->pDown = pRoot->pDown->pRight; pRoot->pDown->pRight->pDown = 0; } void Starfield::overflowHorizontal() { Cell* pTmp = pRoot; pRoot = pRoot->pRight; pRoot->pRight = pTmp; pRoot->pRight->pRight = 0; pRoot->pDown->pRight = pRoot->pRight->pDown; pRoot->pRight->pDown->pRight = 0; }
[ "Salad@Salad-PC.(none)" ]
[ [ [ 1, 120 ] ] ]
6b4c23152d8b605f8f273995e2812a699735895a
ad80c85f09a98b1bfc47191c0e99f3d4559b10d4
/code/src/gfx/npixelformat.cc
58f83bfee208393a62b1d46a461f89d4baffb96c
[]
no_license
DSPNerd/m-nebula
76a4578f5504f6902e054ddd365b42672024de6d
52a32902773c10cf1c6bc3dabefd2fd1587d83b3
refs/heads/master
2021-12-07T18:23:07.272880
2009-07-07T09:47:09
2009-07-07T09:47:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,611
cc
#define N_IMPLEMENTS nGfxServer //------------------------------------------------------------------- // npixelformat.cc // (C) 1999 Andre Weissflog //------------------------------------------------------------------- #include <stdlib.h> #include <string.h> #include "gfx/npixelformat.h" //------------------------------------------------------------------- // nPixelFormat(bpp,palette) // 19-Nov-98 floh created // 17-Dec-99 floh updated //------------------------------------------------------------------- nPixelFormat::nPixelFormat(int _bpp, nPalEntry *_pal) { n_assert(_bpp == 8); int pal_size = (1<<_bpp) * sizeof(nPalEntry); this->type = N_PFTYPE_CLUT; this->bpp = _bpp; this->pal = (nPalEntry *) n_malloc(pal_size); if (_pal) memcpy(this->pal,_pal,pal_size); this->r_mask = this->g_mask = this->b_mask = this->a_mask = 0; this->r_shift = this->g_shift = this->b_mask = this->a_mask = 0; } //------------------------------------------------------------------- // nPixelFormat(bpp,r_mask,g_mask,b_mask,a_mask) // 19-Nov-98 floh created // 17-Dec-99 floh updated //------------------------------------------------------------------- nPixelFormat::nPixelFormat(int _bpp, unsigned int _r_mask, unsigned int _g_mask, unsigned int _b_mask, unsigned int _a_mask) { n_assert((_bpp==16)||(_bpp==24)||(_bpp==32)); unsigned int r,g,b,a; unsigned int m; this->type = N_PFTYPE_RGBA; this->bpp = _bpp; this->pal = NULL; this->r_mask = _r_mask; this->g_mask = _g_mask; this->b_mask = _b_mask; this->a_mask = _a_mask; // compute shift values to shift normalized 8 bit components // to the correct position in the pixel format if (this->r_mask) { for (r=0, m=_r_mask; !(m&1); r++,m>>=1); this->r_shift = r; for (r=0; m&1; r++,m>>=1); this->r_shift -= (8-r); } else this->r_shift = 0; if (this->g_mask) { for (g=0, m=_g_mask; !(m&1); g++,m>>=1); this->g_shift = g; for (g=0; m&1; g++,m>>=1); this->g_shift -= (8-g); } else this->g_shift = 0; if (this->b_mask) { for (b=0, m=_b_mask; !(m&1); b++,m>>=1); this->b_shift = b; for (b=0; m&1; b++,m>>=1); this->b_shift -= (8-b); } else this->b_shift = 0; if (this->a_mask) { for (a=0, m=_a_mask; !(m&1); a++,m>>=1); this->a_shift = a; for (a=0; m&1; a++,m>>=1); this->a_shift -= (8-a); } else this->a_shift = 0; } //------------------------------------------------------------------- // nPixelFormat(nPixelFormat *) // 19-Nov-98 floh created // 17-Dec-99 floh updated //------------------------------------------------------------------- nPixelFormat::nPixelFormat(nPixelFormat *pf) { this->type = pf->type; this->bpp = pf->bpp; if (pf->pal) { ulong pal_size = (1<<pf->bpp) * sizeof(nPalEntry); this->pal = (nPalEntry *) n_malloc(pal_size); memcpy(this->pal,pf->pal,pal_size); } else this->pal = NULL; this->r_mask = pf->r_mask; this->g_mask = pf->g_mask; this->b_mask = pf->b_mask; this->a_mask = pf->a_mask; this->r_shift = pf->r_shift; this->g_shift = pf->g_shift; this->b_shift = pf->b_shift; this->a_shift = pf->a_shift; this->pf_from = NULL; } //------------------------------------------------------------------- // ~nPixelFormat() // 24-Nov-98 floh created //------------------------------------------------------------------- nPixelFormat::~nPixelFormat() { if (this->pal) n_free(this->pal); } //------------------------------------------------------------------- // BeginConv() // 24-Nov-98 floh created // 17-Dec-99 floh updated //------------------------------------------------------------------- bool nPixelFormat::BeginConv(nPixelFormat *from) { this->pf_from = from; // check for illegal combinations... if ((from->type==N_PFTYPE_RGBA) && (this->type==N_PFTYPE_CLUT)) { n_warn("nPixelFormat: illegal conversion, rgba->clut!"); return false; } // copy palette, if necessary if ((this->type==N_PFTYPE_CLUT) && (from->type==N_PFTYPE_CLUT)) { memcpy(this->pal,from->pal,(1<<from->bpp)*sizeof(nPalEntry)); } return true; } //------------------------------------------------------------------- // EndConv() // 24-Nov-98 floh created //------------------------------------------------------------------- void nPixelFormat::EndConv(void) { } //------------------------------------------------------------------- // getPixel() // 26-Nov-98 floh created //------------------------------------------------------------------- static ulong getPixel(int bpp, uchar *src) { ulong p = 0; switch(bpp) { case 16: p = (ulong) *(ushort *)src; break; case 24: { ulong p0 = (ulong) *src++; ulong p1 = (ulong) *src++; ulong p2 = (ulong) *src++; // - 21-Jan-2003 Ilya from EdLanda patch //p = (p0<<16)|(p1<<8)|(p2); // + 21-Jan-2003 Ilya from EdLanda patch p = (p2<<16)|(p1<<8)|(p0); } break; case 32: p = *(ulong *)src; break; }; return p; } //------------------------------------------------------------------- // putPixel() // 26-Nov-98 floh created //------------------------------------------------------------------- static void putPixel(int bpp, uchar *tar, ulong p) { ulong p0,p1,p2; switch(bpp) { case 16: *(ushort *)tar = (ushort) p; break; case 24: // - 21-Jan-2003 Ilya from EdLanda patch //p0 = p>>16 & 0xff; // + 21-Jan-2003 Ilya from EdLanda patch p2 = p>>16 & 0xff; p1 = p>>8 & 0xff; // - 21-Jan-2003 Ilya from EdLanda patch //p2 = p & 0xff; // + 21-Jan-2003 Ilya from EdLanda patch p0 = p & 0xff; *tar++=(uchar)p0; *tar++=(uchar)p1; *tar=(uchar)p2; break; case 32: *(ulong *)tar = p; break; }; } //------------------------------------------------------------------- // Conv() // 24-Nov-98 floh created // 25-Nov-98 floh + wenn Source keinen Alpha-Kanal hat, wird // dieser jetzt automatisch auf voll // undurchsichtig gesetzt. // 17-Dec-99 floh + updated //------------------------------------------------------------------- void nPixelFormat::Conv(uchar *from_buf, uchar *to_buf, int num_pixels) { int i; int from_addr = 0; int to_addr = 0; uchar *src,*tar; // Fallunterscheidung // RGBA->RGBA if ((this->pf_from->type==N_PFTYPE_RGBA) && (this->type==N_PFTYPE_RGBA)) { // special case: identical pixel formats if ((this->pf_from->bpp == this->bpp) && (this->pf_from->r_mask == this->r_mask) && (this->pf_from->g_mask == this->g_mask) && (this->pf_from->b_mask == this->b_mask) && (this->pf_from->a_mask == this->a_mask)) { memcpy(to_buf,from_buf,num_pixels*(this->bpp/8)); } else { int rs,gs,bs,as; rs = this->r_shift - this->pf_from->r_shift; bs = this->b_shift - this->pf_from->b_shift; gs = this->g_shift - this->pf_from->g_shift; as = this->a_shift - this->pf_from->a_shift; src = from_buf; tar = to_buf; for (i=0; i<num_pixels; i++) { unsigned int s,t,r,g,b,a; // read source rgba pixel s = getPixel(this->pf_from->bpp,src); // generate target pixel by masking and shifting r = s & this->pf_from->r_mask; g = s & this->pf_from->g_mask; b = s & this->pf_from->b_mask; if (!this->pf_from->a_mask) a = 0xffffffff; else a = s & this->pf_from->a_mask; if (rs >= 0) r<<=rs; else r>>=-rs; if (gs >= 0) g<<=gs; else g>>=-gs; if (bs >= 0) b<<=bs; else b>>=-bs; if (as >= 0) a<<=as; else a>>=-as; t = r & this->r_mask; t |= g & this->g_mask; t |= b & this->b_mask; t |= a & this->a_mask; putPixel(this->bpp,tar,t); // pointers to next pixel from_addr += this->pf_from->bpp; to_addr += this->bpp; src = from_buf + (from_addr/8); tar = to_buf + (to_addr/8); } } // CLUT->RGBA } else if ((pf_from->type==N_PFTYPE_CLUT) && (type==N_PFTYPE_RGBA)) { int rs,gs,bs,as; rs = this->r_shift; bs = this->b_shift; gs = this->g_shift; as = this->a_shift; src = from_buf; tar = to_buf; for (i=0; i<num_pixels; i++) { unsigned int s,t,r,g,b,a; // read source pixel s = *src; // split to rgba format r = this->pf_from->pal[s].r; g = this->pf_from->pal[s].g; b = this->pf_from->pal[s].b; a = 0xffffffff; // CLUT generally has no alpha channel if (rs >= 0) r<<=rs; else r>>=-rs; if (gs >= 0) g<<=gs; else g>>=-gs; if (bs >= 0) b<<=bs; else b>>=-bs; if (as >= 0) a<<=as; else a>>=-as; t = r & this->r_mask; t |= g & this->g_mask; t |= b & this->b_mask; t |= a & this->a_mask; putPixel(this->bpp,tar,t); to_addr += this->bpp; src++; tar = to_buf + (to_addr/8); } // CLUT->CLUT } else memcpy(to_buf,from_buf,num_pixels); } //-------------------------------------------------------------------- // EOF //--------------------------------------------------------------------
[ "plushe@411252de-2431-11de-b186-ef1da62b6547" ]
[ [ [ 1, 300 ] ] ]
64d03e738c96ef37bef64f918bd87a0d21314701
f2cbdee1dfdcad7b77c597e1af5f40ad83bad4aa
/MyJava/JRex/src/native/jni/org_mozilla_jrex_pref_JRexPreference.cpp
576086b65047eb9657090569414054cb40d4bc58
[]
no_license
jdouglas71/Examples
d03d9effc414965991ca5b46fbcf808a9dd6fe6d
b7829b131581ea3a62cebb2ae35571ec8263fd61
refs/heads/master
2021-01-18T14:23:56.900005
2011-04-07T19:34:04
2011-04-07T19:34:04
1,578,581
1
1
null
null
null
null
UTF-8
C++
false
false
20,251
cpp
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public * License Version 1.1 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor(s): * C.N Medappa <[email protected]><> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the NPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the NPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "org_mozilla_jrex_pref_JRexPreference.h" #include "JRex_JNI_Util.h" #include "JRexPreference.h" using namespace JREX_JNI_UTIL; using namespace JRexPreference; /* * Class: org_mozilla_jrex_pref_JRexPreference * Method: ReadUserPrefs * Signature: (Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_org_mozilla_jrex_pref_JRexPreference_ReadUserPrefs (JNIEnv *env, jobject jprefObj, jstring jprefName){ if(!gXpcomRunning)return; JREX_TRY jboolean copy=JNI_FALSE; const char *prefName=env->GetStringUTFChars(jprefName,&copy); nsresult rv=JRexPreference::ReadUserPrefs(prefName); env->ReleaseStringUTFChars(jprefName,prefName); if (NS_FAILED(rv)) ThrowJRexException(env, "**** ReadUserPrefs()--> ReadUserPrefs Failed ****",rv); JREX_CATCH(env) } /* * Class: org_mozilla_jrex_pref_JRexPreference * Method: ResetPrefs * Signature: ()V */ JNIEXPORT void JNICALL Java_org_mozilla_jrex_pref_JRexPreference_ResetPrefs (JNIEnv *env, jobject jprefObj){ if(!gXpcomRunning)return; JREX_TRY nsresult rv=JRexPreference::ResetPrefs(); if (NS_FAILED(rv)) ThrowJRexException(env, "**** ResetPrefs()--> ResetPrefs Failed ****",rv); JREX_CATCH(env) } /* * Class: org_mozilla_jrex_pref_JRexPreference * Method: ResetUserPrefs * Signature: ()V */ JNIEXPORT void JNICALL Java_org_mozilla_jrex_pref_JRexPreference_ResetUserPrefs (JNIEnv *env, jobject jprefObj){ if(!gXpcomRunning)return; JREX_TRY nsresult rv=JRexPreference::ResetUserPrefs(); if (NS_FAILED(rv)) ThrowJRexException(env, "**** ResetUserPrefs()--> ResetUserPrefs Failed ****",rv); JREX_CATCH(env) } /* * Class: org_mozilla_jrex_pref_JRexPreference * Method: SavePrefFile * Signature: (Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_org_mozilla_jrex_pref_JRexPreference_SavePrefFile (JNIEnv *env, jobject jprefObj, jstring jprefName){ if(!gXpcomRunning)return; JREX_TRY jboolean copy=JNI_FALSE; const char *prefName=env->GetStringUTFChars(jprefName,&copy); nsresult rv=JRexPreference::SavePrefFile(prefName); env->ReleaseStringUTFChars(jprefName,prefName); if (NS_FAILED(rv)) ThrowJRexException(env, "**** SavePrefFile()--> SavePrefFile Failed ****",rv); JREX_CATCH(env) } /* * Class: org_mozilla_jrex_pref_JRexPreference * Method: GetRoot * Signature: ()Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_org_mozilla_jrex_pref_JRexPreference_GetRoot (JNIEnv *env, jobject jprefObj){ if(!gXpcomRunning)return NULL; JREX_TRY char *root=nsnull; nsresult rv=JRexPreference::GetRoot(&root); if (NS_FAILED(rv)) ThrowJRexException(env, "**** GetRoot()--> GetRoot Failed ****",rv); return root==nsnull?NULL:env->NewStringUTF(root); JREX_CATCH(env) return NULL; } /* * Class: org_mozilla_jrex_pref_JRexPreference * Method: GetPrefType * Signature: (Ljava/lang/String;)J */ JNIEXPORT jlong JNICALL Java_org_mozilla_jrex_pref_JRexPreference_GetPrefType (JNIEnv *env, jobject jprefObj, jstring jprefName){ if(!gXpcomRunning)return -1; JREX_TRY jboolean copy=JNI_FALSE; const char *prefName=env->GetStringUTFChars(jprefName,&copy); PRInt32 rVal=0; nsresult rv=JRexPreference::GetPrefType(prefName,&rVal); env->ReleaseStringUTFChars(jprefName,prefName); if (NS_FAILED(rv)) ThrowJRexException(env, "**** GetPrefType()--> GetPrefType Failed ****",rv); return (jlong)rVal; JREX_CATCH(env) return -1; } /* * Class: org_mozilla_jrex_pref_JRexPreference * Method: GetBoolPref * Signature: (Ljava/lang/String;)Z */ JNIEXPORT jboolean JNICALL Java_org_mozilla_jrex_pref_JRexPreference_GetBoolPref (JNIEnv *env, jobject jprefObj, jstring jprefName){ if(!gXpcomRunning)return JNI_FALSE; JREX_TRY jboolean copy=JNI_FALSE; const char *prefName=env->GetStringUTFChars(jprefName,&copy); PRBool rVal=PR_FALSE; nsresult rv=JRexPreference::GetBoolPref(prefName,&rVal); env->ReleaseStringUTFChars(jprefName,prefName); if (NS_FAILED(rv)) ThrowJRexException(env, "**** GetBoolPref()--> GetBoolPref Failed ****",rv); return rVal==PR_TRUE?JNI_TRUE:JNI_FALSE; JREX_CATCH(env) return JNI_FALSE; } /* * Class: org_mozilla_jrex_pref_JRexPreference * Method: SetBoolPref * Signature: (Ljava/lang/String;Z)V */ JNIEXPORT void JNICALL Java_org_mozilla_jrex_pref_JRexPreference_SetBoolPref (JNIEnv *env, jobject jprefObj, jstring jprefName, jboolean jbval){ if(!gXpcomRunning)return; JREX_TRY jboolean copy=JNI_FALSE; const char *prefName=env->GetStringUTFChars(jprefName,&copy); nsresult rv=JRexPreference::SetBoolPref(prefName,(jbval==JNI_TRUE?PR_TRUE:PR_FALSE)); env->ReleaseStringUTFChars(jprefName,prefName); if (NS_FAILED(rv)) ThrowJRexException(env, "**** SetBoolPref()--> SetBoolPref Failed ****",rv); JREX_CATCH(env) } /* * Class: org_mozilla_jrex_pref_JRexPreference * Method: GetCharPref * Signature: (Ljava/lang/String;)C */ JNIEXPORT jstring JNICALL Java_org_mozilla_jrex_pref_JRexPreference_GetCharPref (JNIEnv *env, jobject jprefObj, jstring jprefName){ if(!gXpcomRunning)return NULL; JREX_TRY jboolean copy=JNI_FALSE; const char *prefName=env->GetStringUTFChars(jprefName,&copy); char *rVal=nsnull; nsresult rv=JRexPreference::GetCharPref(prefName,&rVal); env->ReleaseStringUTFChars(jprefName,prefName); if (NS_FAILED(rv)) ThrowJRexException(env, "**** GetCharPref()--> GetCharPref Failed ****",rv); return rVal==nsnull?NULL:env->NewStringUTF(rVal); JREX_CATCH(env) return NULL; } /* * Class: org_mozilla_jrex_pref_JRexPreference * Method: SetCharPref * Signature: (Ljava/lang/String;C)V */ JNIEXPORT void JNICALL Java_org_mozilla_jrex_pref_JRexPreference_SetCharPref (JNIEnv *env, jobject jprefObj, jstring jprefName, jstring jsval){ if(!gXpcomRunning)return; JREX_TRY jboolean copy=JNI_FALSE; const char *prefName=env->GetStringUTFChars(jprefName,&copy); const char *value=env->GetStringUTFChars(jsval,&copy); nsresult rv=JRexPreference::SetCharPref(prefName,value); env->ReleaseStringUTFChars(jprefName,prefName); env->ReleaseStringUTFChars(jsval,value); if (NS_FAILED(rv)) ThrowJRexException(env, "**** SetCharPref()--> SetCharPref Failed ****",rv); JREX_CATCH(env) } /* * Class: org_mozilla_jrex_pref_JRexPreference * Method: GetIntPref * Signature: (Ljava/lang/String;)J */ JNIEXPORT jlong JNICALL Java_org_mozilla_jrex_pref_JRexPreference_GetIntPref (JNIEnv *env, jobject jprefObj, jstring jprefName){ if(!gXpcomRunning)return -1; JREX_TRY jboolean copy=JNI_FALSE; const char *prefName=env->GetStringUTFChars(jprefName,&copy); PRInt32 rVal=0; nsresult rv=JRexPreference::GetIntPref(prefName,&rVal); env->ReleaseStringUTFChars(jprefName,prefName); if (NS_FAILED(rv)) ThrowJRexException(env, "**** GetIntPref()--> GetIntPref Failed ****",rv); return (jlong)rVal; JREX_CATCH(env) return -1; } /* * Class: org_mozilla_jrex_pref_JRexPreference * Method: SetIntPref * Signature: (Ljava/lang/String;J)V */ JNIEXPORT void JNICALL Java_org_mozilla_jrex_pref_JRexPreference_SetIntPref (JNIEnv *env, jobject jprefObj, jstring jprefName, jlong jlval){ if(!gXpcomRunning)return; JREX_TRY jboolean copy=JNI_FALSE; const char *prefName=env->GetStringUTFChars(jprefName,&copy); nsresult rv=JRexPreference::SetIntPref(prefName,(PRInt32)jlval); env->ReleaseStringUTFChars(jprefName,prefName); if (NS_FAILED(rv)) ThrowJRexException(env, "**** SetIntPref()--> SetIntPref Failed ****",rv); JREX_CATCH(env) } /* * Class: org_mozilla_jrex_pref_JRexPreference * Method: ClearUserPref * Signature: (Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_org_mozilla_jrex_pref_JRexPreference_ClearUserPref (JNIEnv *env, jobject jprefObj, jstring jprefName){ if(!gXpcomRunning)return; JREX_TRY jboolean copy=JNI_FALSE; const char *prefName=env->GetStringUTFChars(jprefName,&copy); nsresult rv=JRexPreference::ClearUserPref(prefName); env->ReleaseStringUTFChars(jprefName,prefName); if (NS_FAILED(rv)) ThrowJRexException(env, "**** ClearUserPref()--> ClearUserPref Failed ****",rv); JREX_CATCH(env) } /* * Class: org_mozilla_jrex_pref_JRexPreference * Method: IsPrefLocked * Signature: (Ljava/lang/String;)Z */ JNIEXPORT jboolean JNICALL Java_org_mozilla_jrex_pref_JRexPreference_IsPrefLocked (JNIEnv *env, jobject jprefObj, jstring jprefName){ if(!gXpcomRunning)return JNI_FALSE; JREX_TRY jboolean copy=JNI_FALSE; const char *prefName=env->GetStringUTFChars(jprefName,&copy); PRBool rVal=PR_FALSE; nsresult rv=JRexPreference::IsPrefLocked(prefName,&rVal); env->ReleaseStringUTFChars(jprefName,prefName); if (NS_FAILED(rv)) ThrowJRexException(env, "**** IsPrefLocked()--> IsPrefLocked Failed ****",rv); return rVal==PR_TRUE?JNI_TRUE:JNI_FALSE; JREX_CATCH(env) return JNI_FALSE; } /* * Class: org_mozilla_jrex_pref_JRexPreference * Method: LockPref * Signature: (Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_org_mozilla_jrex_pref_JRexPreference_LockPref (JNIEnv *env, jobject jprefObj, jstring jprefName){ if(!gXpcomRunning)return; JREX_TRY jboolean copy=JNI_FALSE; const char *prefName=env->GetStringUTFChars(jprefName,&copy); nsresult rv=JRexPreference::LockPref(prefName); env->ReleaseStringUTFChars(jprefName,prefName); if (NS_FAILED(rv)) ThrowJRexException(env, "**** LockPref()--> LockPref Failed ****",rv); JREX_CATCH(env) } /* * Class: org_mozilla_jrex_pref_JRexPreference * Method: UnLockPref * Signature: (Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_org_mozilla_jrex_pref_JRexPreference_UnLockPref (JNIEnv *env, jobject jprefObj, jstring jprefName){ if(!gXpcomRunning)return; JREX_TRY jboolean copy=JNI_FALSE; const char *prefName=env->GetStringUTFChars(jprefName,&copy); nsresult rv=JRexPreference::UnlockPref(prefName); env->ReleaseStringUTFChars(jprefName,prefName); if (NS_FAILED(rv)) ThrowJRexException(env, "**** UnlockPref()--> UnLockPref Failed ****",rv); JREX_CATCH(env) } /* * Class: org_mozilla_jrex_pref_JRexPreference * Method: PrefHasUserValue * Signature: (Ljava/lang/String;)Z */ /*JNIEXPORT jboolean JNICALL Java_org_mozilla_jrex_pref_JRexPreference_PrefHasUserValue (JNIEnv *env, jobject jprefObj, jstring jprefName){ if(!gXpcomRunning)return JNI_FALSE; JREX_TRY jboolean copy=JNI_FALSE; const char *prefName=env->GetStringUTFChars(jprefName,&copy); PRBool rVal=PR_FALSE; nsresult rv=JRexPreference::PrefHasUserValue(prefName,&rVal); env->ReleaseStringUTFChars(jprefName,prefName); if (NS_FAILED(rv)) ThrowJRexException(env, "**** PrefHasUserValue()--> PrefHasUserValue Failed ****",rv); return rVal==PR_TRUE?JNI_TRUE:JNI_FALSE; JREX_CATCH(env) return JNI_FALSE; }*/ /* * Class: org_mozilla_jrex_pref_JRexPreference * Method: GetDefaultBoolPref * Signature: (Ljava/lang/String;)Z */ JNIEXPORT jboolean JNICALL Java_org_mozilla_jrex_pref_JRexPreference_GetDefaultBoolPref (JNIEnv *env, jobject jprefObj, jstring jprefName){ if(!gXpcomRunning)return JNI_FALSE; JREX_TRY jboolean copy=JNI_FALSE; const char *prefName=env->GetStringUTFChars(jprefName,&copy); PRBool rVal=PR_FALSE; nsresult rv=JRexPreference::GetDefaultBoolPref(prefName,&rVal); env->ReleaseStringUTFChars(jprefName,prefName); if (NS_FAILED(rv)) ThrowJRexException(env, "**** GetDefaultBoolPref()--> GetDefaultBoolPref Failed ****",rv); return rVal==PR_TRUE?JNI_TRUE:JNI_FALSE; JREX_CATCH(env) return JNI_FALSE; } /* * Class: org_mozilla_jrex_pref_JRexPreference * Method: SetDefaultBoolPref * Signature: (Ljava/lang/String;Z)V */ JNIEXPORT void JNICALL Java_org_mozilla_jrex_pref_JRexPreference_SetDefaultBoolPref (JNIEnv *env, jobject jprefObj, jstring jprefName, jboolean jbval){ if(!gXpcomRunning)return; JREX_TRY jboolean copy=JNI_FALSE; const char *prefName=env->GetStringUTFChars(jprefName,&copy); nsresult rv=JRexPreference::SetDefaultBoolPref(prefName,(jbval==JNI_TRUE?PR_TRUE:PR_FALSE)); env->ReleaseStringUTFChars(jprefName,prefName); if (NS_FAILED(rv)) ThrowJRexException(env, "**** SetDefaultBoolPref()--> SetDefaultBoolPref Failed ****",rv); JREX_CATCH(env) } /* * Class: org_mozilla_jrex_pref_JRexPreference * Method: GetDefaultCharPref * Signature: (Ljava/lang/String;)C */ JNIEXPORT jstring JNICALL Java_org_mozilla_jrex_pref_JRexPreference_GetDefaultCharPref (JNIEnv *env, jobject jprefObj, jstring jprefName){ if(!gXpcomRunning)return NULL; JREX_TRY jboolean copy=JNI_FALSE; const char *prefName=env->GetStringUTFChars(jprefName,&copy); char *rVal=nsnull; nsresult rv=JRexPreference::GetDefaultCharPref(prefName,&rVal); env->ReleaseStringUTFChars(jprefName,prefName); if (NS_FAILED(rv)) ThrowJRexException(env, "**** GetDefaultCharPref()--> GetDefaultCharPref Failed ****",rv); return rVal==nsnull?NULL:env->NewStringUTF(rVal); JREX_CATCH(env) return NULL; } /* * Class: org_mozilla_jrex_pref_JRexPreference * Method: SetDefaultCharPref * Signature: (Ljava/lang/String;C)V */ JNIEXPORT void JNICALL Java_org_mozilla_jrex_pref_JRexPreference_SetDefaultCharPref (JNIEnv *env, jobject jprefObj, jstring jprefName, jstring jsval){ if(!gXpcomRunning)return; JREX_TRY jboolean copy=JNI_FALSE; const char *prefName=env->GetStringUTFChars(jprefName,&copy); const char *value=env->GetStringUTFChars(jsval,&copy); nsresult rv=JRexPreference::SetDefaultCharPref(prefName,value); env->ReleaseStringUTFChars(jprefName,prefName); env->ReleaseStringUTFChars(jsval,value); if (NS_FAILED(rv)) ThrowJRexException(env, "**** SetDefaultCharPref()--> SetDefaultCharPref Failed ****",rv); JREX_CATCH(env) } /* * Class: org_mozilla_jrex_pref_JRexPreference * Method: GetDefaultIntPref * Signature: (Ljava/lang/String;)J */ JNIEXPORT jlong JNICALL Java_org_mozilla_jrex_pref_JRexPreference_GetDefaultIntPref (JNIEnv *env, jobject jprefObj, jstring jprefName){ if(!gXpcomRunning)return -1; JREX_TRY jboolean copy=JNI_FALSE; const char *prefName=env->GetStringUTFChars(jprefName,&copy); PRInt32 rVal=0; nsresult rv=JRexPreference::GetDefaultIntPref(prefName,&rVal); env->ReleaseStringUTFChars(jprefName,prefName); if (NS_FAILED(rv)) ThrowJRexException(env, "**** GetDefaultIntPref()--> GetDefaultIntPref Failed ****",rv); return (jlong)rVal; JREX_CATCH(env) return -1; } /* * Class: org_mozilla_jrex_pref_JRexPreference * Method: SetDefaultIntPref * Signature: (Ljava/lang/String;J)V */ JNIEXPORT void JNICALL Java_org_mozilla_jrex_pref_JRexPreference_SetDefaultIntPref (JNIEnv *env, jobject jprefObj, jstring jprefName, jlong jprefValue){ if(!gXpcomRunning)return; JREX_TRY jboolean copy=JNI_FALSE; const char *prefName=env->GetStringUTFChars(jprefName,&copy); nsresult rv=JRexPreference::SetDefaultIntPref(prefName,(PRInt32)jprefValue); env->ReleaseStringUTFChars(jprefName,prefName); if (NS_FAILED(rv)) ThrowJRexException(env, "**** SetDefaultIntPref()--> SetDefaultIntPref Failed ****",rv); JREX_CATCH(env) } /* * Class: org_mozilla_jrex_pref_JRexPreference * Method: GetPrefChildren * Signature: (Ljava/lang/String;)Ljava/util/Collection; */ JNIEXPORT jobject JNICALL Java_org_mozilla_jrex_pref_JRexPreference_GetPrefChildren (JNIEnv *env, jobject jprefObj, jstring jprefParentName){ if(!gXpcomRunning)return NULL; JREX_TRY JREX_LOGLN("GetPrefChildren()--> **** jprefParentName<"<<jprefParentName<<"> ****") jboolean copy=JNI_FALSE; char *prefName=nsnull; if(jprefParentName!=NULL) prefName=(char*)env->GetStringUTFChars(jprefParentName,&copy); JREX_LOGLN("GetPrefChildren()--> **** USing prefName<"<<(PRInt32)prefName<<"> ****") nsVoidArray *vArray=new nsVoidArray(); if(IS_NULL(vArray)){ ThrowJRexException(env, "**** GetPrefChildren()--> nsVoidArray alloc Failed ****",0); return NULL; } nsresult rv=JRexPreference::GetPrefChildren(prefName,vArray); if(prefName) env->ReleaseStringUTFChars(jprefParentName,prefName); if(NS_FAILED(rv)){ delete vArray; ThrowJRexException(env, "**** GetPrefChildren()--> GetPrefChildren Failed ****",rv); return NULL; } PRInt32 count=vArray->Count(); JREX_LOGLN("GetPrefChildren()--> **** GetPrefChildren count<"<<count<<"> ****") if(count<1){ delete vArray; return NULL; } if (env->EnsureLocalCapacity(3) < 0){ delete vArray; ThrowJRexException(env, "**** GetPrefChildren()--> EnsureLocalCapacity Failed ****",rv); return NULL; } JREX_LOGLN("GetPrefChildren()--> **** EnsureLocalCapacity Done!!! ****") jclass clazz = env->FindClass("java/util/ArrayList"); if(clazz==NULL){ delete vArray; ThrowJRexException(env, "**** GetPrefChildren()--> FindClass ArrayList Failed ****",0); return NULL; } jmethodID arryListCID=env->GetMethodID(clazz,"<init>", "()V"); JREX_LOGLN("GetPrefChildren()--> **** arryListCID <"<<arryListCID<<"> ****") jmethodID arryListAddID=env->GetMethodID(clazz,"add", "(Ljava/lang/Object;)Z"); JREX_LOGLN("GetPrefChildren()--> **** arryListAddID <"<<arryListAddID<<"> ****") jobject arryList=env->NewObject(clazz,arryListCID); JNI_EXP_DESC_CLR("GetPrefChildren() NewObject arryList Exception Occured") if(arryList==NULL){ delete vArray; ThrowJRexException(env, "**** GetPrefChildren()--> arryList Creation Failed ****",0); return NULL; } JREX_LOGLN("GetPrefChildren()--> **** arryList creation Done!!! ****") jstring jchild=NULL; while (vArray->Count()>0) { char *child = NS_REINTERPRET_CAST(char *, vArray->ElementAt(0)); if(NOT_NULL(child)){ jchild=env->NewStringUTF(child); }else jchild=NULL; JREX_LOGLN("GetPrefChildren()--> *** jchild<"<<jchild<<"> ***") if(jchild!=NULL){ jboolean added=env->CallBooleanMethod(arryList,arryListAddID,jchild); JREX_LOGLN("GetPrefChildren()--> *** added<"<<(added==JNI_TRUE)<<"> ***") env->DeleteLocalRef(jchild); } PRBool removed=vArray->RemoveElementAt(0); JREX_LOGLN("GetPrefChildren()--> *** removed<"<<(removed==PR_TRUE)<<"> ***") if(NOT_NULL(child))nsMemory::Free(child); JREX_LOGLN("GetPrefChildren()--> *** Freed Child ***") } env->DeleteLocalRef(clazz); delete vArray; return arryList; JREX_CATCH(env) return NULL; }
[ [ [ 1, 571 ] ] ]
9a98a235a2a0080e9825387fc3c5c5c91b303dbb
f8b364974573f652d7916c3a830e1d8773751277
/emulator/allegrex/instructions/VRNDF2.h
80686c8663d8e034c7d00d4febee602fa862d712
[]
no_license
lemmore22/pspe4all
7a234aece25340c99f49eac280780e08e4f8ef49
77ad0acf0fcb7eda137fdfcb1e93a36428badfd0
refs/heads/master
2021-01-10T08:39:45.222505
2009-08-02T11:58:07
2009-08-02T11:58:07
55,047,469
0
0
null
null
null
null
UTF-8
C++
false
false
1,049
h
template< > struct AllegrexInstructionTemplate< 0xd0230000, 0xffff7f00 > : AllegrexInstructionUnknown { static AllegrexInstructionTemplate &self() { static AllegrexInstructionTemplate insn; return insn; } static AllegrexInstruction *get_instance() { return &AllegrexInstructionTemplate::self(); } virtual AllegrexInstruction *instruction(u32 opcode) { return this; } virtual char const *opcode_name() { return "VRNDF2"; } virtual void interpret(Processor &processor, u32 opcode); virtual void disassemble(u32 address, u32 opcode, char *opcode_name, char *operands, char *comment); protected: AllegrexInstructionTemplate() {} }; typedef AllegrexInstructionTemplate< 0xd0230000, 0xffff7f00 > AllegrexInstruction_VRNDF2; namespace Allegrex { extern AllegrexInstruction_VRNDF2 &VRNDF2; } #ifdef IMPLEMENT_INSTRUCTION AllegrexInstruction_VRNDF2 &Allegrex::VRNDF2 = AllegrexInstruction_VRNDF2::self(); #endif
[ [ [ 1, 41 ] ] ]
1418bfb0a2f8ada3ef6bc1ff9d67ac5ff76d1243
906e87b1936397339734770be45317f06fe66e6e
/include/TGTheme.h
c3955679100b84ad3a6acc4832c300a695f258d4
[]
no_license
kcmohanprasad/tgui
03c1ab47e9058bc763b7e6ffc21a37b4358369bf
9f9cf391fa86b99c7d606c4d196e512a7b06be95
refs/heads/master
2021-01-10T08:52:18.629088
2007-05-17T04:42:58
2007-05-17T04:42:58
52,069,498
0
0
null
null
null
null
UTF-8
C++
false
false
3,323
h
//----------------------------------------------------------------------------- // This source file is part of TGUI (Tiny GUI) // // Copyright (c) 2006-2007 Tubras Software, Ltd // Also see acknowledgements in Readme.html // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to // do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. //----------------------------------------------------------------------------- #ifndef __TGTHEME_H__ #define __TGTHEME_H__ namespace TGUI { class TGBrush; class TGFont; typedef Ogre::SharedPtr<TGBrush> TGSBrush; class _TGUIExport TGTheme { public: TGSBrush m_base; TGSBrush m_baseOpaque; TGSBrush m_baseBright; TGSBrush m_caption; TGSBrush m_captionFocused; TGSBrush m_frame; TGSBrush m_frameFocused; TGSBrush m_frameSelected; TGSBrush m_text; TGSBrush m_textInverted; TGSBrush m_textFocused; TGSBrush m_textHilited; TGSBrush m_exclusiveOverlay; public: static const TGColour DefaultText; TGTheme(); TGTheme(TGColour baseColour, TGColour baseTextColour=DefaultText); TGTheme& TGTheme::operator= (const TGTheme& rhs); virtual ~TGTheme(); TGColour clamp(TGColour c); inline const TGSBrush getBase() {return m_base;} inline const TGSBrush getBaseBright() {return m_baseBright;} inline const TGSBrush getBaseOpaque() {return m_baseOpaque;} inline const TGSBrush getTextBrush() {return m_text;} inline const TGSBrush getTextFocusedBrush() {return m_textFocused;} inline const TGSBrush getTextInvertedBrush() {return m_textInverted;} inline const TGSBrush getCaptionBrush() {return m_caption;} inline const TGSBrush getFrameBrush() {return m_frame;} inline const TGSBrush getFrameFocusedBrush() {return m_frameFocused;} inline const TGSBrush getFrameSelectedBrush() {return m_frameSelected;} inline const TGSBrush getExclusiveOverlay() {return m_exclusiveOverlay;} void setBase(TGColour baseColour, TGColour baseTextColour); void setFont(TGFont* font); }; } #endif
[ "pc0der@a5263bde-0223-0410-8bbb-1954fdd97a2f" ]
[ [ [ 1, 77 ] ] ]
566c32bd952b824b85a39d4ca4b54a6652a29491
b822313f0e48cf146b4ebc6e4548b9ad9da9a78e
/KylinSdk/Client/Source/LobbyScene.h
2e13de7c9ff451749f8449b95a5e784092e055ac
[]
no_license
dzw/kylin001v
5cca7318301931bbb9ede9a06a24a6adfe5a8d48
6cec2ed2e44cea42957301ec5013d264be03ea3e
refs/heads/master
2021-01-10T12:27:26.074650
2011-05-30T07:11:36
2011-05-30T07:11:36
46,501,473
0
0
null
null
null
null
UTF-8
C++
false
false
667
h
#pragma once #include "Showgirl.h" namespace Kylin { class LobbyScene //: public InputListener { public: LobbyScene(); virtual ~LobbyScene(); virtual KBOOL Initialize(); virtual KBOOL LoadActors(); virtual KVOID Tick(KFLOAT fElapsed); virtual KVOID Destroy(); virtual KVOID SpawnActor(KUINT uIndex); protected: virtual KVOID SpawnScene(); protected: Ogre::Camera* m_pCamera; Ogre::SceneNode* m_pNode; KPoint3 m_kPosition; KQuaternion m_kQuaternion; KFLOAT m_fScale; SceneLoader* m_pSceneLoader; KUINT m_uSelectedIndex; Showgirl* m_pShowgirl; AnimQueue m_kAnimQueue; }; }
[ [ [ 1, 36 ] ] ]
87396750a0f115cdd042ab01c6aedeb07169121c
5f0b8d4a0817a46a9ae18a057a62c2442c0eb17e
/Include/Container.h
0ccb8f4548a357026feda0375a67e74d826c058c
[ "BSD-3-Clause" ]
permissive
gui-works/ui
3327cfef7b9bbb596f2202b81f3fc9a32d5cbe2b
023faf07ff7f11aa7d35c7849b669d18f8911cc6
refs/heads/master
2020-07-18T00:46:37.172575
2009-11-18T22:05:25
2009-11-18T22:05:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,020
h
/* * Copyright (c) 2003-2006, Bram Stein * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CONTAINER_H #define CONTAINER_H #include "./Component.h" namespace ui { /** * A Component that can hold other * components. * A container can contain other Components, * and has public methods for manipulating them. */ class Container : public Component { public: /** * Constructor. */ Container(); /** * Copy constructor. */ Container(const Container& rhs); /** * Assignment operator. */ Container& operator=(const Container& rhs); void swap(Container& rhs) throw(); /** * Destructor. */ virtual ~Container(); /** * Returns true if this Component is a Container or not. * @note * Returned true doesnt mean the Container has children, * it might as well be an empty Container. * @return * true if this Component is a Container, false otherwise. */ bool isContainer() const; /** * Returns wether this Container is a top level Container. */ virtual bool isRootContainer() const; /** * Returns true if this container has children. */ bool hasChildren() const; /** * Enables or disables this Component. * Disabling the Component makes this Component * ignore any user input (that is, mouse and key events * generated by a user). */ void setEnabled(bool enable); /** * Returns the preferred size for this Container. */ virtual const util::Dimension& getPreferredSize() const; /** * Remove the specified Component. */ virtual void remove(Component* component); /** * Remove all containers children. */ void removeAll(); /** * Returns the Component at n. * N means the depth level of the Container. * @param * n depth/index level * @returns * the Component at n, or NULL if none is found. */ //Component* getChild(int n) const; /** * Returns the number of components * in the container. * @return * number of components in the container. */ int getNumberOfChildren() const; /** * Add a Component to this Container with given constraint. * Can be overridden to create custom * containers. * @param * comp Component to add to this Container. * @param * constraints Constraints used for laying out this Container. These are hints for the LayoutManager. */ virtual void add(Component* comp, int constraints = -1); /** * Sets the LayoutManager for this Container. * @param * newLayout the new LayoutManager. * @note Note that the previous LayoutManager is freed from * memory. */ void setLayout(layout::LayoutManager* newLayout); /** * Validates this Component. */ void validate() const; /** * Update, for time based motion. After updating, it calls * all the update methods on it's children. * @param * deltaTime time between two sequential frames. This can be * used for calculating frame rate independant motion. */ virtual void updateComponent(float deltaTime); protected: /** * Add a Component to this Container. * This method should not be overridden, * as it is used by add(Component *comp). * @param * component Component to add to this Container. * @param * constraints Constraints used for laying out this Container. These are hints for the LayoutManager. */ void addImpl(Component* component, int constraints); /** * Removes a Component from this Container. * This is the implementation of the normal * remove function (which can be overridden). */ void removeImpl(Component *component); /** * Paint this Component and it's * children. * @param * g A Graphics reference. */ virtual void paintComponent(Graphics& g) const; /** * Paints the Children of this Container. */ void paintChildren(const Container* parent, Graphics& g) const; /** * Draws all the child components of this element. * Method can be overridden to enhance or modify * the drawing routine. */ virtual void paintChildren(Graphics& g) const; private: /** * Validate this Component * and it children recursively. */ void validateTree() const; /** * Holds a pointer to the layoutManager. * Can be NULL(0). * @see LayoutManager. */ layout::LayoutManager* layout; }; } #endif
[ "bs@bram.(none)" ]
[ [ [ 1, 214 ] ] ]
b1f8abec09e19a954b0a392aa2bb0f9e8ac5a3d7
22d9640edca14b31280fae414f188739a82733e4
/Code/VTK/include/vtk-5.2/vtkXMLPHierarchicalBoxDataWriter.h
6573f0ba0c98862179e25f15ff87e84ce83df1c0
[]
no_license
tack1/Casam
ad0a98febdb566c411adfe6983fcf63442b5eed5
3914de9d34c830d4a23a785768579bea80342f41
refs/heads/master
2020-04-06T03:45:40.734355
2009-06-10T14:54:07
2009-06-10T14:54:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,306
h
/*========================================================================= Program: Visualization Toolkit Module: $RCSfile: vtkXMLPHierarchicalBoxDataWriter.h,v $ Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm 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 notice for more information. =========================================================================*/ // .NAME vtkXMLPHierarchicalBoxDataWriter - parallel writer for // vtkHierarchicalBoxDataSet. // .SECTION Description // vtkXMLPCompositeDataWriter writes (in parallel or serially) the VTK XML // multi-group, multi-block hierarchical and hierarchical box files. XML // multi-group data files are meta-files that point to a list of serial VTK // XML files. #ifndef __vtkXMLPHierarchicalBoxDataWriter_h #define __vtkXMLPHierarchicalBoxDataWriter_h #include "vtkXMLHierarchicalBoxDataWriter.h" class vtkMultiProcessController; class VTK_PARALLEL_EXPORT vtkXMLPHierarchicalBoxDataWriter : public vtkXMLHierarchicalBoxDataWriter { public: static vtkXMLPHierarchicalBoxDataWriter* New(); vtkTypeRevisionMacro(vtkXMLPHierarchicalBoxDataWriter, vtkXMLHierarchicalBoxDataWriter); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Controller used to communicate data type of blocks. // By default, the global controller is used. If you want another // controller to be used, set it with this. // If no controller is set, only the local blocks will be written // to the meta-file. virtual void SetController(vtkMultiProcessController*); vtkGetObjectMacro(Controller, vtkMultiProcessController); //BTX protected: vtkXMLPHierarchicalBoxDataWriter(); ~vtkXMLPHierarchicalBoxDataWriter(); virtual void FillDataTypes(vtkCompositeDataSet*); vtkMultiProcessController* Controller; private: vtkXMLPHierarchicalBoxDataWriter(const vtkXMLPHierarchicalBoxDataWriter&); // Not implemented. void operator=(const vtkXMLPHierarchicalBoxDataWriter&); // Not implemented. //ETX }; #endif
[ "nnsmit@9b22acdf-97ab-464f-81e2-08fcc4a6931f" ]
[ [ [ 1, 64 ] ] ]
6a700d3695ed4bb8b77668f7f97e5733fb748542
77aa13a51685597585abf89b5ad30f9ef4011bde
/dep/src/boost/boost/fusion/container/vector/detail/at_impl.hpp
4c4736817d04fd99ea943401fd682201ac2eb457
[ "BSL-1.0" ]
permissive
Zic/Xeon-MMORPG-Emulator
2f195d04bfd0988a9165a52b7a3756c04b3f146c
4473a22e6dd4ec3c9b867d60915841731869a050
refs/heads/master
2021-01-01T16:19:35.213330
2009-05-13T18:12:36
2009-05-14T03:10:17
200,849
8
10
null
null
null
null
UTF-8
C++
false
false
1,471
hpp
/*============================================================================= Copyright (c) 2001-2006 Joel de Guzman 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) ==============================================================================*/ #if !defined(FUSION_AT_IMPL_05042005_0741) #define FUSION_AT_IMPL_05042005_0741 #include <boost/fusion/support/detail/access.hpp> #include <boost/type_traits/is_const.hpp> #include <boost/mpl/at.hpp> #include <boost/mpl/int.hpp> namespace boost { namespace fusion { struct vector_tag; namespace extension { template <typename Tag> struct at_impl; template <> struct at_impl<vector_tag> { template <typename Sequence, typename N> struct apply { typedef mpl::at<typename Sequence::types, N> element; typedef typename mpl::eval_if< is_const<Sequence> , detail::cref_result<element> , detail::ref_result<element> >::type type; static type call(Sequence& v) { return v.at_impl(N()); } }; }; } }} #endif
[ "pepsi1x1@a6a5f009-272a-4b40-a74d-5f9816a51f88" ]
[ [ [ 1, 49 ] ] ]
5d8d45e09803819bca17227fc45abbd85531e23f
208475bcab65438eed5d8380f26eacd25eb58f70
/QianExe/yx_LedChuangLi.cpp
89c314fb94b033ca6ac3c2e3d42b824dd22582f9
[]
no_license
awzhang/MyWork
83b3f0b9df5ff37330c0e976310d75593f806ec4
075ad5d0726c793a0c08f9158080a144e0bb5ea5
refs/heads/master
2021-01-18T07:57:03.219372
2011-07-05T02:41:55
2011-07-05T02:46:30
15,523,223
1
2
null
null
null
null
GB18030
C++
false
false
8,776
cpp
#include "yx_QianStdAfx.h" #if USE_LEDTYPE == 2 #undef MSG_HEAD #define MSG_HEAD ("QianExe-LedChLi") void *G_ThreadLedChuangLiRecv(void *arg) { g_objLedChuangLi.P_ThreadRecv(); } void *G_ThreadLedChuangLiWork(void *arg) { g_objLedChuangLi.P_ThreadWork(); } ////////////////////////////////////////////////////////////////////////// CLedChuangLi::CLedChuangLi() { m_objReadMng.InitCfg(1000, 3000); m_objWorkMng.InitCfg(5000, 10000); m_iComPort = 0; m_bytInfoNo = 0; } CLedChuangLi::~CLedChuangLi() { } int CLedChuangLi::Init() { #if USE_COMBUS == 0 // 打开串口 if( !ComOpen() ) { PRTMSG(MSG_ERR, "Open Com failed!\n"); return ERR_COM; } // 创建接收线程 if( pthread_create(&m_pthreadRecv, NULL, G_ThreadLedChuangLiRecv, NULL) != 0 ) { ComClose(); PRTMSG(MSG_ERR, "Create Recv Thread failed!\n"); return ERR_THREAD; } #endif if( pthread_create(&m_pthreadWork, NULL, G_ThreadLedChuangLiWork, NULL) != 0 ) { ComClose(); PRTMSG(MSG_ERR, "Create Work Thread failed!\n"); return ERR_THREAD; } PRTMSG(MSG_DBG, "Create ChuangLi thread succ!\n"); return 0; } int CLedChuangLi::Release() { #if USE_COMBUS == 0 ComClose(); #endif return 0; } bool CLedChuangLi::ComOpen() { int iResult; struct termios options; m_iComPort = open("/dev/ttySIM1", O_RDWR ); if( -1 == m_iComPort ) { PRTMSG(MSG_ERR, "Open SIM1 failed!\n"); perror(""); return false; } if(tcgetattr(m_iComPort, &options) != 0) { PRTMSG(MSG_ERR, "GetSerialAttr\n"); perror(""); return false; } options.c_iflag &= ~(IGNBRK|BRKINT|IGNPAR|PARMRK|INPCK|ISTRIP|INLCR|IGNCR|ICRNL|IUCLC|IXON|IXOFF|IXANY); options.c_lflag &= ~(ECHO|ECHONL|ISIG|IEXTEN|ICANON); options.c_oflag &= ~OPOST; cfsetispeed(&options,B9600); //扩展盒波特率9600 cfsetospeed(&options,B9600); if(tcsetattr(m_iComPort, TCSANOW, &options) != 0) { PRTMSG(MSG_ERR, "Set com Attr\n"); perror(""); return false; } PRTMSG(MSG_DBG,"ComBus open Succ!\n"); return true; } bool CLedChuangLi::ComClose() { if(m_iComPort != -1) { close(m_iComPort); m_iComPort = -1; return true; } return false; } int CLedChuangLi::ComWrite(char *v_szBuf, int v_iLen) { PRTMSG(MSG_DBG, "Com send one frame!"); PrintString(v_szBuf, v_iLen); #if USE_COMBUS == 0 int iWrited = 0; iWrited = write(m_iComPort, v_szBuf, v_iLen); return iWrited; #endif #if USE_COMBUS == 1 DWORD dwPacketNum; g_objComBus.m_objComBusWorkMng.PushData((BYTE)LV1, (DWORD)v_iLen, v_szBuf, dwPacketNum); return v_iLen; #endif } int CLedChuangLi::Deal0x42(BYTE v_bytDataType,char *v_szData, DWORD v_dwDataLen) { switch( v_bytDataType ) { case 0x08: Deal4208(v_szData, v_dwDataLen); break; default: break; } } int CLedChuangLi::Deal4208(char *v_szBuf, int v_iLen) { byte bytInfoType = v_szBuf[0]; byte bytInfoCnt = v_szBuf[1]; char szbuf[100] = {0}; int ilen = 0, i = 0; DWORD dwPacketNum; byte bytRes = 2; // 缺省为失败 // 即时信息只能有一条 if( bytInfoType == 1 ) { if( bytInfoCnt != 1 || v_iLen != 19) { PRTMSG(MSG_ERR, "4208 len err\n"); goto _DEAL4208_END; } MakeLedFrame(0x01, 'C', 0x00, v_szBuf+2, 17, szbuf, ilen); if( !m_objWorkMng.PushData( (BYTE)LV1, (DWORD)ilen, szbuf, dwPacketNum) ) { bytRes = 1; } } else if( bytInfoType == 2 ) { // 参数长度检查 if( bytInfoCnt > 20 || v_iLen != 17*bytInfoCnt+2 ) goto _DEAL4208_END; // 中心下发D类信息时,车台先撤销C类信息 MakeLedFrame(0x02, 'C', 0x00, NULL, 0, szbuf, ilen); m_objWorkMng.PushData( (BYTE)LV1, (DWORD)ilen, szbuf, dwPacketNum); // 然后再发送D类信息 for(i=0; i<bytInfoCnt; i++) { MakeLedFrame(0x01, 'D', m_bytInfoNo, v_szBuf+2+i*17, 17, szbuf, ilen); if( !m_objWorkMng.PushData( (BYTE)LV1, (DWORD)ilen, szbuf, dwPacketNum) ) { m_bytInfoNo++; } else { break; } } // 全部成功发送到LED屏,则应答正确 if(i == bytInfoCnt) bytRes = 1; } _DEAL4208_END: int iRet = g_objSms.MakeSmsFrame((char*)&bytRes, 1, 0x42, 0x48, szbuf, sizeof(szbuf), ilen); if( !iRet ) iRet = g_objSock.SOCKSNDSMSDATA( szbuf, ilen, LV12, 0, NULL ); return bytRes; } void CLedChuangLi::DealEvent(char v_szCmd, char v_szType, char v_szInfoNo) { char szbuf[100] = {0}; int ilen = 0; DWORD dwPacketNum; MakeLedFrame(v_szCmd, v_szType, v_szInfoNo, NULL, 0, szbuf, ilen); m_objWorkMng.PushData( (BYTE)LV1, (DWORD)ilen, szbuf, dwPacketNum); } void CLedChuangLi::P_ThreadRecv() { char szRead; int iReadLen = 0; int i = 0; while(!g_bProgExit) { iReadLen = read(m_iComPort, (void*)&szRead, 1); // LED的返回值只有一个字节 if(iReadLen > 1) { PRTMSG(MSG_ERR,"Com Read Over Buf!\n"); continue; } if( iReadLen == 1 ) { //PRTMSG(MSG_DBG, "ComBus recv data!\n"); //PrintString(szReadBuf, iReadLen); DWORD dwPacketNum; m_objReadMng.PushData((BYTE)LV1, 1, &szRead, dwPacketNum); } } } void CLedChuangLi::P_ThreadWork() { byte bytLvl = 0; char szBuf[1024] = {0}; DWORD dwLen = 0; DWORD dwPushTm; DWORD dwBufSize = (DWORD)sizeof(szBuf); while( !g_bProgExit ) { dwLen = 0; memset(szBuf, 0, sizeof(szBuf)); // 向串口发送数据 if( !m_objWorkMng.PopData(bytLvl, dwBufSize, dwLen, szBuf, dwPushTm)) { // 发送数据帧 SendCmdForAns(szBuf, dwLen); } usleep(100000); } } bool CLedChuangLi::SendCmdForAns(char *v_szbuf, int v_iLen) { if( v_szbuf == NULL || v_iLen <=0 ) return false; bool bRet = false; BYTE bytlvl = 0; char szResBuf[100] = {0}; DWORD dwResLen = 0; DWORD dwPushTm; for(int i=0; i<3; i++) { ComWrite(v_szbuf, v_iLen); DWORD dwCur = GetTickCount(); do { if( true == g_bProgExit ) goto SNDANDWAIT_END; usleep( 100000 ); if( !m_objReadMng.PopData(bytlvl, (DWORD)(sizeof(szResBuf)), dwResLen, (char*)szResBuf, dwPushTm) ) { if( dwResLen == 1 && szResBuf[0] == 0x55 ) { bRet = true; goto SNDANDWAIT_END; } } } while( GetTickCount() - dwCur < 2*1000 ); // 超时时间2s } SNDANDWAIT_END: if( bRet ) { PRTMSG(MSG_DBG, "LedChuangLi recv right answer!\n"); } else { PRTMSG(MSG_DBG, "LedChuangLi recv wrong answer!\n"); } return bRet; } void CLedChuangLi::MakeLedFrame(char v_szCmd, char v_szType, char v_szInfoNo, char *v_szInfoBuf, int v_iInfoLen, char *v_p_szFrameBuf, int &v_p_iFrameLen) { char szbuf[100] = {0}; int ilen = 0; szbuf[ilen++] = v_szCmd; szbuf[ilen++] = v_szType; szbuf[ilen++] = v_szInfoNo; memcpy(szbuf+ilen, v_szInfoBuf, v_iInfoLen); ilen += v_iInfoLen; szbuf[ilen++] = (char)get_crc( (byte*)szbuf, ilen ); // 校验和 // 转义 ilen = TranData(szbuf, ilen); #if USE_COMBUS == 0 memcpy(v_p_szFrameBuf, szbuf, ilen); v_p_iFrameLen = ilen; #endif #if USE_COMBUS == 1 v_p_szFrameBuf[0] = 0xf7; //0xf7表示由扩展盒的模拟串口2发送出去 memcpy(v_p_szFrameBuf+1, szbuf, ilen); v_p_iFrameLen = ilen+1; #endif } int CLedChuangLi::TranData(char *v_szBuf, int v_iLen) { char szNewBuf[1024] = {0}; int iNewLen = 0; szNewBuf[iNewLen++] = 0x82; for( int i=0; i<v_iLen; i++) { switch(v_szBuf[i]) { case 0x82: szNewBuf[iNewLen++] = 0x81; szNewBuf[iNewLen++] = 0x01; break; case 0x83: szNewBuf[iNewLen++] = 0x81; szNewBuf[iNewLen++] = 0x02; break; case 0x81: szNewBuf[iNewLen++] = 0x81; szNewBuf[iNewLen++] = 0x00; break; default: szNewBuf[iNewLen++]= v_szBuf[i]; break; } } szNewBuf[iNewLen++] = 0x83; memcpy(v_szBuf, szNewBuf, iNewLen); return iNewLen; } //-------------------------------------------------------------------------------------------------------------------------- // 检查校验和(直接取累加和) // buf: 数据缓冲区指针 // len: 数据的长度 // 返回: 校验是否正确 bool CLedChuangLi::check_crc(const byte *buf, const int len) { byte check_sum = get_crc( buf+1, len-1 ); return (buf[0] == check_sum); } //-------------------------------------------------------------------------------------------------------------------------- // 得到校验和的反码, 再加1 byte CLedChuangLi::get_crc(const byte *buf, const int len) { byte check_sum = 0; for(int i=0; i<len; i++) { check_sum += *(buf+i); } check_sum ^= 0xff; check_sum += 1; return check_sum; } #endif
[ [ [ 1, 418 ] ] ]
b271693e0f61cebaa328c3ae9cbc2aa266354de3
6c7ee98a3ef57bb5a9bc5c598eb19a48b35723ec
/of_preRelease_v0061_osx_FAT/libs/MPT/include/common.h
01d926190ab7ff4bc73099714465bcca40fedcf4
[ "MIT" ]
permissive
JGL/tukesprint
6f30699161291be1709b3c6335eaedd5fba16fca
10dca5cc09d1e2f89275262b6a693ab37fa9f126
refs/heads/master
2021-01-19T08:31:11.147274
2010-05-15T16:40:15
2010-05-15T16:40:15
32,330,121
0
1
null
null
null
null
UTF-8
C++
false
false
6,660
h
/* * common.h * * Copyright (c) 2003 Machine Perception Laboratory * University of California San Diego. * Please read the disclaimer and notes about redistribution * at the end of this file. * * Authors: Josh Susskind, Ian Fasel, Bret Fortenberry */ #ifndef __MPLABCOMMON_H__ #define __MPLABCOMMON_H__ #ifdef WIN32 #include <windows.h> #else #include <iostream.h> #include <sys/time.h> #include <pthread.h> #include "errno.h" #endif #include <iostream> #include <algorithm> #ifndef BYTE #define BYTE unsigned char #endif #ifndef PIXEL_TYPE #define PIXEL_TYPE BYTE #endif #undef BOOL typedef int BOOL; #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif #undef PIXEL_TYPE #define PIXEL_TYPE BYTE typedef struct sMUTEX { int activation; #ifdef WIN32 HANDLE mutex; #else pthread_mutex_t mutex; #endif } MUTEX_TYPE; // ================================================================ #ifdef WIN32 #define MUTEX_LOCK_RETURN_TYPE DWORD #define THREAD_RETURN_TYPE void #define THREAD_TYPE HANDLE #define THREAD_COND HANDLE #define TIMETYPE DWORD #define IMAGE_FLIPPED true // ================================================================ #else //if not WIN32 class nRGBTRIPLE{ public: PIXEL_TYPE rgbtRed; PIXEL_TYPE rgbtGreen; PIXEL_TYPE rgbtBlue; // Default & Copy Constructors and = operator nRGBTRIPLE() : rgbtRed(0), rgbtGreen(0), rgbtBlue(0){}; nRGBTRIPLE(PIXEL_TYPE r, PIXEL_TYPE g, PIXEL_TYPE b) : rgbtRed(r), rgbtGreen(g), rgbtBlue(b){}; template<class T> inline nRGBTRIPLE(const T &v){ rgbtRed = static_cast<PIXEL_TYPE>(v); rgbtGreen = static_cast<PIXEL_TYPE>(v); rgbtBlue = static_cast<PIXEL_TYPE>(v); } nRGBTRIPLE(const nRGBTRIPLE &v){ rgbtRed = v.rgbtRed; rgbtGreen = v.rgbtGreen; rgbtBlue = v.rgbtBlue; } template<class T> // inline nRGBTRIPLE& operator=(const T &v){ inline void operator=(const T &v){ rgbtRed = static_cast<PIXEL_TYPE>(v); rgbtGreen = static_cast<PIXEL_TYPE>(v); rgbtBlue = static_cast<PIXEL_TYPE>(v); // return *this; } // inline nRGBTRIPLE& operator=(const nRGBTRIPLE &v){ inline void operator=(const nRGBTRIPLE &v){ rgbtRed = v.rgbtRed; rgbtGreen = v.rgbtGreen; rgbtBlue = v.rgbtBlue; // return *this; } }; #define RGBTRIPLE nRGBTRIPLE //#ifndef FREEIMAGE_H typedef unsigned long DWORD; typedef unsigned short WORD; typedef long LONG; typedef long LONGLONG; //#endif #define MUTEX_LOCK_RETURN_TYPE int #define WAIT_OBJECT_0 0 #define WAIT_TIMEOUT EBUSY #define WAIT_ABANDONED EDEADLK #define WAIT_FAILED EINVAL #define THREAD_RETURN_TYPE void * #define THREAD_TYPE pthread_t #define THREAD_COND pthread_cond_t #define TIMETYPE struct timeval #define IMAGE_FLIPPED false typedef struct tagBITMAPFILEHEADER { // bmfh WORD bfType; DWORD bfSize; WORD bfReserved1; WORD bfReserved2; DWORD bfOffBits; } BITMAPFILEHEADER; #ifndef FREEIMAGE_H typedef struct tagBITMAPINFOHEADER{ // bmih DWORD biSize; LONG biWidth; LONG biHeight; WORD biPlanes; WORD biBitCount; DWORD biCompression; DWORD biSizeImage; LONG biXPelsPerMeter; LONG biYPelsPerMeter; DWORD biClrUsed; DWORD biClrImportant; } BITMAPINFOHEADER; #endif #endif //not WIN32 /////////////////////////////////////////////////////////////////// inline MUTEX_LOCK_RETURN_TYPE LockMutex(MUTEX_TYPE pMutex){ if(pMutex.activation == 1) { std::cout << "error - trying to lock previously locked mutex\n"; return 0; } pMutex.activation = 1; #ifdef WIN32 return WaitForSingleObject( pMutex.mutex, INFINITE ); #else return pthread_mutex_lock(&pMutex.mutex); #endif } /////////////////////////////////////////////////////////////////// inline MUTEX_LOCK_RETURN_TYPE TryLockMutex(MUTEX_TYPE pMutex, DWORD msec = 16){ MUTEX_LOCK_RETURN_TYPE rtn; #ifdef WIN32 rtn = WaitForSingleObject(pMutex.mutex, msec ); #else rtn = pthread_mutex_trylock(&pMutex.mutex); #endif if (rtn == WAIT_OBJECT_0) pMutex.activation = 1; return rtn; } inline void CreateMutex (MUTEX_TYPE &pMutex) { pMutex.activation = 0; #ifdef WIN32 pMutex.mutex = CreateMutex (NULL, FALSE, NULL); #else pthread_mutex_init(&pMutex.mutex,NULL); #endif } inline int ReleaseMutex(MUTEX_TYPE pMutex) { pMutex.activation = 0; #ifdef WIN32 return ReleaseMutex(pMutex.mutex); #else return (pthread_mutex_unlock(&pMutex.mutex)==0); #endif } inline void CreateMutexEvent(THREAD_COND &pCond) { #ifdef WIN32 pCond = CreateEvent(NULL, TRUE, FALSE, NULL); #else pthread_cond_init(&pCond,NULL); #endif } inline void MutexCondSignal(THREAD_COND pCond) { #ifdef WIN32 PulseEvent(pCond); #else pthread_cond_signal(&pCond); #endif } inline void MutexCondWait(THREAD_COND &pCond, MUTEX_TYPE &pMutex) { #ifdef WIN32 WaitForSingleObject( pCond, INFINITE ); #else pthread_cond_wait(&pCond,&pMutex.mutex); #endif } /////////////////////////////////////////////////////////////////// #endif // __MPLABCOMMON_H__ /* * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */
[ "[email protected]@3a5b5021-5be8-e3f2-3ea9-e40b785f49fe" ]
[ [ [ 1, 259 ] ] ]
1b3817252a36f70dd05c13eca6114278757d9ce7
f89e32cc183d64db5fc4eb17c47644a15c99e104
/pcsx2-rr/common/src/Utilities/wxHelpers.cpp
ab1b09fa675480180d2711adb3836b3569f48a72
[]
no_license
mauzus/progenitor
f99b882a48eb47a1cdbfacd2f38505e4c87480b4
7b4f30eb1f022b08e6da7eaafa5d2e77634d7bae
refs/heads/master
2021-01-10T07:24:00.383776
2011-04-28T11:03:43
2011-04-28T11:03:43
45,171,114
0
0
null
null
null
null
UTF-8
C++
false
false
14,425
cpp
/* PCSX2 - PS2 Emulator for PCs * Copyright (C) 2002-2010 PCSX2 Dev Team * * PCSX2 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 Found- * ation, either version 3 of the License, or (at your option) any later version. * * PCSX2 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 PCSX2. * If not, see <http://www.gnu.org/licenses/>. */ #include "PrecompiledHeader.h" #include "wxGuiTools.h" #include "pxStaticText.h" #include "Threading.h" #include "IniInterface.h" #include <wx/cshelp.h> #include <wx/tooltip.h> #include <wx/spinctrl.h> using namespace pxSizerFlags; pxDialogCreationFlags pxDialogFlags() { return pxDialogCreationFlags().CloseBox().Caption().Vertical(); } // -------------------------------------------------------------------------------------- // BaseDeletableObject Implementation // -------------------------------------------------------------------------------------- // This code probably deserves a better home. It's general purpose non-GUI code (the single // wxApp/Gui dependency is in wxGuiTools.cpp for now). // bool BaseDeletableObject::MarkForDeletion() { return !_InterlockedExchange( &m_IsBeingDeleted, true ); } void BaseDeletableObject::DeleteSelf() { if( MarkForDeletion() ) DoDeletion(); } BaseDeletableObject::BaseDeletableObject() { #ifdef _MSC_VER // Bleh, this fails because _CrtIsValidHeapPointer calls HeapValidate on the // pointer, but the pointer is a virtual base class, so it's not a valid block. >_< //pxAssertDev( _CrtIsValidHeapPointer( this ), "BaseDeletableObject types cannot be created on the stack or as temporaries!" ); #endif m_IsBeingDeleted = false; } BaseDeletableObject::~BaseDeletableObject() throw() { AffinityAssert_AllowFrom_MainUI(); } // -------------------------------------------------------------------------------------- // Creates a text control which is right-justified and has it's minimum width configured to suit // the number of digits requested. wxTextCtrl* CreateNumericalTextCtrl( wxWindow* parent, int digits, long flags ) { wxTextCtrl* ctrl = new wxTextCtrl( parent, wxID_ANY ); ctrl->SetWindowStyleFlag( flags ); pxFitToDigits( ctrl, digits ); return ctrl; } void pxFitToDigits( wxWindow* win, int digits ) { int ex; win->GetTextExtent( wxString( L'0', digits+1 ), &ex, NULL ); win->SetMinSize( wxSize( ex+10, wxDefaultCoord ) ); // +10 for text control borders/insets and junk. } void pxFitToDigits( wxSpinCtrl* win, int digits ) { // HACK!! The better way would be to create a pxSpinCtrl class that extends wxSpinCtrl and thus // have access to wxSpinButton::DoGetBestSize(). But since I don't want to do that, we'll just // make/fake it with a value it's pretty common to Win32/GTK/Mac: static const int MagicSpinnerSize = 18; int ex; win->GetTextExtent( wxString( L'0', digits+1 ), &ex, NULL ); win->SetMinSize( wxSize( ex+10+MagicSpinnerSize, wxDefaultCoord ) ); // +10 for text control borders/insets and junk. } bool pxDialogExists( const wxString& name ) { return wxFindWindowByName( name ) != NULL; } // ===================================================================================================== // wxDialogWithHelpers Class Implementations // ===================================================================================================== DEFINE_EVENT_TYPE( pxEvt_OnDialogCreated ) IMPLEMENT_DYNAMIC_CLASS(wxDialogWithHelpers, wxDialog) wxDialogWithHelpers::wxDialogWithHelpers() { m_hasContextHelp = false; m_extraButtonSizer = NULL; Init( pxDialogFlags() ); } wxDialogWithHelpers::wxDialogWithHelpers( wxWindow* parent, const wxString& title, const pxDialogCreationFlags& cflags ) : wxDialog( parent, wxID_ANY, title, wxDefaultPosition, wxDefaultSize, cflags.GetWxWindowFlags() ) { m_hasContextHelp = cflags.hasContextHelp; if( (int)cflags.BoxSizerOrient != 0 ) { SetSizer( new wxBoxSizer( cflags.BoxSizerOrient ) ); *this += StdPadding; } Init( cflags ); SetMinSize( cflags.MinimumSize ); } wxDialogWithHelpers::~wxDialogWithHelpers() throw() { } void wxDialogWithHelpers::Init( const pxDialogCreationFlags& cflags ) { // This fixes it so that the dialogs show up in the task bar in Vista: // (otherwise they go stupid iconized mode if the user minimizes them) if( cflags.hasMinimizeBox ) SetExtraStyle(GetExtraStyle() & ~wxTOPLEVEL_EX_DIALOG); m_extraButtonSizer = NULL; if( m_hasContextHelp ) delete wxHelpProvider::Set( new wxSimpleHelpProvider() ); // GTK/Linux Note: currently the Close (X) button doesn't appear to work in dialogs. Docs // indicate that it should, so I presume the problem is in wxWidgets and that (hopefully!) // an updated version will fix it later. I tried to fix it using a manual Connect but it // didn't do any good. (problem could also be my Co-Linux / x-window manager) Connect( pxEvt_OnDialogCreated, wxCommandEventHandler (wxDialogWithHelpers::OnDialogCreated) ); Connect( wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler (wxDialogWithHelpers::OnOkCancel) ); Connect( wxID_CANCEL, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler (wxDialogWithHelpers::OnOkCancel) ); Connect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler (wxDialogWithHelpers::OnCloseWindow) ); wxCommandEvent createEvent( pxEvt_OnDialogCreated ); createEvent.SetId( GetId() ); AddPendingEvent( createEvent ); } void wxDialogWithHelpers::OnDialogCreated( wxCommandEvent& evt ) { evt.Skip(); if( (evt.GetId() == GetId()) && !GetDialogName().IsEmpty() ) SetName( L"Dialog:" + GetDialogName() ); } wxString wxDialogWithHelpers::GetDialogName() const { return wxEmptyString; } void wxDialogWithHelpers::DoAutoCenter() { // Smart positioning logic! If our parent window is larger than our window by some // good amount, then we center on that. If not, center relative to the screen. This // avoids the popup automatically eclipsing the parent window (which happens in PCSX2 // a lot since the main window is small). bool centerfail = true; if( wxWindow* parent = GetParent() ) { const wxSize parentSize( parent->GetSize() ); if( (parentSize.x > ((int)GetSize().x * 1.5)) || (parentSize.y > ((int)GetSize().y * 1.5)) ) { CenterOnParent(); centerfail = false; } } if( centerfail ) CenterOnScreen(); } void wxDialogWithHelpers::SmartCenterFit() { Fit(); const wxString dlgName( GetDialogName() ); if( dlgName.IsEmpty() ) { DoAutoCenter(); return; } if( wxConfigBase* cfg = wxConfigBase::Get( false ) ) { wxRect screenRect( GetScreenRect() ); IniLoader loader( cfg ); ScopedIniGroup group( loader, L"DialogPositions" ); cfg->SetRecordDefaults( false ); if( GetWindowStyle() & wxRESIZE_BORDER ) { wxSize size; loader.Entry( dlgName + L"_Size", size, screenRect.GetSize() ); SetSize( size ); } if( !cfg->Exists( dlgName + L"_Pos" ) ) DoAutoCenter(); else { wxPoint pos; loader.Entry( dlgName + L"_Pos", pos, screenRect.GetPosition() ); SetPosition( pos ); } cfg->SetRecordDefaults( true ); } } // Overrides wxDialog behavior to include automatic Fit() and CenterOnParent/Screen. The centering // is based on a heuristic the centers against the parent window if the parent window is at least // 75% larger than the fitted dialog. int wxDialogWithHelpers::ShowModal() { SmartCenterFit(); m_CreatedRect = GetScreenRect(); return wxDialog::ShowModal(); } // Overrides wxDialog behavior to include automatic Fit() and CenterOnParent/Screen. The centering // is based on a heuristic the centers against the parent window if the parent window is at least // 75% larger than the fitted dialog. bool wxDialogWithHelpers::Show( bool show ) { if( show ) { SmartCenterFit(); m_CreatedRect = GetScreenRect(); } return wxDialog::Show( show ); } wxStaticText& wxDialogWithHelpers::Label( const wxString& label ) { return *new wxStaticText( this, wxID_ANY, label, wxDefaultPosition, wxDefaultSize, wxALIGN_CENTER_VERTICAL ); } pxStaticText& wxDialogWithHelpers::Text( const wxString& label ) { return *new pxStaticText( this, label ); } pxStaticText& wxDialogWithHelpers::Heading( const wxString& label ) { return *new pxStaticHeading( this, label ); } void wxDialogWithHelpers::OnCloseWindow( wxCloseEvent& evt ) { // Save the dialog position if the dialog is named... // FIXME : This doesn't get called if the app is exited by alt-f4'ing the main app window. // ... not sure how to fix that yet. I could register a list of open windows into wxAppWithHelpers // that systematically get closed. Seems like work, maybe later. --air if( wxConfigBase* cfg = IsIconized() ? NULL : wxConfigBase::Get( false ) ) { const wxString dlgName( GetDialogName() ); const wxRect screenRect( GetScreenRect() ); if( !dlgName.IsEmpty() && ( m_CreatedRect != screenRect) ) { wxPoint pos( screenRect.GetPosition() ); IniSaver saver( cfg ); ScopedIniGroup group( saver, L"DialogPositions" ); if( GetWindowStyle() & wxRESIZE_BORDER ) { wxSize size( screenRect.GetSize() ); saver.Entry( dlgName + L"_Size", size, screenRect.GetSize() ); } saver.Entry( dlgName + L"_Pos", pos, screenRect.GetPosition() ); } } if( !IsModal() ) Destroy(); evt.Skip(); } void wxDialogWithHelpers::OnOkCancel( wxCommandEvent& evt ) { Close(); evt.Skip(); } void wxDialogWithHelpers::AddOkCancel( wxSizer &sizer, bool hasApply ) { wxStdDialogButtonSizer& s_buttons( *new wxStdDialogButtonSizer() ); s_buttons.AddButton( new wxButton( this, wxID_OK ) ); s_buttons.AddButton( new wxButton( this, wxID_CANCEL ) ); if( hasApply ) s_buttons.AddButton( new wxButton( this, wxID_APPLY ) ); m_extraButtonSizer = new wxBoxSizer( wxHORIZONTAL ); // Add the context-sensitive help button on the caption for the platforms // which support it (currently MSW only) if( m_hasContextHelp ) { SetExtraStyle( wxDIALOG_EX_CONTEXTHELP ); #ifndef __WXMSW__ *m_extraButtonSizer += new wxContextHelpButton(this) | StdButton(); #endif } // create a sizer to hold the help and ok/cancel buttons, for platforms // that need a custom help icon. [fixme: help icon prolly better off somewhere else] wxFlexGridSizer& flex( *new wxFlexGridSizer( 2 ) ); flex.AddGrowableCol( 0, 1 ); flex.AddGrowableCol( 1, 15 ); flex += m_extraButtonSizer | pxAlignLeft; flex += s_buttons | (pxExpand & pxCenter); sizer += flex | StdExpand(); s_buttons.Realize(); } void wxDialogWithHelpers::AddOkCancel( wxSizer *sizer, bool hasApply ) { if( sizer == NULL ) sizer = GetSizer(); pxAssume( sizer ); AddOkCancel( *sizer, hasApply ); } wxDialogWithHelpers& wxDialogWithHelpers::SetMinWidth( int newWidth ) { SetMinSize( wxSize( newWidth, GetMinHeight() ) ); if( wxSizer* sizer = GetSizer() ) sizer->SetMinSize( wxSize( newWidth, sizer->GetMinSize().GetHeight() ) ); return *this; } wxDialogWithHelpers& wxDialogWithHelpers::SetMinHeight( int newHeight ) { SetMinSize( wxSize( GetMinWidth(), newHeight ) ); if( wxSizer* sizer = GetSizer() ) sizer->SetMinSize( wxSize( sizer->GetMinSize().GetWidth(), newHeight ) ); return *this; } int wxDialogWithHelpers::GetCharHeight() const { return pxGetCharHeight( this, 1 ); } // -------------------------------------------------------------------------------------- // wxPanelWithHelpers Implementations // -------------------------------------------------------------------------------------- IMPLEMENT_DYNAMIC_CLASS(wxPanelWithHelpers, wxPanel) void wxPanelWithHelpers::Init() { } // Creates a Static Box container for this panel. the static box sizer becomes the default // sizer for this panel. If the panel already has a sizer set, then that sizer will be // transfered to the new StaticBoxSizer (and will be the first item in it's list, retaining // consistent and expected layout) wxPanelWithHelpers* wxPanelWithHelpers::AddFrame( const wxString& label, wxOrientation orient ) { wxSizer* oldSizer = GetSizer(); SetSizer( new wxStaticBoxSizer( orient, this, label ), false ); Init(); if( oldSizer ) *this += oldSizer | pxExpand; return this; } wxStaticText& wxPanelWithHelpers::Label( const wxString& label ) { return *new wxStaticText( this, wxID_ANY, label ); } pxStaticText& wxPanelWithHelpers::Text( const wxString& label ) { return *new pxStaticText( this, label ); } pxStaticText& wxPanelWithHelpers::Heading( const wxString& label ) { return *new pxStaticHeading( this, label ); } wxPanelWithHelpers::wxPanelWithHelpers( wxWindow* parent, wxOrientation orient, const wxString& staticBoxLabel ) : wxPanel( parent ) { SetSizer( new wxStaticBoxSizer( orient, this, staticBoxLabel ) ); Init(); } wxPanelWithHelpers::wxPanelWithHelpers( wxWindow* parent, wxOrientation orient ) : wxPanel( parent ) { SetSizer( new wxBoxSizer( orient ) ); Init(); } wxPanelWithHelpers::wxPanelWithHelpers( wxWindow* parent ) : wxPanel( parent ) { Init(); } wxPanelWithHelpers::wxPanelWithHelpers( wxWindow* parent, const wxPoint& pos, const wxSize& size ) : wxPanel( parent, wxID_ANY, pos, size ) { Init(); } wxPanelWithHelpers& wxPanelWithHelpers::SetMinWidth( int newWidth ) { SetMinSize( wxSize( newWidth, GetMinHeight() ) ); if( wxSizer* sizer = GetSizer() ) sizer->SetMinSize( wxSize( newWidth, sizer->GetMinSize().GetHeight() ) ); return *this; } int pxGetCharHeight( const wxWindow* wind, int rows ) { if( !wind ) return 0; wxClientDC dc(wx_const_cast(wxWindow*, wind)); dc.SetFont( wind->GetFont() ); return (dc.GetCharHeight() + 1 ) * rows; } int pxGetCharHeight( const wxWindow& wind, int rows ) { return pxGetCharHeight( &wind, rows ); }
[ "koeiprogenitor@bfa1b011-20a7-a6e3-c617-88e5d26e11c5" ]
[ [ [ 1, 464 ] ] ]
55e8e2e77eb1b16013c0a686af8545239c354332
989aa92c9dab9a90373c8f28aa996c7714a758eb
/HydraIRC/include/FixedMDICommandBar.h
e03e92a048549c14ac946628dc3f7c9f229ae78a
[]
no_license
john-peterson/hydrairc
5139ce002e2537d4bd8fbdcebfec6853168f23bc
f04b7f4abf0de0d2536aef93bd32bea5c4764445
refs/heads/master
2021-01-16T20:14:03.793977
2010-04-03T02:10:39
2010-04-03T02:10:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,858
h
// Original Code by Nenad Stefanovic [[email protected]] from the WTL Mailing List // Revision 1 - 16/12/2003 class CFixedMDICommandBarCtrl : public CMDICommandBarCtrlImpl<CFixedMDICommandBarCtrl> { public: DECLARE_WND_SUPERCLASS(_T("WTL_FixedMDICommandBar"),GetWndClassName()) typedef CMDICommandBarCtrlImpl<CFixedMDICommandBarCtrl> _baseClass; typedef CCommandBarCtrlImpl<CFixedMDICommandBarCtrl> _baseBaseClass; BEGIN_MSG_MAP(CFixedMDICommandBarCtrl) CHAIN_MSG_MAP(_baseClass) ALT_MSG_MAP(1) // Parent window messages CHAIN_MSG_MAP_ALT(_baseClass, 1) ALT_MSG_MAP(2) // MDI client window messages CHAIN_MSG_MAP_ALT(_baseClass, 2) ALT_MSG_MAP(3) // Message hook messages MESSAGE_RANGE_HANDLER(0, 0xFFFF, OnAllHookMessages) CHAIN_MSG_MAP_ALT(_baseBaseClass, 3) END_MSG_MAP() LRESULT OnAllHookMessages(UINT uMsg, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled) { bHandled = FALSE; if(uMsg == WM_MDIGETACTIVE || uMsg == WM_MDISETMENU) return 1; BOOL bMaximized = FALSE; HWND hWndChild = (HWND)::SendMessage(m_wndMDIClient, WM_MDIGETACTIVE, 0, (LPARAM)&bMaximized); bool bMaxOld = m_bChildMaximized; m_bChildMaximized = (hWndChild != NULL && bMaximized); HICON hIconOld = m_hIconChildMaximized; if(m_bChildMaximized) { if(m_hWndChildMaximized != hWndChild) { ATL::CWindow wnd = m_hWndChildMaximized = hWndChild; m_hIconChildMaximized = wnd.GetIcon(FALSE); if(m_hIconChildMaximized == NULL) { m_hIconChildMaximized = wnd.GetIcon(TRUE); if(m_hIconChildMaximized == NULL) { // no icon set with WM_SETICON, get the class one // need conditional code because types don't match in winuser.h #ifdef _WIN64 m_hIconChildMaximized = (HICON)::GetClassLongPtr(wnd, GCLP_HICONSM); #else m_hIconChildMaximized = (HICON)LongToHandle(::GetClassLongPtr(wnd, GCLP_HICONSM)); #endif } } } } else { m_hWndChildMaximized = NULL; m_hIconChildMaximized = NULL; } /*fix*/ if(bMaxOld != m_bChildMaximized) { #ifdef _CMDBAR_EXTRA_TRACE ATLTRACE2(atlTraceUI, 0, "MDI CmdBar - All messages hook change: m_bChildMaximized = %s\n", m_bChildMaximized ? "true" : "false"); #endif // assuming we are in a rebar, change our size to accomodate new state // we hope that if we are not in a rebar, nCount will be 0 int nCount = (int)::SendMessage(GetParent(), RB_GETBANDCOUNT, 0, 0L); int cxDiff = (m_bChildMaximized ? 1 : -1) * (m_cxLeft + m_cxRight); for(int i = 0; i < nCount; i++) { #if (_WIN32_IE >= 0x0500) REBARBANDINFO rbi = { sizeof(REBARBANDINFO), RBBIM_CHILD | RBBIM_CHILDSIZE | RBBIM_IDEALSIZE | RBBIM_STYLE }; ::SendMessage(GetParent(), RB_GETBANDINFO, i, (LPARAM)&rbi); if(rbi.hwndChild == m_hWnd) { if((rbi.fStyle & RBBS_USECHEVRON) != 0) { rbi.fMask = RBBIM_CHILDSIZE | RBBIM_IDEALSIZE; rbi.cxMinChild += cxDiff; rbi.cxIdeal += cxDiff; ::SendMessage(GetParent(), RB_SETBANDINFO, i, (LPARAM)&rbi); } break; } #elif (_WIN32_IE >= 0x0400) REBARBANDINFO rbi = { sizeof(REBARBANDINFO), RBBIM_CHILD | RBBIM_CHILDSIZE | RBBIM_IDEALSIZE }; ::SendMessage(GetParent(), RB_GETBANDINFO, i, (LPARAM)&rbi); if(rbi.hwndChild == m_hWnd) { rbi.fMask = RBBIM_CHILDSIZE | RBBIM_IDEALSIZE; rbi.cxMinChild += cxDiff; rbi.cxIdeal += cxDiff; ::SendMessage(GetParent(), RB_SETBANDINFO, i, (LPARAM)&rbi); break; } #else //(_WIN32_IE < 0x0400) REBARBANDINFO rbi = { sizeof(REBARBANDINFO), RBBIM_CHILD | RBBIM_CHILDSIZE }; ::SendMessage(GetParent(), RB_GETBANDINFO, i, (LPARAM)&rbi); if(rbi.hwndChild == m_hWnd) { rbi.fMask = RBBIM_CHILDSIZE; rbi.cxMinChild += cxDiff; ::SendMessage(GetParent(), RB_SETBANDINFO, i, (LPARAM)&rbi); break; } #endif //(_WIN32_IE < 0x0400) } /*fix*/ } /*fix*/ if(bMaxOld != m_bChildMaximized || hIconOld != m_hIconChildMaximized) /*fix*/ { // force size change and redraw everything RECT rect = { 0 }; GetWindowRect(&rect); ::MapWindowPoints(NULL, GetParent(), (LPPOINT)&rect, 2); SetRedraw(FALSE); SetWindowPos(NULL, 0, 0, 1, 1, SWP_NOZORDER | SWP_NOMOVE); SetWindowPos(NULL, &rect, SWP_NOZORDER | SWP_NOMOVE); SetRedraw(TRUE); RedrawWindow(NULL, NULL, RDW_FRAME | RDW_INVALIDATE | RDW_UPDATENOW); } return 1; } };
[ "hydra@b2473a34-e2c4-0310-847b-bd686bddb4b0" ]
[ [ [ 1, 129 ] ] ]
77d0e1c87b596910e4e7020be338db8733792eb2
138a353006eb1376668037fcdfbafc05450aa413
/source/ogre/OgreNewt/boost/mpl/aux_/config/overload_resolution.hpp
e5705dff61ba764d2f859297ed2019b4afaaad90
[]
no_license
sonicma7/choreopower
107ed0a5f2eb5fa9e47378702469b77554e44746
1480a8f9512531665695b46dcfdde3f689888053
refs/heads/master
2020-05-16T20:53:11.590126
2009-11-18T03:10:12
2009-11-18T03:10:12
32,246,184
0
0
null
null
null
null
UTF-8
C++
false
false
981
hpp
#ifndef BOOST_MPL_AUX_CONFIG_OVERLOAD_RESOLUTION_HPP_INCLUDED #define BOOST_MPL_AUX_CONFIG_OVERLOAD_RESOLUTION_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2002-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/mpl for documentation. // $Source: /cvsroot/ogre/ogreaddons/ogrenewt/OgreNewt_Main/inc/boost/mpl/aux_/config/overload_resolution.hpp,v $ // $Date: 2006/04/17 23:47:07 $ // $Revision: 1.1 $ #include <boost/mpl/aux_/config/workaround.hpp> #if !defined(BOOST_MPL_CFG_BROKEN_OVERLOAD_RESOLUTION) \ && !defined(BOOST_MPL_PREPROCESSING_MODE) \ && ( BOOST_WORKAROUND(__BORLANDC__, < 0x600) \ || BOOST_WORKAROUND(__MWERKS__, < 0x3001) \ ) # define BOOST_MPL_CFG_BROKEN_OVERLOAD_RESOLUTION #endif #endif // BOOST_MPL_AUX_CONFIG_OVERLOAD_RESOLUTION_HPP_INCLUDED
[ "Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e" ]
[ [ [ 1, 29 ] ] ]
9f617bbc2debf5ac206796eb4faee817f6076551
c5ecda551cefa7aaa54b787850b55a2d8fd12387
/src/UILayer/DlgMainTabSidePanel.h
2183c423900eeccb84a30160c80d6d13203191d7
[]
no_license
firespeed79/easymule
b2520bfc44977c4e0643064bbc7211c0ce30cf66
3f890fa7ed2526c782cfcfabb5aac08c1e70e033
refs/heads/master
2021-05-28T20:52:15.983758
2007-12-05T09:41:56
2007-12-05T09:41:56
null
0
0
null
null
null
null
GB18030
C++
false
false
1,121
h
#pragma once // CDlgMainTabSidePanel 对话框 #include "Resource.h" #include "afxwin.h" #include "SearchButton.h" //#include "SpeedMeter.h" #include "SearchBarCtrl.h" class CDlgMainTabSidePanel : public CDialog { DECLARE_DYNAMIC(CDlgMainTabSidePanel) //DECLARE_ANCHOR_MAP() //Added by thilon on 2007.02.03, for Resize public: CDlgMainTabSidePanel(CWnd* pParent = NULL); // 标准构造函数 virtual ~CDlgMainTabSidePanel(); // 对话框数据 enum { IDD = IDD_MAINTAB_SIDEPANEL }; public: CSearchBarCtrl m_SearchBarCtrl; CSearchButton m_SearchButton; public: int GetDesireWidth(); void Resize(); protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: //afx_msg BOOL OnEraseBkgnd(CDC* pDC); LRESULT OnEraseBkgndEx(WPARAM wParam, LPARAM lParam); virtual BOOL OnInitDialog(); afx_msg void OnSize(UINT nType, int cx, int cy); protected: virtual void OnCancel(); protected: // afx_msg void OnBnClickedSearchbutton(); protected: virtual void OnOK(); public: afx_msg void OnPaint(); };
[ "LanceFong@4a627187-453b-0410-a94d-992500ef832d" ]
[ [ [ 1, 50 ] ] ]
d004ddc1e47b50884118608112cc9a7dbc4f401b
38794c3c38c9c9abfd7206ad353aaae0c0b33f18
/Trab1_a_Inicial/Printer.h
23efcb3c4a2ead4c030a076c2efb5ae25c306356
[]
no_license
Highvolt/laig-part1
37e765cb2705b206c36f987e255ab453abf00dfb
0e07a6fc2c086f49131907767c463d298ff72b1f
refs/heads/master
2021-01-10T20:26:08.520711
2011-09-21T11:29:09
2011-09-21T11:29:09
32,182,761
0
0
null
null
null
null
UTF-8
C++
false
false
82
h
#pragma once class Printer { public: Printer(void); ~Printer(void); };
[ [ [ 1, 8 ] ] ]
cb73a4561ffc2433d6406ce78a13083fc2ad9f0f
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/mangalore/application/playvideohandler.cc
1089d709148a19adf83a9f1fb7436f35c63506bb
[]
no_license
moltenguy1/minimangalore
9f2edf7901e7392490cc22486a7cf13c1790008d
4d849672a6f25d8e441245d374b6bde4b59cbd48
refs/heads/master
2020-04-23T08:57:16.492734
2009-08-01T09:13:33
2009-08-01T09:13:33
35,933,330
0
0
null
null
null
null
UTF-8
C++
false
false
2,597
cc
//------------------------------------------------------------------------------ // application/playvideohandler.cc // (C) 2005 RadonLabs GmbH //------------------------------------------------------------------------------ #include "application/playvideohandler.h" #include "application/app.h" #include "video/nvideoserver.h" #include "input/ninputserver.h" #include "gfx2/ngfxserver2.h" #include "managers/timemanager.h" #include "game/time/systemtimesource.h" namespace Application { ImplementRtti(Application::PlayVideoHandler, Application::StateHandler); ImplementFactory(Application::PlayVideoHandler); using namespace Managers; using namespace Game; //------------------------------------------------------------------------------ /** */ PlayVideoHandler::PlayVideoHandler() : enableScaling(false) { // empty } //------------------------------------------------------------------------------ /** */ PlayVideoHandler::~PlayVideoHandler() { // empty } //------------------------------------------------------------------------------ /** */ void PlayVideoHandler::OnStateEnter(const nString& prevState) { TimeManager::Instance()->ResetAll(); TimeManager::Instance()->Update(); StateHandler::OnStateEnter(prevState); n_assert(!this->videoFileName.IsEmpty()); nVideoServer::Instance()->SetEnableScaling(this->GetEnableScaling()); nVideoServer::Instance()->PlayFile(this->videoFileName.Get()); } //------------------------------------------------------------------------------ /** */ nString PlayVideoHandler::OnFrame() { nString returnState = App::Instance()->GetCurrentState(); TimeManager::Instance()->Update(); nInputServer* inputServer = nInputServer::Instance(); nVideoServer* videoServer = nVideoServer::Instance(); nGfxServer2* gfxServer = nGfxServer2::Instance(); // distribute timestamps to interested subsystems if (gfxServer->Trigger()) { // trigger input and video servers videoServer->Trigger(); inputServer->Trigger(SystemTimeSource::Instance()->GetTime()); // check if video has finished if (!videoServer->IsPlaying()) { returnState = this->nextState; } } else { // handle Alt-F4 pressed returnState = "Exit"; } // flush input events inputServer->FlushEvents(); // trigger kernel server at end of frame nKernelServer::Instance()->Trigger(); return returnState; } } // namespace Application
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 93 ] ] ]
3d5a206a0b9e5fff567aa7cce8510c47fa80f962
94d9e8ec108a2f79068da09cb6ac903c16b77730
/sociarium/graph_utility.h
7d95df005f1a46ee7a7887290af8c132a9afb6a8
[]
no_license
kiyoya/sociarium
d375c0e5abcce11ae4b087930677483d74864d09
b26c2c9cbd23c2f8ef219d0059e42370294865d1
refs/heads/master
2021-01-25T07:28:25.862346
2009-10-22T05:57:42
2009-10-22T05:57:42
318,115
1
0
null
null
null
null
UTF-8
C++
false
false
6,012
h
// s.o.c.i.a.r.i.u.m: graph_utility.h // HASHIMOTO, Yasuhiro (E-mail: hy @ sys.t.u-tokyo.ac.jp) /* Copyright (c) 2005-2009, HASHIMOTO, Yasuhiro, All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of the University of Tokyo nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef INCLUDE_GUARD_SOCIARIUM_PROJECT_GRAPH_UTILITY_H #define INCLUDE_GUARD_SOCIARIUM_PROJECT_GRAPH_UTILITY_H #include <vector> #include <string> #include <utility> #include "../graph/graph.h" namespace hashimoto_ut { class Thread; class BFSTraverser; class DFSTraverser; class BFSRecordingTraverser; class Message; namespace sociarium_project_graph_utility { /* * If the first return value is false, it means the thread was cancelled. */ //////////////////////////////////////////////////////////////////////////////// // Closeness Centrality std::pair<bool, std::vector<double> > closeness_centrality( Thread* parent, std::wstring* status, Message const* message, std::tr1::shared_ptr<BFSTraverser> t); //////////////////////////////////////////////////////////////////////////////// // Mean Shortest Path Length std::pair<bool, double> mean_shortest_path_length( Thread* parent, std::wstring* status, Message const* message, std::tr1::shared_ptr<BFSTraverser> t, node_iterator first, node_iterator last); //////////////////////////////////////////////////////////////////////////////// // All Connected Components std::pair<bool, std::vector<std::vector<Node*> > > connected_components( Thread* parent, std::wstring* status, Message const* message, std::tr1::shared_ptr<BFSTraverser> t, size_t minimum_size=0); //////////////////////////////////////////////////////////////////////////////// // All Strongly Connected Components std::pair<bool, std::vector<std::vector<Node*> > > strongly_connected_components( Thread* parent, std::wstring* status, Message const* message, std::tr1::shared_ptr<DFSTraverser> t_forward, std::tr1::shared_ptr<BFSTraverser> t_backward, size_t minimum_size=0); //////////////////////////////////////////////////////////////////////////////// // Connected Component (starting from the node @n) std::pair<bool, std::vector<Node*> > connected_component( Thread* parent, std::wstring* status, Message const* message, std::tr1::shared_ptr<BFSTraverser> t, Node const* n); //////////////////////////////////////////////////////////////////////////////// // Betweenness Centrality std::pair<bool, std::pair<std::vector<double>, std::vector<double> > > betweenness_centrality( Thread* parent, std::wstring* status, Message const* message, std::tr1::shared_ptr<BFSRecordingTraverser> t); //////////////////////////////////////////////////////////////////////////////// // PageRank std::pair<bool, std::vector<double> > pagerank( Thread* parent, std::wstring* status, Message const* message, std::tr1::shared_ptr<Graph const> g, double dumping_factor, double err); //////////////////////////////////////////////////////////////////////////////// // Modularity std::pair<bool, double> modularity( Thread* parent, std::wstring* status, Message const* message, std::tr1::shared_ptr<Graph const> g, std::vector<std::vector<Node*> > const& community, std::vector<double> const& edge_weight); //////////////////////////////////////////////////////////////////////////////// // All Largest Cliques std::pair<bool, std::vector<std::vector<Node*> > > largest_cliques( Thread* parent, std::wstring* status, Message const* message, std::tr1::shared_ptr<Graph const> g); //////////////////////////////////////////////////////////////////////////////// // 3-Clique Communities std::pair<bool, std::vector<std::vector<Node*> > > clique_communities_3( Thread* parent, std::wstring* status, Message const* message, std::tr1::shared_ptr<Graph const> g); } // The end of the namespace "sociarium_project_graph_utility" } // The end of the namespace "hashimoto_ut" #endif // INCLUDE_GUARD_SOCIARIUM_PROJECT_GRAPH_UTILITY_H
[ [ [ 1, 147 ] ] ]
47484e729abdea0f0b0f592d2c98248d8ef5c84d
110f8081090ba9591d295d617a55a674467d127e
/tests/AlgebraTheoryTest.cpp
6a3118346ba15ec1c18993086390eb847c0949f6
[]
no_license
rayfill/cpplib
617bcf04368a2db70aea8b9418a45d7fd187d8c2
bc37fbf0732141d0107dd93bcf5e0b31f0d078ca
refs/heads/master
2021-01-25T03:49:26.965162
2011-07-17T15:19:11
2011-07-17T15:19:11
783,979
1
0
null
null
null
null
UTF-8
C++
false
false
1,111
cpp
#include <iostream> #include <cppunit/extensions/HelperMacros.h> #include <math/theory/AlgebraTheory.hpp> #include <math/MPI.hpp> #include <iostream> class AlgebraTheoryTest : public CppUnit::TestFixture { private: CPPUNIT_TEST_SUITE(AlgebraTheoryTest); CPPUNIT_TEST(invertTest); CPPUNIT_TEST(gcdTest); CPPUNIT_TEST(lcmTest); CPPUNIT_TEST_SUITE_END(); public: void invertTest() { CPPUNIT_ASSERT((5 * modulusInvert(5, 7)) % 7 == 1); MPInteger a(5U); MPInteger b(7U); CPPUNIT_ASSERT((a * modulusInvert(a, b)) % b == MPInteger(1U)); } void gcdTest() { CPPUNIT_ASSERT(gcd(7, 5) == 1); MPInteger a(7U); MPInteger b(5U); CPPUNIT_ASSERT(gcd(a, b) == 1U); a = MPInteger(30000000U); b = MPInteger(150000U); CPPUNIT_ASSERT(gcd(a, b) == b); } void lcmTest() { CPPUNIT_ASSERT(lcm(7, 5) == 35); CPPUNIT_ASSERT(lcm(6, 8) == 24); MPInteger a(7U), b(5U), c(6U), d(8U); CPPUNIT_ASSERT(lcm(a, b) == MPInteger(35U)); CPPUNIT_ASSERT(lcm(c, d) == MPInteger(24U)); } }; CPPUNIT_TEST_SUITE_REGISTRATION( AlgebraTheoryTest );
[ "bpokazakijr@287b3242-7fab-264f-8401-8509467ab285" ]
[ [ [ 1, 51 ] ] ]
d06acd5f0ec792c3fefc5b5ebefacef402dccfed
30a1e1c0c95239e5fa248fbb1b4ed41c6fe825ff
/c/debug.cpp
4b71dd3067cd873e409ae6067fdaeb94094a2b59
[]
no_license
inspirer/history
ed158ef5c04cdf95270821663820cf613b5c8de0
6df0145cd28477b23748b1b50e4264a67441daae
refs/heads/master
2021-01-01T17:22:46.101365
2011-06-12T00:58:37
2011-06-12T00:58:37
1,882,931
1
0
null
null
null
null
UTF-8
C++
false
false
4,152
cpp
/* debug.cpp * * C Compiler project (cc) * Copyright (C) 2002-03 Eugeniy Gryaznov ([email protected]) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "cc.h" #ifdef DEBUG_TREE // sym::storage const static char *sym_storage[] = { "scs_none", // 0, "scs_extern", // 1, "scs_static", // 2, "scs_auto", // 3, "scs_register",// 4, "scs_typedef", // 5, "scs_???", // 6, "scs_imm", // 7, "scs_bitfield",// 8, "scs_member", // 9, "scs_arg", // 10, "scs_arg_reg", // 11, "scs_label", // 12, "scs_code", // 13, }; // sym::ns_modifier static const char *sym_ns_mod( int i ) { switch( i ) { case 0: return "sym"; case t_struct: return "struct"; case t_union: return "union"; case t_enum: return "enum"; case t_typename:return "typename"; case t_label: return "label"; default: return "unknown_ns_modifier"; } } void debug_show_sym( Sym s, int deep ) { while( s ) { const char *storage, *tag; storage = ( s->storage >= 0 && s->storage < scs_max ) ? sym_storage[s->storage] : "scs_unkn"; tag = sym_ns_mod( s->ns_modifier ); printf( "sym(\n%*sname='%s' mod='%s'", deep+4, "", s->name ? s->name : "", tag ); if( !s->ns_modifier ) printf( " storage='%s'", storage ); switch( s->storage ) { case scs_imm: printf( " value=%I64u", s->loc.val.u );break; case scs_arg: case scs_arg_reg: printf( " offset=%u", s->loc.arg.offset );break; case scs_member: case scs_bitfield: printf( " offset=%u", s->loc.member.offset );break; } printf( "\n%*s", deep+4, "" ); debug_show_type( s->type, deep+4 ); s = s->next; printf( "%*s)%s", deep, "", s ? " => " : "\n" ); } } const char *aggr_type_spec[] = { "t_typename", // 0x40 "t_struct", // 0x41 "t_union", // 0x42 "t_array", // 0x43 "t_func", // 0x44 "t_pointer", // 0x45 "t_enum", // 0x46 "t_label", // 0x47 }; void debug_show_type( Type t, int deep ) { const char *spec; char qual[128]; Type s = t; printf( "type(\n" ); while( s ) { spec = ( BASICTYPE(s) ) ? tdescr[T(s)].name : ( ( T(s) >= t_typename && T(s) <= t_label ) ? aggr_type_spec[T(s)-t_typename] : "unkn_spec" ); qual[0] = qual[1] = 0; if( Q(s) & tq_const ) strcat( qual, " const" ); if( Q(s) & tq_volatile ) strcat( qual, " volatile" ); if( Q(s) & tq_restrict ) strcat( qual, " restrict" ); printf( "%*sspecifier='%s' qual='%s' size=%i align=%i", deep+4, "", spec, qual+1, s->size, s->align ); if( ( T(s) == t_struct || T(s) == t_union ) && s->tagname ) printf( " tag='%s'", s->tagname ); if( T(s) == t_array ) { if( s->ar_size_val > 0 ) printf( " dim=%i", s->ar_size_val ); else if( s->ar_size_val == 0 ) printf( " dim=undef" ); else printf( " dim=var" ); } printf( s->parent ? " =>\n" : "\n" ); if( (T(s) == t_struct || T(s) == t_union) && s == t && s->params ) { printf( "%*scontains = ", deep+4, "" ); debug_show_sym( s->params, deep + 8 ); } else if( s->specifier == t_func ) { if( s->params ) { printf( "%*sparams = ", deep+4, "" ); debug_show_sym( s->params, deep + 8 ); } printf( "%*sreturn = ", deep+4, "" ); debug_show_type( s->parent, deep + 8 ); break; } s = s->parent; } printf( "%*s)\n", deep, "" ); } #endif
[ [ [ 1, 146 ] ] ]
56ac1745b33b09a5bfe85f0732052bd8d25bf4c6
490dc417d83abcdaef818c233b26cd47661e8874
/test.cpp
a9fa5a14f70541a50833aedda8cd586031de1a30
[]
no_license
j0x7c4/cvhw
0c891578962d3586a924d766dee7a012a44a5e29
23b0a09a9f03f9df3b2897e524ecaf394000fde1
refs/heads/master
2016-08-04T09:06:22.787543
2011-12-29T07:19:25
2011-12-29T07:19:25
2,430,222
0
0
null
null
null
null
UTF-8
C++
false
false
1,150
cpp
#include <iostream> #include "cvhw.h" using namespace cv; int main ( ) { CVHW cvhw("C:\\Users\\Jie\\Dropbox\\lena.bmp",CV_8U); Mat image = cvhw.get_image().clone(); Mat res; cvhw.RobertsOperator(image,res,12); imwrite("C:\\Users\\Jie\\Documents\\CVHW\\hw9\\RobertsOperator_12.bmp",res); cvhw.PrewittEdgeDetector(image,res,24); imwrite("C:\\Users\\Jie\\Documents\\CVHW\\hw9\\PrewittEdgeDetector_24.bmp",res); cvhw.SobelEdgeDetector(image,res,38); imwrite("C:\\Users\\Jie\\Documents\\CVHW\\hw9\\SobelEdgeDetector_38.bmp",res); cvhw.FreiAndChenGradientOperator(image,res,30); imwrite("C:\\Users\\Jie\\Documents\\CVHW\\hw9\\FreiAndChenGradientOperator_30.bmp",res); cvhw.KirschCompassOperator(image,res,135); imwrite("C:\\Users\\Jie\\Documents\\CVHW\\hw9\\KirschCompassOperator_135.bmp",res); cvhw.RobinsonCompassOperator(image,res,43); imwrite("C:\\Users\\Jie\\Documents\\CVHW\\hw9\\RobinsonCompassOperator_43.bmp",res); cvhw.NevatiaBabuOperator(image,res,12500); imwrite("C:\\Users\\Jie\\Documents\\CVHW\\hw9\\NevatiaBabuOperator_12500.bmp",res); imshow("res",res); waitKey(0); return 0; }
[ "Jie@Jie-vr-PC.(none)", "[email protected]" ]
[ [ [ 1, 25 ] ], [ [ 26, 26 ] ] ]
8b0b4260d05d18b810970fceb5eff33f78969992
7b379862f58f587d9327db829ae4c6493b745bb1
/Source/OSCListener.h
27fd8331feebaa31136c04f8feb044e5747ebe31
[]
no_license
owenvallis/Nomestate
75e844e8ab68933d481640c12019f0d734c62065
7fe7c06c2893421a3c77b5180e5f27ab61dd0ffd
refs/heads/master
2021-01-19T07:35:14.301832
2011-12-28T07:42:50
2011-12-28T07:42:50
2,950,072
2
0
null
null
null
null
UTF-8
C++
false
false
1,302
h
/* ============================================================================== OSCListener.h Created: 13 Oct 2011 11:32:49pm Author: Dimitri Diakopoulos ============================================================================== */ #ifndef __OSCLISTENER_H_FDF951A6__ #define __OSCLISTENER_H_FDF951A6__ #include "../JuceLibraryCode/JuceHeader.h" #include "OscTypes.h" #include "OscPacketListener.h" #include "UdpSocket.h" #include <deque> #include "OSCMessage.h" class OSCListener : public osc::OscPacketListener, public Thread { public: OSCListener(); ~OSCListener(); void startListening(String, int); void stopListening(); bool hasWaitingMessages(); bool getNextMessage( OSCMessage* ); bool isListening(); bool isActive; virtual void handleOSC() {}; protected: UdpListeningReceiveSocket* socket; /// process an incoming osc message and add it to the queue virtual void ProcessMessage( const osc::ReceivedMessage &m, const IpEndpointName& remoteEndpoint ); private: void run(); std::deque<OSCMessage*> messages; bool socketHasShutdown; }; #endif // __OSCLISTENER_H_FDF951A6__
[ "ow3nskip" ]
[ [ [ 1, 65 ] ] ]
cc2caffa1e1e055a0bf24f2e47b7f6da247ad4bb
58496be10ead81e2531e995f7d66017ffdfc6897
/Sources/Network/TCPServer.cpp
5d09ae002beb461d20c01f4c1a1a9d1d8ee36caf
[]
no_license
Diego160289/cross-fw
ba36fc6c3e3402b2fff940342315596e0365d9dd
532286667b0fd05c9b7f990945f42279bac74543
refs/heads/master
2021-01-10T19:23:43.622578
2011-01-09T14:54:12
2011-01-09T14:54:12
38,457,864
0
0
null
null
null
null
UTF-8
C++
false
false
3,900
cpp
//============================================================================ // Date : 27.12.2010 // Author : Tkachenko Dmitry // Copyright : (c) Tkachenko Dmitry ([email protected]) //============================================================================ #include "TCPServer.h" namespace { class ICtrlItemImpl : public Common::CoClassBase < TYPE_LIST_1(IFaces::Network::ICtrlItem) > { public: DECLARE_UUID(eb463abc-d362-47b0-941d-a3470a75e1ea) ICtrlItemImpl() : Ctrl(0) { } //ICtrlItem virtual IFaces::RetCode CloseMe() { Common::ISyncObject Locker(GetSynObj()); if (!Ctrl) return IFaces::retFail; Ctrl->CloseMe(); return IFaces::retOk; } virtual IFaces::RetCode SendData(const void *data, unsigned bytes) { if (!data || !bytes) return IFaces::retBadParam; Common::ISyncObject Locker(GetSynObj()); if (!Ctrl) return IFaces::retFail; try { Ctrl->SendData(data, bytes); } catch (std::exception &) { return IFaces::retFail; } return IFaces::retOk; } void SetCtrl(Socks::ICtrlItem *ctrl) { Common::ISyncObject Locker(GetSynObj()); Ctrl = ctrl; } private: Socks::ICtrlItem *Ctrl; }; class IClientImpl : private Common::NoCopyable , public Socks::IClient { public: IClientImpl(Socks::ICtrlItem &ctrl, Common::RefObjPtr<ICtrlItemImpl> ctrlItem, Common::RefObjPtr<IFaces::Network::IClient> client) : CtrlItem(ctrlItem) , Client(client) { CtrlItem->SetCtrl(&ctrl); } ~IClientImpl() { CtrlItem->SetCtrl(0); } virtual bool OnData(const void *data, unsigned bytes) { return Client->OnData(data, bytes) == IFaces::retOk; } private: Common::RefObjPtr<ICtrlItemImpl> CtrlItem; Common::RefObjPtr<IFaces::Network::IClient> Client; }; class ClientFactory : private Common::NoCopyable , public Socks::IClientFactory { public: ClientFactory(Common::ISynObj &synObj, IFaces::Network::IClientFactory *factory) : SynObj(synObj) , Factory(factory) { } virtual Socks::IClientPtr CreateClient(Socks::ICtrlItem &ctrl) { Common::RefObjPtr<ICtrlItemImpl> CtrlItem = Common::IBaseImpl<ICtrlItemImpl>::CreateWithSyn(SynObj); Common::RefObjPtr<IFaces::Network::IClient> Client; if (Factory->CreateClient(CtrlItem.Get(), Client.GetPPtr()) != IFaces::retOk) return Socks::IClientPtr(0); Socks::IClientPtr Item(new IClientImpl(ctrl, CtrlItem, Client)); return Item; } private: Common::ISynObj &SynObj; Common::RefObjPtr<IFaces::Network::IClientFactory> Factory; }; } IFaces::RetCode ITCPServerImpl::Start(const char *host, unsigned short port, unsigned threadCount, unsigned maxConnectCount, IFaces::Network::IClientFactory *factory) { if (!host || !factory) return IFaces::retBadParam; Common::ISyncObject Locker(GetSynObj()); if (Server.Get()) return IFaces::retFalse; try { Server.Reset(new Socks::TCPServer(host, port, threadCount, maxConnectCount, Socks::IClientFactoryPtr(new ClientFactory(GetSynObj(), factory)))); } catch (std::exception &) { return IFaces::retFail; } return IFaces::retOk; } IFaces::RetCode ITCPServerImpl::Stop() { Common::ISyncObject Locker(GetSynObj()); if (!Server.Get()) return IFaces::retFail; Server.Release(); return IFaces::retOk; }
[ "TkachenkoDmitryV@d548627a-540d-11de-936b-e9512c4d2277" ]
[ [ [ 1, 148 ] ] ]
f542d62b749331d451602674cf551fac9c97fd2b
463c3b62132d215e245a097a921859ecb498f723
/lib/dlib/svm/kkmeans_abstract.h
4ef5faa9216e82ee2162c51c9cd7703f83d40f44
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
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,916
h
// Copyright (C) 2008 Davis E. King ([email protected]) // License: Boost Software License See LICENSE.txt for the full license. #undef DLIB_KKMEANs_ABSTRACT_ #ifdef DLIB_KKMEANs_ABSTRACT_ #include <cmath> #include "../matrix/matrix_abstract.h" #include "../algs.h" #include "../serialize.h" #include "kernel_abstract.h" #include "kcentroid_abstract.h" #include "../noncopyable.h" namespace dlib { template < typename kernel_type > class kkmeans : public noncopyable { /*! REQUIREMENTS ON kernel_type is a kernel function object as defined in dlib/svm/kernel_abstract.h INITIAL VALUE - number_of_centers() == 1 - get_min_change() == 0.01 WHAT THIS OBJECT REPRESENTS This is an implementation of a kernelized k-means clustering algorithm. It performs k-means clustering by using the kcentroid object. !*/ public: typedef typename kernel_type::scalar_type scalar_type; typedef typename kernel_type::sample_type sample_type; typedef typename kernel_type::mem_manager_type mem_manager_type; kkmeans ( const kcentroid<kernel_type>& kc_ ); /*! ensures - #number_of_centers() == 1 - #get_min_change() == 0.01 - #get_kcentroid(0) == a copy of kc_ !*/ ~kkmeans( ); /*! ensures - all resources associated with *this have been released !*/ void set_kcentroid ( const kcentroid<kernel_type>& kc_ ); /*! ensures - for all idx: - #get_kcentroid(idx) == a copy of kc_ !*/ const kcentroid<kernel_type>& get_kcentroid ( unsigned long i ) const; /*! requires - i < number_of_centers() ensures - returns a const reference to the ith kcentroid object contained in this object. Each kcentroid represents one of the centers found by the k-means clustering algorithm. !*/ const kernel_type& get_kernel ( ) const; /*! ensures - returns a const reference to the kernel used by this object !*/ void set_number_of_centers ( unsigned long num ); /*! requires - num > 0 ensures - #number_of_centers() == num !*/ unsigned long number_of_centers ( ) const; /*! ensures - returns the number of centers used in this instance of the k-means clustering algorithm. !*/ template < typename matrix_type, typename matrix_type2 > void train ( const matrix_type& samples, const matrix_type2& initial_centers, long max_iter = 1000 ); /*! requires - matrix_type and matrix_type2 must either be dlib::matrix objects or convertible to dlib::matrix via vector_to_matrix() - matrix_type::type == sample_type (i.e. matrix_type should contain sample_type objects) - matrix_type2::type == sample_type (i.e. matrix_type2 should contain sample_type objects) - initial_centers.nc() == 1 (i.e. must be a column vector) - samples.nc() == 1 (i.e. must be a column vector) - initial_centers.nr() == number_of_centers() ensures - performs k-means clustering of the given set of samples. The initial center points are taken from the initial_centers argument. - loops over the data and continues to refine the clustering until either less than get_min_change() fraction of the data points change clusters or we have done max_iter iterations over the data. - After this function finishes you can call the operator() function below to determine which centroid a given sample is closest to. !*/ unsigned long operator() ( const sample_type& sample ) const; /*! ensures - returns a number idx such that: - idx < number_of_centers() - get_kcentroid(idx) == the centroid that is closest to the given sample. !*/ void set_min_change ( scalar_type min_change ); /*! requires - 0 <= min_change < 1 ensures - #get_min_change() == min_change !*/ const scalar_type get_min_change ( ) const; /*! ensures - returns the minimum fraction of data points that need to change centers in an iteration of kmeans for the algorithm to keep going. !*/ void swap ( kkmeans& item ); /*! ensures - swaps *this and item !*/ }; // ---------------------------------------------------------------------------------------- template < typename kernel_type > void swap( kkmeans<kernel_type>& a, kkmeans<kernel_type>& b ) { a.swap(b); } /*! provides a global swap function !*/ template < typename kernel_type > void serialize ( const kkmeans<kernel_type>& item, std::ostream& out ); /*! provides serialization support for kkmeans objects !*/ template < typename kernel_type > void deserialize ( kkmeans<kernel_type>& item, std::istream& in ); /*! provides serialization support for kkmeans objects !*/ // ---------------------------------------------------------------------------------------- template < typename vector_type, typename kernel_type > void pick_initial_centers( long num_centers, vector_type& centers, const vector_type& samples, const kernel_type& k, double percentile = 0.01 ); /*! requires - num_centers > 1 - 0 <= percentile < 1 - samples.size() > 1 - vector_type == something with an interface compatible with std::vector - k(samples[0],samples[0]) must be a valid expression that returns a double ensures - finds num_centers candidate cluster centers in the data in the samples vector. Assumes that k is the kernel that will be used during clustering to define the space in which clustering occurs. - The centers are found by looking for points that are far away from other candidate centers. However, if the data is noisy you probably want to ignore the farthest way points since they will be outliers. To do this set percentile to the fraction of outliers you expect the data to contain. - #centers.size() == num_centers - #centers == a vector containing the candidate centers found !*/ // ---------------------------------------------------------------------------------------- } #endif // DLIB_KKMEANs_ABSTRACT_
[ "jimmy@DGJ3X3B1.(none)" ]
[ [ [ 1, 241 ] ] ]
841ddb9195b3f9083d92219ea53418f179ec6918
8c24dd2b8fffd985caf897d5740dba2a19fdcbab
/shared/ruby/generated/node_name.inc
435631067d2d6a8e39fd0fc1a7722b6ec5b719dd
[]
no_license
professor/rhodes
677c279b1813460a3c551b5822f07c6f443a0685
d6a276ee59eee046a5e5b75fabbec591cbccc489
refs/heads/master
2021-04-18T20:19:40.343818
2008-11-07T00:14:15
2008-11-07T00:14:15
72,680
2
0
null
null
null
null
UTF-8
C++
false
false
5,184
inc
case NODE_METHOD: return "NODE_METHOD"; case NODE_FBODY: return "NODE_FBODY"; case NODE_CFUNC: return "NODE_CFUNC"; case NODE_SCOPE: return "NODE_SCOPE"; case NODE_BLOCK: return "NODE_BLOCK"; case NODE_IF: return "NODE_IF"; case NODE_CASE: return "NODE_CASE"; case NODE_WHEN: return "NODE_WHEN"; case NODE_OPT_N: return "NODE_OPT_N"; case NODE_WHILE: return "NODE_WHILE"; case NODE_UNTIL: return "NODE_UNTIL"; case NODE_ITER: return "NODE_ITER"; case NODE_FOR: return "NODE_FOR"; case NODE_BREAK: return "NODE_BREAK"; case NODE_NEXT: return "NODE_NEXT"; case NODE_REDO: return "NODE_REDO"; case NODE_RETRY: return "NODE_RETRY"; case NODE_BEGIN: return "NODE_BEGIN"; case NODE_RESCUE: return "NODE_RESCUE"; case NODE_RESBODY: return "NODE_RESBODY"; case NODE_ENSURE: return "NODE_ENSURE"; case NODE_AND: return "NODE_AND"; case NODE_OR: return "NODE_OR"; case NODE_MASGN: return "NODE_MASGN"; case NODE_LASGN: return "NODE_LASGN"; case NODE_DASGN: return "NODE_DASGN"; case NODE_DASGN_CURR: return "NODE_DASGN_CURR"; case NODE_GASGN: return "NODE_GASGN"; case NODE_IASGN: return "NODE_IASGN"; case NODE_IASGN2: return "NODE_IASGN2"; case NODE_CDECL: return "NODE_CDECL"; case NODE_CVASGN: return "NODE_CVASGN"; case NODE_CVDECL: return "NODE_CVDECL"; case NODE_OP_ASGN1: return "NODE_OP_ASGN1"; case NODE_OP_ASGN2: return "NODE_OP_ASGN2"; case NODE_OP_ASGN_AND: return "NODE_OP_ASGN_AND"; case NODE_OP_ASGN_OR: return "NODE_OP_ASGN_OR"; case NODE_CALL: return "NODE_CALL"; case NODE_FCALL: return "NODE_FCALL"; case NODE_VCALL: return "NODE_VCALL"; case NODE_SUPER: return "NODE_SUPER"; case NODE_ZSUPER: return "NODE_ZSUPER"; case NODE_ARRAY: return "NODE_ARRAY"; case NODE_ZARRAY: return "NODE_ZARRAY"; case NODE_VALUES: return "NODE_VALUES"; case NODE_HASH: return "NODE_HASH"; case NODE_RETURN: return "NODE_RETURN"; case NODE_YIELD: return "NODE_YIELD"; case NODE_LVAR: return "NODE_LVAR"; case NODE_DVAR: return "NODE_DVAR"; case NODE_GVAR: return "NODE_GVAR"; case NODE_IVAR: return "NODE_IVAR"; case NODE_CONST: return "NODE_CONST"; case NODE_CVAR: return "NODE_CVAR"; case NODE_NTH_REF: return "NODE_NTH_REF"; case NODE_BACK_REF: return "NODE_BACK_REF"; case NODE_MATCH: return "NODE_MATCH"; case NODE_MATCH2: return "NODE_MATCH2"; case NODE_MATCH3: return "NODE_MATCH3"; case NODE_LIT: return "NODE_LIT"; case NODE_STR: return "NODE_STR"; case NODE_DSTR: return "NODE_DSTR"; case NODE_XSTR: return "NODE_XSTR"; case NODE_DXSTR: return "NODE_DXSTR"; case NODE_EVSTR: return "NODE_EVSTR"; case NODE_DREGX: return "NODE_DREGX"; case NODE_DREGX_ONCE: return "NODE_DREGX_ONCE"; case NODE_ARGS: return "NODE_ARGS"; case NODE_ARGS_AUX: return "NODE_ARGS_AUX"; case NODE_OPT_ARG: return "NODE_OPT_ARG"; case NODE_POSTARG: return "NODE_POSTARG"; case NODE_ARGSCAT: return "NODE_ARGSCAT"; case NODE_ARGSPUSH: return "NODE_ARGSPUSH"; case NODE_SPLAT: return "NODE_SPLAT"; case NODE_TO_ARY: return "NODE_TO_ARY"; case NODE_BLOCK_ARG: return "NODE_BLOCK_ARG"; case NODE_BLOCK_PASS: return "NODE_BLOCK_PASS"; case NODE_DEFN: return "NODE_DEFN"; case NODE_DEFS: return "NODE_DEFS"; case NODE_ALIAS: return "NODE_ALIAS"; case NODE_VALIAS: return "NODE_VALIAS"; case NODE_UNDEF: return "NODE_UNDEF"; case NODE_CLASS: return "NODE_CLASS"; case NODE_MODULE: return "NODE_MODULE"; case NODE_SCLASS: return "NODE_SCLASS"; case NODE_COLON2: return "NODE_COLON2"; case NODE_COLON3: return "NODE_COLON3"; case NODE_DOT2: return "NODE_DOT2"; case NODE_DOT3: return "NODE_DOT3"; case NODE_FLIP2: return "NODE_FLIP2"; case NODE_FLIP3: return "NODE_FLIP3"; case NODE_ATTRSET: return "NODE_ATTRSET"; case NODE_SELF: return "NODE_SELF"; case NODE_NIL: return "NODE_NIL"; case NODE_TRUE: return "NODE_TRUE"; case NODE_FALSE: return "NODE_FALSE"; case NODE_ERRINFO: return "NODE_ERRINFO"; case NODE_DEFINED: return "NODE_DEFINED"; case NODE_POSTEXE: return "NODE_POSTEXE"; case NODE_ALLOCA: return "NODE_ALLOCA"; case NODE_BMETHOD: return "NODE_BMETHOD"; case NODE_MEMO: return "NODE_MEMO"; case NODE_IFUNC: return "NODE_IFUNC"; case NODE_DSYM: return "NODE_DSYM"; case NODE_ATTRASGN: return "NODE_ATTRASGN"; case NODE_PRELUDE: return "NODE_PRELUDE"; case NODE_LAMBDA: return "NODE_LAMBDA"; case NODE_OPTBLOCK: return "NODE_OPTBLOCK";
[ [ [ 1, 216 ] ] ]
82b0d44d358089eb71cafba040c6d3183fd3131c
9df4b47eb2d37fd7f08b8e723e17f733fd21c92b
/plugintemplate/libs/lib_message.cpp
325db39a65236bbed8b469909978b0d1b678d1a8
[]
no_license
sn4k3/sourcesdk-plugintemplate
d5a806f8793ad328b21cf8e7af81903c98b07143
d89166b79a92b710d275c817be2fb723f6be64b5
refs/heads/master
2020-04-09T07:11:55.754168
2011-01-23T22:58:09
2011-01-23T22:58:09
32,112,282
1
0
null
null
null
null
ISO-8859-1
C++
false
false
23,345
cpp
//========= Copyright © 2010-2011, Tiago Conceição, All rights reserved. ============ // Plugin Template // // Please Read (LICENSE.txt) and (README.txt) // Dont Forget Visit: // (http://www.sourceplugins.com) -> VPS Plugins // (http://www.sourcemm.net) (http://forums.alliedmods.net/forumdisplay.php?f=52) - MMS Plugins // //=================================================================================== //================================================================================= // Includes //================================================================================= #define NO_INCLUDE_LIBRARIES #include "includes/default.h" #include "libs/lib_message.h" #include "tier0/memdbgon.h" //================================================================================= // Static Methods //================================================================================= // Get Message Index int LIB_MESSAGE_CLASS::GetMsgNum(const char *Msg) { #ifdef SOURCEMM return g_SMAPI->FindUserMessage(Msg); #endif char TempMsgName[40]; int dontdoit=0; #ifdef SOURCEMM int MaxScan = g_SMAPI->GetUserMessageCount(); #else int MaxScan= 20; if(LIB_STRING_CLASS::StrLeftEq(VAR_IFACE_GAMESERVERDLL->GetGameDescription(),"Counter-Strike")) MaxScan = 25; #endif for (int i=0;i<MaxScan;i++) { VAR_IFACE_GAMESERVERDLL->GetUserMessageInfo(i,TempMsgName,39,dontdoit); if(strcmp(Msg,TempMsgName) == 0) return i; } return -1; } // Print text to client console. // Filters allowed bool LIB_MESSAGE_CLASS::CPrint(const char *players, const char *msg, ...) { LIB_MRECIPIENTFILTER_CLASS mrf; if(!mrf.AddByFilter(players, false)) return false; MULTIARGS(msg); for(int i = 0; i < mrf.GetRecipientCount(); i++) { CPrint(mrf.GetRecipientEdict(i), string); } mrf.~LIB_MRECIPIENTFILTER_CLASS(); return true; } // Print text to client console. // You must free MRecipientFilter object yourself bool LIB_MESSAGE_CLASS::CPrint(LIB_MRECIPIENTFILTER_CLASS &mrf, const char *msg, ...) { int count = mrf.GetRecipientCount(); if(count == 0) return false; MULTIARGS(msg); for(int i = 0; i < count; i++) { CPrint(mrf.GetRecipientEdict(i), string); } return true; } // Print text to client console. bool LIB_MESSAGE_CLASS::CPrint(edict_t *pEntity, const char *msg, ...) { IPlayerInfo *playerinfo = LIB_ENTITY_CLASS::GetPlayerinfoFromEntity(pEntity); if(!playerinfo) return false; if(playerinfo->IsFakeClient()) return false; // Bot crash protection! MULTIARGS(msg); VAR_IFACE_ENGINE->ClientPrintf(pEntity, string); return true; } // Send a message and log. void LIB_MESSAGE_CLASS::MsgALog(const char *msg, bool isWarning /*= false*/, ...) { MULTIARGS(msg); VAR_IFACE_ENGINE->LogPrint(string); if(isWarning) Msg(string); else Warning(string); } // Shake player screen. // Filters allowed bool LIB_MESSAGE_CLASS::Shake(const char *players, float fTime /*= 10*/, int nType /*= SHAKE_START*/, float fMagnitude /*= 25*/, float fNoise /*= 150*/) { LIB_MRECIPIENTFILTER_CLASS mrf; if(!mrf.AddByFilter(players, false)) return false; bool result = Shake(mrf, fTime, nType, fMagnitude, fNoise); mrf.~LIB_MRECIPIENTFILTER_CLASS(); return result; } // Shake player screen. // You must free MRecipientFilter object yourself bool LIB_MESSAGE_CLASS::Shake(LIB_MRECIPIENTFILTER_CLASS &mrf, float fTime /*= 10*/, int nType /*= SHAKE_START*/, float fMagnitude /*= 25*/, float fNoise /*= 150*/) { if(!mrf.GetRecipientCount()) return false; int shakeIndex = GetMsgNum("Shake"); if(shakeIndex == -1) return false; bf_write *pWrite = VAR_IFACE_ENGINE->UserMessageBegin((IRecipientFilter *) &mrf, shakeIndex); if(!pWrite) return false; pWrite->WriteByte(nType); // shake command (SHAKE_START, STOP, FREQUENCY, AMPLITUDE) pWrite->WriteFloat(fMagnitude); // shake magnitude/amplitude pWrite->WriteFloat(fNoise); // shake noise frequency pWrite->WriteFloat(fTime); // shake lasts this long VAR_IFACE_ENGINE->MessageEnd(); return true; } // Shake player screen. bool LIB_MESSAGE_CLASS::Shake(edict_t *pEntity, float fTime /*= 10*/, int nType /*= SHAKE_START*/, float fMagnitude /*= 25*/, float fNoise /*= 150*/) { LIB_MRECIPIENTFILTER_CLASS mrf; if(!mrf.AddByEntity(pEntity)) return false; bool result = Shake(mrf, fTime, nType, fMagnitude, fNoise); mrf.~LIB_MRECIPIENTFILTER_CLASS(); return result; } // Fade player screen. // Filters allowed bool LIB_MESSAGE_CLASS::Fade(const char *players, short nFlags /*= (FFADE_OUT | FFADE_STAYOUT)*/, float fFadeTime /*= 5*/, float fHoldTime /*= 30*/, int red /*= 0*/, int green /*= 0*/, int blue /*= 0*/, int alpha /*= 255*/) { LIB_MRECIPIENTFILTER_CLASS mrf; if(!mrf.AddByFilter(players, false)) return false; bool result = Fade(mrf, nFlags, fFadeTime, fHoldTime, red, green, blue, alpha); mrf.~LIB_MRECIPIENTFILTER_CLASS(); return result; } // Fade player screen. // You must free MRecipientFilter object yourself bool LIB_MESSAGE_CLASS::Fade(LIB_MRECIPIENTFILTER_CLASS &mrf, short nFlags /*= (FFADE_OUT | FFADE_STAYOUT)*/, float fFadeTime /*= 5*/, float fHoldTime /*= 30*/, int red /*= 0*/, int green /*= 0*/, int blue /*= 0*/, int alpha /*= 255*/) { if(!mrf.GetRecipientCount()) return false; int fadeIndex = GetMsgNum("Fade"); if(fadeIndex == -1) return false; bf_write *pWrite = VAR_IFACE_ENGINE->UserMessageBegin((IRecipientFilter *) &mrf, fadeIndex); if(!pWrite) return false; pWrite->WriteShort((short)(fFadeTime * 1000)); // fade out/in time pWrite->WriteShort((short)(fHoldTime * 1000)); // how long fade lasts pWrite->WriteShort(nFlags); // FFADE_IN - fade back in, FFADE_OUT - fade out to color, FFADE_PURGE - remove all fades, FFADE_STAYOUT - fade and stay, FFADE_MODULATE - blends colors? pWrite->WriteByte(red); // fade red pWrite->WriteByte(green); // fade green pWrite->WriteByte(blue); // fade blue pWrite->WriteByte(alpha); // fade alpha transparency VAR_IFACE_ENGINE->MessageEnd(); return true; } // Fade player screen. bool LIB_MESSAGE_CLASS::Fade(edict_t *pEntity, short nFlags /*= (FFADE_OUT | FFADE_STAYOUT)*/, float fFadeTime /*= 5*/, float fHoldTime /*= 30*/, int red /*= 0*/, int green /*= 0*/, int blue /*= 0*/, int alpha /*= 255*/) { LIB_MRECIPIENTFILTER_CLASS mrf; if(!mrf.AddByEntity(pEntity)) return false; bool result = Fade(mrf, nFlags, fFadeTime, fHoldTime, red, green, blue, alpha); mrf.~LIB_MRECIPIENTFILTER_CLASS(); return result; } // Send text to player chat. // Filters allowed bool LIB_MESSAGE_CLASS::Say(const char *players, const char *msg, ...) { LIB_MRECIPIENTFILTER_CLASS mrf; if(!mrf.AddByFilter(players, false)) return false; MULTIARGS(msg); bool result = Say(mrf, string); mrf.~LIB_MRECIPIENTFILTER_CLASS(); return result; } // Send text to player chat. // You must free MRecipientFilter object yourself bool LIB_MESSAGE_CLASS::Say(LIB_MRECIPIENTFILTER_CLASS &mrf, const char *msg, ...) { if(!mrf.GetRecipientCount()) return false; int sayIndex = GetMsgNum("SayText"); if(sayIndex == -1) return false; //remember to add \x01=yelow, \x03=lightgreen, \x04=green to msg MULTIARGS(msg); int len = strlen(string); if (len > 254) { char tmp[256]; for (int i = 0; i < len; i += 254) { Q_strncpy(tmp, msg + i, 254); tmp[255] = 0; bf_write *pWrite = VAR_IFACE_ENGINE->UserMessageBegin((IRecipientFilter *) &mrf,sayIndex); if(!pWrite) continue; pWrite->WriteByte(0); pWrite->WriteString(tmp); pWrite->WriteByte(0); VAR_IFACE_ENGINE->MessageEnd(); } return true; } bf_write *pWrite = VAR_IFACE_ENGINE->UserMessageBegin((IRecipientFilter *) &mrf,sayIndex); if(!pWrite) return false; pWrite->WriteByte(0); pWrite->WriteString(string); pWrite->WriteByte(0); VAR_IFACE_ENGINE->MessageEnd(); return true; } // Send text to player chat. bool LIB_MESSAGE_CLASS::Say(edict_t *pEntity, const char *msg, ...) { LIB_MRECIPIENTFILTER_CLASS mrf; if(!mrf.AddByEntity(pEntity)) return false; MULTIARGS(msg); bool result = Say(mrf, string); mrf.~LIB_MRECIPIENTFILTER_CLASS(); return result; } void LIB_MESSAGE_CLASS::SayEscapeColors(char *str, unsigned int len) { if(!str) return; LIB_STRING_CLASS::StrReplace(str, "\\x01", SAY_DEFAULT, len); LIB_STRING_CLASS::StrReplace(str, "\\x04", SAY_GREEN, len); LIB_STRING_CLASS::StrReplace(str, "\\x03", SAY_LIGHTGREEN, len); //LIB_STRING_CLASS::StrReplace(str, "\\x03", SAY_RED, len); //LIB_STRING_CLASS::StrReplace(str, "\\x03", SAY_BLUE, len); LIB_STRING_CLASS::StrReplace(str, "\\x05", SAY_OLIVE, len); } // Print text to player on center screen. // Filters allowed bool LIB_MESSAGE_CLASS::CenterSay(const char *players, const char *msg, ...) { LIB_MRECIPIENTFILTER_CLASS mrf; if(!mrf.AddByFilter(players, false)) return false; MULTIARGS(msg); bool result = CenterSay(mrf, string); mrf.~LIB_MRECIPIENTFILTER_CLASS(); return result; } // Print text to player on center screen. // You must free MRecipientFilter object yourself bool LIB_MESSAGE_CLASS::CenterSay(LIB_MRECIPIENTFILTER_CLASS &mrf, const char *msg, ...) { if(!mrf.GetRecipientCount()) return false; int centerIndex = GetMsgNum("TextMsg"); if(centerIndex == -1) return false; MULTIARGS(msg); bf_write *pWrite = VAR_IFACE_ENGINE->UserMessageBegin((IRecipientFilter *) &mrf, centerIndex); if(!pWrite) return false; pWrite->WriteByte(HUD_PRINTCENTER); pWrite->WriteString(string); VAR_IFACE_ENGINE->MessageEnd(); return true; } // Print text to player on center screen. bool LIB_MESSAGE_CLASS::CenterSay(edict_t *pEntity, const char *msg, ...) { LIB_MRECIPIENTFILTER_CLASS mrf; if(!mrf.AddByEntity(pEntity)) return false; MULTIARGS(msg); bool result = CenterSay(mrf, string); mrf.~LIB_MRECIPIENTFILTER_CLASS(); return result; } // Print a hint to player. // Filters allowed bool LIB_MESSAGE_CLASS::Hint(const char *players, const char *msg, ...) { LIB_MRECIPIENTFILTER_CLASS mrf; if(!mrf.AddByFilter(players, false)) return false; MULTIARGS(msg); bool result = Hint(mrf, string); mrf.~LIB_MRECIPIENTFILTER_CLASS(); return result; } // Print a hint to player. // You must free MRecipientFilter object yourself bool LIB_MESSAGE_CLASS::Hint(LIB_MRECIPIENTFILTER_CLASS &mrf, const char *msg, ...) { if(!mrf.GetRecipientCount()) return false; int hintIndex = GetMsgNum("HintText"); if(hintIndex == -1) return false; MULTIARGS(msg); bf_write *pWrite = VAR_IFACE_ENGINE->UserMessageBegin((IRecipientFilter *) &mrf, hintIndex); if(!pWrite) return false; //pWrite->WriteByte(-1); pWrite->WriteByte(1); pWrite->WriteString(string); VAR_IFACE_ENGINE->MessageEnd(); return true; } // Print a hint to player. bool LIB_MESSAGE_CLASS::Hint(edict_t *pEntity, const char *msg, ...) { LIB_MRECIPIENTFILTER_CLASS mrf; if(!mrf.AddByEntity(pEntity)) return false; MULTIARGS(msg); bool result = Hint(mrf, string); mrf.~LIB_MRECIPIENTFILTER_CLASS(); return result; } // Transform a numeric string into int keys to use with menus // eg. "01239" // 0 = 1 Key // ... // 8 = 9 Key // 9 = 0 Key AKA Exit // No digit character is ignored int LIB_MESSAGE_CLASS::MenuOptionsFromString(const char *options /*= "0123456789"*/) { int temp = 0, keys = 0; for (unsigned int i = 0; i < strlen(options); i++) { if(!isdigit(options[i])) continue; temp = options[i]-49; if(temp == -1) temp = 9; if(temp >= 0 && temp <= 9 && !(keys & (1 << temp))) keys |= 1 << temp; } return keys != 0 ? keys : (1<<0) | (1<<1) | (1<<2) | (1<<3) | (1<<4) | (1<<5) | (1<<6) | (1<<7)| (1<<8) | (1<<9); } // Shows a menu to player. // Allow filters bool LIB_MESSAGE_CLASS::Menu(const char *players, int time, const char *msg, const char *options /*= "0123456789"*/, ...) { int menuIndex = GetMsgNum("ShowMenu"); if(menuIndex == -1) return false; LIB_MRECIPIENTFILTER_CLASS mrf; if(!mrf.AddByFilter(players, false)) return false; MULTIARGS2(msg, options); int keys = MenuOptionsFromString(options); char* page; bool bMoreToCome = true; int i = 0; unsigned int len = strlen(string); while (bMoreToCome) { if (len > MAX_MENU_LEN) page = LIB_STRING_CLASS::SubStr(string, i*MAX_MENU_LEN, (i+1)*MAX_MENU_LEN); else { bMoreToCome = false; page = LIB_STRING_CLASS::SubStr(string, i*MAX_MENU_LEN, strlen(string)); } bf_write *pWrite = VAR_IFACE_ENGINE->UserMessageBegin((IRecipientFilter *) &mrf, menuIndex); if(!pWrite) return false; pWrite->WriteWord(keys); //Sets how many options the menu has pWrite->WriteChar(time); //Sets how long the menu stays open -1 for stay until option selected pWrite->WriteByte(bMoreToCome ? 0xFF : 0x00); //is there more data to come? pWrite->WriteString(page); //The text shown on the menu VAR_IFACE_ENGINE->MessageEnd(); len -= strlen(page); delete [] page; ++i; } return true; } // Shows a menu to player. bool LIB_MESSAGE_CLASS::Menu(edict_t *pEntity, int time, const char *msg, int keys /*= (1<<0) | (1<<1) | (1<<2) | (1<<3) | (1<<4) | (1<<5) | (1<<6) | (1<<7)| (1<<8) | (1<<9)*/, ...) { int menuIndex = GetMsgNum("ShowMenu"); if(menuIndex == -1) return false; LIB_MRECIPIENTFILTER_CLASS mrf; if(!mrf.AddByEntity(pEntity)) return false; MULTIARGS(msg); char* page; bool bMoreToCome = true; int i = 0; unsigned int len = strlen(string); while (bMoreToCome) { if (len > MAX_MENU_LEN) page = LIB_STRING_CLASS::SubStr(string, i*MAX_MENU_LEN, (i+1)*MAX_MENU_LEN); else { bMoreToCome = false; page = LIB_STRING_CLASS::SubStr(string, i*MAX_MENU_LEN, strlen(string)); } bf_write *pWrite = VAR_IFACE_ENGINE->UserMessageBegin((IRecipientFilter *) &mrf, menuIndex); if(!pWrite) return false; pWrite->WriteWord(keys); //Sets how many options the menu has pWrite->WriteChar(time); //Sets how long the menu stays open -1 for stay until option selected pWrite->WriteByte(bMoreToCome ? 0xFF : 0x00); //is there more data to come? pWrite->WriteString(page); //The text shown on the menu VAR_IFACE_ENGINE->MessageEnd(); len -= strlen(page); delete [] page; ++i; } return true; } // Shows a menu to player. bool LIB_MESSAGE_CLASS::Menu(edict_t *pEntity, int time, const char *msg, const char *options /*= "0123456789"*/, ...) { return Menu(pEntity, time, msg, MenuOptionsFromString(options)); } // Print a top message to player. // Filters allowed bool LIB_MESSAGE_CLASS::Top(const char *players, int time, const char *msg, int red /*= 255*/, int green /*= 255*/, int blue /*= 255*/, int alpha /*= 255*/, ...) { LIB_MRECIPIENTFILTER_CLASS mrf; if(!mrf.AddByFilter(players, false)) return false; MULTIARGS2(msg, alpha); bool result = Top(mrf, time, string, red, green, blue, alpha); mrf.~LIB_MRECIPIENTFILTER_CLASS(); return result; } // Print a top message to player. // You must free MRecipientFilter object yourself bool LIB_MESSAGE_CLASS::Top(LIB_MRECIPIENTFILTER_CLASS &mrf, int time, const char *msg, int red /*= 255*/, int green /*= 255*/, int blue /*= 255*/, int alpha /*= 255*/, ...) { if(!mrf.GetRecipientCount()) return false; MULTIARGS2(msg, alpha); KeyValues *kv = new KeyValues( "msg" ); kv->SetString( "title", "msg" ); kv->SetString( "msg", string); kv->SetColor( "color", Color( red, green, blue, alpha )); kv->SetInt( "level", 5); kv->SetInt( "time", time); for(int i = 0; i < mrf.GetRecipientCount(); i++) VAR_IFACE_SERVERPLUGINHELPERS->CreateMessage(mrf.GetRecipientEdict(i), DIALOG_MSG, kv, SERVERPLUGIN_CALLBACKS_VAR); kv->deleteThis(); return true; } // Print a top message to player. bool LIB_MESSAGE_CLASS::Top(edict_t *pEntity, int time, const char *msg, int red /*= 255*/, int green /*= 255*/, int blue /*= 255*/, int alpha /*= 255*/, ...) { if(!LIB_ENTITY_CLASS::IsEntitySafe(pEntity)) return false; MULTIARGS2(msg, alpha); KeyValues *kv = new KeyValues( "msg" ); kv->SetString( "title", "msg" ); kv->SetString( "msg", string); kv->SetColor( "color", Color( red, green, blue, alpha )); kv->SetInt( "level", 5); kv->SetInt( "time", time); VAR_IFACE_SERVERPLUGINHELPERS->CreateMessage(pEntity, DIALOG_MSG, kv, SERVERPLUGIN_CALLBACKS_VAR); kv->deleteThis(); return true; } // VGUI_TYPE (1 = special, 2 = url, ) // Sends a VGUI menu to player. // Filters allowed bool LIB_MESSAGE_CLASS::VGUI(const char *players, int VGUI_TYPE, const char *title, const char *text, ...) { LIB_MRECIPIENTFILTER_CLASS mrf; if(!mrf.AddByFilter(players, false)) return false; MULTIARGS(text); bool result = VGUI(mrf, VGUI_TYPE, title, string); mrf.~LIB_MRECIPIENTFILTER_CLASS(); return result; } // VGUI_TYPE (1 = special, 2 = url, ) // Sends a VGUI menu to player. // You must free MRecipientFilter object yourself bool LIB_MESSAGE_CLASS::VGUI(LIB_MRECIPIENTFILTER_CLASS &mrf, int VGUI_TYPE, const char *title, const char *text, ...) { if(!mrf.GetRecipientCount()) return false; int vguiIndex = GetMsgNum("VGUIMenu"); if(vguiIndex == -1) return false; bf_write *pWrite = VAR_IFACE_ENGINE->UserMessageBegin((IRecipientFilter *) &mrf, vguiIndex); if(!pWrite) return false; MULTIARGS(text); pWrite->WriteString("info"); // the HUD message itself pWrite->WriteByte(1); pWrite->WriteByte(3); // I don't know yet the purpose of this byte, it can be 1 or 0 pWrite->WriteString("type"); // the HUD message itself pWrite->WriteString(LIB_STRING_CLASS::StrFormat("%i", VGUI_TYPE)); // the HUD message itself pWrite->WriteString("title"); // the HUD message itself pWrite->WriteString(title); // the HUD message itself pWrite->WriteString("msg"); // the HUD message itself pWrite->WriteString(string); // the HUD message itself VAR_IFACE_ENGINE->MessageEnd(); return true; } // Sends a VGUI menu to player. bool LIB_MESSAGE_CLASS::VGUI(edict_t *pEntity, int VGUI_TYPE, const char *title, const char *text, ...) { LIB_MRECIPIENTFILTER_CLASS mrf; if(!mrf.AddByEntity(pEntity)) return false; MULTIARGS(text); bool result = VGUI(mrf, VGUI_TYPE, title, string); mrf.~LIB_MRECIPIENTFILTER_CLASS(); return result; } // Redirect a player to another ip. // Filters allowed bool LIB_MESSAGE_CLASS::Redirect(const char *players, int time, const char *ip) { #if SOURCE_ENGINE <= SE_DARKMESSIAH return false; #else LIB_MRECIPIENTFILTER_CLASS mrf; if(!mrf.AddByFilter(players, false)) return false; bool result = Redirect(mrf, time, ip); mrf.~LIB_MRECIPIENTFILTER_CLASS(); return result; #endif } // Redirect a player to another ip. // You must free MRecipientFilter object yourself bool LIB_MESSAGE_CLASS::Redirect(LIB_MRECIPIENTFILTER_CLASS &mrf, int time, const char *ip) { #if SOURCE_ENGINE <= SE_DARKMESSIAH return false; #else int count = mrf.GetRecipientCount(); if(!count) return false; KeyValues *kv = new KeyValues("Redirect"); kv->SetInt( "time", time ); kv->SetString( "title", ip ); for(int i = 0; i < count; i++) VAR_IFACE_SERVERPLUGINHELPERS->CreateMessage(mrf.GetRecipientEdict(i), (DIALOG_TYPE)DIALOG_ASKCONNECT, kv, SERVERPLUGIN_CALLBACKS_VAR); kv->deleteThis(); return true; #endif } // Redirect a player to another ip. bool LIB_MESSAGE_CLASS::Redirect(edict_t *pEntity, int time, const char *ip) { #if SOURCE_ENGINE <= SE_DARKMESSIAH return false; #else if(!LIB_ENTITY_CLASS::IsEntitySafe(pEntity)) return false; KeyValues *kv = new KeyValues("Redirect"); kv->SetInt( "time", time ); kv->SetString( "title", ip ); VAR_IFACE_SERVERPLUGINHELPERS->CreateMessage(pEntity, DIALOG_ASKCONNECT, kv, SERVERPLUGIN_CALLBACKS_VAR); kv->deleteThis(); return true; #endif } // Show a RichBox to a player. // Filers allowed bool LIB_MESSAGE_CLASS::RichBox(const char *players, int time, const char *title, const char *msg, ...) { LIB_MRECIPIENTFILTER_CLASS mrf; if(!mrf.AddByFilter(players, false)) return false; MULTIARGS(msg); bool result = RichBox(mrf, time, title, string); mrf.~LIB_MRECIPIENTFILTER_CLASS(); return result; } // Show a RichBox to a player. // You must free MRecipientFilter object yourself bool LIB_MESSAGE_CLASS::RichBox(LIB_MRECIPIENTFILTER_CLASS &mrf, int time, const char *title, const char *msg, ...) { int count = mrf.GetRecipientCount(); if(!count) return false; MULTIARGS(msg); KeyValues *kv = new KeyValues( "RichBox" ); kv->SetString( "title", title ); kv->SetInt( "level", 1 ); kv->SetInt( "time", time ); kv->SetString( "msg", string ); for(int i = 0; i < count; i++) VAR_IFACE_SERVERPLUGINHELPERS->CreateMessage(mrf.GetRecipientEdict(i), DIALOG_TEXT, kv, SERVERPLUGIN_CALLBACKS_VAR); kv->deleteThis(); return true; } // Show a RichBox to a player. bool LIB_MESSAGE_CLASS::RichBox(edict_t *pEntity, int time, const char *title, const char *msg, ...) { if(!LIB_ENTITY_CLASS::IsEntitySafe(pEntity)) return false; MULTIARGS(msg); KeyValues *kv = new KeyValues( "RichBox" ); kv->SetString( "title", title ); kv->SetInt( "level", 1 ); kv->SetInt( "time", time ); kv->SetString( "msg", string ); VAR_IFACE_SERVERPLUGINHELPERS->CreateMessage(pEntity, DIALOG_TEXT, kv, SERVERPLUGIN_CALLBACKS_VAR); kv->deleteThis(); return true; } // Display a Entry box to player. // Filters allowed bool LIB_MESSAGE_CLASS::Entry(const char *players, int time, const char *title, const char *cmd, const char *msg, ...) { LIB_MRECIPIENTFILTER_CLASS mrf; if(!mrf.AddByFilter(players, false)) return false; MULTIARGS(msg); bool result = Entry(mrf, time, title, cmd, string); mrf.~LIB_MRECIPIENTFILTER_CLASS(); return result; } // Display a Entry box to player. // You must free MRecipientFilter object yourself bool LIB_MESSAGE_CLASS::Entry(LIB_MRECIPIENTFILTER_CLASS &mrf, int time, const char *title, const char *cmd, const char *msg, ...) { int count = mrf.GetRecipientCount(); if(!count) return false; MULTIARGS(msg); KeyValues *kv = new KeyValues( "Entry" ); kv->SetString( "title", title ); kv->SetString( "msg", string ); kv->SetString( "command", cmd ); kv->SetInt( "level", 1 ); kv->SetInt( "time", time ); for(int i = 0; i < count; i++) VAR_IFACE_SERVERPLUGINHELPERS->CreateMessage(mrf.GetRecipientEdict(i), DIALOG_ENTRY, kv, SERVERPLUGIN_CALLBACKS_VAR); kv->deleteThis(); return true; } // Display a Entry box to player. bool LIB_MESSAGE_CLASS::Entry(edict_t *pEntity, int time, const char *title, const char *cmd, const char *msg, ...) { if(!LIB_ENTITY_CLASS::IsEntitySafe(pEntity)) return false; MULTIARGS(msg); KeyValues *kv = new KeyValues( "Entry" ); kv->SetString( "title", title ); kv->SetString( "msg", string ); kv->SetString( "command", cmd ); kv->SetInt( "level", 1 ); kv->SetInt( "time", time ); VAR_IFACE_SERVERPLUGINHELPERS->CreateMessage(pEntity, DIALOG_ENTRY, kv, SERVERPLUGIN_CALLBACKS_VAR); kv->deleteThis(); return true; }
[ "[email protected]@2dd402b7-31f5-573d-f87e-a7bc63fa017b" ]
[ [ [ 1, 733 ] ] ]
8413fb06a0c1f2d08ea9d084be215a604b292c23
97f1be9ac088e1c9d3fd73d76c63fc2c4e28749a
/3dc/avp/win95/gadgets/textin.hpp
7a06a89130f4448ff292511c90602711ec592315
[ "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
6,654
hpp
/* textin.hpp Created by DHM. DHM 23/1/98: ------------ Defines a abstract project-independent TextInputState class that can react to typing, special keys like "backspace" etc. in a sensible fashion. The idea is that each project can derive project-specific concrete classes and embed them in objects for that project's user interface system e.g. - into a TextEntryGadget for AvP - into a TELObject for HeadHunter etc. The pure virtual functions are to process carriage returns, and to provide feedback on errors (e.g. typing backspace when there's nothing left). There's a version setting: "LimitedLineLength": - If this is set to true, the implementation involves a fixed-size array of ProjChars. - If it's set to false, there's an unfinished implementation involving a linked list of ProjChars; don't use this option. */ #ifndef _textin_hpp #define _textin_hpp 1 #ifndef _textexp #include "textexp.hpp" #endif #ifdef __cplusplus extern "C" { #endif /* Version settings *****************************************************/ #define LimitedLineLength Yes #define SupportHistory Yes #define SupportAutomation Yes #define SupportCompletion Yes #if !LimitedLineLength #ifndef list_template_hpp #include "list_tem.hpp" #endif #endif /* Constants ***********************************************************/ /* Macros ***************************************************************/ /* Type definitions *****************************************************/ #if SupportCompletion class ConsoleSymbol; // fully declared in CONSSYM.HPP #endif class TextInputState { // Friends: friend void TextExpansion :: TestForExpansions ( TextInputState* pTextInputState_In ); // Constants: private: #if LimitedLineLength enum { MAX_LENGTH_INPUT = 250, // doesn't include a terminator character MAX_SIZE_INPUT = (MAX_LENGTH_INPUT + 1) // does include a terminator character }; #endif // Limited line length #if SupportHistory enum { MAX_LINES_HISTORY = 32 }; #endif // Private data: private: #if LimitedLineLength ProjChar ProjCh[ MAX_SIZE_INPUT ]; // Null-terminated string "in-place" int NumChars; // number of chars befire the null terminator #else List<ProjChar> List_ProjChar; #endif #if SupportHistory List <SCString*> List_pSCString_History; SCString* pSCString_CurrentHistory; // Can be NULL; indicates no cycling through the history has yet occurred. // This does NOT own a reference to the string. #endif #if SupportAutomation int ManualPos; // all characters with index less than this were // typed "by hand", as opposed to being automatically // generated by completion-guessing or by histories #endif #if SupportCompletion ConsoleSymbol* pConsoleSym_CurrentCompletion; // Can be NULL; indicates no cycling through the history has yet occurred. #endif int CursorPos; // cursor is to the left of the character with this index OurBool bForceUpperCase_Val; static OurBool bOverwrite_Val; // otherise it's insert mode public: virtual ~TextInputState(); SCString& GetCurrentState(void); // returns a ref to a copy of the "string under construction" in its current state void CharTyped ( char Ch // note that this _is _ a char ); void Key_Backspace(void); void Key_End(void); void Key_Home(void); void Key_Left(void); void Key_Right(void); void Key_Delete(void); static OurBool bOverwrite(void) { return bOverwrite_Val; } static void ToggleTypingMode(void); // toggles overwrite/insert mode public: virtual void ProcessCarriageReturn(void) = 0; protected: virtual void TextEntryError(void) = 0; // called e.g. when no more text can be typed, or no more deleted // may make a beep noise // Protected methods: protected: // Constructor is protected since it's an abstract base class TextInputState ( OurBool bForceUpperCase, char* pProjCh_Init // could be const ); void TryToInsertAt ( SCString* pSCString_ToInsert, int Pos_Where ); int bOvertypeAt ( ProjChar ProjCh_In, int Pos_Where ); // return value: was overtype succesful? int bInsertAt ( ProjChar ProjCh_In, int Pos_Where ); // return value: was insertion succesful? void DeleteAt( int Pos ); void Clear(void); #if SupportHistory void History_SelectNxt(void); void History_SelectPrv(void); void AddToHistory ( SCString& SCString_ToAdd ); #endif #if SupportAutomation void FullyManual(void); /* Flags the string as if all its content has been manually typed (call when the user types something that signifies he/she accepts something that might have been generated by completion/history code). */ OurBool bManualMatch ( ProjChar* pProjCh ) const; OurBool bManualMatchInsensitive ( ProjChar* pProjCh ) const; /* Returns true iff there's a match with the manually-typed prefix of the current state string and the input comparison string */ #endif #if SupportCompletion void Completion_SelectNxt(void); void Completion_SelectPrv(void); #endif // I'm not sure what interface I should supply; this is a stopgap so that I can write // rendering functions for AvP public: void SetString ( SCString& SCString_ToUse ); #if LimitedLineLength const ProjChar* GetProjChar(void) const { return &ProjCh[0]; } int GetCursorPos(void) const { return CursorPos; } int GetNumChars(void) const { return NumChars; } #endif #if SupportHistory private: SCString* GetNxtMatchingHistory(void) const; SCString* GetPrvMatchingHistory(void) const; // will return NULL if it wraps around internally i.e. no matches #endif #if SupportCompletion private: ConsoleSymbol* GetNxtMatchingCompletion(void) const; ConsoleSymbol* GetPrvMatchingCompletion(void) const; // will return NULL if it wraps around internally i.e. no matches #endif }; // end of class TextInputState /* Exported globals *****************************************************/ /* Function prototypes **************************************************/ /* End of the header ****************************************************/ #ifdef __cplusplus }; #endif #endif
[ "a_jagers@ANTHONYJ.(none)" ]
[ [ [ 1, 297 ] ] ]
07a1ecee2e2917a0f2ce430881d56f9e402d50bc
0a340b0f117dd183a3ebe774f3e9e5cee821bd64
/cob_driver/cob_canopen_motor/common/src/TimeStamp.cpp
7ebc03d4e62e591d5f0e70a7ef628a8249b22a3f
[]
no_license
ipa-grg/care-o-bot
f8374381b7b14848794a5c9b273133c3cf74bb9c
c937984d7c00db688f830980576a698d1509f965
refs/heads/master
2021-01-16T20:56:20.302177
2010-04-23T14:21:57
2010-04-23T14:21:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,634
cpp
/**************************************************************** * * Copyright (c) 2010 * * Fraunhofer Institute for Manufacturing Engineering * and Automation (IPA) * * +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * * Project name: care-o-bot * ROS stack name: cob3_common * ROS package name: generic_can * Description: * * +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * * Author: Christian Connette, email:[email protected] * Supervised by: Christian Connette, email:[email protected] * * Date of creation: Feb 2009 * ToDo: Check if this is still neccessary. Can we use the ROS-Infrastructure within the implementation? * * +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Fraunhofer Institute for Manufacturing * Engineering and Automation (IPA) nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License LGPL as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License LGPL for more details. * * You should have received a copy of the GNU Lesser General Public * License LGPL along with this program. * If not, see <http://www.gnu.org/licenses/>. * ****************************************************************/ #include <canopen_motor/TimeStamp.h> //----------------------------------------------------------------------------- TimeStamp::TimeStamp() { m_TimeStamp.tv_sec = 0; m_TimeStamp.tv_nsec = 0; } void TimeStamp::SetNow() { ::clock_gettime(CLOCK_REALTIME, &m_TimeStamp); } double TimeStamp::TimespecToDouble(const ::timespec& LargeInt) { return double(LargeInt.tv_sec) + double(LargeInt.tv_nsec) / 1e9; } ::timespec TimeStamp::DoubleToTimespec(double TimeS) { ::timespec DeltaTime; if (! ( TimeS < 4e9 && TimeS > 0.0 )) { DeltaTime.tv_sec = 0; DeltaTime.tv_nsec = 0; return DeltaTime; } DeltaTime.tv_sec = ::time_t(TimeS); DeltaTime.tv_nsec = static_cast<long int>((TimeS - double(DeltaTime.tv_sec)) * 1e9); return DeltaTime; } double TimeStamp::operator-(const TimeStamp& EarlierTime) const { ::timespec Res; Res.tv_sec = m_TimeStamp.tv_sec - EarlierTime.m_TimeStamp.tv_sec; Res.tv_nsec = m_TimeStamp.tv_nsec - EarlierTime.m_TimeStamp.tv_nsec; if (Res.tv_nsec < 0) { Res.tv_sec--; Res.tv_nsec += 1000000000; } return TimespecToDouble(Res); } void TimeStamp::operator+=(double TimeS) { ::timespec Dbl = DoubleToTimespec(TimeS); m_TimeStamp.tv_sec += Dbl.tv_sec; m_TimeStamp.tv_nsec += Dbl.tv_nsec; if (m_TimeStamp.tv_nsec > 1000000000) { m_TimeStamp.tv_sec++; m_TimeStamp.tv_nsec -= 1000000000; } } void TimeStamp::operator-=(double TimeS) { ::timespec Dbl = DoubleToTimespec(TimeS); m_TimeStamp.tv_sec -= Dbl.tv_sec; m_TimeStamp.tv_nsec -= Dbl.tv_nsec; if (m_TimeStamp.tv_nsec < 0.0) { m_TimeStamp.tv_sec--; m_TimeStamp.tv_nsec += 1000000000; } } bool TimeStamp::operator>(const TimeStamp& Time) { if (m_TimeStamp.tv_sec > Time.m_TimeStamp.tv_sec) return true; if ((m_TimeStamp.tv_sec == Time.m_TimeStamp.tv_sec) && (m_TimeStamp.tv_nsec > Time.m_TimeStamp.tv_nsec)) return true; return false; } bool TimeStamp::operator<(const TimeStamp& Time) { if (m_TimeStamp.tv_sec < Time.m_TimeStamp.tv_sec) return true; if ((m_TimeStamp.tv_sec == Time.m_TimeStamp.tv_sec) && (m_TimeStamp.tv_nsec < Time.m_TimeStamp.tv_nsec)) return true; return false; } void TimeStamp::getTimeStamp(long& lSeconds, long& lNanoSeconds) { lSeconds = m_TimeStamp.tv_sec; lNanoSeconds = m_TimeStamp.tv_nsec; }; void TimeStamp::setTimeStamp(const long& lSeconds, const long& lNanoSeconds) { m_TimeStamp.tv_sec = lSeconds; m_TimeStamp.tv_nsec = lNanoSeconds; }; std::string TimeStamp::CurrentToString() { # define TIME_SIZE 400 const struct tm *tm; size_t len; time_t now; char pres[TIME_SIZE]; std::string s; now = time ( NULL ); tm = localtime ( &now ); len = strftime ( pres, TIME_SIZE, "%Y-%m-%d %H:%M:%S.", tm ); s = (std::string)pres + NumToString(m_TimeStamp.tv_nsec / 1000); return s; # undef TIME_SIZE } std::string TimeStamp::ToString() { # define TIME_SIZE 4000 const struct tm *tm; size_t len; time_t now; char pres[TIME_SIZE]; std::string s; tm = localtime ( &m_TimeStamp.tv_sec ); len = strftime ( pres, TIME_SIZE, "%Y-%m-%d %H:%M:%S.", tm ); s = (std::string)pres + NumToString(m_TimeStamp.tv_nsec / 1000); return s; # undef TIME_SIZE }
[ "cpc@okeanos.(none)", "[email protected]" ]
[ [ [ 1, 53 ], [ 55, 195 ] ], [ [ 54, 54 ] ] ]
948379c1ae838471082c6965730b1ab5487eaed7
ce262ae496ab3eeebfcbb337da86d34eb689c07b
/SEFoundation/SERendering/SECullState.h
71bac4ddfd9757ef11e3710a10900eb666c08489
[]
no_license
pizibing/swingengine
d8d9208c00ec2944817e1aab51287a3c38103bea
e7109d7b3e28c4421c173712eaf872771550669e
refs/heads/master
2021-01-16T18:29:10.689858
2011-06-23T04:27:46
2011-06-23T04:27:46
33,969,301
0
0
null
null
null
null
GB18030
C++
false
false
2,279
h
// Swing Engine Version 1 Source Code // Most of techniques in the engine are mainly based on David Eberly's // Wild Magic 4 open-source code.The author of Swing Engine learned a lot // from Eberly's experience of architecture and algorithm. // Several sub-systems are totally new,and others are re-implimented or // re-organized based on Wild Magic 4's sub-systems. // Copyright (c) 2007-2010. All Rights Reserved // // Eberly's permission: // Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation; either version 2.1 of the License, or (at // your option) any later version. The license is available for reading at // the location: // http://www.gnu.org/copyleft/lgpl.html #ifndef Swing_CullState_H #define Swing_CullState_H #include "SEFoundationLIB.h" #include "SEPlatforms.h" #include "SEGlobalState.h" namespace Swing { //---------------------------------------------------------------------------- // Description: // Author:Sun Che // Date:20080701 //---------------------------------------------------------------------------- class SE_FOUNDATION_API SECullState : public SEGlobalState { SE_DECLARE_RTTI; SE_DECLARE_NAME_ID; SE_DECLARE_STREAM; SE_DECLARE_INITIALIZE; SE_DECLARE_TERMINATE; public: virtual StateType GetStateType(void) const { return CULL; } SECullState(void); virtual ~SECullState(void); enum FrontMode { FT_CCW, // 逆时针索引顺序为正面 FT_CW, // 顺时针索引顺序为正面 FT_COUNT }; enum CullMode { CT_FRONT, // 剔除正面朝向的三角形 CT_BACK, // 剔除被面朝向的三角形 CT_COUNT }; bool Enabled; // default: true FrontMode FrontFace; // default: FT_CW CullMode CullFace; // default: CT_BACK private: static const char* ms_pFrontMode[FT_COUNT]; static const char* ms_pCullMode[CT_COUNT]; }; typedef SESmartPointer<SECullState> SECullStatePtr; } #endif
[ "[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac" ]
[ [ [ 1, 77 ] ] ]
473331707499d394df0fa7ef6cbd1af11f6168d9
2aff7486e6c7afdbda48b7a5f424b257d47199df
/src/Gui/MainFrameDerived.h
b7afe1167e8d7152cbb489c6177071ca73f28417
[]
no_license
offlinehacker/LDI_test
46111c60985d735c00ea768bdd3553de48ba2ced
7b77d3261ee657819bae3262e3ad78793b636622
refs/heads/master
2021-01-10T20:44:55.324019
2011-08-17T16:41:43
2011-08-17T16:41:43
2,220,496
1
0
null
null
null
null
UTF-8
C++
false
false
1,406
h
#ifndef __MainFrameDerived__ #define __MainFrameDerived__ /** @file Subclass of MainFrame, which is generated by wxFormBuilder. */ #include "Frames/MainFrame.h" #include "CameraSelectorDerived.h" #include "wx/filedlg.h" /** Implementing MainFrame */ class MainFrameDerived : public MainFrame { protected: // Handlers for MainFrame events. void OnVideoSelector1Change( wxCommandEvent& event ); void OnVideoSelector2Change( wxCommandEvent& event ); void OnVideoSelector3Change( wxCommandEvent& event ); void OnVideoSelector4Change( wxCommandEvent& event ); void LoadOptionsClicked( wxCommandEvent& event ); void SaveOptionsClicked( wxCommandEvent& event ); void ExitClicked( wxCommandEvent& event ); void SelectCameraSourceClicked( wxCommandEvent& event ); void StartCameraCaptureClicked( wxCommandEvent& event ); void StopCameraCaptureClicked( wxCommandEvent& event ); void StartVideoProcessingClicked( wxCommandEvent& event ); void StopVideoProcessingClicked( wxCommandEvent& event ); void StartVideoRecordingClicked( wxCommandEvent& event ); void StopVideoRecordingClicked( wxCommandEvent& event ); void OpenDebugLogClicked( wxCommandEvent& event ); void HelpClicked( wxCommandEvent& event ); void AboutClicked( wxCommandEvent& event ); public: /** Constructor */ MainFrameDerived( wxWindow* parent ); }; #endif // __MainFrameDerived__
[ [ [ 1, 42 ] ] ]
abac74e8cc2da6d3a54e8e6a95b3d54cb2c695bb
4c49943d28c7acb2c54c46c1b9c90b83edce8383
/HTML5i/ContextWebGL.cpp
4a752e8831dff90385417be25e77d3a743d02a08
[]
no_license
flier/HTML5i
68f4bcec7093f330b159f64976250ca5f974bca7
980ad8c112761471665c8acfc5064d1a87a8f32a
refs/heads/master
2020-03-27T05:08:04.843399
2011-03-26T18:02:38
2011-03-26T18:02:38
1,498,619
0
1
null
null
null
null
UTF-8
C++
false
false
410
cpp
// ContextWebGL.cpp : Implementation of CContextWebGL #include "stdafx.h" #include "ContextWebGL.h" // CContextWebGL STDMETHODIMP CContextWebGL::InterfaceSupportsErrorInfo(REFIID riid) { static const IID* const arr[] = { &IID_IContextWebGL }; for (int i=0; i < sizeof(arr) / sizeof(arr[0]); i++) { if (InlineIsEqualGUID(*arr[i],riid)) return S_OK; } return S_FALSE; }
[ [ [ 1, 22 ] ] ]
43f3315294f2d3c205579119fcb1e63d5d801d3f
d754bfcdedfa005210ff699cc3afb7737fa622d6
/src/oglwidget.h
c57249954de88df35939f5deb4f1b301d0742fe7
[]
no_license
sid1980/Software-Raytracer
d23ea03a53534b7908a12cf6ce9642d1bdc0bbfb
a460fa90df1c8757a97b394e081a9aab39a2df16
refs/heads/master
2021-12-02T07:25:49.953191
2011-06-22T22:45:11
2011-06-22T22:45:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,786
h
#ifndef CCSOPENGL #define CCSOPENGL #include <QGLWidget> #include <QtGui/QApplication> #include <qevent.h> #include <OpenGL/glu.h> #include "octree.h" #include "scene.h" #include "raytracer.h" /** RGBA-Farbwert */ typedef GLfloat CGColor4[4]; /** Punkt im 3D-Raum (homogene Koordinaten) */ typedef GLfloat CGPoint4D[4]; /** Punkt im 2D-Raum (homogene Koordinaten) */ typedef GLfloat CGPoint2D[2]; #ifndef M_PI #define M_PI 3.14159265358979323846 #endif class Triangle; class Sphere; class Rect; /** * Basisklasse fuer OpengGL Fenster. * - Initialisiert alle OpenGL relevanten * Sachen. * - Drehfunktion mit der Maus * - Zoomfunktion mit dem Mausrad * - glPrint Funktion fuer 3D-Schrift */ class OglWidget : public QGLWidget { Q_OBJECT public: OglWidget(QWidget *parent = 0); virtual ~OglWidget(void); void setScene(Scene* scene) { //glDeleteLists(screenList, 1); this->scene = scene; //generateDisplayLists(); } Scene* getScene() const { return scene; } Color **pixel; void setPixel(Color** pixel) { this->pixel = pixel; } bool getBoundingBoxes() const { return showBBoxes; } void setBoundingBoxes(bool visible) { showBBoxes = visible; } // Kann man hier auch protected slots verwenden? public slots: void setXRotation(qint32 angle); void setYRotation(qint32 angle); void setZRotation(qint32 angle); protected: void generateDisplayLists(); // OpenGL void initializeGL (); void paintGL (); void resizeGL (qint32 width, qint32 height); // Events void mousePressEvent (QMouseEvent *event); void mouseMoveEvent (QMouseEvent *event); void wheelEvent (QWheelEvent *event); void normalizeAngle (qint32 *angle); // Initialisierung void initLight (); //virtual void generateDisplayLists(){} // Zeichnen void drawScene(); void drawContent(); void renderObject (Object* o, bool box = false) const; void renderOctree (const Octree* o) const; void renderTriangle (Triangle* t, bool box) const; void renderSphere (Sphere* s, bool box) const; void renderRect (Rect* r, bool box) const; void renderCube (const Cube &c) const; void drawRay(const Ray &r) const; void drawVertex(const Vector3D &p) const; void drawLine(const Vector3D &from, const Vector3D &to); void drawScreen(); void ocIntersect(const Octree *octree, const Ray &ray); qint32 xRot; qint32 yRot; qint32 zRot; qint32 zZoom; QPoint lastPos; // Der zu zeichnende Octree //Octree* octree; int screenList; /// Projektion Scene* scene; // Gibt an, ob die Bounding Boxes gezeichnet werden sollen bool showBBoxes; GLUquadricObj *quadratic; }; const qreal GL_NEAR = 0.01f; const qreal GL_FAR = 600.0f; #endif
[ [ [ 1, 121 ] ] ]
e2c3d4d1586c50fd6cc4a8c6b3b0aebf39c7117c
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/nGENE Proj/ShapeSphere.cpp
e5b3d6d3d113b29bdd83b5d7c3b8931ca491bbd4
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
2,742
cpp
/* --------------------------------------------------------------------------- This source file is part of nGENE Tech. Copyright (c) 2006- Wojciech Toman This program is free software. File: ShapeSphere.cpp Version: 0.03 --------------------------------------------------------------------------- */ #include "PrecompiledHeaders.h" #include "PhysXMapping.h" #include "Shape.h" #include "ShapeEnumerator.h" #include "ShapeSphere.h" #pragma warning(push) #pragma warning(disable:4512) #include "NxSphereShapeDesc.h" #pragma warning(pop) namespace nGENE { // Initialize static members TypeInfo ShapeSphere::Type(L"ShapeSphere", &Shape::Type); ShapeSphere::ShapeSphere(): m_pSphereDesc(new NxSphereShapeDesc()) { init(); } //---------------------------------------------------------------------- ShapeSphere::~ShapeSphere() { cleanup(); } //---------------------------------------------------------------------- void ShapeSphere::init() { } //---------------------------------------------------------------------- void ShapeSphere::cleanup() { NGENE_DELETE(m_pSphereDesc); } //---------------------------------------------------------------------- void ShapeSphere::setDimensions(const Vector3& _dims) { Shape::setDimensions(_dims); m_pSphereDesc->radius = _dims.x; } //---------------------------------------------------------------------- void ShapeSphere::setTrigger(bool _value) { Shape::setTrigger(_value); if(_value) m_pSphereDesc->shapeFlags |= NX_TRIGGER_ENABLE; else m_pSphereDesc->shapeFlags &= ~NX_TRIGGER_ENABLE; } //---------------------------------------------------------------------- void ShapeSphere::setLocalPos(const Vector3& _pos) { Shape::setLocalPos(_pos); m_pSphereDesc->localPose.t.x = _pos.x; m_pSphereDesc->localPose.t.y = _pos.y; m_pSphereDesc->localPose.t.z = _pos.z; } //---------------------------------------------------------------------- NxShapeDesc* ShapeSphere::getShapeDesc() { return (static_cast<NxShapeDesc*>(m_pSphereDesc)); } //---------------------------------------------------------------------- //---------------------------------------------------------------------- //---------------------------------------------------------------------- SphereShapeFactory::SphereShapeFactory() { } //---------------------------------------------------------------------- SphereShapeFactory::~SphereShapeFactory() { } //---------------------------------------------------------------------- Shape* SphereShapeFactory::createShape() { return new ShapeSphere(); } //---------------------------------------------------------------------- }
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 96 ] ] ]
533f24b2ff4bf7928a413ab66632664bf9dbd1e4
4ea18bdd6e29708401219df82fd2ea63fa3e3c59
/old/CGUITTFont.cpp
0717c0e1cc0eab150ff023762ca811044142d9d2
[]
no_license
sitc428/fyp3dgame
e4a11f027474f0eb52c711ab577034edcae86a17
6b06dc8a44d8e057336579c5e11c16b438720e63
refs/heads/master
2020-04-05T14:54:58.764314
2011-01-24T04:16:24
2011-01-24T04:16:24
32,114,726
0
0
null
null
null
null
UTF-8
C++
false
false
10,740
cpp
#include <irrlicht/irrlicht.h> #include "CGUITTFont.h" namespace irr { namespace gui { // -------------------------------------------------------- CGUITTGlyph::CGUITTGlyph() : IReferenceCounted() ,size(0) ,top(0) ,left(0) ,texw(0) ,texh(0) ,imgw(0) ,imgh(0) ,tex(NULL) ,top16(0) ,left16(0) ,texw16(0) ,texh16(0) ,imgw16(0) ,imgh16(0) ,tex16(NULL) ,offset(0) ,image(NULL) { } CGUITTGlyph::~CGUITTGlyph() { delete[] image; } void CGUITTGlyph::cache(u32 idx_, FT_Face face_, video::IVideoDriver* driver_) { FT_Set_Pixel_Sizes(face_, 0, size); if ( !FT_Load_Glyph(face_, idx_, FT_LOAD_NO_HINTING|FT_LOAD_NO_BITMAP) ) { FT_GlyphSlot glyph = face_->glyph; FT_Bitmap bits; if (glyph->format == ft_glyph_format_outline ) { if (!FT_Render_Glyph( glyph, FT_RENDER_MODE_NORMAL)) { bits = glyph->bitmap; u8 *pt = bits.buffer; delete[] image; image = new u8[bits.width * bits.rows]; memcpy(image,pt,bits.width * bits.rows); top = glyph->bitmap_top; left = glyph->bitmap_left; imgw = 1; imgh = 1; texw = bits.width; texh = bits.rows; for(;;) { if (imgw > texw) { break; } else { imgw <<= 1; } } for(;;) { if (imgh > texh) { break; } else { imgh <<= 1; } } if (imgw > imgh) { imgh = imgw; } else { imgw = imgh; } u32 *texd = new u32[imgw*imgh]; memset(texd,0,imgw*imgh*sizeof(u32)); u32 *texp = texd; offset = size - bits.rows; bool cflag = (driver_->getDriverType() == video::EDT_DIRECT3D8); for (int i = 0;i < bits.rows;i++) { u32 *rowp = texp; for (int j = 0;j < bits.width;j++) { if (*pt) { if (cflag) { *rowp = *pt; *rowp *= 0x01010101; } else { *rowp = *pt << 24; *rowp |= 0xffffff; } } else { *rowp = 0; } pt++; rowp++; } texp += imgw; } c8 name[128]; sprintf(name,"TTFontGlyph%d",idx_); video::IImage *img = driver_->createImageFromData(video::ECF_A8R8G8B8,core::dimension2d<s32>(imgw,imgh),texd); bool flg16 = driver_->getTextureCreationFlag(video::ETCF_ALWAYS_16_BIT); bool flg32 = driver_->getTextureCreationFlag(video::ETCF_ALWAYS_32_BIT); driver_->setTextureCreationFlag(video::ETCF_ALWAYS_16_BIT,false); driver_->setTextureCreationFlag(video::ETCF_ALWAYS_32_BIT,true); tex = driver_->addTexture(name,img); img->drop(); driver_->setTextureCreationFlag(video::ETCF_ALWAYS_32_BIT,flg32); driver_->setTextureCreationFlag(video::ETCF_ALWAYS_16_BIT,flg16); delete[] texd; cached = true; } } } if (!FT_Load_Glyph(face_,idx_,FT_LOAD_NO_HINTING|FT_LOAD_RENDER|FT_LOAD_MONOCHROME)) { FT_GlyphSlot glyph = face_->glyph; FT_Bitmap bits = glyph->bitmap; u8 *pt = bits.buffer; top16 = glyph->bitmap_top; left16 = glyph->bitmap_left; imgw16 = 1; imgh16 = 1; texw16 = bits.width; texh16 = bits.rows; for(;;) { if (imgw16 >= texw16) { break; } else { imgw16 <<= 1; } } for(;;) { if (imgh16 >= texh16) { break; } else { imgh16 <<= 1; } } if (imgw16 > imgh16) { imgh16 = imgw16; } else { imgw16 = imgh16; } u16 *texd16 = new u16[imgw16*imgh16]; memset(texd16,0,imgw16*imgh16*sizeof(u16)); u16 *texp16 = texd16; offset = size - bits.rows; for (int y = 0;y < bits.rows;y++) { u16 *rowp = texp16; for (int x = 0;x < bits.width;x++) { if (pt[y * bits.pitch + (x / 8)] & (0x80 >> (x % 8))) { *rowp = 0xffff; } rowp++; } texp16 += imgw16; } c8 name[128]; sprintf(name,"TTFontGlyph%d_16",idx_); video::IImage *img = driver_->createImageFromData(video::ECF_A1R5G5B5,core::dimension2d<s32>(imgw16,imgh16),texd16); tex16 = driver_->addTexture(name,img); img->drop(); driver_->makeColorKeyTexture(tex16,video::SColor(0,0,0,0)); delete[] texd16; } } // -------------------------------------------------------- FT_Library CGUITTFace::library = 0; //! loads a font file bool CGUITTFace::load(const c8* filename) { if ( !library ) { if (FT_Init_FreeType( &library )) { return false; } } if (FT_New_Face( library,filename,0,&face )) { return false; } return true; } // -------------------------------------------------------- //! constructor CGUITTFont::CGUITTFont(video::IVideoDriver* driver) : Driver(driver) , tt_face(0) { #ifdef _DEBUG setDebugName("CGUITTFont"); #endif if (Driver) Driver->grab(); AntiAlias = true; TransParency = false; } //! destructor CGUITTFont::~CGUITTFont() { if ( tt_face ) tt_face->drop(); if (Driver) Driver->drop(); clearGlyphs(); } bool CGUITTFont::attach(CGUITTFace *Face,u32 size) { if (!Driver || !Face) return false; if ( tt_face ) tt_face->drop(); tt_face = Face; if ( !tt_face ) return false; tt_face->grab(); clearGlyphs(); Glyphs.reallocate(tt_face->face->num_glyphs); Glyphs.set_used(tt_face->face->num_glyphs); for (int i = 0;i < tt_face->face->num_glyphs;i++) { CGUITTGlyph * glyph = new CGUITTGlyph(); glyph->size = size; glyph->cached = false; // glyph->cache((wchar_t)i + 1); Glyphs[i] = glyph; } return true; } void CGUITTFont::clearGlyphs() { for ( unsigned int i=0; i < Glyphs.size(); ++i ) { delete Glyphs[i]; Glyphs[i] = 0; } } u32 CGUITTFont::getGlyphByChar(wchar_t c) const { u32 idx = FT_Get_Char_Index( tt_face->face, c ); if ( idx && !Glyphs[idx - 1]->cached ) Glyphs[idx - 1]->cache(idx, tt_face->face, Driver); return idx; } //! returns the dimension of a text core::dimension2d<s32> CGUITTFont::getDimension(const wchar_t* text) const { core::dimension2d<s32> dim(0, Glyphs[0]->size); for(const wchar_t* p = text; *p; ++p){ dim.Width += getWidthFromCharacter(*p); } return dim; } inline s32 CGUITTFont::getWidthFromCharacter(wchar_t c) const { u32 n = getGlyphByChar(c); if ( n > 0) { int w = Glyphs[n - 1]->texw; s32 left = Glyphs[n - 1]->left; if (w + left > 0) return w + left; } if (c >= 0x2000) { return Glyphs[0]->size; } else { return Glyphs[0]->size / 2; } } //! draws an text and clips it to the specified rectangle if wanted void CGUITTFont::draw(const wchar_t* text, const core::rect<s32>& position, video::SColor color, bool hcenter, bool vcenter, const core::rect<s32>* clip) { if (!Driver) return; core::dimension2d<s32> textDimension; core::position2d<s32> offset = position.UpperLeftCorner; video::SColor colors[4]; for (int i = 0;i < 4;i++) { colors[i] = color; } if (hcenter || vcenter) { textDimension = getDimension(text); if (hcenter) offset.X = ((position.getWidth() - textDimension.Width)>>1) + offset.X; if (vcenter) offset.Y = ((position.getHeight() - textDimension.Height)>>1) + offset.Y; } u32 n; while(*text) { n = getGlyphByChar(*text); if ( n > 0) { if (AntiAlias) { s32 imgw = Glyphs[n-1]->imgw; s32 imgh = Glyphs[n-1]->imgh; s32 texw = Glyphs[n-1]->texw; s32 texh = Glyphs[n-1]->texh; s32 offx = Glyphs[n-1]->left; s32 offy = Glyphs[n-1]->size - Glyphs[n-1]->top; if (Driver->getDriverType() != video::EDT_SOFTWARE) { if (!TransParency) color.color |= 0xff000000; Driver->draw2DImage(Glyphs[n-1]->tex,core::position2d<s32>(offset.X+offx,offset.Y+offy),core::rect<s32>(0,0,imgw-1,imgh-1),clip,color,true); } else { s32 a = color.getAlpha(); s32 r = color.getRed(); s32 g = color.getGreen(); s32 b = color.getBlue(); u8 *pt = Glyphs[n-1]->image; if (!TransParency) a = 255; for (int y = 0;y < texh;y++) { for (int x = 0;x < texw;x++) { if (!clip || clip->isPointInside(core::position2d<s32>(offset.X+x+offx,offset.Y+y+offy))) { if (*pt) { Driver->draw2DRectangle(video::SColor((a * *pt)/255,r,g,b),core::rect<s32>(offset.X+x+offx,offset.Y+y+offy,offset.X+x+offx+1,offset.Y+y+offy+1)); } pt++; } } } } } else { s32 imgw = Glyphs[n-1]->imgw16; s32 imgh = Glyphs[n-1]->imgh16; // s32 texw = Glyphs[n-1]->texw16; // s32 texh = Glyphs[n-1]->texh16; s32 offx = Glyphs[n-1]->left16; s32 offy = Glyphs[n-1]->size - Glyphs[n-1]->top16; if (!TransParency) { color.color |= 0xff000000; } Driver->draw2DImage(Glyphs[n-1]->tex16, core::position2d<s32>(offset.X+offx,offset.Y+offy), core::rect<s32>(0,0,imgw-1,imgh-1), clip, color, true); } offset.X += getWidthFromCharacter(*text); } else { offset.X += getWidthFromCharacter(*text); } ++text; } } //! Calculates the index of the character in the text which is on a specific position. s32 CGUITTFont::getCharacterFromPos(const wchar_t* text, s32 pixel_x) const { s32 x = 0; s32 idx = 0; while (text[idx]){ x += getWidthFromCharacter(text[idx]); if (x >= pixel_x) return idx; ++idx; } return -1; } void CGUITTFont::setKerningWidth(s32 kerning){ } void CGUITTFont::setKerningHeight(s32 kerning){ } s32 CGUITTFont::getKerningWidth(const wchar_t* thisLetter, const wchar_t* previousLetter) const{ return 0; } s32 CGUITTFont::getKerningHeight() const{ return 0; } } // end namespace gui } // end namespace irr
[ "[email protected]@723dad30-d554-0410-9681-1d1d8597b35f" ]
[ [ [ 1, 462 ] ] ]
29a0797e868ac1ecb9ec096da78fd0ff8f0cbe60
2a4e02aa8bb8afa331b62fa867c7abf1d7bc1c2c
/setclass.h
a09e7a63c462d738efdf1f730e3aeb5b5cf633e1
[]
no_license
calebsmith/SetLAB
ae67031ae008240d19652301585edc3caa5a55b2
74be0b2543c1b6724da73fbd3fde5e3feb4d24d8
refs/heads/master
2021-01-01T05:41:59.826992
2011-08-18T02:23:50
2011-08-18T02:23:50
2,225,628
0
0
null
null
null
null
UTF-8
C++
false
false
22,375
h
#ifndef SETCLASS_H #define SETCLASS_H const bool DEBUG = 0; #include <math.h> #include <algorithm> #include <iostream> #include <string> using namespace std; const int PITCH_LIMIT = 640; const int MOD_LIMIT = 31; class Set { private: int* plist; int* pclist; int pitch; int length; int pitch_class; int* pc_array; int* sc_array; int* temp_array; int* icv; int* temp_icv; long long int setint; long long int scint; long long int comset; long long int mset; long long int zset; int cardinality; string fname; static int Modulus; static int Canon; static int Default_M; static int Ordered; static int Multi; static int Base; //derive internal values void findpc() {int r = findpc(pitch); pitch_class = r; return;}; int findpc(int p){ while (p >=Modulus) { p = p - Modulus;}; while (p < 0) { p = p + Modulus;}; return p; }; void findbool(){ int i; int thispc; for (i = 0; i < Modulus; i++)//reset to 0 { pc_array[i] = 0; } for (i = 0; i < length; i++)//mark 1 if pc is present { thispc = pclist[i]; pc_array[thispc] = 1; } }; void findcardinality(){ int i; cardinality = 0; for (i = 0; i < Modulus; i++) { if (pc_array[i] >= 1) cardinality+=1; } }; int findcardinality(int intin){ int i; int tempcard = 0; int* set; set = new int[Modulus]; to_binary(intin); for (i = 0; i < Modulus; i++){set[i] = temp_array[i];} for (i = 0; i < Modulus; i++) { if (set[i] >= 1) tempcard+=1; } delete [] set; return tempcard; }; long long int transpose_int(long long int intin, int shift){ long long int answer; int i, i2; int* set; int* tempset; set = new int [Modulus]; tempset = new int [Modulus]; to_binary(intin); for (i = 0; i <Modulus; i++){set[i] = temp_array[i];} for (i = 0; i < Modulus; i++) { i2 = i + shift; while (i2 >= Modulus){i2 = i2 - Modulus;}; while (i2 < 0){i2 = i2 + Modulus;}; tempset[i2] = set[i]; } answer = to_decimal(tempset, Modulus); delete [] set; delete [] tempset; return answer; }; long long int inversion_int(long long int intin){ long long int answer; int i, i2; int* set; int* tempset; set = new int[Modulus]; tempset = new int[Modulus]; to_binary(intin); for (i = 0; i <Modulus; i++){set[i] = temp_array[i];} for (i = 0; i < Modulus; i++) { i2 = (Modulus - 1) - i; if (i2 == Modulus) i2 -= Modulus; tempset[i2] = set[i]; } answer = to_decimal(tempset, Modulus); delete [] set; delete [] tempset; return answer; }; long long int m_int(long long int intin){long long int r = m_int(intin, Default_M);return r;}; long long int mi_int(long long int intin){long long int r = m_int(intin, Modulus - Default_M); return r;}; long long int m_int(long long int intin, int value){ long long int answer; int i, i2; int* set; int* tempset; set = new int[Modulus]; tempset = new int [Modulus]; to_binary(intin); for (i = 0; i <Modulus; i++){set[i] = temp_array[i];} for (i = 0; i < Modulus; i++) { i2 = i * value; while (i2 >= Modulus){i2 -= Modulus;} tempset[i2] = set[i]; } answer = to_decimal(tempset, Modulus); delete [] set; delete [] tempset; return answer; }; //conduct a search for a pitch or pc void search(int search_num, bool pitchtype){ int i; int i2 = 0; delete [] s.list; s.list = new long long int[length]; for (i = 0; i < length; i++) { if (pitchtype == 0) { if (pclist[i] == search_num) { s.list[i2] = i; i2++; } } if (pitchtype == 1) { if (plist[i] == search_num) { s.list[i2] = i; i2++; } } } s.size = i2; return; }; void derive_pitches(int intin){ int i,i2; delete [] pc_array; pc_array = new int[Modulus]; to_binary(intin); for (i = 0; i <Modulus; i++){pc_array[i] = temp_array[i];} int newcard = 0; newcard = findcardinality(intin); length = newcard; i2 = 0; delete [] plist; delete [] pclist; plist = new int[newcard]; pclist = new int[newcard]; for (i = 0; i < Modulus; i++) { if (pc_array[i] >= 1) { plist[i2] = i; pclist[i2] = i; i2++; } } }; void reset(){ int i; pitch = 0; pitch_class = 0; setint= 0; scint = 0; comset = 0; mset = 0; zset = -1; length = 0; cardinality = 0; fname = ""; plist = new int[1]; pclist = new int[1]; s.list = new long long int[1]; tto.list = new long long int[1]; embedded.list = new long long int[1]; pc_array = new int[Modulus]; sc_array = new int[Modulus]; temp_array = new int[Modulus]; icv = new int[(Modulus / 2) + 1]; temp_icv = new int[(Modulus / 2) + 1]; for (i = 0; i < Modulus; i++) { pc_array[i] = 0; sc_array[i] = 0; temp_array[i] = 0; } for (i = 0; i < (Modulus / 2) + 1; i++) { icv[i] = 0; temp_icv[i] = 0; } refresh(); }; protected: public: struct list_answer{ long long int* list; int size; } s, tto, embedded; //constructor, destrcutor, copier, and equals overload Set() {reset();}; ~Set() { delete [] pc_array; delete [] sc_array; delete [] temp_array; delete [] icv; delete [] temp_icv; delete [] plist; delete [] pclist;delete [] s.list; delete [] tto.list; delete [] embedded.list; }; void clear(){ delete [] plist; delete [] pclist; delete [] pc_array; delete [] sc_array; delete [] icv; delete [] temp_icv; delete [] s.list; delete [] tto.list; delete [] embedded.list; delete [] temp_array; reset(); }; Set(const Set& a){ delete [] plist; delete [] pclist; delete [] pc_array; delete [] sc_array; delete [] temp_array; delete icv; delete [] temp_icv; delete [] tto.list; tto.list = new long long int[1]; delete [] s.list; s.list = new long long int[1]; delete [] embedded.list; embedded.list = new long long int[1]; length = a.length; plist = new int[length]; pclist = new int[length]; int i; for (i = 0; i < length; i++) { plist[i] = a.plist[i]; pclist[i] = a.pclist[i]; } Modulus = a.Modulus; Canon = a.Canon; Ordered = a.Ordered; Default_M = a.Default_M; Multi = a.Multi; pc_array = new int [Modulus]; sc_array = new int [Modulus]; temp_array = new int [Modulus]; icv = new int [(Modulus / 2) + 1]; temp_icv = new int [(Modulus / 2) + 1]; for (i = 0; i < Modulus; i++) { pc_array[i] = a.pc_array[i]; sc_array[i] = a.sc_array[i]; temp_array[i] = a.temp_array[i]; } for (i = 0; i < (Modulus / 2) + 1; i++) { icv[i] = a.icv[i]; temp_icv[i] = a.temp_icv[i]; } setint = a.setint; scint = a.scint; comset = a.comset; mset = a.mset; zset = a.zset; cardinality = a.cardinality; fname = a.fname; }; Set& operator= (const Set &a){ if(this == &a) return *this; delete [] plist; delete [] pclist; delete [] pc_array; delete [] sc_array; delete [] temp_array; delete [] icv; delete [] temp_icv; delete [] tto.list; tto.list = new long long int[1]; delete [] s.list; s.list = new long long int[1]; delete [] embedded.list; embedded.list = new long long int[1]; length = a.length; plist = new int[length]; pclist = new int[length]; int i; for (i = 0; i < length; i++) { plist[i] = a.plist[i]; pclist[i] = a.pclist[i]; } Modulus = a.Modulus; Canon = a.Canon; Ordered = a.Ordered; Default_M = a.Default_M; Multi= a.Multi; pc_array = new int [Modulus]; sc_array = new int [Modulus]; temp_array = new int [Modulus]; icv = new int [(Modulus / 2) + 1]; temp_icv = new int [(Modulus / 2) + 1]; for (i = 0; i < Modulus; i++) { pc_array[i] = a.pc_array[i]; sc_array[i] = a.sc_array[i]; temp_array[i] = a.temp_array[i]; } for (i = 0; i < (Modulus / 2) + 1; i++) { icv[i] = a.icv[i]; temp_icv[i] = a.temp_icv[i]; } setint = a.setint; scint = a.scint; comset = a.comset; mset = a.mset; zset = a.zset; cardinality = a.cardinality; fname = a.fname; return *this; }; void make(int size){ delete [] pclist; delete [] plist; length = size; plist = new int[length]; pclist = new int[length]; return; }; void assign(int list_number, int number){ if (list_number > length) add(number); if (list_number < 0) return; pitch = number; while (pitch > PITCH_LIMIT) {pitch-= Modulus;} while (pitch < -PITCH_LIMIT) {pitch+= Modulus;} plist[list_number] = pitch; pclist[list_number] = findpc(pitch); return; }; //assign a pitch to the set object w/ add. Others include insert, remove, and swap_p void add(int number){ int i; int temp_pc; //if multisets are off, check for pitch already in set if(Multi == false){ for (i = 0; i < length; i++){ temp_pc = findpc(plist[i]); if (number == plist[i] || number == temp_pc) return; } } int* pbuffer; pbuffer = new int[length]; for (i = 0; i < length; i++){pbuffer[i] = plist[i];} delete [] pclist; delete [] plist; pclist = new int[length + 1]; plist = new int[length + 1]; for (i = 0; i < length; i++) { plist[i] = pbuffer[i]; pclist[i] = findpc(plist[i]); } delete [] pbuffer; pitch = number; while (pitch > PITCH_LIMIT) {pitch-= Modulus;} while (pitch < -PITCH_LIMIT) {pitch+= Modulus;} plist[length] = pitch; pclist[length] = findpc(pitch); length++; refresh(); return; }; //remove a pitch/pc from the corresponding list. parameter is number in list void remove(int list_number){ //make sure parameter is within bounds and there is an element to remove if (length < 1 || list_number < 0 || list_number >= length) return; int i; int* pbuffer; pbuffer = new int[length]; for (i = 0; i < length;i++) { pbuffer[i]=plist[i]; } delete [] plist; delete [] pclist; length--; pclist= new int[length]; plist = new int[length]; for (i = 0; i< list_number;i++) { plist[i] = pbuffer[i]; pclist[i] = findpc(pbuffer[i]); } for (i = list_number; i < length; i++) { plist[i] = pbuffer[i + 1]; pclist[i] = findpc(pbuffer[i + 1]); } delete [] pbuffer; refresh(); return; }; void insert(int number, int list_number){ if (list_number < 0) return; if (length < 1 || list_number >= length) {add(number); return;} int i, temp_pc; if(Multi == false) { for (i = 0; i < length; i++) { temp_pc = findpc(plist[i]); if (number == plist[i] || number == temp_pc) return; } } int* pbuffer; pbuffer = new int[length]; for (i = 0; i < length; i++) { pbuffer[i] = plist[i]; } delete [] plist; delete [] pclist; length++; pclist= new int[length]; plist = new int[length]; for (i = 0; i < list_number; i++) { plist[i] = pbuffer[i]; pclist[i] = findpc(pbuffer[i]); } plist[list_number] = number; pclist[list_number] = findpc(number); for (i = list_number + 1; i < length; i++) { plist[i] = pbuffer[i - 1]; pclist[i] = findpc(pbuffer[i - 1]); } delete [] pbuffer; refresh(); return; }; void swap_p(int num, int num2){ if (num < 0 || num2 < 0 || num >= length || num2 >= length) return; //swap pitches in list int temp = plist[num]; plist[num] = plist[num2]; plist[num2] = temp; //swap pitch classes in list int temp_pc = pclist[num]; pclist[num] = pclist[num2]; pclist[num2] = temp_pc; return; }; //change status for individual set, what has been changed for the whole group void change_mod(int newmod){ delete [] pc_array; delete [] sc_array; delete [] temp_array; delete [] icv; delete [] temp_icv; Modulus = newmod; pc_array = new int [Modulus]; sc_array = new int [Modulus]; temp_array = new int [Modulus]; icv = new int [(Modulus / 2) + 1]; temp_icv = new int [(Modulus / 2) + 1]; int i; for (i = 0; i < length;i++) {pclist[i] = findpc(plist[i]); } refresh(); return; }; void change_canon(int value){ if (value < 0 || value > 3) return; Canon = value; refresh(); return; }; void change_multi(bool value){ Multi = value; return; }; void change_order(bool value){ if (value == 1 || value == 0) Ordered = value; return; }; void change_m(int value){ if (Default_M <= 0) return; Default_M = value; while (Default_M > Modulus){ Default_M -= Modulus; } refresh(); return; }; //very experimental. NOT IMPLEMENTED void change_base(int value){ Base = value; refresh(); return; }; void search_pc(int search_num){bool pitchtype = 0; search(search_num, pitchtype);}; void search_p(int search_num){bool pitchtype = 1; search(search_num, pitchtype);}; void search(int search_num) {bool pitchtype = 0; search(search_num, pitchtype);}; //perform operations on the set long long int to_decimal(int[],int); void to_binary(long long int); //int* to_binary(long long int); void transpose(int value){ int i; int temp; for (i = 0; i < length;i++) { temp = plist[i] + value; while (temp > PITCH_LIMIT) {temp = temp - Modulus;} while (temp < -PITCH_LIMIT) {temp = temp + Modulus;} plist[i] = temp; pclist[i] = findpc(plist[i]); } setint = transpose_int(setint, value); to_binary(setint); for (i = 0; i < Modulus; i++){pc_array[i] = temp_array[i];} }; void invert(){ int i; for (i = 0; i < length; i++) { plist[i] = -plist[i]; pclist[i] = findpc(plist[i]); } setint = inversion_int(setint); to_binary(setint); for (i = 0; i < Modulus; i++){pc_array[i] = temp_array[i];} refresh(); }; void multiply () {multiply(Default_M);}; void multiply(int value){ int i; int temp; for (i = 0; i < length; i++) { temp = plist[i] * value; while (temp > PITCH_LIMIT) {temp-= Modulus;} while (temp < -PITCH_LIMIT) {temp += Modulus;} plist[i] = temp; pclist[i] = findpc(plist[i]); } setint = m_int(setint); to_binary(setint); for (i = 0; i < Modulus; i++){pc_array[i] = temp_array[i];} refresh(); }; void refresh(){ findbool(); findcardinality(); setint = to_decimal(pc_array, Modulus); prime(); fortename(); findicv(); compliment(); mpartner(); //zpartner(); if (Modulus <= 12) zpartner(); if (Modulus > 12) zset = -1; }; void prime() {scint = prime(setint); int i; to_binary(scint); for (i = 0; i < Modulus; i++){sc_array[i] = temp_array[i];}}; long long int prime(long long int intin); void findicv(){findicv(scint);int i; for(i= 0; i < (Modulus / 2) + 1;i++){icv[i] = temp_icv[i];} return;}; void findicv(long long int intin); //int* findicv(long long int intin); void fortename(){fname = fortename(scint); return;}; string fortename (long long int); long long int fname_to_scint(string fnamein); void set_from_fname(string fnamein){ long long int val; val = fname_to_scint(fnamein); if (val < 0 || val > 4095) return; if (Modulus != 12 || Canon != 1) {return;} clear(); derive_pitches(val); refresh(); return; }; void set_from_int(long long int intin){ clear(); derive_pitches(intin); refresh(); }; void set_from_z(){ if (zset != -1) { long long int z = zset;//stored before set is cleared clear(); derive_pitches(z); refresh(); } }; void set_from_c(){ long long int c = comset; //store before clearing the set clear(); derive_pitches(c); refresh(); }; void compliment(){comset = abstract_compliment(scint); return;}; long long int compliment(long long int intin){long long int r; r = abstract_compliment(intin); return r;}; long long int literal_compliment(long long int intin){ long long int answer; int* set; int* temp; set = new int[Modulus]; temp = new int[Modulus]; int i; to_binary(intin); for (i = 0; i < Modulus; i++){set[i] = temp_array[i];} for (i = 0; i < Modulus; i++) { if (set[i] == 0) temp[i] = 1; if (set[i] == 1) temp[i] = 0; } delete [] set; answer = to_decimal(temp,Modulus); delete [] temp; return answer; }; long long int abstract_compliment(long long int intin){ long long int answer; long long int tempdec; tempdec = literal_compliment(intin); answer = prime(tempdec); return answer; }; void mpartner(){mset = mpartner(setint); return;}; long long int mpartner(long long int intin){ long long int answer; answer = prime(m_int(intin)); return answer; }; void zpartner() {zset = zpartner(setint); return;}; long long int zpartner(long long int); long long int lowest(long long int* listofints, int size); void all_tto(long long int); //for output int get_p(int p){int r; r = plist[p]; return r;}; int get_pc(int p) {int r; r = pclist[p]; return r;}; int* get_binary() { int* answer; answer = new int[Modulus]; int i; for (i = 0; i < Modulus; i++) { *(answer + i) = pc_array[i]; } return answer; }; int* get_binary_fixed(){ int* answer; answer = new int[Modulus]; answer = get_fixed(pc_array); return answer; }; int* get_sc() { int* answer; answer = new int[Modulus]; int i; for (i = 0; i < Modulus; i++) { *(answer + i) = sc_array[i]; } return answer; }; int* get_sc_fixed() { int* answer; answer = new int[Modulus]; answer = get_fixed(sc_array); return answer; }; string list_string(int* list, int style, int size){ string answer; if (size == 0) { if (style == 0 || style == 2) size = get_card(); if (style == 1) size = get_length(); if (style == 3) size = (Modulus / 2) + 1; if (style > 3) return "error - no size specified"; } int* temp_list; temp_list = new int[size]; int i, i2; for (i = 0; i < size; i++) {temp_list[i] = list[i];} if (style == 0) answer += "{"; if (style == 1) answer += "<"; if (style == 2) answer += "("; for (i = 0; i < size; i++) { if (list[i] < 10) answer += char(list[i] + '0'); if (list[i] > 9 ) { for (i2 = 0; i2 < list[i] / 10; i2++) { if (i2 == (list[i] /10) - 1) { answer += char((i2 + 1)+ '0'); answer += char((list[i] - ((i2 +1)* 10)) + '0'); } } } if (style != 3 && i < size - 1) answer += ","; } if (style == 0) answer += "}"; if (style == 1) answer += ">"; if (style == 2) answer += ")"; delete [] temp_list; return answer; }; string list_string(int* list){string r;r = list_string(list, 0, 0);return r;}; string list_string(long long int intin){string r;r = list_string(intin, 0, 0);return r;}; string list_string(int* list, int style) {string r; r = list_string(list, style,0); return r;}; string list_string(long long int intin, int style) {string r; r = list_string(intin,style,0); return r;}; string list_string(long long int intin, int style, int size){ string answer; if (intin == -1) return "none"; if (intin == 0 && style == 0) return "{}"; if (intin == 0 && style == 1) return "<>"; if (intin == 0 && style == 2) return "()"; int* list; list = new int[Modulus]; to_binary(intin); int i,i2; i2 = 0; for (i = 0; i < Modulus; i++) { if (temp_array[i] > 0) { list[i2] = i; i2++; } } size = findcardinality(intin); answer = list_string(list,style, size); delete [] list; return answer; }; int* list_int(long long int intin){ int* answer; answer = new int[Modulus]; return answer; }; int* get_fixed(int* list){ int* answer; answer = new int[Modulus]; int i,i2; i2 = 0; for (i = 0; i < Modulus; i++) { if (list[i] > 0) {answer[i2] = i; i2++;} } return answer; } long long int get_integer() {long long int r = setint; return r;}; int get_modulus() {int r = Modulus; return r;}; long long int get_sc_integer() {long long int r = scint; return r;}; string get_fname() {string r = fname; return r;}; int get_cardinality() {int r = get_card(); return r;}; int get_card() {int r = cardinality; return r;}; int get_length() {int r = length; return r;}; //int get_icv(int n){int r = icv[n]; return r;}; int* get_icv(){int* r; r = new int[Modulus / 2 +1]; int i; for (i= 0; i < Modulus / 2 + 1; i++) {r[i] = icv[i];} return r;}; int* get_icv(long long int intin){findicv(intin); int* r; r = new int[Modulus / 2 + 1]; int i; for (i = 0; i < Modulus / 2 + 1; i++) {r[i] = temp_icv[i];} return r;}; long long int get_compliment() {long long int r; r = comset; return r;}; long long int get_mpartner() {long long int r; r = mset; return r;}; long long int get_zpartner() {long long int r; r = zset; return r;}; }; #include "groupclass.h" #include "pageclass.h" #endif
[ [ [ 1, 872 ] ] ]
c534f2a33d699f1e23fe88ee5981ddb8208773f9
1092bd6dc9b728f3789ba96e37e51cdfb9e19301
/loci/anim/blend_info.h
414cba69a9ad4d1e7c99782e7ce87df1e8daa2fd
[]
no_license
dtbinh/loci-extended
772239e63b4e3e94746db82d0e23a56d860b6f0d
f4b5ad6c4412e75324d19b71559a66dd20f4f23f
refs/heads/master
2021-01-10T12:23:52.467480
2011-03-15T22:03:06
2011-03-15T22:03:06
36,032,427
0
0
null
null
null
null
UTF-8
C++
false
false
3,830
h
#ifndef LOCI_ANIM_BLEND_INFO_H_ #define LOCI_ANIM_BLEND_INFO_H_ /** * Describes the properties of a blend. * blend_info structures are propagated through the blend-tree and carry information * about how a node should perform a blend, such as which weights to use. * * @file blend_info.h * @author David Gill * @date 29/03/2010 */ #include <vector> #include "loci/pose.h" #include "loci/skeleton.h" #include "loci/numeric/vector.h" namespace loci { namespace anim { class blend_info { public: typedef std::vector<double> weight_list; typedef numeric::vector2f direction_type; blend_info(double amount, weight_list & weights, pose & destination, skeleton & figure, double speed, const direction_type & direction, bone_pose::rotation_type & rotation_delta) : amount_(amount) , weights_(&weights) , destination_(&destination) , figure_(&figure) , speed_(speed) , direction_(&direction) , rotation_delta_(&rotation_delta) { } blend_info(double amount, const blend_info & other) : amount_(amount) , weights_(other.weights_) , destination_(other.destination_) , figure_(other.figure_) , speed_(other.speed_) , direction_(other.direction_) , rotation_delta_(other.rotation_delta_) { } blend_info(weight_list & weights, const blend_info & other) : amount_(other.amount_) , weights_(&weights) , destination_(other.destination_) , figure_(other.figure_) , speed_(other.speed_) , direction_(other.direction_) , rotation_delta_(other.rotation_delta_) { } blend_info(double amount, weight_list & weights, const blend_info & other) : amount_(amount) , weights_(&weights) , destination_(other.destination_) , figure_(other.figure_) , speed_(other.speed_) , direction_(other.direction_) , rotation_delta_(other.rotation_delta_) { } blend_info(double amount, weight_list & weights, pose & destination, bone_pose::rotation_type & rotation_delta, const blend_info & other) : amount_(amount) , weights_(&weights) , destination_(&destination) , figure_(other.figure_) , speed_(other.speed_) , direction_(other.direction_) , rotation_delta_(&rotation_delta) { } double amount() const { return amount_; } const weight_list & weights() const { return *weights_; } pose & destination() const { return *destination_; } boost::shared_ptr<const hierarchy> structure() const { return figure_->structure(); } boost::shared_ptr<const named_indices> name_bindings() const { return figure_->name_bindings(); } const skeleton & figure() const { return *figure_; } double speed() const { return speed_; } const direction_type & direction() const { return *direction_; } bone_pose::rotation_type & rotation_delta() const { return *rotation_delta_; } private: double amount_; weight_list * weights_; pose * destination_; skeleton * figure_; double speed_; const direction_type * direction_; bone_pose::rotation_type * rotation_delta_; }; } // namespace anim } // namespace loci #endif // LOCI_ANIM_BLEND_INFO_H_
[ "[email protected]@0e8bac56-0901-9d1a-f0c4-3841fc69e132" ]
[ [ [ 1, 114 ] ] ]
0990288751dac2729db61896cfb7e2291e4c9292
5a05acb4caae7d8eb6ab4731dcda528e2696b093
/GameEngine/Gfx/Material.hpp
9abd99654e01e319aa5b2397ef98be402a34efe6
[]
no_license
andreparker/spiralengine
aea8b22491aaae4c14f1cdb20f5407a4fb725922
36a4942045f49a7255004ec968b188f8088758f4
refs/heads/master
2021-01-22T12:12:39.066832
2010-05-07T00:02:31
2010-05-07T00:02:31
33,547,546
0
0
null
null
null
null
UTF-8
C++
false
false
2,617
hpp
/*! */ #ifndef MATERIAL_HPP #define MATERIAL_HPP #include <boost/shared_ptr.hpp> #include "Color.hpp" namespace Spiral { class Texture; class Material { public: Material(); Material( const Rgba& ambient, const Rgba& diffuse, const Rgba& specular, const Rgba& emissive ); const Rgba& GetAmbient()const; const Rgba& GetDiffuse()const; const Rgba& GetSpecular()const; const Rgba& GetEmissive()const; void SetAmbient( const Rgba& ambient ); void SetDiffuse( const Rgba& diffuse ); void SetSpecular( const Rgba& specular ); void SetEmissive( const Rgba& emissive ); void SetDiffuseTexture( boost::shared_ptr<Texture>& diffuse ); void SetEffectTexture( boost::shared_ptr<Texture>& effect ); boost::shared_ptr<Texture> GetDiffuseTexture()const; boost::shared_ptr<Texture> GetEffectTexture()const; private: Rgba m_ambient; Rgba m_diffuse; Rgba m_specular; Rgba m_emissive; private: boost::shared_ptr<Texture> m_diffuseTexture; boost::shared_ptr<Texture> m_effectTexture; // e.g normal maps etc }; inline Material::Material(): m_ambient(),m_diffuse(),m_specular(),m_emissive(),m_diffuseTexture(){} inline Material::Material( const Rgba& ambient, const Rgba& diffuse, const Rgba& specular, const Rgba& emissive ): m_ambient( ambient ), m_diffuse( diffuse ), m_specular( specular ), m_emissive( emissive ), m_diffuseTexture(), m_effectTexture(){} inline const Rgba& Material::GetAmbient() const { return m_ambient; } inline const Rgba& Material::GetDiffuse() const { return m_diffuse; } inline const Rgba& Material::GetSpecular() const { return m_specular; } inline const Rgba& Material::GetEmissive() const { return m_emissive; } inline void Material::SetAmbient( const Rgba& ambient ) { m_ambient = ambient; } inline void Material::SetDiffuse( const Rgba& diffuse ) { m_diffuse = diffuse; } inline void Material::SetSpecular( const Rgba& specular ) { m_specular = specular; } inline void Material::SetEmissive( const Rgba& emissive ) { m_emissive = emissive; } inline void Material::SetDiffuseTexture( boost::shared_ptr<Texture>& diffuse ) { m_diffuseTexture = diffuse; } inline void Material::SetEffectTexture( boost::shared_ptr<Texture>& effect ) { m_effectTexture = effect; } inline boost::shared_ptr<Texture> Material::GetDiffuseTexture() const { return m_diffuseTexture; } inline boost::shared_ptr<Texture> Material::GetEffectTexture() const { return m_effectTexture; } } #endif
[ "DreLnBrown@e933ee44-1dc6-11de-9e56-bf19dc6c588e" ]
[ [ [ 1, 111 ] ] ]
7ac1ead9c435a775aa1d39f8a927e9cdbabee51e
e5f7a02c92c5a60c924e07813bc0b7b8944c2ce8
/7-continuation/7.5.2-b/test.cpp
d5e9fb11065b2c169ce12b31db223aebae14d8db
[]
no_license
7shi/thunkben
b8fe8f29b43c030721e8a08290c91275c9f455fe
9bc99c5a957e087bb41bd6f87cf7dfa44e7b55f6
refs/heads/main
2022-12-27T19:53:39.322464
2011-11-30T16:57:45
2011-11-30T16:57:45
303,163,701
0
0
null
null
null
null
UTF-8
C++
false
false
3,155
cpp
#include <string.h> #include <functional> #include <vector> #include <stack> typedef struct { unsigned long eip, esp, ebp, ebx, edi, esi; void *stack; int length; } myjmp_buf; _declspec(naked) int _fastcall mysetjmp(myjmp_buf *jbuf) { _asm { pop edx mov [ecx ], edx mov [ecx+ 4], esp mov [ecx+ 8], ebp mov [ecx+12], ebx mov [ecx+16], edi mov [ecx+20], esi xor eax, eax mov [ecx+24], eax mov [ecx+28], eax jmp edx } } _declspec(naked) void _fastcall mylongjmp(myjmp_buf *jbuf, int value) { _asm { mov eax, edx mov edx, ecx mov esp, [edx+ 4] mov edi, esp mov esi, [edx+24] mov ecx, [edx+28] cld rep movsb mov ebp, [edx+ 8] mov ebx, [edx+12] mov edi, [edx+16] mov esi, [edx+20] jmp dword ptr [edx] } } void save_stack(std::vector<char> *dest, unsigned long last, myjmp_buf *callee) { callee->length = last - callee->esp; dest->resize(callee->length); callee->stack = &(*dest)[0]; memcpy(callee->stack, (void *)callee->esp, callee->length); } class CoroutineBase { public: virtual ~CoroutineBase() {} }; static std::stack<CoroutineBase *> coroutines; template <class T> class Coroutine : public CoroutineBase { myjmp_buf caller, callee; std::vector<char> stack; std::function<void()> f; int status; unsigned long last; public: T value; Coroutine() : status(0) {} Coroutine(const decltype(f) &f) : f(f), status(0) {} void operator=(const decltype(f) &f) { this->f = f; } bool operator()() { if (status == 0) _alloca(32 * 1024); if (mysetjmp(&caller)) return true; switch (status) { case 0: last = caller.esp; status = 1; coroutines.push(this); f(); coroutines.pop(); status = 3; break; case 2: if (caller.esp < callee.esp) return false; status = 1; coroutines.push(this); mylongjmp(&callee, 1); } return false; } T yield(T value) { if (coroutines.top() == this) { coroutines.pop(); status = 2; this->value = value; if (mysetjmp(&callee) == 0) { save_stack(&stack, last, &callee); mylongjmp(&caller, 1); } } return this->value; } }; template <class T> T yield(T value) { auto cr = dynamic_cast<Coroutine<T> *>(coroutines.top()); return cr ? cr->yield(value) : T(); } #include <stdio.h> void test() { for (int i = 0; i <= 0; i++) yield(i); printf("test: done\n"); } Coroutine<int> cr = test; void test2() { if (cr()) printf("test2: %d\n", cr.value); } int main() { if (cr()) printf("main: %d\n", cr.value); test2(); if (cr()) printf("main: %d\n", cr.value); }
[ [ [ 1, 132 ] ] ]