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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7083d80f0c94aeaddfd89afa382a67af89ca74ef | 4aadb120c23f44519fbd5254e56fc91c0eb3772c | /Source/src/EduNetCommon/EduNetGuiTypes.h | 1e26d571bd1ec4b4b59ba3e1dc17cdf5fec9c726 | [] | no_license | janfietz/edunetgames | d06cfb021d8f24cdcf3848a59cab694fbfd9c0ba | 04d787b0afca7c99b0f4c0692002b4abb8eea410 | refs/heads/master | 2016-09-10T19:24:04.051842 | 2011-04-17T11:00:09 | 2011-04-17T11:00:09 | 33,568,741 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,283 | h | #ifndef __EDUNETGUITYPES_H__
#define __EDUNETGUITYPES_H__
//-----------------------------------------------------------------------------
// Copyright (c) 2009, Jan Fietz, Cyrus Preuss
// 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 EduNetGames 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.
//-----------------------------------------------------------------------------
#if 1 // EDUNET_HAVE_GLUI
// forward all glui classes
class GLUI;
class GLUI_Control;
class GLUI_Listbox;
class GLUI_StaticText;
class GLUI_EditText;
class GLUI_Panel;
class GLUI_Spinner;
class GLUI_RadioButton;
class GLUI_RadioGroup;
class GLUI_Glut_Window;
class GLUI_TreePanel;
class GLUI_Scrollbar;
class GLUI_List;
class Arcball;
extern GLUI* getRootGLUI();
#endif // EDUNET_HAVE_GLUI
#endif // __EDUNETGUITYPES_H__
| [
"janfietz@localhost"
] | [
[
[
1,
57
]
]
] |
8fb688d62f1c51c224c3a8cb08c1cf7710afcb86 | 155c4955c117f0a37bb9481cd1456b392d0e9a77 | /Tessa/TessaInstructions/ConstantStringInstruction.h | 9b411396f8592d6394eadf8d0f5268ba0f23a228 | [] | no_license | zwetan/tessa | 605720899aa2eb4207632700abe7e2ca157d19e6 | 940404b580054c47f3ced7cf8995794901cf0aaa | refs/heads/master | 2021-01-19T19:54:00.236268 | 2011-08-31T00:18:24 | 2011-08-31T00:18:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 217 | h |
namespace TessaInstructions {
using namespace avmplus;
class ConstantStringInstruction : ConstantValueInstruction {
private:
Stringp value;
public:
ConstantStringInstruction(Stringp value);
};
} | [
"[email protected]"
] | [
[
[
1,
12
]
]
] |
388d35a27037e283c057a7c93c64b8a3c34adef0 | d9a78f212155bb978f5ac27d30eb0489bca87c3f | /PB/src/PbServer/GeneratedFiles/Debug/moc_PBLauncher.cpp | fe5e39537de42a85e652e4cd19af330ac9b94217 | [] | no_license | marchon/pokerbridge | 1ed4a6a521f8644dcd0b6ec66a1ac46879b8473c | 97d42ef318bf08f3bc0c0cb1d95bd31eb2a3a8a9 | refs/heads/master | 2021-01-10T07:15:26.496252 | 2010-05-17T20:01:29 | 2010-05-17T20:01:29 | 36,398,892 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,889 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'PBLauncher.h'
**
** Created: Mon 29. Mar 17:08:49 2010
** by: The Qt Meta Object Compiler version 61 (Qt 4.5.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "stdafx.h"
#include "..\..\PBLauncher.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'PBLauncher.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 61
#error "This file was generated using the moc from 4.5.2. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_PBLauncher[] = {
// content:
2, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0 // eod
};
static const char qt_meta_stringdata_PBLauncher[] = {
"PBLauncher\0"
};
const QMetaObject PBLauncher::staticMetaObject = {
{ &QObject::staticMetaObject, qt_meta_stringdata_PBLauncher,
qt_meta_data_PBLauncher, 0 }
};
const QMetaObject *PBLauncher::metaObject() const
{
return &staticMetaObject;
}
void *PBLauncher::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_PBLauncher))
return static_cast<void*>(const_cast< PBLauncher*>(this));
return QObject::qt_metacast(_clname);
}
int PBLauncher::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_END_MOC_NAMESPACE
| [
"[email protected]"
] | [
[
[
1,
64
]
]
] |
a4daa32aaad12fca194b739a015cb2522eb02348 | 836523304390560c1b0b655888a4abef63a1b4a5 | /DsoFramer_V2.3.0.1/dsofprint.cpp | 4ad229c5d293a9c66f84c252cb5d95b0ec466296 | [] | no_license | paranoiagu/UDSOnlineEditor | 4675ed403fe5acf437ff034a17f3eaa932e7b780 | 7eaae6fef51a01f09d28021ca6e6f2affa7c9658 | refs/heads/master | 2021-01-11T03:19:59.238691 | 2011-10-03T06:02:35 | 2011-10-03T06:02:35 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 68,208 | cpp | /***************************************************************************
* DSOFPRINT.CPP
*
* CDsoDocObject: Print Code for CDsoDocObject object
*
* Copyright ?999-2004; Microsoft Corporation. All rights reserved.
* Written by Microsoft Developer Support Office Integration (PSS DSOI)
*
* This code is provided via KB 311765 as a sample. It is not a formal
* product and has not been tested with all containers or servers. Use it
* for educational purposes only. See the EULA.TXT file included in the
* KB download for full terms of use and restrictions.
*
* THIS CODE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
*
***************************************************************************/
#include "dsoframer.h"
#include "msoffice.h"
#include <atlbase.h>
#include <atlconv.h>
#include <afxdisp.h>
#include <afxwin.h>
#include <tchar.h>
#include <wininet.h>
#include <afxinet.h>
#include "XMLHttpClient.h"
#include <atlbase.h>
#include <mshtml.h>
#include <mshtmdid.h>
#include <comdef.h>
#import "C:\Program Files\Microsoft Office\Office12\MSWORD.olb" rename("ExitWindows","ExitWindowsEx"),rename_namespace("MSWord")
//using namespace MSWord;
#import "C:\Program Files\Microsoft Office\Office12\EXCEL.exe" rename("RGB","RGBEx"),rename("DialogBox","DialogBoxEx"),rename_namespace("MSExcel")
//using namespace MSExcel;
#import "C:\Program Files\Microsoft Office\Office12\MSPPT.OLB" named_guids,rename_namespace("MSPPT")
//using namespace MSPPT;
#import "C:\WINDOWS\system32\msxml3.dll"
using namespace MSXML2;
extern char* BSTR2char(const BSTR bstr) ;
////////////////////////////////////////////////////////////////////////
// CDsoFramerControl::_PrintOutOld
//
// Prints the current object by calling IOleCommandTarget for Print.
//
STDMETHODIMP CDsoFramerControl::_PrintOutOld(VARIANT PromptToSelectPrinter)
{
DWORD dwOption = BOOL_FROM_VARIANT(PromptToSelectPrinter, FALSE)
? OLECMDEXECOPT_PROMPTUSER : OLECMDEXECOPT_DODEFAULT;
TRACE1("CDsoFramerControl::_PrintOutOld(%d)\n", dwOption);
CHECK_NULL_RETURN(m_pDocObjFrame, ProvideErrorInfo(DSO_E_DOCUMENTNOTOPEN));
// Cannot access object if in modal condition...
if ((m_fModalState) || (m_pDocObjFrame->InPrintPreview()))
return ProvideErrorInfo(DSO_E_INMODALSTATE);
return m_pDocObjFrame->DoOleCommand(OLECMDID_PRINT, dwOption, NULL, NULL);
}
////////////////////////////////////////////////////////////////////////
// CDsoFramerControl::PrintOut
//
// Prints document using either IPrint or IOleCommandTarget, depending
// on parameters passed. This offers a bit more control over printing if
// the doc object server supports IPrint interface.
//
STDMETHODIMP CDsoFramerControl::PrintOut(VARIANT PromptUser, VARIANT PrinterName,
VARIANT Copies, VARIANT FromPage, VARIANT ToPage, VARIANT OutputFile)
{
HRESULT hr;
BOOL fPromptUser = BOOL_FROM_VARIANT(PromptUser, FALSE);
LPWSTR pwszPrinter = LPWSTR_FROM_VARIANT(PrinterName);
LPWSTR pwszOutput = LPWSTR_FROM_VARIANT(OutputFile);
LONG lCopies = LONG_FROM_VARIANT(Copies, 1);
LONG lFrom = LONG_FROM_VARIANT(FromPage, 0);
LONG lTo = LONG_FROM_VARIANT(ToPage, 0);
TRACE3("CDsoFramerControl::PrintOut(%d, %S, %d)\n", fPromptUser, pwszPrinter, lCopies);
CHECK_NULL_RETURN(m_pDocObjFrame, ProvideErrorInfo(DSO_E_DOCUMENTNOTOPEN));
// First we do validation of all parameters passed to the function...
if ((pwszPrinter) && (*pwszPrinter == L'\0'))
return E_INVALIDARG;
if ((pwszOutput) && (*pwszOutput == L'\0'))
return E_INVALIDARG;
if ((lCopies < 1) || (lCopies > 200))
return E_INVALIDARG;
if (((lFrom != 0) || (lTo != 0)) && ((lFrom < 1) || (lTo < lFrom)))
return E_INVALIDARG;
// Cannot access object if in modal condition...
if ((m_fModalState) || (m_pDocObjFrame->InPrintPreview()))
return ProvideErrorInfo(DSO_E_INMODALSTATE);
// If no printer name was provided, we can print to the default device
// using IOleCommandTarget with OLECMDID_PRINT...
if (pwszPrinter == NULL)
return _PrintOutOld(PromptUser);
// Ask the embedded document to print itself to specific printer...
hr = m_pDocObjFrame->PrintDocument(pwszPrinter, pwszOutput, (UINT)lCopies,
(UINT)lFrom, (UINT)lTo, fPromptUser);
// If call failed because interface doesn't exist, change error
// to let caller know it is because DocObj doesn't support this command...
if (FAILED(hr) && (hr == E_NOINTERFACE))
hr = DSO_E_COMMANDNOTSUPPORTED;
return ProvideErrorInfo(hr);
}
////////////////////////////////////////////////////////////////////////
// CDsoFramerControl::PrintPreview
//
// Asks embedded object to attempt a print preview (only Office docs do this).
//
STDMETHODIMP CDsoFramerControl::PrintPreview()
{
HRESULT hr;
ODS("CDsoFramerControl::PrintPreview\n");
CHECK_NULL_RETURN(m_pDocObjFrame, ProvideErrorInfo(DSO_E_DOCUMENTNOTOPEN));
if (m_fModalState) // Cannot access object if in modal condition...
return ProvideErrorInfo(DSO_E_INMODALSTATE);
// Try to set object into print preview mode...
hr = m_pDocObjFrame->StartPrintPreview();
// If call failed because interface doesn't exist, change error
// to let caller know it is because DocObj doesn't support this command...
if (FAILED(hr) && (hr == E_NOINTERFACE))
hr = DSO_E_COMMANDNOTSUPPORTED;
return ProvideErrorInfo(hr);
}
////////////////////////////////////////////////////////////////////////
// CDsoFramerControl::PrintPreviewExit
//
// Closes an active preview.
//
STDMETHODIMP CDsoFramerControl::PrintPreviewExit()
{
ODS("CDsoFramerControl::PrintPreviewExit\n");
CHECK_NULL_RETURN(m_pDocObjFrame, ProvideErrorInfo(DSO_E_DOCUMENTNOTOPEN));
// Try to set object out of print preview mode...
if (m_pDocObjFrame->InPrintPreview())
m_pDocObjFrame->ExitPrintPreview(TRUE);
return S_OK;
}
////////////////////////////////////////////////////////////////////////
// CDsoDocObject::PrintDocument
//
// We can use the IPrint interface for an ActiveX Document object to
// selectively print object to a given printer.
//
STDMETHODIMP CDsoDocObject::PrintDocument(LPCWSTR pwszPrinter, LPCWSTR pwszOutput, UINT cCopies, UINT nFrom, UINT nTo, BOOL fPromptUser)
{
HRESULT hr;
IPrint *print;
HANDLE hPrint;
DVTARGETDEVICE* ptd = NULL;
ODS("CDsoDocObject::PrintDocument\n");
CHECK_NULL_RETURN(m_pole, E_UNEXPECTED);
// First thing we need to do is ask object for IPrint. If it does not
// support it, we cannot continue. It is up to DocObj if this is allowed...
hr = m_pole->QueryInterface(IID_IPrint, (void**)&print);
RETURN_ON_FAILURE(hr);
// Now setup printer settings into DEVMODE for IPrint. Open printer
// settings and gather default DEVMODE...
if (FOpenPrinter(pwszPrinter, &hPrint))
{
LPDEVMODEW pdevMode = NULL;
LPWSTR pwszDefProcessor = NULL;
LPWSTR pwszDefDriver = NULL;
LPWSTR pwszDefPort = NULL;
LPWSTR pwszPort;
DWORD cbDevModeSize;
if (FGetPrinterSettings(hPrint, &pwszDefProcessor,
&pwszDefDriver, &pwszDefPort, &pdevMode, &cbDevModeSize) && (pdevMode))
{
DWORD cbPrintName, cbDeviceName, cbOutputName;
DWORD cbDVTargetSize;
pdevMode->dmFields |= DM_COPIES;
pdevMode->dmCopies = (WORD)((cCopies) ? cCopies : 1);
pwszPort = ((pwszOutput) ? (LPWSTR)pwszOutput : pwszDefPort);
// We calculate the size we will need for the TARGETDEVICE structure...
cbPrintName = ((lstrlenW(pwszDefProcessor) + 1) * sizeof(WCHAR));
cbDeviceName = ((lstrlenW(pwszDefDriver) + 1) * sizeof(WCHAR));
cbOutputName = ((lstrlenW(pwszPort) + 1) * sizeof(WCHAR));
cbDVTargetSize = sizeof(DWORD) + sizeof(DEVNAMES) + cbPrintName +
cbDeviceName + cbOutputName + cbDevModeSize;
// Allocate new target device using COM Task Allocator...
ptd = (DVTARGETDEVICE*)CoTaskMemAlloc(cbDVTargetSize);
if (ptd)
{
// Copy all the data in the DVT...
DWORD dwOffset = sizeof(DWORD) + sizeof(DEVNAMES);
ptd->tdSize = cbDVTargetSize;
ptd->tdDriverNameOffset = (WORD)dwOffset;
memcpy((BYTE*)(((BYTE*)ptd) + dwOffset), pwszDefProcessor, cbPrintName);
dwOffset += cbPrintName;
ptd->tdDeviceNameOffset = (WORD)dwOffset;
memcpy((BYTE*)(((BYTE*)ptd) + dwOffset), pwszDefDriver, cbDeviceName);
dwOffset += cbDeviceName;
ptd->tdPortNameOffset = (WORD)dwOffset;
memcpy((BYTE*)(((BYTE*)ptd) + dwOffset), pwszPort, cbOutputName);
dwOffset += cbOutputName;
ptd->tdExtDevmodeOffset = (WORD)dwOffset;
memcpy((BYTE*)(((BYTE*)ptd) + dwOffset), pdevMode, cbDevModeSize);
dwOffset += cbDevModeSize;
ASSERT(dwOffset == cbDVTargetSize);
}
else hr = E_OUTOFMEMORY;
// We're done with the devmode...
DsoMemFree(pdevMode);
}
else hr = E_WIN32_LASTERROR;
SAFE_FREESTRING(pwszDefPort);
SAFE_FREESTRING(pwszDefDriver);
SAFE_FREESTRING(pwszDefProcessor);
ClosePrinter(hPrint);
}
else hr = E_WIN32_LASTERROR;
// If we were successful in getting TARGETDEVICE struct, provide the page range
// for the print job and ask docobj server to print it...
if (SUCCEEDED(hr))
{
PAGESET *ppgset;
DWORD cbPgRngSize = sizeof(PAGESET) + sizeof(PAGERANGE);
LONG cPages, cLastPage;
DWORD grfPrintFlags;
// Setup the page range to print...
if ((ppgset = (PAGESET*)CoTaskMemAlloc(cbPgRngSize)) != NULL)
{
ppgset->cbStruct = cbPgRngSize;
ppgset->cPageRange = 1;
ppgset->fOddPages = TRUE;
ppgset->fEvenPages = TRUE;
ppgset->cPageRange = 1;
ppgset->rgPages[0].nFromPage = ((nFrom) ? nFrom : 1);
ppgset->rgPages[0].nToPage = ((nTo) ? nTo : PAGESET_TOLASTPAGE);
// Give indication we are waiting (on the print)...
HCURSOR hCur = SetCursor(LoadCursor(NULL, IDC_WAIT));
SEH_TRY
// Setup the initial page number (optional)...
print->SetInitialPageNum(ppgset->rgPages[0].nFromPage);
grfPrintFlags = (PRINTFLAG_MAYBOTHERUSER | PRINTFLAG_RECOMPOSETODEVICE);
if (fPromptUser) grfPrintFlags |= PRINTFLAG_PROMPTUSER;
if (pwszOutput) grfPrintFlags |= PRINTFLAG_PRINTTOFILE;
// Now ask server to print it using settings passed...
hr = print->Print(grfPrintFlags, &ptd, &ppgset, NULL, (IContinueCallback*)&m_xContinueCallback,
ppgset->rgPages[0].nFromPage, &cPages, &cLastPage);
SEH_EXCEPT(hr)
SetCursor(hCur);
if (ppgset)
CoTaskMemFree(ppgset);
}
else hr = E_OUTOFMEMORY;
}
// We are done...
if (ptd) CoTaskMemFree(ptd);
print->Release();
return hr;
}
////////////////////////////////////////////////////////////////////////
// CDsoDocObject::StartPrintPreview
//
// Ask embedded object to go into print preview (if supportted).
//
STDMETHODIMP CDsoDocObject::StartPrintPreview()
{
HRESULT hr;
IOleInplacePrintPreview *prev;
HCURSOR hCur;
ODS("CDsoDocObject::StartPrintPreview\n");
CHECK_NULL_RETURN(m_pole, E_UNEXPECTED);
// No need to do anything if already in preview...
if (InPrintPreview()) return S_FALSE;
// Otherwise, ask document server if it supports preview...
hr = m_pole->QueryInterface(IID_IOleInplacePrintPreview, (void**)&prev);
if (SUCCEEDED(hr))
{
// Tell user we waiting (switch to preview can be slow for very large docs)...
hCur = SetCursor(LoadCursor(NULL, IDC_WAIT));
// If it does, make sure it can go into preview mode...
hr = prev->QueryStatus();
if (SUCCEEDED(hr))
{
SEH_TRY
if (m_hwndCtl) // Notify the control that preview started...
SendMessage(m_hwndCtl, DSO_WM_ASYNCH_STATECHANGE, DSO_STATE_INTERACTIVE, (LPARAM)FALSE);
// We will allow application to bother user and switch printers...
hr = prev->StartPrintPreview(
(PREVIEWFLAG_MAYBOTHERUSER | PREVIEWFLAG_PROMPTUSER | PREVIEWFLAG_USERMAYCHANGEPRINTER),
NULL, (IOlePreviewCallback*)&m_xPreviewCallback, 1);
SEH_EXCEPT(hr)
// If the call succeeds, we keep hold of interface to close preview later
if (SUCCEEDED(hr))
{
SAFE_SET_INTERFACE(m_pprtprv, prev);
}
else
{ // Otherwise, notify the control that preview failed...
if (m_hwndCtl)
PostMessage(m_hwndCtl, DSO_WM_ASYNCH_STATECHANGE, DSO_STATE_INTERACTIVE, (LPARAM)TRUE);
}
}
SetCursor(hCur);
prev->Release();
}
return hr;
}
////////////////////////////////////////////////////////////////////////
// CDsoDocObject::ExitPrintPreview
//
// Drop out of print preview and restore items as needed.
//
STDMETHODIMP CDsoDocObject::ExitPrintPreview(BOOL fForceExit)
{
TRACE1("CDsoDocObject::ExitPrintPreview(fForceExit=%d)\n", (DWORD)fForceExit);
// If the user closes the app or otherwise terminates the preview, we need
// to notify the ActiveDocument server to leave preview mode...
try{
if (m_pprtprv)
{
if (fForceExit) // Tell docobj we want to end preview...
{
HRESULT hr = m_pprtprv->EndPrintPreview (TRUE);
ASSERT(SUCCEEDED(hr));
}
if (m_hwndCtl) // Notify the control that preview ended...
PostMessage(m_hwndCtl, DSO_WM_ASYNCH_STATECHANGE, DSO_STATE_INTERACTIVE, (LPARAM)TRUE);
}
}catch(...){
}
// Free our reference to preview interface...
SAFE_RELEASE_INTERFACE(m_pprtprv);
return S_OK;
}
STDMETHODIMP CDsoFramerControl::get_GetApplication(IDispatch** ppdisp)
{
IDispatch *pActiveDocument;
this->get_ActiveDocument(&pActiveDocument);
//DISPID dispid;
LPOLESTR rgszNames =L"Application";
//DISPPARAMS dpNoArgs = {NULL, NULL, 0, 0};
VARIANT vResult;
HRESULT hr;
if (pActiveDocument){
hr = DsoDispatchInvoke(pActiveDocument, rgszNames,0, DISPATCH_PROPERTYGET, 0, NULL,&vResult);
*ppdisp = (vResult.pdispVal);
vResult.pdispVal->AddRef();
}
return ProvideErrorInfo(hr);
}
HRESULT CDsoFramerControl::SetCurrUserName(BSTR strCurrUserName, VARIANT_BOOL* pbool)
{
char * strCurName = NULL;
LPWSTR strwName;
if ((strCurrUserName) && (SysStringLen(strCurrUserName) > 0)){
strwName = SysAllocString(strCurrUserName);
strCurName = DsoConvertToMBCS(strwName);
}
if(!strCurName){
*pbool = FALSE;
return S_OK;
}
IDispatch * lDisp = m_pDocDispatch;
if(!lDisp){
get_ActiveDocument(&lDisp);
if(!lDisp){
*pbool = FALSE;
return S_OK;
}
}
try{
switch(m_nOriginalFileType){
case FILE_TYPE_WORD:
{
CComQIPtr<MSWord::_Document> spDoc(lDisp);
if(!spDoc)
break;
CComPtr<MSWord::_Application> spApp(spDoc->GetApplication());
spApp->put_UserName(A2BSTR(strCurName));
// spApp->put_PrintPreview(VARIANT_TRUE);
spApp.Release();
spDoc.Release();
}
break;
case FILE_TYPE_EXCEL:
{
}
break;
case FILE_TYPE_PPT:
case FILE_TYPE_PDF:
case FILE_TYPE_UNK:
default:
break;
}
}catch(...){
}
*pbool = TRUE;
DsoMemFree((void*)(strCurName));
return S_OK;
}
HRESULT CDsoFramerControl::SetTrackRevisions( long vbool, VARIANT_BOOL* pbool)
{
IDispatch * lDisp = m_pDocDispatch;
if(!lDisp){
get_ActiveDocument(&lDisp);
if(!lDisp){
*pbool = FALSE;
return S_OK;
}
}
// COleVariant covTrue((short)TRUE), covFalse((short)FALSE), covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
try{
switch(m_nOriginalFileType){
case FILE_TYPE_WORD:
{
CComQIPtr<MSWord::_Document> spDoc(lDisp);
if(!spDoc)
break;
if(4 == vbool){
spDoc->AcceptAllRevisions();
}else{
spDoc->put_TrackRevisions( vbool );
}
spDoc.Release();
/*_Document doc;
doc.AttachDispatch(lDisp);
doc.SetTrackRevisions (vbool);
doc.DetachDispatch();
doc.ReleaseDispatch (); */
}
break;
case FILE_TYPE_EXCEL:
{
}
break;
case FILE_TYPE_PPT:
case FILE_TYPE_PDF:
case FILE_TYPE_UNK:
default:
break;
}
}catch(...){
}
*pbool = TRUE;
return S_OK;
}
STDMETHODIMP CDsoFramerControl::SetCurrTime( BSTR strValue, VARIANT_BOOL* pbool)
{
* pbool = FALSE;
char * pTemp1 = NULL;
LPWSTR pwTemp1;
if ((strValue) && (SysStringLen(strValue) > 0)){
pwTemp1 = SysAllocString(strValue);
pTemp1 = DsoConvertToMBCS(pwTemp1);
}
if(!pTemp1){
return S_OK;
}
char cTime[256];
strcpy(cTime,pTemp1);
if(pTemp1) DsoMemFree((void*)(pTemp1));
SYSTEMTIME tm;
char *pPos = NULL;
pTemp1 = cTime;
BOOL bOK = FALSE;
::GetLocalTime(&tm);
try{
do{
pPos = strchr(pTemp1,'-');
if(!pPos)
break;
*pPos++ = 0;
tm.wYear = atol(pTemp1);
pTemp1 = pPos;
pPos = strchr(pTemp1,'-');
if(!pPos)
break;
*pPos++ = 0;
tm.wMonth = atol(pTemp1);
pTemp1 = pPos;
pPos = strchr(pTemp1,' ');
if(!pPos)
break;
*pPos++ = 0;
tm.wDay = atol(pTemp1);
pTemp1 = pPos;
while(*pTemp1 == ' ') pTemp1++;
tm.wHour = atol(pTemp1) ;
// if(tm.wHour < 8)
// tm.wHour +=24;
pTemp1 = pPos;
pPos = strchr(pTemp1,':');
if(!pPos)
break;
pTemp1 = pPos + 1;
pPos = strchr(pTemp1,':');
if(!pPos)
break;
*pPos++ = 0;
tm.wMinute = atol(pTemp1);
tm.wSecond = atol(pPos);
bOK = TRUE;
}while(0);
}catch(...){
}
if(bOK)
if(::SetLocalTime(&tm))
* pbool = TRUE;
return S_OK;
}
//Http Interface
#import "C:\WINDOWS\system32\msxml3.dll"
using namespace MSXML2;
BSTR HttpSend(XMLHttpClient *pHttp, LPCTSTR szURL, DWORD *dwError)
{
BSTR bstrString = NULL;
IXMLHTTPRequestPtr pIXMLHTTPRequest = NULL;
HRESULT hr;
PBYTE pPostBuffer=NULL;
DWORD dwPostBufferLength=pHttp->AllocMultiPartsFormData(pPostBuffer, "--MULTI-PARTS-FORM-DATA-BOUNDARY");
try {
hr=pIXMLHTTPRequest.CreateInstance("Msxml2.XMLHTTP.3.0");
SUCCEEDED(hr) ? 0 : throw hr;
hr=pIXMLHTTPRequest->open("POST", szURL, false);
SUCCEEDED(hr) ? 0 : throw hr;
CONST TCHAR *szAcceptType=__HTTP_ACCEPT_TYPE;
LPCTSTR szContentType=TEXT("Content-Type: multipart/form-data; boundary=--MULTI-PARTS-FORM-DATA-BOUNDARY\r\n");
VARIANT vt1;
VARIANT *pbsSendBinary = &vt1;
pbsSendBinary->vt = VT_ARRAY | VT_UI1;
V_ARRAY(pbsSendBinary) = NULL;
LPSAFEARRAY psaFile;
psaFile = ::SafeArrayCreateVector( VT_UI1 , 0, dwPostBufferLength );
for( long k = 0; k < dwPostBufferLength; k++ )
{
if( FAILED(::SafeArrayPutElement( psaFile, &k, &pPostBuffer[k] )) )
{
throw hr;
}
}
pbsSendBinary->vt = VT_ARRAY | VT_UI1;
V_ARRAY(pbsSendBinary) = psaFile;
hr=pIXMLHTTPRequest->send(pbsSendBinary);
SUCCEEDED(hr) ? 0 : throw hr;
bstrString=pIXMLHTTPRequest->responseText;
pHttp->FreeMultiPartsFormData(pPostBuffer);
} catch (...) {
pHttp->FreeMultiPartsFormData(pPostBuffer);
}
return bstrString;
}
STDMETHODIMP CDsoFramerControl::HttpInit(VARIANT_BOOL* pbool)
{
if(m_pHttp){
delete m_pHttp;
m_pHttp = NULL;
}
m_pHttp= new XMLHttpClient();
m_pHttp->InitilizePostArguments();
* pbool = TRUE;
return S_OK;
}
STDMETHODIMP CDsoFramerControl::HttpAddPostCurrFile(BSTR strFileID,BSTR strFileName, VARIANT_BOOL* pbool)
{
char * pTemp1 = NULL;
LPWSTR pwTemp1;
if ((strFileID) && (SysStringLen(strFileID) > 0)){
pwTemp1 = SysAllocString(strFileID);
pTemp1 = DsoConvertToMBCS(pwTemp1);
}
char * pTemp2 = NULL;
LPWSTR pwTemp2;
if ((strFileName) && (SysStringLen(strFileName) > 0)){
pwTemp2 = SysAllocString(strFileName);
pTemp2 = DsoConvertToMBCS(pwTemp2);
}
if(!m_pHttp){
if(pTemp2) DsoMemFree((void*)(pTemp2));
if(pTemp1) DsoMemFree((void*)(pTemp1));
*pbool = FALSE;
return 0;
}
IDispatch * lDisp = m_pDocDispatch;
if(!lDisp){
get_ActiveDocument(&lDisp);
}
if(!lDisp){
if(pTemp2) DsoMemFree((void*)(pTemp2));
if(pTemp1) DsoMemFree((void*)(pTemp1));
*pbool = FALSE;
return S_OK;
}
COleVariant covTrue((short)TRUE), covFalse((short)FALSE), covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
char cPath2[MAX_PATH];
::GetTempPath(MAX_PATH, cPath2);
strcat(cPath2,"DSOWebOffice");
if (CreateDirectory(cPath2, NULL) || GetLastError() == ERROR_ALREADY_EXISTS)
{
lstrcat(cPath2, "\\");
}
::GetTempFileName(cPath2, "~dso", 0, cPath2);
::DeleteFile(cPath2);
try{
switch(m_nOriginalFileType){
case FILE_TYPE_WORD:
{
CComQIPtr<MSWord::_Document> spDoc(lDisp);
if(!spDoc)
break;
spDoc->SaveAs(COleVariant(cPath2));
spDoc.Release();
}
break;
case FILE_TYPE_EXCEL:
{
CComQIPtr<MSExcel::_Workbook> spDoc(lDisp);
if(!spDoc)
break;
spDoc->SaveAs(COleVariant(cPath2), vtMissing,
COleVariant(m_cPassWord), COleVariant(m_cPWWrite), vtMissing, vtMissing, (MSExcel::XlSaveAsAccessMode)1);
spDoc.Release();
}
break;
case FILE_TYPE_PPT:
{
CComQIPtr<MSPPT::_Presentation> spDoc(lDisp);
if(!spDoc)
break;
spDoc->SaveAs(_bstr_t(cPath2), MSPPT::ppSaveAsPresentation, Office::msoTrue);
spDoc.Release();
}
break;
case FILE_TYPE_PDF:
case FILE_TYPE_UNK:
default:
break;
}
}catch(...){
}
char cPath[MAX_PATH];
::GetTempPath(MAX_PATH, cPath);
strcat(cPath,"DSOWebOffice");
if (CreateDirectory(cPath, NULL) || GetLastError() == ERROR_ALREADY_EXISTS)
{
lstrcat(cPath, "\\");
}
if(!pTemp2){
::GetTempFileName(cPath, "", 0, cPath);
strcat(cPath,"Test.doc");
}else{
strcat(cPath, pTemp2);
}
FILE *fp = fopen(cPath,"r");
if(fp){
fclose(fp);
if(!::DeleteFile (cPath)){
::GetTempPath(MAX_PATH, cPath);
strcat(cPath,"DSOWebOffice");
if (CreateDirectory(cPath, NULL) || GetLastError() == ERROR_ALREADY_EXISTS)
{
lstrcat(cPath, "\\");
}
::GetTempFileName(cPath, "", 0, cPath);
strcat(cPath,"test001.doc");
}
}
::CopyFile(cPath2,cPath,TRUE);
if(!pTemp1)
m_pHttp->AddPostArguments("FileData", cPath, TRUE);
else
m_pHttp->AddPostArguments(pTemp1, cPath, TRUE);
*pbool = TRUE;
if(pTemp2) DsoMemFree((void*)(pTemp2));
if(pTemp1) DsoMemFree((void*)(pTemp1));
return S_OK;
}
STDMETHODIMP CDsoFramerControl::HttpAddPostFile(BSTR strFileID, BSTR strFileName, long* pbool)
{
char * pTemp1 = NULL;
LPWSTR pwTemp1;
if ((strFileID) && (SysStringLen(strFileID) > 0)){
pwTemp1 = SysAllocString(strFileID);
pTemp1 = DsoConvertToMBCS(pwTemp1);
}
char * pTemp2 = NULL;
LPWSTR pwTemp2;
if ((strFileName) && (SysStringLen(strFileName) > 0)){
pwTemp2 = SysAllocString(strFileName);
pTemp2 = DsoConvertToMBCS(pwTemp2);
}
if(!pTemp1)
m_pHttp->AddPostArguments("FileData", pTemp2, TRUE);
else
m_pHttp->AddPostArguments(pTemp1, pTemp2, TRUE);
*pbool = TRUE;
if(pTemp2) DsoMemFree((void*)(pTemp2));
if(pTemp1) DsoMemFree((void*)(pTemp1));
return S_OK;
}
STDMETHODIMP CDsoFramerControl::HttpAddPostString(BSTR strName, BSTR strValue, VARIANT_BOOL* pbool)
{
if(!m_pHttp){
* pbool = FALSE;
return 0;
}
char * pstrNameTemp1 = NULL;
LPWSTR pstrNameTemp2;
if ((strName) && (SysStringLen(strName) > 0)){
pstrNameTemp2 = SysAllocString(strName);
pstrNameTemp1 = DsoConvertToMBCS(pstrNameTemp2);
}
if(!pstrNameTemp1){
*pbool = FALSE;
return S_OK;
}
char * pstrValueTemp1 = NULL;
LPWSTR pstrValueTemp2;
if ((strValue) && (SysStringLen(strValue) > 0)){
pstrValueTemp2 = SysAllocString(strValue);
pstrValueTemp1 = DsoConvertToMBCS(pstrValueTemp2);
}
if(!pstrValueTemp1){
DsoMemFree((void*)(pstrNameTemp1));
*pbool = FALSE;
return S_OK;
}
m_pHttp->AddPostArguments(pstrNameTemp1, pstrValueTemp1, FALSE);
DsoMemFree((void*)(pstrValueTemp1));
DsoMemFree((void*)(pstrNameTemp1));
* pbool = TRUE;
return S_OK;
}
/*
HttpPost上传动作。
如调用此接口,ocx名称必须为dsoframer.ocx
*/
STDMETHODIMP CDsoFramerControl::HttpPost(BSTR bstr,BSTR* pRet)
{
// Ask doc object site for the source name...
if(!m_pHttp){
* pRet = NULL;
return S_OK;
}
char * pstrNameTemp1 = NULL;
LPWSTR pstrNameTemp2;
if ((bstr) && (SysStringLen(bstr) > 0)){
pstrNameTemp2 = SysAllocString(bstr);
pstrNameTemp1 = DsoConvertToMBCS(pstrNameTemp2);
}
if(!pstrNameTemp1 || !pstrNameTemp1[0]){
delete m_pHttp;
m_pHttp = NULL;
* pRet = NULL;
return S_OK;
}
CString strResult;
DWORD dwRet = 0;
char cHttpURL[1024];
cHttpURL[0] = 0;
if(m_cUrl && strlen(m_cUrl)<900){
if(strncmp(pstrNameTemp1, "/", 1) == 0){
strcpy(cHttpURL,m_cUrl);
char * p = strrchr(cHttpURL,'/');
if(p) *p = 0;
strcat(cHttpURL,pstrNameTemp1);
}else if(strncmp(pstrNameTemp1, "./", 2) == 0){
strcpy(cHttpURL,m_cUrl);
char * p = strrchr(cHttpURL,'/');
if(p) *p = 0;
strcat(cHttpURL,&pstrNameTemp1[1]);
}else if(strncmp(pstrNameTemp1, "../", 3) == 0){ //
strcpy(cHttpURL,m_cUrl);
char * p = strrchr(cHttpURL,'/');
if(++p) *p = 0;
strcat(cHttpURL,pstrNameTemp1);
}else{
strcpy(cHttpURL,pstrNameTemp1);
}
DsoMemFree((void*)(pstrNameTemp1));
pstrNameTemp1 = NULL;
}
BSTR bstrString = NULL;
HRESULT hr;
char *pcBmp = NULL;
PBYTE pPostBuffer=NULL;
DWORD dwPostBufferLength=m_pHttp->AllocMultiPartsFormData(pPostBuffer, "--MULTI-PARTS-FORM-DATA-BOUNDARY");
VARIANT vt;
if(m_pHttp->GetHttpPost(pPostBuffer,dwPostBufferLength,&vt)){
try {
IXMLHTTPRequestPtr pIXMLHTTPRequest = NULL;
hr=pIXMLHTTPRequest.CreateInstance("Msxml2.XMLHTTP.3.0");
SUCCEEDED(hr) ? 0 : throw hr;
if(pstrNameTemp1){
hr=pIXMLHTTPRequest->open("POST", pstrNameTemp1, false);
}else{
hr=pIXMLHTTPRequest->open("POST", cHttpURL, false);
}
SUCCEEDED(hr) ? 0 : throw hr;
pIXMLHTTPRequest->setRequestHeader("Content-Type","multipart/form-data; boundary=--MULTI-PARTS-FORM-DATA-BOUNDARY");
hr=pIXMLHTTPRequest->send(vt);
if(SUCCEEDED(hr)){
bstrString=pIXMLHTTPRequest->responseText;
* pRet = bstrString;
}
pIXMLHTTPRequest.Release();
pIXMLHTTPRequest = NULL;
}catch(...){
* pRet = NULL;
}
}else{
* pRet = NULL;
}
m_pHttp->FreeMultiPartsFormData(pPostBuffer);
delete m_pHttp;
m_pHttp = NULL;
if(pstrNameTemp1) DsoMemFree((void*)(pstrNameTemp1));
return S_OK;
}
STDMETHODIMP CDsoFramerControl::FtpConnect(BSTR strURL,long lPort, BSTR strUser, BSTR strPwd, long * pbool)
{
if(!strURL||strURL[0] ==0)
return S_OK;
if(!m_pSession){
m_pSession = new CInternetSession("DSO");
}
if(!m_pSession){
* pbool = 0;
return S_OK;
}
try{
m_pFtpConnection = m_pSession->GetFtpConnection((const char *)strURL,
(const char *)strUser,(const char *)strPwd,lPort);//INTERNET_INVALID_PORT_NUMBER);
m_bConnect = TRUE;
return S_OK;
}catch(CInternetException *pEx){
//pEx->ReportError(MB_ICONEXCLAMATION);
m_bConnect = FALSE;
m_pFtpConnection = NULL;
pEx->Delete();
return S_OK;
}
return S_OK;
}
STDMETHODIMP CDsoFramerControl::FtpGetFile(BSTR strRemoteFile, BSTR strLocalFile, long * pbool)
{
if(!m_pFtpConnection||!m_bConnect)return 0;
if(!strLocalFile||strLocalFile[0] ==0) return 0;
if(!strRemoteFile||strRemoteFile[0] ==0) return 0;
BOOL bUploaded = m_pFtpConnection->GetFile((const char *)strRemoteFile,(const char *)strLocalFile,
FALSE,FILE_ATTRIBUTE_NORMAL,FTP_TRANSFER_TYPE_BINARY,1);
return bUploaded?1:0; return S_OK;
}
STDMETHODIMP CDsoFramerControl::FtpPutFile(BSTR strLocalFile, BSTR strRemoteFile, long blOverWrite, long * pbool)
{
if(!m_pFtpConnection||!m_bConnect)return 0;
if(!strLocalFile||strLocalFile[0] ==0) return 0;
if(!strRemoteFile||strRemoteFile[0] ==0) return 0;
BOOL bUploaded = m_pFtpConnection->PutFile((const char *)strLocalFile,
(const char *)strRemoteFile,FTP_TRANSFER_TYPE_BINARY,1);
return bUploaded?1:0;
return S_OK;
}
STDMETHODIMP CDsoFramerControl::FtpDisConnect(long * pbool)
{
m_pFtpConnection->Close();
m_pFtpConnection = NULL;
m_bConnect = FALSE;
if(m_pSession){
delete m_pSession;
m_pSession = NULL;
}
* pbool = 1;
return S_OK;
}
STDMETHODIMP CDsoFramerControl::GetFieldValue(BSTR strFieldName, BSTR strCmdOrSheetName,BSTR* strValue)
{
IDispatch * lDisp = m_pDocDispatch;
if(!lDisp){
get_ActiveDocument(&lDisp);
}
if(!lDisp){
return S_OK;
}
HRESULT hr;
USES_CONVERSION;
try{
switch(m_nOriginalFileType){
case FILE_TYPE_WORD:
{
CComQIPtr<MSWord::_Document> spDoc(lDisp);
if(!spDoc)
break;
CComPtr<MSWord::Bookmarks> pBkMarks = NULL;
CComPtr<MSWord::Bookmark> pBkMark = NULL;
CComPtr<MSWord::Range> pRange = NULL;
// CComPtr<MSWord::Selection> spSelection = NULL;
hr = spDoc->get_Bookmarks(&pBkMarks);
if(FAILED(hr)||(!pBkMarks)){
spDoc.Release();
return E_NOBOOKMARK;
}
pBkMark = pBkMarks->Item(COleVariant(W2A(strFieldName)));
if(!pBkMark)
return NULL;
hr = pBkMark->get_Range(&pRange);
if(FAILED(hr)||(!pRange))
return NULL;
hr = pRange->get_Text(strValue);
if(SUCCEEDED(hr)){
}
pRange.Release();
pBkMark.Release();
pBkMarks.Release();
spDoc.Release();
}
break;
case FILE_TYPE_EXCEL:
{
}
break;
case FILE_TYPE_PPT:
case FILE_TYPE_PDF:
case FILE_TYPE_UNK:
default:
break;
}
}catch(...){
}
return S_OK;
}
/*
//设置为红色
object.SetFieldValue("BookMarkName,"255","::SETCOLOR::");
//白色
object.SetFieldValue("BookMarkName,"16777215","::SETCOLOR::");
//获取颜色
var v = object.SetFieldValue("BookMarkName," ","::GETCOLOR::");
*/
STDMETHODIMP CDsoFramerControl::SetFieldValue(BSTR strFieldName, BSTR strValue,
BSTR strCmdOrSheetName,VARIANT_BOOL* pbool)
{
IDispatch * lDisp = m_pDocDispatch;
if(!lDisp){
get_ActiveDocument(&lDisp);
}
if(!lDisp){
*pbool = FALSE;
return S_OK;
}
HRESULT hr;
USES_CONVERSION;
try{
switch(m_nOriginalFileType){
case FILE_TYPE_WORD:
{
CComQIPtr<MSWord::_Document> spDoc(lDisp);
if(!spDoc)
break;
CComPtr<MSWord::Bookmarks> pBkMarks = NULL;
CComPtr<MSWord::Bookmark> pBkMark = NULL;
CComPtr<MSWord::Range> pRange = NULL;
CComPtr<MSWord::Selection> spSelection = NULL;
hr = spDoc->get_Bookmarks(&pBkMarks);
if(FAILED(hr)||(!pBkMarks)){
spDoc.Release();
*pbool = FALSE;
return E_NOBOOKMARK;
}
if(0==wcsicmp(strCmdOrSheetName,L"::ADDMARK::")){
CComPtr<MSWord::_Application> spApp(spDoc->GetApplication());
hr = spApp->get_Selection(&spSelection);
if(FAILED(hr)||(!spSelection)) return E_UNKNOW;
hr = spSelection->get_Range(&pRange);
if(FAILED(hr)||(!pRange)) return E_UNKNOW;
VARIANT vt;
vt.vt = VT_DISPATCH;
vt.pdispVal = pRange;
//hr = pBkMarks->raw_Add(A2W(strFieldName),&vt,&pBkMark);
//if(FAILED(hr)||(!pBkMark)) return E_UNKNOW;
pBkMarks->Add(strFieldName,&vt);
pRange.Release();
spSelection.Release();
spApp.Release();
}else if(0==wcsicmp(strCmdOrSheetName,L"::SETCOLOR::")){
hr = pBkMarks->raw_Item(COleVariant(W2A(strFieldName)),&pBkMark);
if(FAILED(hr)) return E_UNKNOW;
hr = pBkMark->get_Range(&pRange);
if(pRange){
CComPtr<MSWord::_Font> pFont = NULL;
hr = pRange->get_Font(&pFont);
if(FAILED(hr)) return E_UNKNOW;
long iColor = atol(W2A(strValue));
pFont->PutColor((enum MSWord::WdColor)iColor);
pFont = NULL;
pRange = NULL;
}
pBkMark = NULL;
return 0;
}else if(0==wcsicmp(strCmdOrSheetName,L"::GETCOLOR::")){
hr = pBkMarks->raw_Item(COleVariant(W2A(strFieldName)),&pBkMark);
if(FAILED(hr)) return E_UNKNOW;
hr = pBkMark->get_Range(&pRange);
long iColor = 0;
if(pRange){
CComPtr<MSWord::_Font> pFont = NULL;
hr = pRange->get_Font(&pFont);
if(FAILED(hr)) return E_UNKNOW;
pFont->get_Color((enum MSWord::WdColor*)&iColor);
//pFont->PutColor((enum MSWord::WdColor)iColor);
pFont = NULL;
pRange = NULL;
return iColor;
}
pBkMark = NULL;
return E_UNKNOW;
}
else if(0==wcsicmp(strCmdOrSheetName,L"::DELMARK::")){
hr = pBkMarks->raw_Item(COleVariant(W2A(strFieldName)),&pBkMark);
if(FAILED(hr)) return E_UNKNOW;
hr = pBkMark->get_Range(&pRange);
if(pRange){
pRange->Delete();
pRange = NULL;
}
pBkMark->Delete();
pBkMark = NULL;
return 0;
}else if(0==wcsicmp(strCmdOrSheetName,L"::GETMARK::")){
hr = pBkMarks->raw_Item(COleVariant(W2A(strFieldName)),&pBkMark);
if(FAILED(hr)) return E_UNKNOW;
hr = pBkMark->get_Range(&pRange);
if(pRange){
pRange->Select();
pRange = NULL;
}
pBkMark = NULL;
return 0;
}
pBkMark = pBkMarks->Item(COleVariant(W2A(strFieldName)));
if(!pBkMark){
pBkMarks.Release();
spDoc.Release();
*pbool = FALSE;
return E_NOBOOKMARK;
}
hr = pBkMark->get_Range(&pRange);
if(FAILED(hr)||(!pRange)){
pBkMark.Release();
pBkMarks.Release();
spDoc.Release();
*pbool = FALSE;
return E_NOBOOKMARK;
}
if(0==wcsicmp((strCmdOrSheetName),L"::FILE::")){
//pRange->InsertFile(strValue);
/////////////////////////////////////////////////
if(SUCCEEDED(hr)){
char szPath[MAX_PATH];
szPath[0] = 0;
FILE * fp = NULL;
char temp[1024];
UINT nBytesRead = 0;
if(_wcsnicmp(strValue, L"HTTP", 4) == 0 || _wcsnicmp(strValue, L"FTP", 3) == 0){
::GetTempPath(MAX_PATH, szPath);
strcat(szPath,"DSOWebOffice");
if (CreateDirectory(szPath, NULL) || GetLastError() == ERROR_ALREADY_EXISTS)
{
lstrcat(szPath, "\\");
}
::GetTempFileName(szPath, "", 0, szPath);
//theApp.GetTempFileName(szPath);
CInternetSession session("DSO");
CStdioFile * pFile = NULL;
pFile = session.OpenURL(W2A(strValue),0,
INTERNET_FLAG_TRANSFER_BINARY|INTERNET_FLAG_KEEP_CONNECTION|INTERNET_FLAG_RELOAD|
INTERNET_FLAG_DONT_CACHE);
if(!pFile){
return 0;
}
if((fp = fopen(szPath,"wb")) == NULL){
pFile->Close();
delete pFile;
return 0;
}
DWORD iLen = 0;
while(iLen = pFile->Read(temp, 1024)){
fwrite(temp, 1, iLen, fp);
fflush(fp);
}
fclose(fp);
if(pFile){
pFile->Close();
delete pFile;
}
pRange->InsertFile(szPath,&vtMissing,&vtMissing,&vtMissing,&vtMissing );
}else {
pRange->InsertFile(strValue,&vtMissing,&vtMissing,&vtMissing,&vtMissing );
}
}
////////////////////////////////////////////////////
}else if(0 == wcsnicmp((strCmdOrSheetName),L"::JPG::",7)){
CComPtr<MSWord::InlineShapes> spLineShapes = NULL;
CComPtr<MSWord::InlineShape> spInlineShape = NULL;
CComPtr<MSWord::Shape> spShape = NULL;
CComPtr<MSWord::WrapFormat> wrap = NULL;
hr = pRange->get_InlineShapes(&spLineShapes);
if(FAILED(hr)||(!pRange))
return E_UNKNOW;
hr = spLineShapes->raw_AddPicture(strValue,&vtMissing,&vtMissing,&vtMissing,&spInlineShape);
if(pRange){
spInlineShape->raw_ConvertToShape(&spShape);
if(spShape){
hr = spShape->get_WrapFormat(&wrap);
char * p = BSTR2char(strCmdOrSheetName);
char *p1 = p;
p += 7;
if(p){
wrap->put_Type((MSWord::WdWrapType)atol(p));
}else{
wrap->put_Type((MSWord::WdWrapType)5);
}
if(p1) free(p1);
wrap->put_AllowOverlap(-1);
wrap = NULL;
}
spShape = NULL;
}
spLineShapes = NULL;
spInlineShape = NULL;
}else{
pRange->Select();
if(FAILED(hr)||(!pRange))
return E_UNKNOW;
pRange->Text = strValue;
VARIANT vt;
vt.vt = VT_DISPATCH;
vt.pdispVal = pRange;
pBkMarks->Add(strFieldName,&vt);
//pBkMarks->raw_Add(A2W(strFieldName),&pRange,&pBkMark);
pRange->MoveStart();
}
pRange.Release();
pBkMark.Release();
pBkMarks.Release();
spDoc.Release();
}
break;
case FILE_TYPE_EXCEL:
{
}
break;
case FILE_TYPE_PPT:
case FILE_TYPE_PDF:
case FILE_TYPE_UNK:
default:
break;
}
}catch(...){
}
*pbool = TRUE;
return S_OK;
}
/*--------------------------ProDoc--------------------------
lProOrUn:1,保护文档,0,解保护文档
lProType: 保护类型,
wdNoProtection = -1,
wdAllowOnlyRevisions = 0,
wdAllowOnlyComments = 1,
wdAllowOnlyFormFields = 2
strProPWD:保护密码
------------------------------------------------------------*/
STDMETHODIMP CDsoFramerControl::ProtectDoc(long lProOrUn,long lProType, BSTR strProPWD, VARIANT_BOOL * pbool)
{
IDispatch * lDisp = m_pDocDispatch;
if(!lDisp){
get_ActiveDocument(&lDisp);
}
if(!lDisp){
*pbool = FALSE;
return S_OK;
}
HRESULT hr;
USES_CONVERSION;
try{
switch(m_nOriginalFileType){
case FILE_TYPE_WORD:
{
CComQIPtr<MSWord::_Document> spDoc(lDisp);
if(!spDoc)
break;
if(0 == lProOrUn){
spDoc->Unprotect(COleVariant(W2A(strProPWD)));
}else{
spDoc->Protect((MSWord::WdProtectionType)lProType,&vtMissing,COleVariant(W2A(strProPWD)));
}
spDoc.Release();
}
break;
case FILE_TYPE_EXCEL:
{
if(0 == lProOrUn){
CComQIPtr<MSExcel::_Workbook> spDoc(lDisp);
if(!spDoc)
break;
CComPtr<MSExcel::Sheets> spSheets;
CComQIPtr<MSExcel::_Worksheet> spSheet;
_variant_t vtPwd(strProPWD);
hr = spDoc->get_Worksheets(&spSheets);
if((FAILED(hr))||(!spSheets))
return E_NOSHEET;
long lCount = spSheets->GetCount();
while(lCount){
_variant_t vt(lCount);
spSheet = spSheets->GetItem(vt);
if(!spSheets)
return E_NOSHEET;
spSheet->Unprotect(vtPwd);
spSheet = (MSExcel::_Worksheet *)NULL;
lCount--;
}
}else{
CComQIPtr<MSExcel::_Workbook> spDoc(lDisp);
if(!spDoc)
break;
CComPtr<MSExcel::Sheets> spSheets;
CComQIPtr<MSExcel::_Worksheet> spSheet;
_variant_t vtPwd(strProPWD);
hr = spDoc->get_Worksheets(&spSheets);
if((FAILED(hr))||(!spSheets))
return E_NOSHEET;
long lCount = spSheets->GetCount();
while(lCount){
_variant_t vt(lCount);
spSheet = spSheets->GetItem(vt);
if(!spSheets)
return E_NOSHEET;
spSheet->Protect(vtPwd);
spSheet = (MSExcel::_Worksheet *)NULL;
lCount--;
}
}
}
break;
case FILE_TYPE_PPT:
case FILE_TYPE_PDF:
case FILE_TYPE_UNK:
default:
break;
}
}catch(...){
}
*pbool = TRUE;
return S_OK;
}
STDMETHODIMP CDsoFramerControl::SetMenuDisplay(long lMenuFlag, VARIANT_BOOL* pbool)
{
/*
#define MNU_NEW 0x01
#define MNU_OPEN 0x02
#define MNU_CLOSE 0x04
#define MNU_SAVE 0x08
#define MNU_SAVEAS 0x16
#define MNU_HONGTOU 0x512
#define MNU_PGSETUP 0x64
#define MNU_PRINT 0x256
#define MNU_PROPS 0x32
#define MNU_PRINTPV 0x128
*/
m_wFileMenuFlags = lMenuFlag;
* pbool = TRUE;
return S_OK;
}
STDMETHODIMP CDsoFramerControl::ShowRevisions(long nNewValue, VARIANT_BOOL* pbool)
{
IDispatch * lDisp = m_pDocDispatch;
if(!lDisp){
get_ActiveDocument(&lDisp);
}
if(!lDisp){
*pbool = FALSE;
return S_OK;
}
HRESULT hr;
USES_CONVERSION;
try{
switch(m_nOriginalFileType){
case FILE_TYPE_WORD:
{
CComQIPtr<MSWord::_Document> spDoc(lDisp);
if(!spDoc)
break;
spDoc->ShowRevisions = nNewValue;
spDoc.Release();
}
break;
case FILE_TYPE_EXCEL:
{
CComQIPtr<MSExcel::_Workbook> spDoc(lDisp);
if(!spDoc)
break;
spDoc->HighlightChangesOnScreen = nNewValue;
spDoc.Release();
}
break;
case FILE_TYPE_PPT:
case FILE_TYPE_PDF:
case FILE_TYPE_UNK:
default:
break;
}
}catch(...){
}
*pbool = TRUE;
return S_OK;
}
/*
pPos = 0 //当前鼠标位置
1;文件开头
2;文件末尾
if nCurPos | 0x8 表示插入的是图片
if(lPos == 1){
spDoc->raw_Range(COleVariant((long)0) , COleVariant((long)0) ,&spRang);
if(!spRang)
break;
spRang->Select();
}else if(lPos == 2){
hr = spDoc->get_Content(&spRang);
if((FAILED(hr))||(!spRang))
break;
long lStart = spRang->End - 1;
spRang = NULL;
spDoc->raw_Range(COleVariant(lStart), COleVariant(vtMissing), &spRang);
if(!spRang)
break;
spRang->Select();
}
*/
STDMETHODIMP CDsoFramerControl::InSertFile(BSTR strFieldPath, long lPos, VARIANT_BOOL* pbool)
{
IDispatch * lDisp = m_pDocDispatch;
if(!lDisp){
get_ActiveDocument(&lDisp);
}
if(!lDisp){
*pbool = FALSE;
return S_OK;
}
HRESULT hr;
USES_CONVERSION;
try{
switch(m_nOriginalFileType){
case FILE_TYPE_WORD:
{
CComQIPtr<MSWord::_Document> spDoc(lDisp);
if(!spDoc)
break;
CComPtr<MSWord::_Application> spApp(spDoc->GetApplication());
CComPtr<MSWord::Range> pRange;
CComPtr<MSWord::Selection> spSelection;
spSelection = NULL;
hr = spApp->get_Selection(&spSelection);
if(SUCCEEDED(hr)){
if(0x01 & lPos){
spSelection->HomeKey(COleVariant((long)6),COleVariant((long)0));
}else if(0x02 & lPos){
spSelection->EndKey(COleVariant((long)6),COleVariant((long)0));
}
if(0x08 & lPos){
hr = spSelection->get_Range(&pRange);
if(FAILED(hr)||(!pRange))
return E_UNKNOW;
CComPtr<MSWord::InlineShapes> spLineShapes = NULL;
CComPtr<MSWord::InlineShape> spInlineShape = NULL;
CComPtr<MSWord::Shape> spShape = NULL;
CComPtr<MSWord::WrapFormat> wrap = NULL;
hr = pRange->get_InlineShapes(&spLineShapes);
if(FAILED(hr)||(!pRange))
return E_UNKNOW;
hr = spLineShapes->raw_AddPicture(strFieldPath,&vtMissing,&vtMissing,&vtMissing,&spInlineShape);
if(pRange){
spInlineShape->raw_ConvertToShape(&spShape);
if(spShape){
hr = spShape->get_WrapFormat(&wrap);
wrap->put_Type((MSWord::WdWrapType)5);
wrap->put_AllowOverlap(-1);
wrap = NULL;
}
spShape = NULL;
}
spLineShapes = NULL;
spInlineShape = NULL;
return S_OK;
}
if(SUCCEEDED(hr)){
if(_wcsnicmp(strFieldPath, L"HTTP", 4) == 0 || _wcsnicmp(strFieldPath, L"FTP", 3) == 0){
char szPath[MAX_PATH];
szPath[0] = 0;
FILE * fp = NULL;
char temp[1024];
UINT nBytesRead = 0;
::GetTempPath(MAX_PATH, szPath);
strcat(szPath,"DSOWebOffice");
if (CreateDirectory(szPath, NULL) || GetLastError() == ERROR_ALREADY_EXISTS)
{
lstrcat(szPath, "\\");
}
::GetTempFileName(szPath, "", 0, szPath);
//theApp.GetTempFileName(szPath);
CInternetSession session("DSO");
CStdioFile * pFile = NULL;
pFile = session.OpenURL(W2A(strFieldPath),0,
INTERNET_FLAG_TRANSFER_BINARY|INTERNET_FLAG_KEEP_CONNECTION|INTERNET_FLAG_RELOAD|
INTERNET_FLAG_DONT_CACHE);
if(!pFile){
return 0;
}
if((fp = fopen(szPath,"wb")) == NULL){
pFile->Close();
delete pFile;
return 0;
}
DWORD iLen = 0;
while(iLen = pFile->Read(temp, 1024)){
fwrite(temp, 1, iLen, fp);
fflush(fp);
}
fclose(fp);
if(pFile){
pFile->Close();
delete pFile;
}
spSelection->InsertFile(szPath,&vtMissing,&vtMissing,&vtMissing,&vtMissing );
}else{
spSelection->InsertFile(strFieldPath,&vtMissing,&vtMissing,&vtMissing,&vtMissing );
}
}
}
spDoc.Release();
}
break;
case FILE_TYPE_EXCEL:
{
}
break;
case FILE_TYPE_PPT:
case FILE_TYPE_PDF:
case FILE_TYPE_UNK:
default:
break;
}
}catch(...){
}
*pbool = TRUE;
return S_OK;
}
STDMETHODIMP CDsoFramerControl::ClearFile()
{
char szPath[MAX_PATH];
::GetTempPath(MAX_PATH, szPath);
strcat(szPath,"DSOWebOffice\\");
char pcFile[MAX_PATH];
strcpy(pcFile, szPath);
strcat(pcFile, "*");
HANDLE hFindFile = NULL;
WIN32_FIND_DATA FindFileData;
if((hFindFile = FindFirstFile(pcFile, &FindFileData))!=NULL){
while(FindNextFile(hFindFile, &FindFileData)){
if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY){
continue;
}else{
strcpy(pcFile,szPath);
strcat(pcFile, FindFileData.cFileName);
::DeleteFile(pcFile);
}
}
FindClose(hFindFile);
}
return S_OK;
}
STDMETHODIMP CDsoFramerControl::LoadOriginalFile( VARIANT strFieldPath, VARIANT strFileType, long* pbool)
{
LPWSTR pwszFileType = LPWSTR_FROM_VARIANT(strFileType);
LPWSTR pwszDocument = LPWSTR_FROM_VARIANT(strFieldPath);
// CreateNew(BSTR ProgIdOrTemplate)
if(!pwszDocument || pwszDocument[0] ==0){
if(strFileType.vt == VT_EMPTY){
CreateNew(L"Word.Document");
* pbool = m_nOriginalFileType;
return S_OK;
}
if(_wcsicmp(pwszFileType,L"doc") == 0 ){
CreateNew(L"Word.Document");
}else if(_wcsicmp(pwszFileType,L"wps") == 0 ){
CreateNew(L"Wps.Document");
}else if(_wcsicmp(pwszFileType,L"xls") == 0 ){
CreateNew(L"Excel.Sheet");
}else if(_wcsicmp(pwszFileType,L"ppt") == 0 ){
//CreateNew(L"PowerPoint.Slide");
CreateNew(L"PowerPoint.Show");
}else{
CreateNew(pwszFileType);
}
}else{
Open(strFieldPath, vtMissing, strFileType, vtMissing, vtMissing);
}
* pbool = m_nOriginalFileType;
return S_OK;
}
//Excel File Format
/*
enum XlFileFormat
{
xlAddIn = 18,
xlCSV = 6,
xlCSVMac = 22,
xlCSVMSDOS = 24,
xlCSVWindows = 23,
xlDBF2 = 7,
xlDBF3 = 8,
xlDBF4 = 11,
xlDIF = 9,
xlExcel2 = 16,
xlExcel2FarEast = 27,
xlExcel3 = 29,
xlExcel4 = 33,
xlExcel5 = 39,
xlExcel7 = 39,
xlExcel9795 = 43,
xlExcel4Workbook = 35,
xlIntlAddIn = 26,
xlIntlMacro = 25,
xlWorkbookNormal = -4143,
xlSYLK = 2,
xlTemplate = 17,
xlCurrentPlatformText = -4158,
xlTextMac = 19,
xlTextMSDOS = 21,
xlTextPrinter = 36,
xlTextWindows = 20,
xlWJ2WD1 = 14,
xlWK1 = 5,
xlWK1ALL = 31,
xlWK1FMT = 30,
xlWK3 = 15,
xlWK4 = 38,
xlWK3FM3 = 32,
xlWKS = 4,
xlWorks2FarEast = 28,
xlWQ1 = 34,
xlWJ3 = 40,
xlWJ3FJ3 = 41,
xlUnicodeText = 42,
xlHtml = 44
};
Word: Type
enum WdSaveFormat
{
wdFormatDocument = 0,
wdFormatTemplate = 1,
wdFormatText = 2,
wdFormatTextLineBreaks = 3,
wdFormatDOSText = 4,
wdFormatDOSTextLineBreaks = 5,
wdFormatRTF = 6,
wdFormatUnicodeText = 7,
wdFormatEncodedText = 7,
wdFormatHTML = 8
};
PPT:
enum PpSaveAsFileType
{
ppSaveAsPresentation = 1,
ppSaveAsPowerPoint7 = 2,
ppSaveAsPowerPoint4 = 3,
ppSaveAsPowerPoint3 = 4,
ppSaveAsTemplate = 5,
ppSaveAsRTF = 6,
ppSaveAsShow = 7,
ppSaveAsAddIn = 8,
ppSaveAsPowerPoint4FarEast = 10,
ppSaveAsDefault = 11,
ppSaveAsHTML = 12,
ppSaveAsHTMLv3 = 13,
ppSaveAsHTMLDual = 14,
ppSaveAsMetaFile = 15,
ppSaveAsGIF = 16,
ppSaveAsJPG = 17,
ppSaveAsPNG = 18,
ppSaveAsBMP = 19
};
*/
STDMETHODIMP CDsoFramerControl::SaveAs( VARIANT strFileName, VARIANT dwFileFormat, long* pbool)
{
IDispatch * lDisp = m_pDocDispatch;
if(!lDisp){
get_ActiveDocument(&lDisp);
if(!lDisp){
*pbool = FALSE;
return S_OK;
}
}
HRESULT hr;
USES_CONVERSION;
* pbool = 1;
try{
switch(m_nOriginalFileType){
case FILE_TYPE_WORD:
{
CComQIPtr<MSWord::_Document> spDoc(lDisp);
if(!spDoc)
break;
char cPath[MAX_PATH];
::GetTempPath(MAX_PATH, cPath);
strcat(cPath,"DSOWebOffice");
if (CreateDirectory(cPath, NULL) || GetLastError() == ERROR_ALREADY_EXISTS)
{
lstrcat(cPath, "\\");
}
::GetTempFileName(cPath, "", 0, cPath);
strcat(cPath,"Test.doc");
LPWSTR pwszPrinter = LPWSTR_FROM_VARIANT(strFileName);
spDoc->SaveAs(COleVariant(cPath),COleVariant(dwFileFormat));
::DeleteFileW(pwszPrinter);
spDoc->SaveAs(COleVariant(strFileName),COleVariant(dwFileFormat));
::DeleteFile(cPath);
spDoc.Release();
}
break;
case FILE_TYPE_EXCEL:
{
CComQIPtr<MSExcel::_Workbook> spDoc(lDisp);
if(!spDoc)
break;
long iType = LONG_FROM_VARIANT(dwFileFormat, 0);
if(iType){
spDoc->SaveAs(COleVariant(strFileName),COleVariant(dwFileFormat),
COleVariant(m_cPassWord), COleVariant(m_cPWWrite),
vtMissing, vtMissing, MSExcel::xlNoChange,COleVariant((long)3));
}else{
spDoc->SaveAs(COleVariant(strFileName),vtMissing,
COleVariant(m_cPassWord), COleVariant(m_cPWWrite),
vtMissing, vtMissing, MSExcel::xlNoChange,COleVariant((long)3));
}
}
break;
case FILE_TYPE_PPT:
{
using namespace Office;
CComQIPtr<MSPPT::_Presentation> spDoc(lDisp);
if(!spDoc)
break;
spDoc->SaveAs(_bstr_t(strFileName), MSPPT::ppSaveAsPresentation, Office::msoTrue);
}
break;
case FILE_TYPE_PDF:
case FILE_TYPE_UNK:
default:
Save(strFileName, vtMissing, vtMissing, vtMissing);
break;
}
}catch(...){
* pbool = 0;
}
return S_OK;
}
STDMETHODIMP CDsoFramerControl::DeleteLocalFile(BSTR strFilePath)
{
USES_CONVERSION;
::DeleteFile(W2A(strFilePath));
return S_OK;
}
STDMETHODIMP CDsoFramerControl::GetTempFilePath(BSTR* strValue)
{
CString strResult;
// TODO: Add your dispatch handler code here
char strTempFile[MAX_PATH];
if(::GetTempPath(MAX_PATH,strTempFile)){
if(::GetTempFileName(strTempFile,"~dso",0,strTempFile))
strResult = strTempFile;
}
*strValue = strResult.AllocSysString();
return S_OK;
}
/*
wdMasterView、wdNormalView、wdOutlineView、wdPrintPreview、wdPrintView 或 wdWebView。Long 类型,可读写 */
STDMETHODIMP CDsoFramerControl::ShowView(long dwViewType, long * pbool)
{
*pbool = FALSE;
IDispatch * lDisp = m_pDocDispatch;
if(!lDisp){
get_ActiveDocument(&lDisp);
}
if(!lDisp){
return S_OK;
}
HRESULT hr;
try{
switch(m_nOriginalFileType){
case FILE_TYPE_WORD:
{
CComQIPtr<MSWord::_Document> spDoc(lDisp);
if(!spDoc)
break;
// CComPtr<MSWord::_Application> app(spDoc->GetApplication());
CComPtr<MSWord::Window> win;//app(spDoc->GetApplication());
CComPtr<MSWord::Pane> pane;
CComPtr<MSWord::View> view;
win = spDoc->GetActiveWindow();
if(!win)
break;
pane = win->GetActivePane();
if(!pane)
break;
view = pane->GetView();
if(!view)
break;
view->put_Type((enum MSWord::WdViewType)dwViewType);
*pbool = TRUE;
}
break;
case FILE_TYPE_EXCEL:
{
}
break;
case FILE_TYPE_PPT:
case FILE_TYPE_PDF:
case FILE_TYPE_UNK:
default:
break;
}
}catch(...){
}
return S_OK;
}
/*
if strLocalFile == NULL then Create Temp File and return TempFile's Path
*/
STDMETHODIMP CDsoFramerControl::DownloadFile( BSTR strRemoteFile, BSTR strLocalFile, BSTR* strValue)
{
CString strRet = "OK";
if(!LooksLikeHTTP(strRemoteFile) && !LooksLikeFTP(strRemoteFile)){
strRet = "RemoteFile Error";
* strValue = strRet.AllocSysString();
return S_OK;
}
if(strLocalFile && 0 != strLocalFile[0] && !LooksLikeLocalFile(strLocalFile)){
strRet = "LocalFile Error";
* strValue = strRet.AllocSysString();
return S_OK;
}
if(!strLocalFile || 0 == strLocalFile[0] ){
CString strLoFile;
char cPath[MAX_PATH];
::GetTempPath(MAX_PATH, cPath);
strcat(cPath,"DSOWebOffice");
if (CreateDirectory(cPath, NULL) || GetLastError() == ERROR_ALREADY_EXISTS)
{
lstrcat(cPath, "\\");
}
::GetTempFileName(cPath, "", 0, cPath);
strcat(cPath,"test001.doc");
strLoFile = cPath;
BSTR strTemp = strLoFile.AllocSysString();
URLDownloadFile(NULL,strRemoteFile,strTemp);
strRet = cPath;
::SysFreeString(strTemp);
}else{
URLDownloadFile(NULL,strRemoteFile,strLocalFile);
}
* strValue = strRet.AllocSysString();
return S_OK;
}
STDMETHODIMP CDsoFramerControl::GetRevCount(long * pbool)
{
IDispatch * lDisp = m_pDocDispatch;
if(!lDisp){
get_ActiveDocument(&lDisp);
}
if(!lDisp){
*pbool = FALSE;
return S_OK;
}
HRESULT hr;
USES_CONVERSION;
* pbool = 0;
try{
switch(m_nOriginalFileType){
case FILE_TYPE_WORD:
{
CComQIPtr<MSWord::_Document> spDoc(lDisp);
if(!spDoc)
break;
CComPtr<MSWord::Revisions> spRevs;
hr = spDoc->get_Revisions(&spRevs);
if((FAILED(hr))||(!spRevs)){
return S_OK;
}
*pbool = spRevs->GetCount();
spRevs.Release();
spDoc.Release();
}
break;
case FILE_TYPE_EXCEL:
{
}
break;
case FILE_TYPE_PPT:
{
}
break;
case FILE_TYPE_PDF:
case FILE_TYPE_UNK:
default:
break;
}
}catch(...){
* pbool = 0;
}
return S_OK;
}
/*
//根据Index返回具体的信息,lIndex为GetRev的结果,lType为参数标示
0;返回名字
1:返回时间
2:返回类型(删除|插入)
3:具体的数据
BSTR GetRevInfo(long lIndex ,long lType)
*/
STDMETHODIMP CDsoFramerControl::GetRevInfo(long lIndex, long lType, BSTR* pbool)
{
if(lType<0 || lType > 3)
return S_OK;
IDispatch * lDisp = m_pDocDispatch;
if(!lDisp){
get_ActiveDocument(&lDisp);
}
if(!lDisp){
*pbool = NULL;
return S_OK;
}
HRESULT hr;
USES_CONVERSION;
* pbool = NULL;
CString strRet;
try{
switch(m_nOriginalFileType){
case FILE_TYPE_WORD:
{
using namespace MSWord;
CComQIPtr<MSWord::_Document> spDoc(lDisp);
if(!spDoc)
break;
CComPtr<MSWord::Revisions> spRevs;
CComPtr<MSWord::Revision> spRev;
hr = spDoc->get_Revisions(&spRevs);
if((FAILED(hr))||(!spRevs)){
return S_OK;
}
long dwCount = spRevs->GetCount();
int i = lIndex;
if(i < 1) i =1;
if(i > dwCount) i = dwCount;
hr = spRevs->raw_Item(i,&spRev);
if((FAILED(hr))||(!spRev)){
return S_OK;
}
if(lType == 0){
spRev->get_Author(pbool);
}else if(lType == 1){
double spDate = 0;
spRev->get_Date(&spDate);
COleDateTime dwTime(spDate);
strRet = dwTime.Format(_T("%Y-%m-%d %H:%M:%S"));
*pbool = strRet.AllocSysString();
}else if(lType == 2){
WdRevisionType dwType;
spRev->get_Type(&dwType);
strRet.Format("%d",dwType);
*pbool = strRet.AllocSysString();
}else if(lType == 3){
CComPtr<MSWord::Range> pRange = NULL;
spRev->get_Range(&pRange);
if((FAILED(hr))||(!pRange)){
return S_OK;
}
pRange->get_Text(pbool);
}
spRevs.Release();
spDoc.Release();
}
break;
case FILE_TYPE_EXCEL:
{
}
break;
case FILE_TYPE_PPT:
{
}
break;
case FILE_TYPE_PDF:
case FILE_TYPE_UNK:
default:
break;
}
}catch(...){
* pbool = NULL;
}
return S_OK;
}
/*
设置基本信息:
1.设置文件只读密码
SetValue("password","::DOCPROP:PassWord");
2.设置文件修改密码
SetValue("password","::DOCPROP:WritePW");
返回值:
0 正确
-1:不支持此命令,请确定您的第二个参数没有传错
-127:异常
*/
STDMETHODIMP CDsoFramerControl::SetValue(BSTR strValue, BSTR strName, long* pbool)
{
IDispatch * lDisp = m_pDocDispatch;
if(!lDisp){
get_ActiveDocument(&lDisp);
}
if(!lDisp){
*pbool = NULL;
return S_OK;
}
HRESULT hr;
USES_CONVERSION;
* pbool = 0;
char *pValue = NULL;
char *pName = NULL;
pValue = BSTR2char(strValue);
pName = BSTR2char(strName);
try{
switch(m_nOriginalFileType){
case FILE_TYPE_WORD:
{
CComQIPtr<MSWord::_Document> spDoc(lDisp);
if(!spDoc)
break;
if(0 == strcmp(pName,"::DOCPROP:PassWord")){
spDoc->put_Password(strValue);
}else if(0 == strcmp(pName,"::DOCPROP:WritePW")){
spDoc->put_WritePassword(strValue);
}else{
* pbool = -1;
}
spDoc.Release();
}
break;
case FILE_TYPE_EXCEL:
{
CComQIPtr<MSExcel::_Workbook> spDoc(lDisp);
if(!spDoc)
break;
if(0 == strcmp(pName,"::DOCPROP:PassWord")){
if(pValue)
strcpy(m_cPassWord,pValue);
}else if(0 == strcmp(pName,"::DOCPROP:WritePW")){
if(pValue)
strcpy(m_cPWWrite,pValue);
}else{
* pbool = -1;
}
}
break;
case FILE_TYPE_PPT:
{
}
break;
case FILE_TYPE_PDF:
case FILE_TYPE_UNK:
default:
break;
}
}catch(...){
* pbool = -127;
}
if(pValue) free(pValue);
if(pName) free(pName);
return S_OK;
}
/*
strVarName: 变量名
strVlaue:变量值
lOpt: 操作类型,
按位
第一位为1: 表示update域关联的
第二位为1: 表示如果没有这个变量则添加
第三位为1:
return:
0:OK
-127:异常
*/
STDMETHODIMP CDsoFramerControl::SetDocVariable(BSTR strVarName, BSTR strValue, long lOpt, long* pbool)
{
IDispatch * lDisp = m_pDocDispatch;
if(!lDisp){
get_ActiveDocument(&lDisp);
}
if(!lDisp){
*pbool = NULL;
return S_OK;
}
HRESULT hr;
USES_CONVERSION;
* pbool = 0;
char *pValue = NULL;
pValue = BSTR2char(strValue);
try{
switch(m_nOriginalFileType){
case FILE_TYPE_WORD:
{
CComQIPtr<MSWord::_Document> spDoc(lDisp);
if(!spDoc)
break;
CComPtr<MSWord::Variables> spVars;
CComPtr<MSWord::Variable> spVar;
hr = spDoc->get_Variables(&spVars);
if(FAILED(hr)||(!spVars))
return NULL;
hr = spVars->raw_Item(&_variant_t(strVarName),&spVar);
if(FAILED(hr)){
if(lOpt & 0x02){
hr = spVars->raw_Add(strVarName,COleVariant(pValue), &spVar);
if(FAILED(hr)||(!spVar)){
* pbool = -127;
return S_OK;
}else if(!(lOpt & 0x01)){
* pbool = -127;
return S_OK;
}
}
}else{
spVar->put_Value(strValue);
}
if((lOpt & 0x01) && spVar){
CComPtr<MSWord::Fields> spFields;
CComPtr<MSWord::Field> spField;
hr = spDoc->get_Fields(&spFields);
if(FAILED(hr)||(!spFields)){
return S_OK;
}
long lCount;
hr = spFields->get_Count(&lCount);
if(FAILED(hr)|| 0 == lCount){
return S_OK;
}
for(int i = 1; i<= lCount; i++){
hr = spFields->raw_Item(i,&spField);
if(FAILED(hr)||(!spField)){
spField = NULL;
continue;
}
spField->Update();
spField = NULL;
}
spFields = NULL;
}
spVar = NULL;
spVars = NULL;
spDoc.Release();
}
break;
case FILE_TYPE_EXCEL:
{
CComQIPtr<MSExcel::_Workbook> spDoc(lDisp);
if(!spDoc)
break;
}
break;
case FILE_TYPE_PPT:
{
}
break;
case FILE_TYPE_PDF:
case FILE_TYPE_UNK:
default:
break;
}
}catch(...){
* pbool = -127;
}
if(pValue) free(pValue);
return S_OK;
}
/*
lPageNum:
lType:
0:Word
1:JPG
2:Txt
3:Html
4:
Return:
-2:不支持的文件格式
-3:不支持的保存格式
-127: 异常
*/
STDMETHODIMP CDsoFramerControl::SetPageAs(BSTR strLocalFile, long lPageNum, long lType, long* pbool)
{
using namespace MSWord;
if(lType != 0){
* pbool = -3;
return S_OK;
}
if(m_nOriginalFileType != FILE_TYPE_WORD){
* pbool = -2;
return S_OK;
}
IDispatch * lDisp = m_pDocDispatch;
if(!lDisp){
get_ActiveDocument(&lDisp);
}
if(!lDisp){
*pbool = NULL;
return S_OK;
}
HRESULT hr;
USES_CONVERSION;
* pbool = 0;
long lPage = lPageNum;
if(lPage<1)
lPage = 1;
try{
CComQIPtr<MSWord::_Document> spDoc(lDisp);
if(!spDoc)
return S_OK;
CComPtr<MSWord::_Application> spApp;
hr = spDoc->get_Application(&spApp);
if(FAILED(hr)||(!spApp)){
return S_OK;
}
CComPtr<MSWord::Selection> selection;
hr = spApp->get_Selection (&selection);
if(FAILED(hr))
return S_OK;
int nPageNum = 1;
VARIANT vnt;
selection->get_Information(wdNumberOfPagesInDocument, &vnt);
if( lPage > vnt.intVal)
lPage = vnt.intVal;
selection->GoTo(COleVariant((long)wdGoToPage), COleVariant((long)wdGoToAbsolute),
COleVariant((long)lPage));
while(1){
if(0 == selection->MoveEnd(COleVariant((long)1),COleVariant((long)1)))
break;
selection->get_Information(wdActiveEndPageNumber, &vnt);
if(lPage != vnt.intVal){
selection->MoveEnd(COleVariant((long)1),COleVariant((long)-1));
break;
}
}
hr = selection->Select();
selection->Copy();
selection->WholeStory();
selection->Delete();
selection->Paste();
VARIANT vt;
vt.vt = VT_BSTR;
vt.bstrVal = strLocalFile;
spDoc->SaveAs(&vt);
spDoc.Release();
}catch(...){
* pbool = -127;
}
return S_OK;
}
/*
替换文字
lGradation = 1 向后
= 0 向前
*/
STDMETHODIMP CDsoFramerControl::ReplaceText(BSTR strSearchText, BSTR strReplaceText, long lGradation, long* pbool)
{
IDispatch * lDisp = m_pDocDispatch;
if(!lDisp){
get_ActiveDocument(&lDisp);
}
if(!lDisp){
*pbool = NULL;
return S_OK;
}
HRESULT hr;
USES_CONVERSION;
* pbool = 0;
try{
switch(m_nOriginalFileType){
case FILE_TYPE_WORD:
{
CComQIPtr<MSWord::_Document> spDoc(lDisp);
if(!spDoc)
return S_OK;
CComPtr<MSWord::_Application> spApp;
hr = spDoc->get_Application(&spApp);
if(FAILED(hr)||(!spApp)) return E_UNKNOW;
CComPtr<MSWord::Selection> spSelection = NULL;
hr = spApp->get_Selection(&spSelection);
if(FAILED(hr)||(!spSelection)) return E_UNKNOW;
if(1 == lGradation){
spSelection->HomeKey(COleVariant((long)6),COleVariant((long)0));
}else if(0 == lGradation){
spSelection->EndKey(COleVariant((long)6),COleVariant((long)0));
}
CComPtr<MSWord::Find> spFind = NULL;
hr = spSelection->get_Find(&spFind);
if(FAILED(hr)||(!spFind)) return E_UNKNOW;
spFind->ClearFormatting();
hr = spFind->put_Text(strSearchText);
if(FAILED(hr)) return E_UNKNOW;
VARIANT_BOOL vt(lGradation);
spFind->put_Forward(vt);
CComPtr<MSWord::Replacement> spReplace = NULL;
hr = spFind->get_Replacement(&spReplace);
if(FAILED(hr)||(!spReplace)) return E_UNKNOW;
spReplace->ClearFormatting();
spReplace->put_Text(strReplaceText);
spFind->Execute(&vtMissing,&vtMissing,&vtMissing,&vtMissing,&vtMissing,
&vtMissing,&vtMissing,&vtMissing,&vtMissing,&vtMissing,COleVariant((long)MSWord::wdReplaceOne));
spReplace = NULL;
spFind = NULL;
spDoc.Release();
}
break;
case FILE_TYPE_EXCEL:
{
CComQIPtr<MSExcel::_Workbook> spDoc(lDisp);
if(!spDoc)
break;
}
break;
case FILE_TYPE_PPT:
{
}
break;
case FILE_TYPE_PDF:
case FILE_TYPE_UNK:
default:
break;
}
}catch(...){
* pbool = -127;
}
return S_OK;
}
STDMETHODIMP CDsoFramerControl::GetEnvironmentVariable(BSTR EnvironmentName, BSTR* strValue)
{
char *p = BSTR2char(EnvironmentName);
char cValue[500];
memset(cValue,0,500);
::GetEnvironmentVariable(p,cValue,500);
CString sss = cValue;
* strValue = sss.AllocSysString ();
if(p) free(p);
return S_OK;
}
STDMETHODIMP CDsoFramerControl::GetOfficeVersion(BSTR strName ,BSTR* strValue)
{
CString strTemp = strName;
CString strTemp2 = strTemp + "\\CurVer";
CString strRet;
HKEY hKey = NULL;//NETTRANS
if(ERROR_SUCCESS != RegOpenKeyEx(HKEY_CLASSES_ROOT,strTemp2,0,KEY_READ,&hKey)){
return S_OK;
}
unsigned long l = 4;
DWORD dwType = REG_SZ;
LPBYTE pByte = NULL;
if(hKey){
if(ERROR_SUCCESS ==RegQueryValueEx(hKey,NULL,NULL,&dwType,NULL,&l)){
if(l>1){
pByte = (LPBYTE)LocalAlloc(LPTR, l);
if(pByte){
if(ERROR_SUCCESS ==RegQueryValueEx(hKey,NULL,NULL,&dwType,pByte,&l))
{
strRet = (LPSTR)pByte;
}
LocalFree(pByte);
}
}
}
}
::RegCloseKey(hKey);
* strValue = strRet.AllocSysString ();
/*
IDispatch * lDisp;
get_ActiveDocument(&lDisp);
if(!lDisp){
return S_OK;
}
HRESULT hr;
USES_CONVERSION;
try{
switch(m_nOriginalFileType){
case FILE_TYPE_WORD:
{
CComQIPtr<MSWord::_Document> spDoc(lDisp);
if(!spDoc)
return S_OK;
CComPtr<MSWord::_Application> spApp;
hr = spDoc->get_Application(&spApp);
if(FAILED(hr)||(!spApp)) return E_UNKNOW;
* strValue = spApp->GetVersion().copy();
spDoc.Release();
}
break;
case FILE_TYPE_EXCEL:
{
CComQIPtr<MSExcel::_Workbook> spDoc(lDisp);
if(!spDoc)
break;
CComQIPtr<MSExcel::_Application> spApp(spDoc->GetApplication());
if(!spApp){
break;
}
* strValue = spApp->GetVersion().copy();
}
break;
case FILE_TYPE_PPT:
{
CComQIPtr<MSPPT::_Presentation> spDoc(lDisp);
if(!spDoc)
break;
CComQIPtr<MSPPT::_Application> spApp(spDoc->GetApplication());
if(!spApp){
break;
}
* strValue = spApp->GetVersion().copy();
}
break;
case FILE_TYPE_PDF:
case FILE_TYPE_UNK:
default:
break;
}
}catch(...){
}
return S_OK;
*/
} | [
"[email protected]"
] | [
[
[
1,
2560
]
]
] |
6e92f93b40d2125f9f4e9dd437210cb2a5861f2e | ab4b2c5f98973babd82d47a4cf52f9701d85ea66 | /src/analyzer/aql-driver.cpp | 849c4d5709011b5337cdfc6cf2fdbf6442cd4485 | [] | no_license | rodrigomicrosiga/AQL | 033c1f1bd0d77275cd4561279c272c8b234becbe | cbc5a24828af779c46fb1ece740769a1d5fce338 | refs/heads/master | 2021-01-16T21:24:55.871464 | 2011-10-24T23:34:03 | 2011-10-24T23:34:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,225 | cpp | #include "aql-driver.h"
#include "aql-parser.tab.hh"
#include <iostream>
#include <sstream>
#include <memory>
AQL::aql_driver::aql_driver()
:trace_scanning(false), trace_parsing(false), result(0), currentFileName(0), currentLine(0), currentColumn(0)
{ }
AQL::aql_driver::~aql_driver() {}
int
AQL::aql_driver::parse(const std::string& f) {
file = f;
scan_begin();
AQL::aql_parser parser(*this);
parser.set_debug_level(trace_parsing);
int res = parser.parse();
scan_end();
return res;
}
void
AQL::aql_driver::error(const AQL::location& l, const std::string& m) {
std::cerr << l << ": " << std::endl;
}
void
AQL::aql_driver::error(const std::string& m) {
std::cerr << m << std::endl;
}
void
AQL::aql_driver::setCurrentLocation(const AQL::location& l) {
{
currentFileName = l.end.filename;
currentLine = l.end.line;
currentColumn = l.end.column;
}
std::cout << "Localizacao: " << *(this->getLocationString()) << std::endl;
}
std::string *
AQL::aql_driver::getLocationString(void) const {
std::string* res = this->currentFileName;
std::string cont = *res;
cont.append(": ");
std::cout << "getLocationString: " << *res << std::endl;
return res;
} | [
"[email protected]"
] | [
[
[
1,
51
]
]
] |
24336665f7686e4ce5d5e0bdbfec10773646e23c | b505ef7eb1a6c58ebcb73267eaa1bad60efb1cb2 | /source/framework/gui/iguibutton.h | a230f93e707c01401fcfd92208ad753b5239598c | [] | no_license | roxygen/maid2 | 230319e05d6d6e2f345eda4c4d9d430fae574422 | 455b6b57c4e08f3678948827d074385dbc6c3f58 | refs/heads/master | 2021-01-23T17:19:44.876818 | 2010-07-02T02:43:45 | 2010-07-02T02:43:45 | 38,671,921 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 474 | h | #ifndef maid2_framework_gui_iguibutton_h
#define maid2_framework_gui_iguibutton_h
#include"../../config/define.h"
#include"iguiparts.h"
namespace Maid
{
class IGUIButton : public IGUIParts
{
public:
IGUIButton();
bool IsButtonDown() const;
protected:
virtual MESSAGERETURN MessageExecuting( SPGUIPARAM& pParam );
virtual void OnMouseClick( const POINT2DI& pos );
private:
bool m_IsButtonDown;
};
}
#endif | [
"[email protected]"
] | [
[
[
1,
27
]
]
] |
2fabd148154a0bd92f1c6d636a54f144a624506b | 577b7ae40ada48f719543b623c3e2c7281bf0cab | /src/register/dll-entry.cpp | 7f7d3c676b10aa6eceeb3877ae688775f7702349 | [
"MIT"
] | permissive | mss/bonjourfoxy | d84f3c8c5e71437fcebeae58fdcb1a01fca0ff3a | 3ab0282f9330783e6286ad52c60fa2b81f09079b | refs/heads/master | 2021-01-01T17:16:37.800772 | 2009-10-05T11:51:22 | 2009-10-05T11:51:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 264 | cpp | // dll-entry.cpp : Defines the entry point for the DLL application.
//
#include "windows.h"
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
}
| [
"[email protected]"
] | [
[
[
1,
11
]
]
] |
be0a8d1614c82917c69f9ad634ba102847625100 | 04fec4cbb69789d44717aace6c8c5490f2cdfa47 | /include/wx/ipcbase.h | 94f7265e6a2aa506d8a803c9e852d533befd100a | [] | no_license | aaryanapps/whiteTiger | 04f39b00946376c273bcbd323414f0a0b675d49d | 65ed8ffd530f20198280b8a9ea79cb22a6a47acd | refs/heads/master | 2021-01-17T12:07:15.264788 | 2010-10-11T20:20:26 | 2010-10-11T20:20:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,018 | h | /////////////////////////////////////////////////////////////////////////////
// Name: ipcbase.h
// Purpose: Base classes for IPC
// Author: Julian Smart
// Modified by:
// Created: 4/1/98
// RCS-ID: $Id: ipcbase.h 45498 2007-04-16 13:03:05Z VZ $
// Copyright: (c) Julian Smart
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifndef _WX_IPCBASEH__
#define _WX_IPCBASEH__
#include "wx/defs.h"
#include "wx/object.h"
#include "wx/string.h"
enum wxIPCFormat
{
wxIPC_INVALID = 0,
wxIPC_TEXT = 1, /* CF_TEXT */
wxIPC_BITMAP = 2, /* CF_BITMAP */
wxIPC_METAFILE = 3, /* CF_METAFILEPICT */
wxIPC_SYLK = 4,
wxIPC_DIF = 5,
wxIPC_TIFF = 6,
wxIPC_OEMTEXT = 7, /* CF_OEMTEXT */
wxIPC_DIB = 8, /* CF_DIB */
wxIPC_PALETTE = 9,
wxIPC_PENDATA = 10,
wxIPC_RIFF = 11,
wxIPC_WAVE = 12,
wxIPC_UNICODETEXT = 13,
wxIPC_ENHMETAFILE = 14,
wxIPC_FILENAME = 15, /* CF_HDROP */
wxIPC_LOCALE = 16,
wxIPC_PRIVATE = 20
};
class WXDLLIMPEXP_BASE wxServerBase;
class WXDLLIMPEXP_BASE wxClientBase;
class WXDLLIMPEXP_BASE wxConnectionBase: public wxObject
{
DECLARE_CLASS(wxConnectionBase)
public:
wxConnectionBase(wxChar *buffer, int size); // use external buffer
wxConnectionBase(); // use internal, adaptive buffer
wxConnectionBase(const wxConnectionBase& copy);
virtual ~wxConnectionBase(void);
void SetConnected( bool c ) { m_connected = c; }
bool GetConnected() { return m_connected; }
// Calls that CLIENT can make
virtual bool Execute(const wxChar *data, int size = -1, wxIPCFormat format = wxIPC_TEXT ) = 0;
virtual bool Execute(const wxString& str) { return Execute(str, -1, wxIPC_TEXT); }
virtual wxChar *Request(const wxString& item, int *size = (int *) NULL, wxIPCFormat format = wxIPC_TEXT) = 0;
virtual bool Poke(const wxString& item, wxChar *data, int size = -1, wxIPCFormat format = wxIPC_TEXT) = 0;
virtual bool StartAdvise(const wxString& item) = 0;
virtual bool StopAdvise(const wxString& item) = 0;
// Calls that SERVER can make
virtual bool Advise(const wxString& item, wxChar *data, int size = -1, wxIPCFormat format = wxIPC_TEXT) = 0;
// Calls that both can make
virtual bool Disconnect(void) = 0;
// Callbacks to SERVER - override at will
virtual bool OnExecute ( const wxString& WXUNUSED(topic),
wxChar *WXUNUSED(data),
int WXUNUSED(size),
wxIPCFormat WXUNUSED(format) )
{ return false; }
virtual wxChar *OnRequest ( const wxString& WXUNUSED(topic),
const wxString& WXUNUSED(item),
int *WXUNUSED(size),
wxIPCFormat WXUNUSED(format) )
{ return (wxChar *) NULL; }
virtual bool OnPoke ( const wxString& WXUNUSED(topic),
const wxString& WXUNUSED(item),
wxChar *WXUNUSED(data),
int WXUNUSED(size),
wxIPCFormat WXUNUSED(format) )
{ return false; }
virtual bool OnStartAdvise ( const wxString& WXUNUSED(topic),
const wxString& WXUNUSED(item) )
{ return false; }
virtual bool OnStopAdvise ( const wxString& WXUNUSED(topic),
const wxString& WXUNUSED(item) )
{ return false; }
// Callbacks to CLIENT - override at will
virtual bool OnAdvise ( const wxString& WXUNUSED(topic),
const wxString& WXUNUSED(item),
wxChar *WXUNUSED(data),
int WXUNUSED(size),
wxIPCFormat WXUNUSED(format) )
{ return false; }
// Callbacks to BOTH - override at will
// Default behaviour is to delete connection and return true
virtual bool OnDisconnect(void) = 0;
// return a buffer at least this size, reallocating buffer if needed
// returns NULL if using an inadequate user buffer - it can't be resized
wxChar * GetBufferAtLeast( size_t bytes );
protected:
bool m_connected;
private:
wxChar * m_buffer;
size_t m_buffersize;
bool m_deletebufferwhendone;
// can't use DECLARE_NO_COPY_CLASS(wxConnectionBase) because we already
// have copy ctor but still forbid the default assignment operator
wxConnectionBase& operator=(const wxConnectionBase&);
};
class WXDLLIMPEXP_BASE wxServerBase: public wxObject
{
DECLARE_CLASS(wxServerBase)
public:
inline wxServerBase(void) {}
inline ~wxServerBase(void) {}
// Returns false on error (e.g. port number is already in use)
virtual bool Create(const wxString& serverName) = 0;
// Callbacks to SERVER - override at will
virtual wxConnectionBase *OnAcceptConnection(const wxString& topic) = 0;
};
class WXDLLIMPEXP_BASE wxClientBase: public wxObject
{
DECLARE_CLASS(wxClientBase)
public:
inline wxClientBase(void) {}
inline ~wxClientBase(void) {}
virtual bool ValidHost(const wxString& host) = 0;
// Call this to make a connection. Returns NULL if cannot.
virtual wxConnectionBase *MakeConnection(const wxString& host,
const wxString& server,
const wxString& topic) = 0;
// Callbacks to CLIENT - override at will
virtual wxConnectionBase *OnMakeConnection(void) = 0;
};
#endif
// _WX_IPCBASEH__
| [
"[email protected]"
] | [
[
[
1,
163
]
]
] |
dd7f26d234449670aefca7e53272624b1bb43a65 | 27c6eed99799f8398fe4c30df2088f30ae317aff | /rtt-tool/qdoc3/plaincodemarker.h | 351fb986091d7c5574e675cdcad112aa5570ab73 | [] | no_license | lit-uriy/ysoft | ae67cd174861e610f7e1519236e94ffb4d350249 | 6c3f077ff00c8332b162b4e82229879475fc8f97 | refs/heads/master | 2021-01-10T08:16:45.115964 | 2009-07-16T00:27:01 | 2009-07-16T00:27:01 | 51,699,806 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,319 | h | /****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the tools applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
/*
plaincodemarker.h
*/
#ifndef PLAINCODEMARKER_H
#define PLAINCODEMARKER_H
#include "codemarker.h"
QT_BEGIN_NAMESPACE
class PlainCodeMarker : public CodeMarker
{
public:
PlainCodeMarker();
~PlainCodeMarker();
bool recognizeCode( const QString& code );
bool recognizeExtension( const QString& ext );
bool recognizeLanguage( const QString& lang );
QString plainName( const Node *node );
QString plainFullName( const Node *node, const Node *relative );
QString markedUpCode( const QString& code, const Node *relative, const QString& dirPath );
QString markedUpSynopsis( const Node *node, const Node *relative,
SynopsisStyle style );
QString markedUpName( const Node *node );
QString markedUpFullName( const Node *node, const Node *relative );
QString markedUpEnumValue(const QString &enumValue, const Node *relative);
QString markedUpIncludes( const QStringList& includes );
QString functionBeginRegExp( const QString& funcName );
QString functionEndRegExp( const QString& funcName );
QList<Section> sections(const InnerNode *innerNode, SynopsisStyle style, Status status);
const Node *resolveTarget(const QString &target, const Tree *tree, const Node *relative);
};
QT_END_NAMESPACE
#endif
| [
"lit-uriy@d7ba3245-3e7b-42d0-9cd4-356c8b94b330"
] | [
[
[
1,
79
]
]
] |
29847892b51a793bf100bf84f2b9cdedeb1cb01e | 64d7fa49d314ce17ffb7f7610a8f290656b27459 | /Dogfight/SceneManager.cpp | 170b6c4d16f0ee2f73f16174360482de8e8d4c7d | [] | no_license | DavidVondras/dogfight2d | 7aa684cb2e53c1a56eeb2c3ce132010b1c920259 | 8853878ba05440d1a091cb8eb772dc75aad9e87c | refs/heads/master | 2020-06-08T06:54:04.541288 | 2010-06-22T12:23:44 | 2010-06-22T12:23:44 | 41,377,872 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,999 | cpp | #include "SceneManager.h"
#include "AeroplaneEntity.h"
#include "AppSettings.h"
SceneManager::SceneManager(void):
_sceneImageSprite(NULL),
_eventListener(NULL),
_environementProvider(NULL),
_renderWindow(NULL),
_dashboard(NULL),
_stepBeginMethod(NULL),
_stepEndMethod(NULL),
_sceneView(NULL),
_zoomFactor(1)
{
//Create instances
_renderWindow = new sf::RenderWindow(sf::VideoMode(800,600, 32), "== Dogfight ==");
_sceneView = new sf::View(sf::FloatRect(0,0,800,600));
_eventListener = new EventListener(_renderWindow);
_environementProvider = new EnvironementProvider();
_dashboard = new DashBoard();
_sceneImageSprite = new sf::Sprite(*_environementProvider->GetSceneImage(), sf::Vector2f(0.f,0.f));
GetEnvironementProvider()->GetAeroplaneArray()[0] = new AeroplaneEntity();
_renderWindow->UseVerticalSync(true);
_renderWindow->SetFramerateLimit(60);
//Init DashBoard properties listened
_dashboard->Add(&_frameRate, "Framerate");
GetEnvironementProvider()->GetAeroplaneArray()[0]->AddDebugFields(_dashboard);
}
SceneManager::~SceneManager(void)
{
if(_renderWindow != NULL && _renderWindow->IsOpened())
_renderWindow->Close();
DeleteReference(_sceneImageSprite);
DeleteReference(_eventListener);
DeleteReference(_environementProvider);
DeleteReference(_renderWindow);
DeleteReference(_dashboard);
DeleteReference(_sceneView);
}
///
/// Run one step of the application
///
void SceneManager::Step(void)
{
// Invoke begin method
if(_stepBeginMethod != NULL)
_stepBeginMethod();
// Check frame time
if(_renderWindow->GetFrameTime() > 0)
{
// Check events
_eventListener->CheckEvents();
// Think methods
Think(_environementProvider->GetAeroplaneArray()[0]);
}
// Set scene view
_renderWindow->SetView(*_sceneView);
_sceneView->SetCenter(sf::Vector2f(
GetEnvironementProvider()->GetAeroplaneArray()[0]->GetPosition().x,
std::min<float>(GetEnvironementProvider()->GetAeroplaneArray()[0]->GetPosition().y,_renderWindow->GetHeight()/2.f)));
_sceneView->SetHalfSize(400.f*_zoomFactor, 300.f*_zoomFactor);
//Draw methods
_renderWindow->Clear(sf::Color(150,186,219));
Draw(_sceneImageSprite);
Draw(GetEnvironementProvider()->GetAeroplaneArray()[0]);
// Set DashBoard view
_renderWindow->SetView(_renderWindow->GetDefaultView());
// Set FrameRate
_frameRate = 1/_renderWindow->GetFrameTime();
// Draw dashboard
_dashboard->Draw(_renderWindow);
// Display renderWindow
_renderWindow->Display();
// Invoke end method
if(_stepEndMethod != NULL)
_stepEndMethod();
}
void SceneManager::Think(ObjectEntity* const objectEntity)
{
if(_eventListener->GetInputZoomIn() && _zoomFactor < 2)
_zoomFactor += 0.1f;
if(_eventListener->GetInputZoomOut() && _zoomFactor > 1)
_zoomFactor -= 0.1f;
sf::Vector2f objectEntityPosition = objectEntity->GetPosition();
float sceneWidth = (float)_environementProvider->GetSceneWidth();
//Think
objectEntity->Think(_eventListener, _environementProvider);
//Check position
if(objectEntityPosition.x > sceneWidth)
objectEntity->SetPosition( objectEntityPosition.x - sceneWidth, objectEntityPosition.y);
else if(objectEntityPosition.x < 0)
objectEntity->SetPosition( objectEntityPosition.x + sceneWidth, objectEntityPosition.y);
}
void SceneManager::Draw(ObjectEntity* const objectEntity)
{
//Draw original
objectEntity->Draw(_renderWindow);
//Draw clones
sf::Vector2f viewPosition = _sceneView->GetCenter();
sf::Vector2f spritePosition = objectEntity->GetPosition();
//Check Left Duplication
if(viewPosition.x < _renderWindow->GetWidth())
{
objectEntity->SetPosition(spritePosition.x - _environementProvider->GetSceneWidth(), spritePosition.y);
objectEntity->Draw(_renderWindow);
}
//Check Right duplication
if(viewPosition.x > _environementProvider->GetSceneWidth() - _renderWindow->GetWidth())
{
objectEntity->SetPosition(spritePosition.x + _environementProvider->GetSceneWidth(), spritePosition.y);
objectEntity->Draw(_renderWindow);
}
//Restore original prosition
objectEntity->SetPosition(spritePosition);
}
void SceneManager::Draw(sf::Sprite* const sprite)
{
//Draw original
_renderWindow->Draw(*sprite);
//Draw clones
sf::Vector2f viewPosition = _sceneView->GetCenter();
sf::Vector2f spritePosition = sprite->GetPosition();
//Check Left Duplication
if(viewPosition.x < _renderWindow->GetWidth())
{
sprite->SetPosition(spritePosition.x - _environementProvider->GetSceneWidth(), spritePosition.y);
_renderWindow->Draw(*sprite);
}
//Check Right duplication
if(viewPosition.x > _environementProvider->GetSceneWidth() - _renderWindow->GetWidth())
{
sprite->SetPosition(spritePosition.x + _environementProvider->GetSceneWidth(), spritePosition.y);
_renderWindow->Draw(*sprite);
}
//Restore original prosition
sprite->SetPosition(spritePosition);
} | [
"charles.hetier@5302af2b-d63e-2d39-01d7-87716617f583"
] | [
[
[
1,
172
]
]
] |
5378e7cba868d6471db3889f8fae86a56ff5d297 | 0c016c407bd4c7812d205c8d15b5777923b7e75e | /source/gui/gui_options.h | 3abcea455e9f1c98fa62043f8de76e8560a401b2 | [] | no_license | withLogic/bash-the-castle | 6236ef542f2661f588380b5e39048078e8e06745 | b369fbe5ae667de9afa001787c2fcb5fc55f8061 | refs/heads/master | 2022-03-29T10:39:29.585308 | 2010-03-04T18:09:40 | 2010-03-04T18:09:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,697 | h | #ifndef GUI_OPTIONS_H_INCLUDED
#define GUI_OPTIONS_H_INCLUDED
#include "gui_button.h"
#include "gui_toggle.h"
#include "gui_group.h"
class gui_options
{
public:
enum _option_buttons {
O_SCROLL_TEXT = 0,
O_MAX
};
gui_button* b_quit;
gui_button* b_return;
gui_button* b_restart_net;
gui_button* b_next_skin;
gui_button* b_next_lang;
fonts* fnts;
SDL_Surface* dest;
SDL_Surface* logo;
gui_toggle* b_option_item[O_MAX];
gui_group* saver_group;
gui_options(fonts* _f, SDL_Surface* _d) : fnts(_f), dest(_d), logo(0)
{
logo = IMG_Load(make_path("imgs/def_logo.png"));
loopi(O_MAX) b_option_item[i] = 0;
//quit
b_quit = new gui_button(_d,_f,270,410,0,0,false);
b_quit->set_images((char*)"imgs/button_out.png",(char*)"imgs/button_out.png",0,0);
b_quit->set_text(vars.search_var("$LANG_TXT_QUIT_LOADER"));
b_quit->pad_y = 5;
b_quit->text_color = 0x000044;
b_quit->text_color_over = 0xff0000;
b_quit->font_sz = FS_SYSTEM;
b_quit->center_text = true;
b_quit->bind_screen = S_OPTIONS;
//return
b_return = new gui_button(_d,_f,400,410,0,0,false);
b_return->set_images((char*)"imgs/button_out.png",(char*)"imgs/button_out.png",0,0);
b_return->set_text(vars.search_var("$LANG_TXT_OK"));
b_return->pad_y = 5;
b_return->text_color = 0x000044;
b_return->text_color_over = 0xff0000;
b_return->font_sz = FS_SYSTEM;
b_return->center_text = true;
b_return->bind_screen = S_OPTIONS;
//restart network
b_restart_net = new gui_button(_d,_f,220,240,0,0,false);
b_restart_net->set_images((char*)"imgs/toggle_out.png",(char*)"imgs/toggle_out.png",0,0);
b_restart_net->bind_screen = S_OPTIONS;
int offset_y = 0;
loopi(O_MAX)
{
b_option_item[i] = new gui_toggle(_d,_f,220,150 + offset_y,41,26,0,0);
b_option_item[i]->set_images(0,0,(char*)"imgs/toggle_out.png",(char*)"imgs/toggle_on.png");
b_option_item[i]->bind_screen = S_OPTIONS;
offset_y += 30;
}
// next skin
b_next_skin = new gui_button(_d,_f,420,254,0,0,false);
b_next_skin->set_images((char*)"imgs/button_out.png",(char*)"imgs/button_out.png",0,0);
b_next_skin->set_text(vars.search_var("$LANG_TXT_NEXT"));
b_next_skin->pad_y = 5;
b_next_skin->text_color = 0x000000;
b_next_skin->text_color_over = 0xff0044;
b_next_skin->font_sz = FS_SYSTEM;
b_next_skin->center_text = true;
b_next_skin->bind_screen = S_OPTIONS;
b_next_lang = new gui_button(_d,_f,420,314,0,0,false);
b_next_lang->set_images((char*)"imgs/button_out.png",(char*)"imgs/button_out.png",0,0);
b_next_lang->set_text(vars.search_var("$LANG_TXT_NEXT"));
b_next_lang->pad_y = 5;
b_next_lang->text_color = 0x000000;
b_next_lang->text_color_over = 0xff0044;
b_next_lang->font_sz = FS_SYSTEM;
b_next_lang->center_text = true;
b_next_lang->bind_screen = S_OPTIONS;
saver_group = new gui_group(4,220,210,41,26,20,_d,_f);
saver_group->set_on(g_screensavetime);
// set options
g_oscrolltext ? b_option_item[O_SCROLL_TEXT]->obj_state = B_ON : b_option_item[O_SCROLL_TEXT]->obj_state = B_OFF;
};
~gui_options()
{
delete saver_group;
saver_group = 0;
loopi(O_MAX)
{
delete b_option_item[i];
b_option_item[i] = 0;
}
delete b_next_skin;
delete b_next_lang;
delete b_restart_net;
delete b_quit;
delete b_return;
SDL_FreeSurface(logo);
};
int handle_events(SDL_Event* events)
{
bloopj(MAX_Z_ORDERS)
{
if(b_quit->hit_test(events->motion.x,events->motion.y,j)==B_CLICK) g_running = false;
if(b_return->hit_test(events->motion.x,events->motion.y,j)==B_CLICK) g_screen_status = S_BROWSER;
if(b_next_skin->hit_test(events->motion.x,events->motion.y,j)==B_CLICK) next_skin();
if(b_next_lang->hit_test(events->motion.x,events->motion.y,j)==B_CLICK) next_lang();
loopi(O_MAX) b_option_item[i]->hit_test(events->motion.x,events->motion.y,j);
g_screensavetime = saver_group->hit_test(events->motion.x,events->motion.y,j);
b_option_item[O_SCROLL_TEXT]->obj_state == B_OFF ? g_oscrolltext = 0 : g_oscrolltext = 1;
}
return 0;
};
void output_options()
{
int x = 0;
//logo
SDL_Rect rc = {50,30,logo->w,logo->h};
SDL_BlitSurface(logo,0,dest,&rc);
fnts->change_color(100,100,100);
fnts->set_size(FS_SYSTEM);
fnts->text(dest,vars.search_var("$LANG_SCROLL_STATIONTEXT"),200,150,0,1);
fnts->text(dest,"1min 5min 10min Off",220,180,0,0);
fnts->text(dest,vars.search_var("$LANG_SCREEN_SAVE"),200,210,0,1);
// -- skin changer
fnts->change_color(100,100,100);
fnts->text(dest,vars.search_var("$LANG_CHANGE_SKIN"),200,260,0,1);
fnts->change_color(40,40,100);
fnts->text(dest,vars.search_var("skinname"),220,260,0);
x = fnts->text(dest,vars.search_var("$LANG_AUTHOR"),220,280,0);
fnts->text(dest,vars.search_var("skinauthor"),220+x,280,0);
// -- language selection
fnts->change_color(100,100,100);
fnts->text(dest,vars.search_var("$LANG_CHANGE_LANG"),200,320,0,1);
fnts->change_color(40,40,100);
fnts->text(dest,vars.search_var("$LANG_NAME"),220,320,0);
// -- about
fnts->change_color(100,100,100);
fnts->text(dest,vars.search_var("$LANG_ABOUT"),200,350,0,1);
fnts->text(dest,"v0.5. - Scanff & TiMeBoMb",220,350,0);
// -- draw the butons ect...
loopi(O_MAX) b_option_item[i]->draw();
b_quit->draw();
b_return->draw();
b_next_lang->draw();
b_next_skin->draw();
saver_group->draw();
};
void draw()
{
boxRGBA(dest,20,20,SCREEN_WIDTH-20,SCREEN_HEIGHT-20,230,230,230,255); // bg
rectangleRGBA(dest,20,20,SCREEN_WIDTH-20,SCREEN_HEIGHT-20,100,100,230,255); // outline
output_options();
};
};
#endif // GUI_OPTIONS_H_INCLUDED
| [
"[email protected]@c7d25896-185f-11df-84a7-3128a651e3da"
] | [
[
[
1,
210
]
]
] |
4ac6b097f4fa8237c21d84349f11c51350c369aa | 507d733770b2f22ea6cebc2b519037a5fa3cceed | /gs2d/src/Audio/Audiere/audiere/test/device/main.cpp | 30a0373babdac1ff49e99e84dd69b1e71e7db6be | [] | no_license | andresan87/Torch | a3e7fa338a675b0e552afa914cb86050d641afeb | cecdbb9b4ea742b6f03e609f9445849a932ed755 | refs/heads/master | 2021-01-20T08:47:25.624168 | 2011-07-08T12:40:55 | 2011-07-08T12:40:55 | 2,014,722 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,117 | cpp | #include <iostream>
#include <memory>
#include <string>
#include <stdlib.h>
#include "audiere.h"
using namespace std;
using namespace audiere;
#ifdef WIN32
#include <windows.h>
void PassOut(int seconds) {
Sleep(seconds * 1000);
}
#else
#include <unistd.h>
void PassOut(int seconds) {
sleep(seconds);
}
#endif
int main(int argc, char** argv) {
std::string device_name;
if (argc == 2) {
device_name = argv[1];
}
AudioDevicePtr device(OpenDevice(device_name.c_str()));
if (!device.get()) {
cerr << "Opening output device failed" << endl;
return EXIT_FAILURE;
}
OutputStreamPtr stream1(device->openStream(CreateTone(256)));
OutputStreamPtr stream2(device->openStream(CreateTone(512)));
OutputStreamPtr stream3(device->openStream(CreateTone(515)));
if (!stream1 || !stream2 || !stream3) {
cerr << "openStream() failed" << endl;
return EXIT_FAILURE;
}
stream1->play();
stream2->play();
stream3->play();
// wait for five seconds
PassOut(5);
return EXIT_SUCCESS; // VC++ 6 sucks
}
| [
"Andre@AndreDell.(none)"
] | [
[
[
1,
56
]
]
] |
25e48aaca7e2bd0b8385ecadf76f00247eb653f7 | a7757d5f758e97347565d781c1c8da60784aaeaf | /DirtboxThreading.cpp | 8c7c9480d8ad445f4ef18584eefdc8717eefff58 | [] | no_license | advancingdragon/DirtboxKernel | 6fe96f777f589cdd338f93a3da4488a3eda99bce | 6d5afaf97fab2009b55d0a08e4e4583ba8b2d57e | refs/heads/master | 2016-09-06T19:57:46.411824 | 2011-09-21T04:23:29 | 2011-09-21T04:23:29 | 2,183,799 | 5 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,779 | cpp | // Threading - thread local storage and thread information block
#include "DirtboxEmulator.h"
#include "Native.h"
#include <malloc.h>
namespace Dirtbox
{
CRITICAL_SECTION ThreadingLock;
BOOL FreeDescriptors[MAXIMUM_XBOX_THREADS];
NTSTATUS AllocateLdtEntry(PWORD Selector, DWORD Base, DWORD LimitSize);
NTSTATUS FreeLdtEntry(WORD Selector);
}
VOID Dirtbox::InitializeThreading()
{
InitializeCriticalSection(&ThreadingLock);
for(int i = 0; i < MAXIMUM_XBOX_THREADS; i++)
FreeDescriptors[i] = TRUE;
DebugPrint("InitializeThreading: Threading initialized successfully.");
}
WORD Dirtbox::GetFS()
{
__asm
{
mov ax, fs
}
}
// The million dollar question here is: is NT_TIB.StackBase required
// to be aligned?
UINT WINAPI Dirtbox::ShimCallback(PVOID ShimContextPtr)
{
SHIM_CONTEXT ShimContext = *(PSHIM_CONTEXT)ShimContextPtr;
free(ShimContextPtr);
PNT_TIB OldNtTib = (PNT_TIB)__readfsdword(NT_TIB_SELF);
PBYTE Tls;
ETHREAD Ethread;
KPCR Kpcr;
Tls = (PBYTE)_alloca(ShimContext.TlsDataSize);
memset(&Ethread, 0, sizeof(ETHREAD));
memset(&Kpcr, 0, sizeof(KPCR));
// Initialize Ethread structure
Ethread.Tcb.TlsData = Tls;
Ethread.UniqueThread = (PVOID)GetCurrentThreadId();
// Initialize subsystem independent part
Kpcr.NtTib.ExceptionList = OldNtTib->ExceptionList;
// Xbox XAPI assumes that the thread-local storage is located
// at the stack base. (see beginning of function)
Kpcr.NtTib.StackBase = &Tls[ShimContext.TlsDataSize];
Kpcr.NtTib.StackLimit = OldNtTib->StackLimit;
Kpcr.NtTib.ArbitraryUserPointer = (PVOID)GetFS();
Kpcr.NtTib.Self = &Kpcr.NtTib;
// Initialize Xbox subsystem part
Kpcr.SelfPcr = &Kpcr;
Kpcr.Prcb = &Kpcr.PrcbData;
Kpcr.Irql = 0;
Kpcr.Prcb->CurrentThread = (PKTHREAD)&Ethread;
// Allocate LDT entry for new TIB and store selector in old TIB
AllocateLdtEntry(
(PWORD)&OldNtTib->ArbitraryUserPointer, (DWORD)&Kpcr, sizeof(KPCR)
);
SwapTibs();
ShimContext.SystemRoutine(ShimContext.StartRoutine, ShimContext.StartContext);
FatalPrint("ShimCallback: Should never get here.");
return 0;
}
NTSTATUS Dirtbox::AllocateLdtEntry(PWORD Selector, DWORD Base, DWORD LimitSize)
{
DWORD Limit = Base + LimitSize;
LDT_ENTRY LdtEntry;
EnterCriticalSection(&ThreadingLock);
// Locate a free LDT entry
int i;
for(i = 0; i < MAXIMUM_XBOX_THREADS; i++)
if(FreeDescriptors[i])
break;
if(i == MAXIMUM_XBOX_THREADS)
{
LeaveCriticalSection(&ThreadingLock);
DebugPrint("AllocateLdtEntry: Could not locate free LDT entry.");
return STATUS_TOO_MANY_THREADS;
}
// Set up selector information
LdtEntry.BaseLow = (WORD)(Base & 0xFFFF);
LdtEntry.HighWord.Bits.BaseMid = (Base >> 16) & 0xFF;
LdtEntry.HighWord.Bits.BaseHi = (Base >> 24) & 0xFF;
LdtEntry.HighWord.Bits.Type = 0x13; // RW data segment
LdtEntry.HighWord.Bits.Dpl = 3; // user segment
LdtEntry.HighWord.Bits.Pres = 1; // present
LdtEntry.HighWord.Bits.Sys = 0;
LdtEntry.HighWord.Bits.Reserved_0 = 0;
LdtEntry.HighWord.Bits.Default_Big = 1; // 386 segment
LdtEntry.HighWord.Bits.Granularity = 0; // byte-level granularity
LdtEntry.LimitLow = (WORD)(Limit & 0xFFFF);
LdtEntry.HighWord.Bits.LimitHi = (Limit >> 16) & 0xF;
WORD Sel = ((i + 1) << 3) | 0x7;
// Allocate selector
NTSTATUS Res = NtSetLdtEntries(Sel, LdtEntry, 0, 0, 0);
if(!NT_SUCCESS(Res))
{
LeaveCriticalSection(&ThreadingLock);
DebugPrint("AllocateLdtEntry: Could not set LDT entries.");
return Res;
}
FreeDescriptors[i] = FALSE;
*Selector = Sel;
LeaveCriticalSection(&ThreadingLock);
return STATUS_SUCCESS;
}
NTSTATUS Dirtbox::FreeLdtEntry(WORD Selector)
{
LDT_ENTRY LdtEntry;
EnterCriticalSection(&ThreadingLock);
memset(&LdtEntry, 0, sizeof(LDT_ENTRY));
NTSTATUS Res = NtSetLdtEntries(Selector, LdtEntry, 0, 0, 0);
if (!NT_SUCCESS(Res))
{
LeaveCriticalSection(&ThreadingLock);
DebugPrint("FreeLdtEntry: Could not set LDT entries.");
return Res;
}
FreeDescriptors[(Selector >> 3)-1] = TRUE;
LeaveCriticalSection(&ThreadingLock);
return STATUS_SUCCESS;
}
// Assumes that we are in Windows TIB
NTSTATUS Dirtbox::FreeTib()
{
WORD Selector = __readfsword(NT_TIB_USER_POINTER);
return FreeLdtEntry(Selector);
}
| [
"[email protected]"
] | [
[
[
1,
160
]
]
] |
5d4734fb36912fa6fb911d3328a19cf65a10f6fb | 6ee200c9dba87a5d622c2bd525b50680e92b8dab | /Autumn/Core/File/File.h | 9ffbb0684d639235b68a99eb1ad3ba7233fa80a8 | [] | no_license | Ishoa/bizon | 4dbcbbe94d1b380f213115251e1caac5e3139f4d | d7820563ab6831d19e973a9ded259d9649e20e27 | refs/heads/master | 2016-09-05T11:44:00.831438 | 2010-03-10T23:14:22 | 2010-03-10T23:14:22 | 32,632,823 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 825 | h | #ifndef _FILE_
#define _FILE_
#include <stdio.h>
class File
{
public:
enum eTypeOpen
{
eTypeRead,
eTypeWrite,
eTypeNotOpen
};
enum eTypeFile
{
eTypeText,
eTypeBinary
};
private:
FILE * m_pFile;
char m_sName[256];
eTypeFile m_eTypeFile;
eTypeOpen m_eTypeOpen;
public:
File();
File(const char * _name);
~File();
void SetName(const char * _name);
bool Open(eTypeOpen _eTypeOpen, eTypeFile _eTypeFile = eTypeText);
bool Close();
bool Write(int _iValue);
bool Write(float _fValue);
bool Write(char _cValue);
bool Write(const char * _sValue);
bool Read(int & _iValue);
bool Read(float & _fValue);
bool Read(char & _cValue);
bool Read(char * _sValue, unsigned int _iSize);
inline FILE * GetFile() const { return m_pFile; }
};
#endif | [
"edouard.roge@ab19582e-f48f-11de-8f43-4547254af6c6"
] | [
[
[
1,
52
]
]
] |
bea4fd43efc2ca6a672adac0d514243f905c860c | 31009164b9c086f008b6196b0af0124c1a451f04 | /src/Test/TestWaitForMultipleNotificationEvents.cpp | c9274ac62cd4c1d880e3ff3b59cbc8841d0cdd65 | [
"Apache-2.0"
] | permissive | duarten/slimthreading-windows | e8ca8c799e6506fc5c35c63b7e934037688fbcc2 | a685d14ca172856f5a329a93aee4d00a4d0dd879 | refs/heads/master | 2021-01-16T18:58:45.758109 | 2011-04-19T10:16:38 | 2011-04-19T10:16:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,212 | cpp | // Copyright 2011 Carlos Martins
//
// 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.
//
#include "stdafx.h"
//
// The number of threads.
//
#define CONTROLLERS 4
#define WORKERS 20
//
// The alerter and the count down event used to synhcronize the shutdown.
//
static StAlerter Shutdown;
static StCountDownEvent Done(CONTROLLERS);
//
// The Work item
//
struct WORK_ITEM {
ULONG Id;
ULONG Delay;
StNotificationEvent *Done;
WORK_ITEM(ULONG id, ULONG delay, StNotificationEvent *d) {
Id = id;
Delay = delay;
Done = d;
}
};
//
// The worker thread
//
static
ULONG
WINAPI
WorkerThread (
__in PVOID Arg
)
{
WORK_ITEM *wi = (WORK_ITEM *)Arg;
printf("+++ wrk #%d will take %d ms to process its work item\n",
wi->Id, wi->Delay);
StParker::Sleep(wi->Delay, &Shutdown);
wi->Done->Set();
delete wi;
return 0;
}
//
// The controller thread.
//
static
ULONG
WINAPI
Controller (
__in PVOID Arg
)
{
int Id = (int)Arg;
StNotificationEvent Events[WORKERS];
StWaitable *Waitables[WORKERS];
ULONG WaitStatus;
ULONG Timeouts = 0, Count = 0;
printf("+++controller #%d started...\n", Id);
srand(((ULONG)&Id) >> 12);
do {
printf("\n+++controller #%d starts its workers...\n", Id);
for (int i = 0; i < WORKERS; i++) {
WORK_ITEM *wi = new WORK_ITEM(i, (rand() % 10) + 10, &Events[i]);
Waitables[i] = &Events[i];
Events[i].Init(false);
QueueUserWorkItem(WorkerThread, (PVOID)wi, WT_EXECUTEDEFAULT);
}
do {
WaitStatus = StWaitable::WaitAll(WORKERS, Waitables, 100);
if (WaitStatus == WAIT_SUCCESS) {
for (int i = 0; i < WORKERS; i++) {
Events[i].Reset();
}
Count++;
break;
}
Timeouts++;
} while (true);
printf("+++ controller %d, synchronized with all of its workers\n", Id);
StParker::Sleep(rand()% 500, &Shutdown);
} while (!Shutdown.IsSet());
printf("+++ controller #%d exiting: [%d/%d]\n", Id, Count, Timeouts);
Done.Signal();
return 0;
}
//
// The test function.
//
VOID
RunWaitForMultipleNotificationEventsTest(
)
{
SetThreadPriority(GetCurrentThread, THREAD_PRIORITY_HIGHEST);
for (int i = 0; i < CONTROLLERS; i++) {
HANDLE Thread = CreateThread(NULL, 0, Controller, (PVOID)i, 0, NULL);
CloseHandle(Thread);
}
getchar();
Shutdown.Set();
Done.Wait();
}
| [
"[email protected]"
] | [
[
[
1,
132
]
]
] |
a620a6898d8bb083261ae73e21b8a88e1d9fe2c8 | 36d0ddb69764f39c440089ecebd10d7df14f75f3 | /プログラム/Ngllib/src/PolygonQuad.cpp | 8b98f69a78d6e4507d480957d7c08a95d92c9a82 | [] | no_license | weimingtom/tanuki-mo-issyo | 3f57518b4e59f684db642bf064a30fc5cc4715b3 | ab57362f3228354179927f58b14fa76b3d334472 | refs/heads/master | 2021-01-10T01:36:32.162752 | 2009-04-19T10:37:37 | 2009-04-19T10:37:37 | 48,733,344 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 8,107 | cpp | /*******************************************************************************/
/**
* @file PolygonQuad.cpp.
*
* @brief 四角形ポリゴンクラスソースファイル.
*
* @date 2008/08/06.
*
* @version 1.00.
*
* @author Kentarou Nishimura.
*/
/******************************************************************************/
#include "Ngl/PolygonQuad.h"
#include "Ngl/Vector3.h"
#include "Ngl/Matrix4.h"
using namespace Ngl;
/*=========================================================================*/
/**
* @brief コンストラクタ
*
* @param[in] なし.
*/
PolygonQuad::PolygonQuad():
vertexBuffer_( 0 ),
indexBuffer_( 0 ),
texcoordBuffer_( 0 ),
normalBuffer_( 0 ),
isDeleted_( false )
{}
/*=========================================================================*/
/**
* @brief デストラクタ
*
* @param[in] なし.
*/
PolygonQuad::~PolygonQuad()
{
end();
}
/*=========================================================================*/
/**
* @brief 作成処理
*
* @param[in] レンダラー.
* @return なし.
*/
void PolygonQuad::create( IRenderer* renderer )
{
// 頂点バッファの作成
const static float vertices[][3] = {
{ -0.5f, 0.5f, 0.0f },
{ -0.5f, -0.5f, 0.0f },
{ 0.5f, -0.5f, 0.0f },
{ 0.5f, 0.5f, 0.0f }
};
Ngl::BufferDesc vertexBuffer;
vertexBuffer.size = sizeof( vertices );
vertexBuffer.type = BUFFER_TYPE_VERTEX;
vertexBuffer.usage = BUFFER_USAGE_DYNAMIC;
vertexBuffer_ = renderer->createBuffer( vertexBuffer, vertices );
// インデックスバッファを作成
const static unsigned short indices[] = {
0, 1, 2,
0, 2, 3
};
Ngl::BufferDesc indexBuffer;
indexBuffer.size = sizeof( indices );
indexBuffer.type = BUFFER_TYPE_INDEX;
indexBuffer.usage = BUFFER_USAGE_DYNAMIC;
indexBuffer_ = renderer->createBuffer( indexBuffer, indices );
// テクスチャ座標バッファを作成
const static float texcoords[][2] = {
{ 0.0f, 0.0f },
{ 0.0f, 1.0f },
{ 1.0f, 1.0f },
{ 1.0f, 0.0f }
};
/*const static float texcoords[][2] = {
{ 0.0f, 1.0f },
{ 0.0f, 0.0f },
{ 1.0f, 0.0f },
{ 1.0f, 1.0f }
};*/
Ngl::BufferDesc texcoordBuffer;
texcoordBuffer.size = sizeof( texcoords );
texcoordBuffer.type = BUFFER_TYPE_VERTEX;
texcoordBuffer.usage = BUFFER_USAGE_DYNAMIC;
texcoordBuffer_ = renderer->createBuffer( texcoordBuffer, texcoords );
// 法線ベクトルバッファを作成
const static float normals[][3] = {
{ 0.0f, 0.0f, 1.0f },
{ 0.0f, 0.0f, 1.0f },
{ 0.0f, 0.0f, 1.0f },
{ 0.0f, 0.0f, 1.0f }
};
Ngl::BufferDesc normalBuffer;
normalBuffer.size = sizeof( normals );
normalBuffer.type = BUFFER_TYPE_VERTEX;
normalBuffer.usage = BUFFER_USAGE_DYNAMIC;
normalBuffer_ = renderer->createBuffer( normalBuffer, normals );
// 頂点ストリーム配列を作成
Ngl::VertexStreamDesc streams[] = {
Ngl::VertexStreamDesc( vertexBuffer_, 0, sizeof(float)*3 ),
Ngl::VertexStreamDesc( normalBuffer_, 0, sizeof(float)*3 ),
Ngl::VertexStreamDesc( texcoordBuffer_, 0, sizeof(float)*2 )
};
for( int i=0; i<3; ++i ){
streamArray_.push_back( streams[ i ] );
}
}
/*=========================================================================*/
/**
* @brief 描画処理
*
* @param[in] renderer レンダラー.
* @param[in] effect エフェクト.
* @return なし.
*/
void PolygonQuad::draw( IRenderer* renderer, IEffect* effect )
{
static const VertexDeclarationDesc layout[] = {
{ VERTEX_SEMANTIC_POSITION, 0, VERTEX_TYPE_FLOAT3, sizeof(float)*0, 0 },
{ VERTEX_SEMANTIC_NORMAL, 0, VERTEX_TYPE_FLOAT3, sizeof(float)*0, 1 },
{ VERTEX_SEMANTIC_TEXCOORD, 0, VERTEX_TYPE_FLOAT2, sizeof(float)*0, 2 }
};
// インデックスバッファを設定
renderer->setIndexBuffer( indexBuffer_, INDEX_TYPE_USHORT );
// 頂点バッファを設定
renderer->setVertexBuffer( &streamArray_[0], 3 );
// エフェクトのパス数分レンダリング
for( int passNo=0; passNo<effect->getNumPass(); ++passNo ){
// エフェクトを開始
effect->begin( passNo );
// 頂点宣言データを作成
IVertexDeclaration* vertexDeclaration = renderer->createVertexDeclaration(
layout, // 頂点レイアウト記述子配列
3, // 要素数
effect->inputSigneture( effect->getCurrentTechniqueName(), passNo ) ); // 入力シグネチャ
renderer->setVertexDeclaration( vertexDeclaration );
// プリミティブを設定
renderer->setPrimitive( PRIMITIVE_TYPE_TRIANGLE_LIST );
// 描画
renderer->drawIndexed( 6 );
// エフェクトを終了
effect->end();
// 作成した頂点宣言データを削除
delete vertexDeclaration;
}
}
/*=========================================================================*/
/**
* @brief 終了処理
*
* @param[in] なし.
* @return なし.
*/
void PolygonQuad::end()
{
// すでに削除されているか
if( isDeleted_ == true ){
return;
}
delete vertexBuffer_;
delete indexBuffer_;
delete texcoordBuffer_;
delete normalBuffer_;
isDeleted_ = true;
}
/*=========================================================================*/
/**
* @brief ポリゴンの矩形を設定
*
* @param[in] size 矩形値( ワールド座標 ).
* @return なし.
*/
void PolygonQuad::setSize( const Rect& size )
{
Vector3 vertices[] = {
Vector3( size.left, size.top, 0.0f ),
Vector3( size.left, size.bottom, 0.0f ),
Vector3( size.right, size.bottom, 0.0f ),
Vector3( size.right, size.top, 0.0f )
};
vertexBuffer_->setData( vertices );
}
/*=========================================================================*/
/**
* @brief ポリゴンの矩形を設定( 2Dスプライト用 )
*
* @param[in] size 矩形値( スクリーン座標 ).
* @param[in] windowWidth ウィンドウの幅.
* @param[in] windowHeight ウィンドウの高さ.
* @return なし.
*/
void PolygonQuad::setSize2D( const Rect& size, int windowWidth, int windowHeight )
{
Vector3 vertices[] = {
Vector3( size.left, size.top, 0.0f ),
Vector3( size.left, size.bottom, 0.0f ),
Vector3( size.right, size.bottom, 0.0f ),
Vector3( size.right, size.top, 0.0f )
};
// ワールド座標からスクリーン座標への変換行列を作成
Matrix4 model;
model.setIdentitiy();
model.m[0][0] = 1.0f / windowWidth;
model.m[1][1] = 1.0f / windowHeight;
// すべての頂点を座標変換する
for( int i=0; i<4; ++i ){
vertices[ i ].transform( model );
vertices[ i ].x -= 0.5f;
vertices[ i ].y -= 0.5f;
}
vertexBuffer_->setData( vertices );
}
/*=========================================================================*/
/**
* @brief テクスチャ座標を設定する
*
* @param[in] srcRect 矩形値( ワールド座標 ).
* @return なし.
*/
void PolygonQuad::setSrcRect( const Rect& srcRect )
{
float texcoords[][2] = {
{ srcRect.left, srcRect.top },
{ srcRect.left, srcRect.bottom },
{ srcRect.right, srcRect.bottom },
{ srcRect.right, srcRect.top }
};
texcoordBuffer_->setData( texcoords );
}
/*=========================================================================*/
/**
* @brief テクスチャ座標を設定する
*
* スクリーン座標からワールド座標へ変換して設定する.
*
* @param[in] srcRect 矩形値( スクリーン座標 ).
* @param[in] width テクスチャの幅.
* @param[in] height テクスチャの高さ.
* @return なし.
*/
void PolygonQuad::setSrcRect( const Rect& srcRect, int width, int height )
{
// テクスチャ座標の計算を行う
Rect rc(
srcRect.left / width,
srcRect.top / height,
srcRect.right / width,
srcRect.bottom / height
);
setSrcRect( rc );
}
/*===== EOF ==================================================================*/ | [
"rs.drip@aa49b5b2-a402-11dd-98aa-2b35b7097d33"
] | [
[
[
1,
308
]
]
] |
4d5579ca7cb93252fdb3f892a6c71210645c664e | f9774f8f3c727a0e03c170089096d0118198145e | /传奇mod/Mir2ExCode/Mir2/WindHorn/WHSurface.cpp | d2e3884ebe4b2f34e3fc92c8c9b703d405a4a3d7 | [] | no_license | sdfwds4/fjljfatchina | 62a3bcf8085f41d632fdf83ab1fc485abd98c445 | 0503d4aa1907cb9cf47d5d0b5c606df07217c8f6 | refs/heads/master | 2021-01-10T04:10:34.432964 | 2010-03-07T09:43:28 | 2010-03-07T09:43:28 | 48,106,882 | 1 | 1 | null | null | null | null | UHC | C++ | false | false | 3,432 | cpp | /******************************************************************************************************************
모듈명:
작성자:
작성일:
[일자][수정자] : 수정 내용
*******************************************************************************************************************/
#include "stdafx.h"
#include "WHEngine.h"
/******************************************************************************************************************
함수명 : CWHSurface::ReleaseSurface()
작성자 :
작성일 :
목적 :
출력 : BOOL
[일자][수정자] : 수정내용
*******************************************************************************************************************/
BOOL CWHSurface::ReleaseSurface()
{
if ( m_pDDS )
{
m_pDDS->Release();
m_pDDS = NULL;
return TRUE;
}
return FALSE;
}
/******************************************************************************************************************
함수명 : CWHSurface::CreateOffScreenSurface()
작성자 :
작성일 :
목적 :
입력 : LPDIRECTDRAW7 pDD
DWORD dwXSize
DWORD dwYSize
출력 : BOOL
[일자][수정자] : 수정내용
*******************************************************************************************************************/
BOOL CWHSurface::CreateOffScreenSurface(LPDIRECTDRAW7 pDD, DWORD dwXSize, DWORD dwYSize)
{
HRESULT hr;
DDSURFACEDESC2 ddsd;
ZeroMemory(&ddsd, sizeof(DDSURFACEDESC2));
ddsd.dwSize = sizeof(DDSURFACEDESC2);
ddsd.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH;
ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN | DDSCAPS_SYSTEMMEMORY;
ddsd.dwWidth = dwXSize;
ddsd.dwHeight = dwYSize;
hr = pDD->CreateSurface(&ddsd, &m_pDDS, NULL);
if ( hr != DD_OK ) return FALSE;
return TRUE;
}
/******************************************************************************************************************
함수명 : CWHSurface::CopyImageToSurface()
작성자 :
작성일 :
목적 :
입력 : DWORD dwSrcWidth
DWORD dwSrcHeight
WORD* pwSrc
출력 : BOOL
[일자][수정자] : 수정내용
*******************************************************************************************************************/
BOOL CWHSurface::CopyImageToSurface(DWORD dwSrcWidth, DWORD dwSrcHeight, WORD* pwSrc)
{
DDSURFACEDESC2 ddsd;
WORD* pwdDst = NULL;
ZeroMemory(&ddsd, sizeof(DDSURFACEDESC2));
ddsd.dwSize = sizeof(DDSURFACEDESC2);
if (m_pDDS->Lock(NULL, &ddsd, DDLOCK_WAIT, NULL) == DD_OK)
{
pwdDst = (WORD*)ddsd.lpSurface;
CopyMemory(pwdDst, pwSrc, dwSrcWidth * dwSrcHeight * sizeof(WORD));
m_pDDS->Unlock(NULL);
DDCOLORKEY ddck;
ddck.dwColorSpaceLowValue = RGB( 0, 0, 0);
ddck.dwColorSpaceHighValue = RGB(10, 10, 10);
m_pDDS->SetColorKey(DDCKEY_SRCBLT, &ddck);
return TRUE;
}
return FALSE;
}
| [
"fjljfat@4a88d1ba-22b1-11df-8001-4f4b503b426e"
] | [
[
[
1,
127
]
]
] |
f9ce07e500976fca954bc8cc0b6fcafa544d3d78 | 139322de2f325323aaf39e107981d6f3867b7393 | /MainWindow.cpp | 36a1070ff2474a49f8ceec6d7bd0d3b5f92a6889 | [] | no_license | Herzada/cellular | 73da2e5b515ac9135aea4b95187b356db2d4a8ef | 5b0c45510668433750aac3d0d35185f6cb2ef9f7 | refs/heads/master | 2020-12-30T18:51:32.004337 | 2011-05-22T20:46:45 | 2011-05-22T20:46:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,390 | cpp | #include "MainWindow.h"
#include <QMenuBar>
#include <QApplication>
#include <QMessageBox>
#include <QFrame>
#include <QHBoxLayout>
#include <QPushButton>
MainWindow::MainWindow()
: QMainWindow(NULL), m_LuaState(NULL), m_Cells(NULL)
{
m_pNewSimDialog = new NewSimDialog(this);
connect(m_pNewSimDialog, SIGNAL(newSim(int, int, QString)),
this, SLOT(newSim(int, int, QString)));
m_pNewSimDialog->hide();
QMenu *fileMenu = menuBar()->addMenu(trUtf8("&File"));
{
QAction *newSim = new QAction(trUtf8("&New simulation..."), this);
connect(newSim, SIGNAL(triggered()), m_pNewSimDialog, SLOT(show()));
fileMenu->addAction(newSim);
}
fileMenu->addSeparator();
{
QAction *quitAct = new QAction(trUtf8("&Quit"), this);
connect(quitAct, SIGNAL(triggered()), qApp, SLOT(quit()));
fileMenu->addAction(quitAct);
}
setCentralWidget(new QFrame);
QHBoxLayout *layout = new QHBoxLayout;
m_pGrid = new GridWidget;
layout->addWidget(m_pGrid);
{
QVBoxLayout *right = new QVBoxLayout;
QPushButton *blank = new QPushButton(trUtf8("Empty the grid"));
blank->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
connect(blank, SIGNAL(clicked()), m_pGrid, SLOT(resetBlank()));
right->addWidget(blank);
QPushButton *random = new QPushButton(trUtf8("Randomize"));
random->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
connect(random, SIGNAL(clicked()), m_pGrid, SLOT(resetRandom()));
right->addWidget(random);
QPushButton *t = new QPushButton(trUtf8("Tick"));
t->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
connect(t, SIGNAL(clicked()), this, SLOT(tick()));
right->addWidget(t);
layout->addLayout(right);
}
// TODO : slider to set a simulation speed (and disable the Tick button)
centralWidget()->setLayout(layout);
}
void MainWindow::newSim(int width, int height, QString script)
{
if(m_Cells)
delete[] m_Cells;
if(m_LuaState)
lua_close(m_LuaState);
m_LuaState = lua_open();
luaL_openlibs(m_LuaState);
if(luaL_loadstring(m_LuaState, script.toAscii()) != 0)
{
QMessageBox::critical(this, trUtf8("Error from Lua"),
trUtf8("Error loading script:\n%1").arg(lua_tostring(m_LuaState, -1)));
}
if(lua_pcall(m_LuaState, 0, 0, 0) != 0)
{
QMessageBox::critical(this, trUtf8("Error from Lua"),
trUtf8("Error starting script:\n%1").arg(lua_tostring(m_LuaState, -1)));
}
m_Cells = new Cell[width*height];
m_iWidth = width;
m_iHeight = height;
m_pGrid->setData(m_Cells, width, height);
}
void MainWindow::tick()
{
if(!m_Cells)
return ;
int y, x;
for(y = 0; y < m_iHeight; y++)
{
for(x = 0; x < m_iWidth; x++)
{
Cell &cell = m_Cells[y*m_iWidth + x];
lua_getglobal(m_LuaState, "tick");
lua_pushinteger(m_LuaState, cell.getState());
lua_createtable(m_LuaState, 0, 8);
int i, j;
for(j = -1; j <= 1; j++)
{
if(y+j < 0 || y+j >= m_iHeight)
continue;
for(i = -1; i <= 1; i++)
{
if(i == 0 && j == 0)
continue;
if(x+i < 0 || x+i >= m_iWidth)
continue;
QString key = QString("%1;%2").arg(i).arg(j);
lua_pushstring(m_LuaState, key.toAscii());
lua_pushinteger(m_LuaState, m_Cells[(y+j)*m_iWidth + x+i].getState());
lua_settable(m_LuaState, -3);
}
}
if(lua_pcall(m_LuaState, 2, 1, 0) != 0)
{
QMessageBox::critical(this, trUtf8("Error from Lua"),
trUtf8("An error occurred:\n%1").arg(lua_tostring(m_LuaState, -1)));
}
cell.setFutureState(lua_tointeger(m_LuaState, -1));
}
}
for(y = 0; y < m_iHeight; y++)
{
for(x = 0; x < m_iWidth; x++)
m_Cells[y*m_iWidth + x].tick();
}
m_pGrid->update();
}
| [
"[email protected]"
] | [
[
[
1,
133
]
]
] |
2fcdc3f3717269b4b255119df43c667466385b00 | df238aa31eb8c74e2c208188109813272472beec | /BCGInclude/BCGPControlBarImpl.h | 0407283da991a7ef6d568395fe5f97d578c51f6c | [] | no_license | myme5261314/plugin-system | d3166f36972c73f74768faae00ac9b6e0d58d862 | be490acba46c7f0d561adc373acd840201c0570c | refs/heads/master | 2020-03-29T20:00:01.155206 | 2011-06-27T15:23:30 | 2011-06-27T15:23:30 | 39,724,191 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,508 | h | //*******************************************************************************
// COPYRIGHT NOTES
// ---------------
// This is a part of the BCGControlBar Library
// Copyright (C) 1998-2008 BCGSoft Ltd.
// All rights reserved.
//
// This source code can be used, distributed or modified
// only under terms and conditions
// of the accompanying license agreement.
//*******************************************************************************
// BCGControlBarImpl.h: interface for the CBCGPControlBarImpl class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_BCGPCONTROLBARIMPL_H__F8388FA2_30D5_11D3_95C5_00A0C9289F1B__INCLUDED_)
#define AFX_BCGPCONTROLBARIMPL_H__F8388FA2_30D5_11D3_95C5_00A0C9289F1B__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "BCGCBPro.h"
class CBCGPControlBar;
class BCGCBPRODLLEXPORT CBCGPControlBarImpl
{
friend class CBCGPToolBar;
friend class CBCGPDialogBar;
friend class CBCGPReBar;
public:
CBCGPControlBarImpl(CBCGPControlBar* pBar);
virtual ~CBCGPControlBarImpl();
void GetGripperRect (CRect& rectGripper, BOOL bClientCoord = FALSE);
// Attributes:
protected:
CBCGPControlBar* m_pBar;
// Operations:
protected:
void CalcNcSize (NCCALCSIZE_PARAMS FAR* lpncsp);
void DrawNcArea ();
BOOL GetBackgroundFromParent (CDC* pDC);
};
#endif // !defined(AFX_BCGPCONTROLBARIMPL_H__F8388FA2_30D5_11D3_95C5_00A0C9289F1B__INCLUDED_)
| [
"myme5261314@ec588229-7da7-b333-41f6-0e1ebc3afda5"
] | [
[
[
1,
52
]
]
] |
ce3ccddaf171ee5f69ce8bdd4649e714e93d9d4d | 28aa891f07cc2240c771b5fb6130b1f4025ddc84 | /extern/oolua/include/oolua_exception.h | a6c3c5f1d5ab703fe84de760606a69f14cb30e03 | [
"MIT"
] | permissive | Hincoin/mid-autumn | e7476d8c9826db1cc775028573fc01ab3effa8fe | 5271496fb820f8ab1d613a1c2355504251997fef | refs/heads/master | 2021-01-10T19:17:01.479703 | 2011-12-19T14:32:51 | 2011-12-19T14:32:51 | 34,730,620 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,654 | h | ///////////////////////////////////////////////////////////////////////////////
/// @file oolua_exception.h
/// @author Liam Devine
/// @email
/// See http://www.liamdevine.co.uk for contact details.
/// @licence
/// See licence.txt for more details.
///////////////////////////////////////////////////////////////////////////////
#ifndef OOLUA_EXCEPTION_H_
# define OOLUA_EXCEPTION_H_
# ifdef OOLUA_NO_EXCEPTIONS
# include "lua_includes.h"
namespace OOLUA
{
struct Bad_cast_error : public std::runtime_error
{
Bad_cast_error(std::string const & msg):std::runtime_error(msg){}
};
struct Syntax_error : public std::runtime_error
{
Syntax_error(lua_State* s)
:std::runtime_error( lua_tostring(s, -1) )
{}
};
struct Runtime_error : public std::runtime_error
{
Runtime_error(lua_State* s)
:std::runtime_error( lua_tostring(s, -1) )
{}
};
struct Memory_error : public std::runtime_error
{
Memory_error(lua_State* s)
:std::runtime_error( lua_tostring(s, -1) )
{}
};
struct File_error : public std::runtime_error
{
File_error(lua_State* s)
:std::runtime_error( lua_tostring(s, -1) )
{}
};
struct Type_error : public std::runtime_error
{
Type_error(std::string const& str)
:std::runtime_error( str )
{}
};
}
# endif
#endif//OOLUA_EXCEPTION_H_
| [
"luozhiyuan@ea6f400c-e855-0410-84ee-31f796524d81"
] | [
[
[
1,
54
]
]
] |
b8106efbad699602142f95ad2d41631e24866a22 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /SMDK/Limn/LimnDW/Common/LimnModel_DiamondWizard_DualEfficiencyCurve.h | d2fa74a5fb7519c7155b676c3b2ea59b4366d1b6 | [] | 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,685 | h | #pragma once
//
//-------------------------------------------------------------------------------------------------------
//
// DIAMOND WIZARD SPECIFIC - DUAL EFFICIENCY CURVE
//
// Parameter Access Class
class C_ModelParameters_DiamondWizard_DualEfficiencyCurve: public CLimn_ModelData_Base
{
public:
C_ModelParameters_DiamondWizard_DualEfficiencyCurve(void) : CLimn_ModelData_Base(&sm_Common)
{
m_nSGs=0;
};
C_ModelParameters_DiamondWizard_DualEfficiencyCurve(double* ModelParams, int nSG) : CLimn_ModelData_Base(&sm_Common, ModelParams) // usually called from parameter passing
{
//m_pData=ModelParams;
Initialise(nSG);
}
~C_ModelParameters_DiamondWizard_DualEfficiencyCurve(void)
{
};
static CLimn_ModelData_Common sm_Common;
CDoubleRef OversizeStreamID;
CDoubleRef UndersizeStreamID;
CDoubleRef WaterSplit_1;
CDoubleRef FeSiSplit_1;
CDoubleRef Alpha_1;
CDoubleRef Rf_1;
CVectorRef D50c_1;
CDoubleRef DiamondD50c_1;
CDoubleRef WaterSplit_2;
CDoubleRef FeSiSplit_2;
CDoubleRef Alpha_2;
CDoubleRef Rf_2;
CVectorRef D50c_2;
CDoubleRef DiamondD50c_2;
bool Product1IsOversize() { return OversizeStreamID() < 1.5 ? true : false ; };
bool Product3IsUndersize() { return UndersizeStreamID() > 2.5 ? true : false ; };
void Initialise(int nSGs)
{
CLimn_ModelData_Base::Initialise();
m_nSGs = nSGs;
OversizeStreamID .Initialise(this, "OversizeStreamID", 1, "", true);
UndersizeStreamID .Initialise(this, "UndersizeStreamID", 2, "", true);
MarkText("Curve:1");
WaterSplit_1 .Initialise(this, "WaterSplit_1", 0.25, "Frac(.)");
FeSiSplit_1 .Initialise(this, "FeSiSplit_1", 0.25, "Frac(.)");
Alpha_1 .Initialise(this, "Alpha_1", 10, "");
Rf_1 .Initialise(this, "Rf_1", 0, "");
D50c_1 .Initialise(this, "D50", m_nSGs, DI_SG, "D50c_1", 30, "L(mm)");
DiamondD50c_1 .Initialise(this, "DiamondD50c_1", 30, "L(mm)");
MarkText("Curve:2");
WaterSplit_2 .Initialise(this, "WaterSplit_2", 0.25, "Frac(.)");
FeSiSplit_2 .Initialise(this, "FeSiSplit_2", 0.25, "Frac(.)");
Alpha_2 .Initialise(this, "Alpha_2", 10, "");
Rf_2 .Initialise(this, "Rf_2", 0, "");
D50c_2 .Initialise(this, "D50", m_nSGs, DI_SG, "D50c_2", 7, "L(mm)");
DiamondD50c_2 .Initialise(this, "DiamondD50c_2", 7, "L(mm)");
};
protected:
int m_nSGs;
};
//
// Limn callable model
C_LINKAGE DLLMODEL int _Model_DiamondWizard_DualEfficiencyCurve (int nRows,
int nColumns,
int nParameters,
int nReturns,
double* ModelParams,
double* ModelReturn,
double* CombinedFeed,
double* Product1,
double* Product2,
double* Product3,
double* Product4,
double* Product5,
double* Product6 ) ;
//
// Error information
C_LINKAGE int DLLMODEL _Error_DiamondWizard_DualEfficiencyCurve ( int errorIndex, LPSTR errorBuffer ) ;
//
// Parameter information
C_LINKAGE int DLLMODEL _Parameter_DiamondWizard_DualEfficiencyCurve ( int parameterIndex, LPSTR parameterInfoBuffer ) ;
//
| [
"[email protected]"
] | [
[
[
1,
93
]
]
] |
46610cffd672650c1abb1a938d60cf013d6b25f9 | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/Dependencies/Xerces/include/xercesc/util/regx/XMLRangeFactory.hpp | 8387b3e9a6e11c262247ca94a5d9b79e1fc06651 | [] | 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,286 | hpp | /*
* Copyright 2001-2002,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: XMLRangeFactory.hpp 176195 2004-11-12 23:24:58Z knoaman $
*/
#if !defined(XMLRANGEFACTORY_HPP)
#define XMLRANGEFACTORY_HPP
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/regx/RangeFactory.hpp>
XERCES_CPP_NAMESPACE_BEGIN
class XMLUTIL_EXPORT XMLRangeFactory: public RangeFactory {
public:
// -----------------------------------------------------------------------
// Constructors and operators
// -----------------------------------------------------------------------
XMLRangeFactory();
~XMLRangeFactory();
// -----------------------------------------------------------------------
// Initialization methods
// -----------------------------------------------------------------------
void initializeKeywordMap(RangeTokenMap *rangeTokMap = 0);
protected:
// -----------------------------------------------------------------------
// Protected Helper methods
// -----------------------------------------------------------------------
void buildRanges(RangeTokenMap *rangeTokMap = 0);
private:
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
XMLRangeFactory(const XMLRangeFactory&);
XMLRangeFactory& operator=(const XMLRangeFactory&);
};
XERCES_CPP_NAMESPACE_END
#endif
/**
* End file XMLRangeFactory.hpp
*/
| [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
] | [
[
[
1,
65
]
]
] |
566d2e087366ed5a7c042072c65e4472f0fcef47 | 27167a5a0340fdc9544752bd724db27d3699a9a2 | /include/dockwins/TabDockingBox.h | 3d17ad0656314786955625620ab0f9d939670dbb | [] | no_license | eaglexmw-gmail/wtl-dockwins | 2b464be3958e1683cd668a10abafb528f43ac695 | ae307a1978b73bfd2823945068224bb6c01ae350 | refs/heads/master | 2020-06-30T21:03:26.075864 | 2011-10-23T12:50:14 | 2011-10-23T12:50:14 | 200,951,487 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 22,236 | h | // Copyright (c) 2002
// Sergey Klimov ([email protected])
// WTL Docking windows
//
// This code is provided "as is", with absolutely no warranty expressed
// or implied. Any use is at your own risk.
//
// This code may be used in compiled form in any way you desire. This
// file may be redistributed unmodified 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. If
// the source code in this file is used in any commercial application
// then a simple email would be nice.
#ifndef WTL_DW_TABDOCKINGBOX_H_INCLUDED_
#define WTL_DW_TABDOCKINGBOX_H_INCLUDED_
#pragma once
#include <dockwins/atlgdix.h>
#include "CustomTabCtrl.h"
#include "DotNetTabCtrl.h"
#include "DockingBox.h"
#include "FlyingTabs.h"
namespace dockwins
{
template<class TTraits = COutlookLikeDockingBoxTraits>
class CTabDockingBox :
public CDockingBoxBaseImpl<CTabDockingBox<TTraits>, CWindow, TTraits>
{
typedef CDockingBoxBaseImpl<CTabDockingBox, CWindow, TTraits> baseClass;
typedef CTabDockingBox thisClass;
typedef CFlyingTabCtrl CTabCtrl;
protected:
static void SetIndex(DFDOCKRECT* pHdr, int index)
{
pHdr->rect.left = index;
pHdr->rect.right = index;
pHdr->rect.top = index;
pHdr->rect.bottom = index;
}
static int GetIndex(DFDOCKRECT* pHdr)
{
return pHdr->rect.left;
}
public:
static HWND CreateInstance(HWND hWnd)
{
thisClass* ptr = new thisClass;
HWND hNewWnd = ptr->Create(hWnd);
ATLASSERT(hNewWnd);
if (hNewWnd == NULL)
delete ptr;
return hNewWnd;
}
virtual bool DockMe(DFDOCKRECT* pHdr)
{
if (CDockingBox::IsWindowBox(pHdr->hdr.hBar))
{
ATLASSERT(m_wnd.m_hWnd);
HWND hActiveWnd = m_wnd.m_hWnd;
int n = m_tabs.GetItemCount();
ATLASSERT(n >= 2);
while (n > 0)
{
pHdr->hdr.hWnd = GetItemHWND(--n);
if (pHdr->hdr.hWnd != NULL)
{
RemoveWindow(pHdr->hdr.hWnd);
m_docker.Dock(pHdr);
}
}
pHdr->hdr.hWnd = hActiveWnd;
// pHdr->hdr.code=DC_ACTIVATE;
m_docker.Activate(&pHdr->hdr);
PostMessage(WM_CLOSE);
}
else
m_docker.Dock(pHdr);
return true;
}
bool IsPointInAcceptedArea(POINT* pPt) const
{
HWND hWnd =::WindowFromPoint(*pPt);
while ((hWnd != m_hWnd)
&& (hWnd != NULL))
hWnd =::GetParent(hWnd);
bool bRes = (hWnd != NULL);
if (bRes)
{
CRect rc;
CPoint pt(*pPt);
m_tabs.GetTabsRect(&rc);
m_tabs.ScreenToClient(pPt);
bRes = (rc.PtInRect(*pPt) != FALSE);
if (!bRes)
{
bRes =::SendMessage(m_hWnd, WM_NCHITTEST, NULL, MAKELPARAM(pt.x, pt.y)) == HTCAPTION;
if (bRes)
{
if (!IsDocking() || m_caption.IsHorizontal())
pPt->y = (rc.bottom + rc.top) / 2;
else
*pPt = rc.CenterPoint();
// now only horizontal tab control supported
///11 ATLASSERT((m_tabs.GetWindowLong(GWL_STYLE)&TCS_VERTICAL)==0);
ATLASSERT((m_tabs.GetWindowLong(GWL_STYLE)&CTCS_VERTICAL) == 0);
}
}
}
return bRes;
}
LRESULT OnAcceptDock(DFDOCKRECT* pHdr)
{
CPoint pt(pHdr->rect.left, pHdr->rect.top);
BOOL bRes = IsPointInAcceptedArea(&pt);
if (bRes)
{
MSG msg = {0};
int curSel = m_tabs.GetCurSel();
ATLASSERT(curSel != -1);
HWND hWnd = GetItemHWND(curSel);
///11 bool bHorizontal=!(m_tabs.GetWindowLong(GWL_STYLE)&TCS_VERTICAL);
bool bHorizontal = !(m_tabs.GetWindowLong(GWL_STYLE)&CTCS_VERTICAL);
int pos = bHorizontal ? pt.x : pt.y;
///11 TCHITTESTINFO tchti = { 0 };
CTCHITTESTINFO tchti = { 0 };
tchti.pt.x = pt.x;
tchti.pt.y = pt.y;
int index = m_tabs.HitTest(&tchti);
if ((hWnd != NULL) && (hWnd != pHdr->hdr.hWnd))
{
if (index == -1)
{
RECT rc;
m_tabs.GetItemRect(0, &rc);
if (bHorizontal)
index = (rc.left > pos) ? 0 : m_tabs.GetItemCount();
else
index = (rc.top > pos) ? 0 : m_tabs.GetItemCount();
}
m_prevSelItem = curSel;
curSel = InsertWndTab(index, pHdr->hdr.hWnd, 0);
// dispatch all notifications
while (PeekMessage(&msg, NULL, WM_NOTIFY, WM_NOTIFY, PM_REMOVE))
DispatchMessage(&msg);
m_prevItem = curSel;
m_prevPos = pos;
ATLASSERT(index == curSel);
}
if (
(index != -1)
&& (index != curSel)
&&
!((index == m_prevItem)
&& ((pos - m_prevPos) * (m_prevItem - curSel) <= 0)))
{
m_tabs.SwapItemPositions(curSel, index, false, false);
// m_tabs.MoveItem(curSel,index);
curSel = index;
m_tabs.SetCurSel(curSel);
m_prevItem = m_tabs.HitTest(&tchti);
}
m_prevPos = pos;
pHdr->hdr.hBar = m_hWnd;
SetIndex(pHdr, curSel);
//check next message
while (WaitMessage())
{
//redraw first
while (PeekMessage(&msg, NULL, WM_PAINT, WM_PAINT, PM_REMOVE))
DispatchMessage(&msg);
if (PeekMessage(&msg, 0, WM_SYSKEYDOWN, WM_SYSKEYDOWN, PM_NOREMOVE))
break;
if (PeekMessage(&msg, pHdr->hdr.hWnd, 0, 0, PM_NOREMOVE))
{
if (pHdr->hdr.hWnd == msg.hwnd)
break;
else
{
if (PeekMessage(&msg, msg.hwnd, msg.message, msg.message, PM_REMOVE))
DispatchMessage(&msg);
}
}
}
pt.x = GET_X_LPARAM(msg.lParam);
pt.y = GET_Y_LPARAM(msg.lParam);
::ClientToScreen(msg.hwnd, &pt);
if (msg.message != WM_MOUSEMOVE
|| (::GetKeyState(VK_CONTROL) & 0x8000)
|| !IsPointInAcceptedArea(&pt))
{
if (GetItemHWND(curSel) == NULL)
{
m_tabs.DeleteItem(curSel, false);
ATLASSERT(m_prevSelItem >= 0);
ATLASSERT(m_prevSelItem < m_tabs.GetItemCount());
m_tabs.SetCurSel(m_prevSelItem);
}
//let control update itself!!!
while (PeekMessage(&msg, NULL, WM_PAINT, WM_PAINT, PM_REMOVE))
DispatchMessage(&msg);
}
}
return bRes;
}
LRESULT OnDock(DFDOCKRECT* pHdr)
{
ATLASSERT(pHdr->hdr.hWnd);
int index = GetIndex(pHdr);
int n = m_tabs.GetItemCount();
if ((index < 0) || (index > n))
index = n;
return (InsertWndTab(index, pHdr->hdr.hWnd) != -1);
}
LRESULT OnUndock(DFMHDR* pHdr)
{
CWindow wnd(pHdr->hWnd);
ATLASSERT(::IsWindow(pHdr->hWnd));
BOOL bRes = RemoveWindow(pHdr->hWnd);
IsStillAlive();
return bRes;
}
LRESULT OnActivate(DFMHDR* pHdr)
{
int index = FindItem(pHdr->hWnd);
BOOL bRes = (index != -1);
if (bRes)
m_tabs.SetCurSel(index);
if (!IsVisible())
Show();
return bRes;
}
void PrepareForDock(CWindow wnd)
{
wnd.ShowWindow(SW_HIDE);
DWORD style = wnd.GetWindowLong(GWL_STYLE);
DWORD newStyle = style & (~(WS_POPUP | WS_CAPTION)) | WS_CHILD;
wnd.SetWindowLong(GWL_STYLE, newStyle);
wnd.SetParent(m_hWnd);
wnd.SendMessage(WM_NCACTIVATE, TRUE);
wnd.SendMessage(WMDF_NDOCKSTATECHANGED,
MAKEWPARAM(TRUE, FALSE),
reinterpret_cast<LPARAM>(m_hWnd));
}
void PrepareForUndock(CWindow wnd)
{
wnd.ShowWindow(SW_HIDE);
DWORD style = wnd.GetWindowLong(GWL_STYLE);
DWORD newStyle = style & (~WS_CHILD) | WS_POPUP | WS_CAPTION;
wnd.SetWindowLong(GWL_STYLE, newStyle);
wnd.SetParent(NULL);
wnd.SendMessage(WMDF_NDOCKSTATECHANGED,
FALSE,
reinterpret_cast<LPARAM>(m_hWnd));
}
int InsertWndTab(int index, CWindow wnd)
{
ATLASSERT(wnd.IsWindow());
PrepareForDock(wnd);
return InsertWndTab(index, wnd, reinterpret_cast<DWORD>(wnd.m_hWnd));
}
int InsertWndTab(int index, CWindow wnd, DWORD param)
{
ATLASSERT(index >= 0);
ATLASSERT(index <= m_tabs.GetItemCount());
ATLASSERT(wnd.IsWindow());
int txtLen = wnd.GetWindowTextLength() + 1;
TCHAR* ptxt = new TCHAR[txtLen];
wnd.GetWindowText(ptxt, txtLen);
int image = -1;
HICON hIcon = wnd.GetIcon(FALSE);
if (hIcon == NULL)
hIcon = (HICON)GetClassLongPtr(wnd.m_hWnd, GCLP_HICONSM);
if (hIcon)
image = m_images.AddIcon(hIcon);
index = m_tabs.InsertItem(index, ptxt, image, param);
delete[] ptxt;
return index;
}
BOOL RemoveWindow(CWindow wnd)
{
int index = FindItem(wnd);
BOOL bRes = (index != -1);
if (bRes)
{
/*
TCITEM tci;
tci.mask=TCIF_IMAGE ;
if(m_tabs.GetItem(index,&tci))
m_images.Remove(tci.iImage);
*/
if (m_wnd.m_hWnd == wnd.m_hWnd)
m_wnd.m_hWnd = NULL;
bRes = m_tabs.DeleteItem(index);
if (bRes)
PrepareForUndock(wnd);
}
return bRes;
}
int FindItem(HWND hWnd) const
{
int n = m_tabs.GetItemCount();
for (int i = 0; i < n; i++)
{
if (GetItemHWND(i) == hWnd)
return i;
}
return -1;
}
HWND GetItemHWND(int index) const
{
return reinterpret_cast<HWND>(m_tabs.GetItemData(index));
}
void AdjustCurentItem()
{
if (m_wnd.m_hWnd != 0)
{
ATLASSERT(m_wnd.GetParent() == m_hWnd);
CRect rc;
GetClientRect(&rc);
m_tabs.AdjustRect(FALSE, &rc);
ATLASSERT((m_wnd.GetWindowLong(GWL_STYLE) & WS_CAPTION) == 0);
m_wnd.SetWindowPos(HWND_TOP, &rc, SWP_SHOWWINDOW);
}
}
void UpdateWindowCaption()
{
if (m_wnd.m_hWnd != 0)
{
ATLASSERT(m_wnd.GetParent() == m_hWnd);
int len = m_wnd.GetWindowTextLength() + 1;
TCHAR* ptxt = new TCHAR[len];
m_wnd.GetWindowText(ptxt, len);
SetWindowText(ptxt);
HICON hIcon = m_wnd.GetIcon(FALSE);
SetIcon(hIcon , FALSE);
delete [] ptxt;
}
}
void IsStillAlive()
{
int n = m_tabs.GetItemCount();
if (n <= 1)
{
PostMessage(WM_CLOSE, TRUE);
if (n == 0)
Hide();
}
}
bool CanBeClosed(WPARAM param)
{
int n = m_tabs.GetItemCount();
bool bRes = (param == 0);
if (!bRes)
{
bRes = n < 2;
if (bRes && (n != 0))
{
HWND hWnd = GetItemHWND(0);
ATLASSERT(hWnd);
if (hWnd)
{
::ShowWindow(hWnd, SW_HIDE);
RemoveWindow(hWnd);
if (IsDocking())
{
DFDOCKREPLACE dockHdr;
dockHdr.hdr.hBar = GetOwnerDockingBar();
dockHdr.hdr.hWnd = m_hWnd;
dockHdr.hWnd = hWnd;
m_docker.Replace(&dockHdr);
}
else
{
RECT rc;
BOOL bRes = GetWindowRect(&rc);
if (bRes)
bRes =::SetWindowPos(hWnd, HWND_TOP, rc.left, rc.top,
rc.right - rc.left, rc.bottom - rc.top, SWP_SHOWWINDOW);
}
ATLASSERT(!IsDocking());
}
}
}
else
{
bRes = n < 2;
if (!bRes)
bRes = baseClass::CanBeClosed(param);
}
return bRes;
}
public:
bool OnGetDockingPosition(DFDOCKPOS* pHdr) const
{
pHdr->hdr.hBar = GetOwnerDockingBar();
bool bRes = baseClass::OnGetDockingPosition(pHdr);
pHdr->nIndex = FindItem(pHdr->hdr.hWnd);
ATLASSERT(pHdr->nIndex != -1);
if (m_tabs.GetItemCount() == 2)
pHdr->hdr.hBar = GetItemHWND((pHdr->nIndex == 0) ? 1 : 0);
else
pHdr->hdr.hBar = m_hWnd;
if (m_wnd.m_hWnd == pHdr->hdr.hWnd)
pHdr->dwDockSide |= CDockingSide::sActive;
return bRes;
}
bool OnSetDockingPosition(DFDOCKPOS* pHdr)
{
ATLASSERT(pHdr->hdr.hWnd);
int index = pHdr->nIndex;
int n = m_tabs.GetItemCount();
if ((index < 0) || (index > n))
index = n;
return (InsertWndTab(index, pHdr->hdr.hWnd) != -1);
}
#ifdef DF_AUTO_HIDE_FEATURES
bool PinUp(const CDockingSide& side, UINT width, bool bVisualize = false)
{
if (IsDocking())
Undock();
DFPINUP pinHdr;
pinHdr.hdr.hWnd = m_wnd;
pinHdr.hdr.hBar = GetOwnerDockingBar();
// pinHdr.hdr.code=DC_PINUP;
pinHdr.dwDockSide = side;
pinHdr.nWidth = width;
pinHdr.dwFlags = (bVisualize) ? DFPU_VISUALIZE : 0 ;
pinHdr.n = m_tabs.GetItemCount();
bool bRes = false;
try
{
pinHdr.phWnds = new HWND[pinHdr.n];
int n = static_cast<int>(pinHdr.n);
while (--n >= 0)
{
pinHdr.phWnds[n] = GetItemHWND(n);
ATLASSERT(::IsWindow(pinHdr.phWnds[n]));
RemoveWindow(pinHdr.phWnds[n]);
}
bRes = m_docker.PinUp(&pinHdr);
delete [] pinHdr.phWnds;
PostMessage(WM_CLOSE);
}
catch (std::bad_alloc& /*e*/)
{
}
return bRes;
}
#endif
DECLARE_WND_CLASS(_T("CTabDockingBox"))
BEGIN_MSG_MAP(thisClass)
MESSAGE_HANDLER(WM_CREATE, OnCreate)
MESSAGE_HANDLER(WM_SIZE, OnSize)
MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBkgnd)
MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
MESSAGE_HANDLER(WM_SETFOCUS, OnSetFocus)
///11 NOTIFY_CODE_HANDLER(TCN_SELCHANGE, OnTabSelChange)
///11 NOTIFY_CODE_HANDLER(TCN_TABLEAVCTRL, OnTabLeavCtrl)
NOTIFY_CODE_HANDLER(CTCN_SELCHANGE, OnTabSelChange)
NOTIFY_CODE_HANDLER(CTCN_TABLEAVCTRL, OnTabLeavCtrl)
NOTIFY_CODE_HANDLER(NM_DBLCLK, OnTabDblClk)
REFLECT_NOTIFICATIONS()
CHAIN_MSG_MAP(baseClass)
END_MSG_MAP()
LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
///11 m_tabs.Create(m_hWnd, rcDefault, NULL,WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | TCS_TOOLTIPS | TCS_BOTTOM);
m_tabs.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | CTCS_TOOLTIPS | CTCS_BOTTOM);
BOOL bRes = m_images.Create(16, 16, ILC_COLOR32 | ILC_MASK , 0, 5);
ATLASSERT(bRes);
if (bRes)
m_tabs.SetImageList(m_images);
return 0;
}
LRESULT OnSize(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
{
if (wParam != SIZE_MINIMIZED)
{
RECT rc;
GetClientRect(&rc);
m_tabs.SetWindowPos(NULL, &rc , SWP_NOZORDER | SWP_NOACTIVATE);
AdjustCurentItem();
}
bHandled = FALSE;
return 1;
}
LRESULT OnEraseBkgnd(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
return 0;
}
LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
bHandled = FALSE;
m_images.Destroy();
return 0;
}
LRESULT OnSetFocus(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
int index = m_tabs.GetCurSel();
if (index != -1)
{
HWND hWnd = GetItemHWND(index);
if (hWnd != NULL
&&::IsWindowVisible(hWnd))
::SetFocus(hWnd);
}
bHandled = FALSE;
return 1;
}
LRESULT OnTabSelChange(int /*idCtrl*/, LPNMHDR pnmh, BOOL& /*bHandled*/)
{
if (pnmh->hwndFrom == m_tabs)
{
int index = m_tabs.GetCurSel();
if (index != -1)
{
HWND hWnd = GetItemHWND(index);
if (hWnd != NULL && (hWnd != m_wnd))
{
if (m_wnd.m_hWnd != NULL)
{
ATLASSERT(::GetParent(m_wnd.m_hWnd) == m_hWnd);
m_wnd.ShowWindow(SW_HIDE);
}
m_wnd = hWnd;
UpdateWindowCaption();
AdjustCurentItem();
::SetFocus(hWnd);
}
}
}
return 0;
}
LRESULT OnTabLeavCtrl(int /*idCtrl*/, LPNMHDR pnmh, BOOL& /*bHandled*/)
{
BOOL bRes = TRUE;
if (pnmh->hwndFrom == m_tabs)
{
int index = m_tabs.GetCurSel();
ATLASSERT(index != -1);
if (index != -1)
{
HWND hWnd = GetItemHWND(index);
ATLASSERT(::IsWindow(hWnd));
CRect rc;
::GetWindowRect(hWnd, &rc);
::PostMessage(hWnd, WM_NCLBUTTONDOWN, HTCAPTION, MAKELPARAM(rc.right, rc.bottom));
/*
DWORD dwPos = ::GetMessagePos();
CPoint pt(GET_X_LPARAM(dwPos), GET_Y_LPARAM(dwPos));
DWORD style=m_tabs.GetWindowLong(GWL_STYLE);
///11 if(style&TCS_VERTICAL)
if(style&CTCS_VERTICAL)
{
///11 if(style&TCS_BOTTOM)
if(style&CTCS_BOTTOM)
pt.x=2*rc.right-pt.x;
else
pt.x=2*rc.left-pt.x;
}
else
{
///11 if(style&TCS_BOTTOM)
if(style&CTCS_BOTTOM)
pt.y=2*rc.bottom-pt.y;
else
pt.y=2*rc.top-pt.y;
}
::PostMessage(hWnd,WM_NCLBUTTONDOWN,HTCAPTION,MAKELPARAM(pt.x,pt.y));
*/
bRes = FALSE;
}
}
return bRes;
}
LRESULT OnTabDblClk(int /*idCtrl*/, LPNMHDR pnmh, BOOL& /*bHandled*/)
{
if (pnmh->hwndFrom == m_tabs)
{
int index = m_tabs.GetCurSel();
ATLASSERT(index != -1);
if (index != -1)
{
HWND hWnd = GetItemHWND(index);
ATLASSERT(::IsWindow(hWnd));
::PostMessage(hWnd, WM_NCLBUTTONDBLCLK, HTCAPTION, 0);
}
}
return 0;
}
protected:
CImageList m_images;
CTabCtrl m_tabs;
CWindow m_wnd;
////
int m_prevSelItem;
int m_prevItem;
int m_prevPos;
};
template <class TCaption, class TBox, DWORD t_dwStyle = 0, DWORD t_dwExStyle = 0>
struct CBoxedDockingWindowTraits
: CDockingBoxTraits<TCaption, t_dwStyle, t_dwExStyle>
{
typedef TBox CBox;
};
typedef CBoxedDockingWindowTraits < COutlookLikeCaption, CTabDockingBox<COutlookLikeDockingBoxTraits>,
WS_OVERLAPPEDWINDOW | WS_POPUP | WS_VISIBLE |
WS_CLIPCHILDREN | WS_CLIPSIBLINGS, WS_EX_TOOLWINDOW >
COutlookLikeBoxedDockingWindowTraits;
typedef CBoxedDockingWindowTraits < COutlookLikeExCaption, CTabDockingBox<COutlookLikeExDockingBoxTraits>,
WS_OVERLAPPEDWINDOW | WS_POPUP | WS_VISIBLE |
WS_CLIPCHILDREN | WS_CLIPSIBLINGS, WS_EX_TOOLWINDOW >
COutlookLikeExBoxedDockingWindowTraits;
typedef CBoxedDockingWindowTraits < CVC6LikeCaption, CTabDockingBox<CVC6LikeDockingBoxTraits>,
WS_OVERLAPPEDWINDOW | WS_POPUP | WS_VISIBLE |
WS_CLIPCHILDREN | WS_CLIPSIBLINGS, WS_EX_TOOLWINDOW >
CVC6LikeBoxedDockingWindowTraits;
}//namespace dockwins
#endif // WTL_DW_TABDOCKINGBOX_H_INCLUDED_
| [
"[email protected]"
] | [
[
[
1,
732
]
]
] |
29c44604975862c9dcc80346d224a65c976a04ae | f71e82b7ed19200280b7164a2e959310d9bfa210 | /ExampleAIModule/ExampleAIModule/Scout.h | dc3a4e7b926426c9a305e47acfe89a235a714992 | [] | no_license | albertouri/manolobot | 05cf4ee217e85f1332e0e063fcc209da4b71c7b5 | 44e7fee46abcf4f1efa6d292ea8ec7cdc57eb7c8 | refs/heads/master | 2021-01-02T08:32:48.281836 | 2011-02-03T23:28:08 | 2011-02-03T23:28:08 | 39,591,406 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 624 | h | #pragma once
#include <BWAPI.h>
#include <BWTA.h>
#include "Grafo.h"
#include "Nodo.h"
using namespace BWAPI;
using namespace BWTA;
class Scout
{
public:
Scout(Unit *unidad);
Scout(Unit *unidad, Grafo *g);
~Scout(void);
//void asignarNuevoScout(Unit* nuevoScout);
bool exists(void);
void explorar(void);
void cambiarModo(int m);
void setExplorador(Unit *u);
Unit* getExplorador();
private:
Position* posActual; //-- nuevo
Grafo *grafo;
int tiempoMax;
bool primeraExploracion;
void dibujarPosiciones(void);
void dibujarGrilla(void);
//Region *regActual;
};
| [
"[email protected]",
"marianomoreno3@82b963ee-1e64-6eb5-a9c5-6632919fd137"
] | [
[
[
1,
3
],
[
10,
13
],
[
17,
17
],
[
19,
21
],
[
25,
26
],
[
39,
39
]
],
[
[
4,
9
],
[
14,
16
],
[
18,
18
],
[
22,
24
],
[
27,
38
]
]
] |
4495325bc53c14205e8b0187f155ad913fb41abd | f2acff1dd22184a3e8f8578caf1ebeaa720c30c8 | /IIKH team2/IIKH team2/Main.cpp | f16a8885c6d4b308f45db9922cf52ad6cfaed95e | [] | no_license | amanized/iikh | 7a1dbc0c127aaae1013416703bc59c97f823c6a2 | 49424586de5f5f5d83ebe3958a38e5961b4cd03d | refs/heads/master | 2016-09-05T14:03:02.898473 | 2010-09-29T07:32:08 | 2010-09-29T07:32:08 | 41,376,269 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,006 | cpp | #include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
//클래스 선언
int choice_L=0; //대메뉴 선택을 하는 변수(Large)
system("cls");
cout<<"────────────────────────"<<endl;
cout<<"*****************OOP Project*******************"<<endl;
cout<<"────────────────────────"<<endl<<endl;
while(true){
cout<<"────────────────────────"<<endl;
cout<<"1.레시피"<<endl;
cout<<"2.식단"<<endl;
cout<<"3.종료"<<endl;
cout<<"────────────────────────"<<endl;
cin>>choice_L;
switch(choice_L){
case 1 :
//레시피 조회 및 관리
break;
case 2 :
//식단
break;
case 3 :
//종료
return 0;
default:
cout<<"illegal Expression"<<endl;
break;
}
}
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
43
]
]
] |
19092337fe0a941c034e05e09c5764d9e1e2dc89 | d54d8b1bbc9575f3c96853e0c67f17c1ad7ab546 | /hlsdk-2.3-p3/singleplayer/cl_dll/entity.cpp | 95775b1ce51446de35344facc5ce1f60617c6c22 | [] | no_license | joropito/amxxgroup | 637ee71e250ffd6a7e628f77893caef4c4b1af0a | f948042ee63ebac6ad0332f8a77393322157fa8f | refs/heads/master | 2021-01-10T09:21:31.449489 | 2010-04-11T21:34:27 | 2010-04-11T21:34:27 | 47,087,485 | 1 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 27,685 | cpp | //========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================
// Client side entity management functions
#include <memory.h>
#include "hud.h"
#include "cl_util.h"
#include "const.h"
#include "entity_types.h"
#include "studio_event.h" // def. of mstudioevent_t
#include "r_efx.h"
#include "event_api.h"
#include "pm_defs.h"
#include "pmtrace.h"
#include "pm_shared.h"
#define DLLEXPORT __declspec( dllexport )
void Game_AddObjects( void );
extern vec3_t v_origin;
int g_iAlive = 1;
extern "C"
{
int DLLEXPORT HUD_AddEntity( int type, struct cl_entity_s *ent, const char *modelname );
void DLLEXPORT HUD_CreateEntities( void );
void DLLEXPORT HUD_StudioEvent( const struct mstudioevent_s *event, const struct cl_entity_s *entity );
void DLLEXPORT HUD_TxferLocalOverrides( struct entity_state_s *state, const struct clientdata_s *client );
void DLLEXPORT HUD_ProcessPlayerState( struct entity_state_s *dst, const struct entity_state_s *src );
void DLLEXPORT HUD_TxferPredictionData ( struct entity_state_s *ps, const struct entity_state_s *pps, struct clientdata_s *pcd, const struct clientdata_s *ppcd, struct weapon_data_s *wd, const struct weapon_data_s *pwd );
void DLLEXPORT HUD_TempEntUpdate( double frametime, double client_time, double cl_gravity, struct tempent_s **ppTempEntFree, struct tempent_s **ppTempEntActive, int ( *Callback_AddVisibleEntity )( struct cl_entity_s *pEntity ), void ( *Callback_TempEntPlaySound )( struct tempent_s *pTemp, float damp ) );
struct cl_entity_s DLLEXPORT *HUD_GetUserEntity( int index );
}
/*
========================
HUD_AddEntity
Return 0 to filter entity from visible list for rendering
========================
*/
int DLLEXPORT HUD_AddEntity( int type, struct cl_entity_s *ent, const char *modelname )
{
switch ( type )
{
case ET_NORMAL:
case ET_PLAYER:
case ET_BEAM:
case ET_TEMPENTITY:
case ET_FRAGMENTED:
default:
break;
}
// each frame every entity passes this function, so the overview hooks it to filter the overview entities
// in spectator mode:
// each frame every entity passes this function, so the overview hooks
// it to filter the overview entities
if ( g_iUser1 )
{
gHUD.m_Spectator.AddOverviewEntity( type, ent, modelname );
if ( ( g_iUser1 == OBS_IN_EYE || gHUD.m_Spectator.m_pip->value == INSET_IN_EYE ) &&
ent->index == g_iUser2 )
return 0; // don't draw the player we are following in eye
}
return 1;
}
/*
=========================
HUD_TxferLocalOverrides
The server sends us our origin with extra precision as part of the clientdata structure, not during the normal
playerstate update in entity_state_t. In order for these overrides to eventually get to the appropriate playerstate
structure, we need to copy them into the state structure at this point.
=========================
*/
void DLLEXPORT HUD_TxferLocalOverrides( struct entity_state_s *state, const struct clientdata_s *client )
{
VectorCopy( client->origin, state->origin );
// Spectator
state->iuser1 = client->iuser1;
state->iuser2 = client->iuser2;
// Duck prevention
state->iuser3 = client->iuser3;
// Fire prevention
state->iuser4 = client->iuser4;
}
/*
=========================
HUD_ProcessPlayerState
We have received entity_state_t for this player over the network. We need to copy appropriate fields to the
playerstate structure
=========================
*/
void DLLEXPORT HUD_ProcessPlayerState( struct entity_state_s *dst, const struct entity_state_s *src )
{
// Copy in network data
VectorCopy( src->origin, dst->origin );
VectorCopy( src->angles, dst->angles );
VectorCopy( src->velocity, dst->velocity );
dst->frame = src->frame;
dst->modelindex = src->modelindex;
dst->skin = src->skin;
dst->effects = src->effects;
dst->weaponmodel = src->weaponmodel;
dst->movetype = src->movetype;
dst->sequence = src->sequence;
dst->animtime = src->animtime;
dst->solid = src->solid;
dst->rendermode = src->rendermode;
dst->renderamt = src->renderamt;
dst->rendercolor.r = src->rendercolor.r;
dst->rendercolor.g = src->rendercolor.g;
dst->rendercolor.b = src->rendercolor.b;
dst->renderfx = src->renderfx;
dst->framerate = src->framerate;
dst->body = src->body;
memcpy( &dst->controller[0], &src->controller[0], 4 * sizeof( byte ) );
memcpy( &dst->blending[0], &src->blending[0], 2 * sizeof( byte ) );
VectorCopy( src->basevelocity, dst->basevelocity );
dst->friction = src->friction;
dst->gravity = src->gravity;
dst->gaitsequence = src->gaitsequence;
dst->spectator = src->spectator;
dst->usehull = src->usehull;
dst->playerclass = src->playerclass;
dst->team = src->team;
dst->colormap = src->colormap;
// Save off some data so other areas of the Client DLL can get to it
cl_entity_t *player = gEngfuncs.GetLocalPlayer(); // Get the local player's index
if ( dst->number == player->index )
{
g_iPlayerClass = dst->playerclass;
g_iTeamNumber = dst->team;
g_iUser1 = src->iuser1;
g_iUser2 = src->iuser2;
g_iUser3 = src->iuser3;
}
}
/*
=========================
HUD_TxferPredictionData
Because we can predict an arbitrary number of frames before the server responds with an update, we need to be able to copy client side prediction data in
from the state that the server ack'd receiving, which can be anywhere along the predicted frame path ( i.e., we could predict 20 frames into the future and the server ack's
up through 10 of those frames, so we need to copy persistent client-side only state from the 10th predicted frame to the slot the server
update is occupying.
=========================
*/
void DLLEXPORT HUD_TxferPredictionData ( struct entity_state_s *ps, const struct entity_state_s *pps, struct clientdata_s *pcd, const struct clientdata_s *ppcd, struct weapon_data_s *wd, const struct weapon_data_s *pwd )
{
ps->oldbuttons = pps->oldbuttons;
ps->flFallVelocity = pps->flFallVelocity;
ps->iStepLeft = pps->iStepLeft;
ps->playerclass = pps->playerclass;
pcd->viewmodel = ppcd->viewmodel;
pcd->m_iId = ppcd->m_iId;
pcd->ammo_shells = ppcd->ammo_shells;
pcd->ammo_nails = ppcd->ammo_nails;
pcd->ammo_cells = ppcd->ammo_cells;
pcd->ammo_rockets = ppcd->ammo_rockets;
pcd->m_flNextAttack = ppcd->m_flNextAttack;
pcd->fov = ppcd->fov;
pcd->weaponanim = ppcd->weaponanim;
pcd->tfstate = ppcd->tfstate;
pcd->maxspeed = ppcd->maxspeed;
pcd->deadflag = ppcd->deadflag;
// Spectating or not dead == get control over view angles.
g_iAlive = ( ppcd->iuser1 || ( pcd->deadflag == DEAD_NO ) ) ? 1 : 0;
// Spectator
pcd->iuser1 = ppcd->iuser1;
pcd->iuser2 = ppcd->iuser2;
// Duck prevention
pcd->iuser3 = ppcd->iuser3;
if ( gEngfuncs.IsSpectateOnly() )
{
// in specator mode we tell the engine who we want to spectate and how
// iuser3 is not used for duck prevention (since the spectator can't duck at all)
pcd->iuser1 = g_iUser1; // observer mode
pcd->iuser2 = g_iUser2; // first target
pcd->iuser3 = g_iUser3; // second target
}
// Fire prevention
pcd->iuser4 = ppcd->iuser4;
pcd->fuser2 = ppcd->fuser2;
pcd->fuser3 = ppcd->fuser3;
VectorCopy( ppcd->vuser1, pcd->vuser1 );
VectorCopy( ppcd->vuser2, pcd->vuser2 );
VectorCopy( ppcd->vuser3, pcd->vuser3 );
VectorCopy( ppcd->vuser4, pcd->vuser4 );
memcpy( wd, pwd, 32 * sizeof( weapon_data_t ) );
}
/*
//#define TEST_IT
#if defined( TEST_IT )
cl_entity_t mymodel[9];
void MoveModel( void )
{
cl_entity_t *player;
int i, j;
int modelindex;
struct model_s *mod;
// Load it up with some bogus data
player = gEngfuncs.GetLocalPlayer();
if ( !player )
return;
mod = gEngfuncs.CL_LoadModel( "models/sentry3.mdl", &modelindex );
for ( i = 0; i < 3; i++ )
{
for ( j = 0; j < 3; j++ )
{
// Don't draw over ourself...
if ( ( i == 1 ) && ( j == 1 ) )
continue;
mymodel[ i * 3 + j ] = *player;
mymodel[ i * 3 + j ].player = 0;
mymodel[ i * 3 + j ].model = mod;
mymodel[ i * 3 + j ].curstate.modelindex = modelindex;
// Move it out a bit
mymodel[ i * 3 + j ].origin[0] = player->origin[0] + 50 * ( 1 - i );
mymodel[ i * 3 + j ].origin[1] = player->origin[1] + 50 * ( 1 - j );
gEngfuncs.CL_CreateVisibleEntity( ET_NORMAL, &mymodel[i*3+j] );
}
}
}
#endif
//#define TRACE_TEST
#if defined( TRACE_TEST )
extern int hitent;
cl_entity_t hit;
void TraceModel( void )
{
cl_entity_t *ent;
if ( hitent <= 0 )
return;
// Load it up with some bogus data
ent = gEngfuncs.GetEntityByIndex( hitent );
if ( !ent )
return;
hit = *ent;
//hit.curstate.rendermode = kRenderTransTexture;
//hit.curstate.renderfx = kRenderFxGlowShell;
//hit.curstate.renderamt = 100;
hit.origin[2] += 40;
gEngfuncs.CL_CreateVisibleEntity( ET_NORMAL, &hit );
}
#endif
*/
/*
void ParticleCallback( struct particle_s *particle, float frametime )
{
int i;
for ( i = 0; i < 3; i++ )
{
particle->org[ i ] += particle->vel[ i ] * frametime;
}
}
cvar_t *color = NULL;
void Particles( void )
{
static float lasttime;
float curtime;
curtime = gEngfuncs.GetClientTime();
if ( ( curtime - lasttime ) < 2.0 )
return;
if ( !color )
{
color = gEngfuncs.pfnRegisterVariable ( "color","255 0 0", 0 );
}
lasttime = curtime;
// Create a few particles
particle_t *p;
int i, j;
for ( i = 0; i < 1000; i++ )
{
int r, g, b;
p = gEngfuncs.pEfxAPI->R_AllocParticle( ParticleCallback );
if ( !p )
break;
for ( j = 0; j < 3; j++ )
{
p->org[ j ] = v_origin[ j ] + gEngfuncs.pfnRandomFloat( -32.0, 32.0 );;
p->vel[ j ] = gEngfuncs.pfnRandomFloat( -100.0, 100.0 );
}
if ( color )
{
sscanf( color->string, "%i %i %i", &r, &g, &b );
}
else
{
r = 192;
g = 0;
b = 0;
}
p->color = gEngfuncs.pEfxAPI->R_LookupColor( r, g, b );
gEngfuncs.pEfxAPI->R_GetPackedColor( &p->packedColor, p->color );
// p->die is set to current time so all you have to do is add an additional time to it
p->die += 3.0;
}
}
*/
/*
void TempEntCallback ( struct tempent_s *ent, float frametime, float currenttime )
{
int i;
for ( i = 0; i < 3; i++ )
{
ent->entity.curstate.origin[ i ] += ent->entity.baseline.origin[ i ] * frametime;
}
}
void TempEnts( void )
{
static float lasttime;
float curtime;
curtime = gEngfuncs.GetClientTime();
if ( ( curtime - lasttime ) < 10.0 )
return;
lasttime = curtime;
TEMPENTITY *p;
int i, j;
struct model_s *mod;
vec3_t origin;
int index;
mod = gEngfuncs.CL_LoadModel( "sprites/laserdot.spr", &index );
for ( i = 0; i < 100; i++ )
{
for ( j = 0; j < 3; j++ )
{
origin[ j ] = v_origin[ j ];
if ( j != 2 )
{
origin[ j ] += 75;
}
}
p = gEngfuncs.pEfxAPI->CL_TentEntAllocCustom( (float *)&origin, mod, 0, TempEntCallback );
if ( !p )
break;
for ( j = 0; j < 3; j++ )
{
p->entity.curstate.origin[ j ] = origin[ j ];
// Store velocity in baseline origin
p->entity.baseline.origin[ j ] = gEngfuncs.pfnRandomFloat( -100, 100 );
}
// p->die is set to current time so all you have to do is add an additional time to it
p->die += 10.0;
}
}
*/
#if defined( BEAM_TEST )
// Note can't index beam[ 0 ] in Beam callback, so don't use that index
// Room for 1 beam ( 0 can't be used )
static cl_entity_t beams[ 2 ];
void BeamEndModel( void )
{
cl_entity_t *player, *model;
int modelindex;
struct model_s *mod;
// Load it up with some bogus data
player = gEngfuncs.GetLocalPlayer();
if ( !player )
return;
mod = gEngfuncs.CL_LoadModel( "models/sentry3.mdl", &modelindex );
if ( !mod )
return;
// Slot 1
model = &beams[ 1 ];
*model = *player;
model->player = 0;
model->model = mod;
model->curstate.modelindex = modelindex;
// Move it out a bit
model->origin[0] = player->origin[0] - 100;
model->origin[1] = player->origin[1];
model->attachment[0] = model->origin;
model->attachment[1] = model->origin;
model->attachment[2] = model->origin;
model->attachment[3] = model->origin;
gEngfuncs.CL_CreateVisibleEntity( ET_NORMAL, model );
}
void Beams( void )
{
static float lasttime;
float curtime;
struct model_s *mod;
int index;
BeamEndModel();
curtime = gEngfuncs.GetClientTime();
float end[ 3 ];
if ( ( curtime - lasttime ) < 10.0 )
return;
mod = gEngfuncs.CL_LoadModel( "sprites/laserbeam.spr", &index );
if ( !mod )
return;
lasttime = curtime;
end [ 0 ] = v_origin.x + 100;
end [ 1 ] = v_origin.y + 100;
end [ 2 ] = v_origin.z;
BEAM *p1;
p1 = gEngfuncs.pEfxAPI->R_BeamEntPoint( -1, end, index,
10.0, 2.0, 0.3, 1.0, 5.0, 0.0, 1.0, 1.0, 1.0, 1.0 );
}
#endif
/*
=========================
HUD_CreateEntities
Gives us a chance to add additional entities to the render this frame
=========================
*/
void DLLEXPORT HUD_CreateEntities( void )
{
// e.g., create a persistent cl_entity_t somewhere.
// Load an appropriate model into it ( gEngfuncs.CL_LoadModel )
// Call gEngfuncs.CL_CreateVisibleEntity to add it to the visedicts list
/*
#if defined( TEST_IT )
MoveModel();
#endif
#if defined( TRACE_TEST )
TraceModel();
#endif
*/
/*
Particles();
*/
/*
TempEnts();
*/
#if defined( BEAM_TEST )
Beams();
#endif
// Add in any game specific objects
Game_AddObjects();
GetClientVoiceMgr()->CreateEntities();
}
/*
=========================
HUD_StudioEvent
The entity's studio model description indicated an event was
fired during this frame, handle the event by it's tag ( e.g., muzzleflash, sound )
=========================
*/
void DLLEXPORT HUD_StudioEvent( const struct mstudioevent_s *event, const struct cl_entity_s *entity )
{
switch( event->event )
{
case 5001:
gEngfuncs.pEfxAPI->R_MuzzleFlash( (float *)&entity->attachment[0], atoi( event->options) );
break;
case 5011:
gEngfuncs.pEfxAPI->R_MuzzleFlash( (float *)&entity->attachment[1], atoi( event->options) );
break;
case 5021:
gEngfuncs.pEfxAPI->R_MuzzleFlash( (float *)&entity->attachment[2], atoi( event->options) );
break;
case 5031:
gEngfuncs.pEfxAPI->R_MuzzleFlash( (float *)&entity->attachment[3], atoi( event->options) );
break;
case 5002:
gEngfuncs.pEfxAPI->R_SparkEffect( (float *)&entity->attachment[0], atoi( event->options), -100, 100 );
break;
// Client side sound
case 5004:
gEngfuncs.pfnPlaySoundByNameAtLocation( (char *)event->options, 1.0, (float *)&entity->attachment[0] );
break;
default:
break;
}
}
/*
=================
CL_UpdateTEnts
Simulation and cleanup of temporary entities
=================
*/
void DLLEXPORT HUD_TempEntUpdate (
double frametime, // Simulation time
double client_time, // Absolute time on client
double cl_gravity, // True gravity on client
TEMPENTITY **ppTempEntFree, // List of freed temporary ents
TEMPENTITY **ppTempEntActive, // List
int ( *Callback_AddVisibleEntity )( cl_entity_t *pEntity ),
void ( *Callback_TempEntPlaySound )( TEMPENTITY *pTemp, float damp ) )
{
static int gTempEntFrame = 0;
int i;
TEMPENTITY *pTemp, *pnext, *pprev;
float freq, gravity, gravitySlow, life, fastFreq;
// Nothing to simulate
if ( !*ppTempEntActive )
return;
// in order to have tents collide with players, we have to run the player prediction code so
// that the client has the player list. We run this code once when we detect any COLLIDEALL
// tent, then set this BOOL to true so the code doesn't get run again if there's more than
// one COLLIDEALL ent for this update. (often are).
gEngfuncs.pEventAPI->EV_SetUpPlayerPrediction( false, true );
// Store off the old count
gEngfuncs.pEventAPI->EV_PushPMStates();
// Now add in all of the players.
gEngfuncs.pEventAPI->EV_SetSolidPlayers ( -1 );
// !!!BUGBUG -- This needs to be time based
gTempEntFrame = (gTempEntFrame+1) & 31;
pTemp = *ppTempEntActive;
// !!! Don't simulate while paused.... This is sort of a hack, revisit.
if ( frametime <= 0 )
{
while ( pTemp )
{
if ( !(pTemp->flags & FTENT_NOMODEL ) )
{
Callback_AddVisibleEntity( &pTemp->entity );
}
pTemp = pTemp->next;
}
goto finish;
}
pprev = NULL;
freq = client_time * 0.01;
fastFreq = client_time * 5.5;
gravity = -frametime * cl_gravity;
gravitySlow = gravity * 0.5;
while ( pTemp )
{
int active;
active = 1;
life = pTemp->die - client_time;
pnext = pTemp->next;
if ( life < 0 )
{
if ( pTemp->flags & FTENT_FADEOUT )
{
if (pTemp->entity.curstate.rendermode == kRenderNormal)
pTemp->entity.curstate.rendermode = kRenderTransTexture;
pTemp->entity.curstate.renderamt = pTemp->entity.baseline.renderamt * ( 1 + life * pTemp->fadeSpeed );
if ( pTemp->entity.curstate.renderamt <= 0 )
active = 0;
}
else
active = 0;
}
if ( !active ) // Kill it
{
pTemp->next = *ppTempEntFree;
*ppTempEntFree = pTemp;
if ( !pprev ) // Deleting at head of list
*ppTempEntActive = pnext;
else
pprev->next = pnext;
}
else
{
pprev = pTemp;
VectorCopy( pTemp->entity.origin, pTemp->entity.prevstate.origin );
if ( pTemp->flags & FTENT_SPARKSHOWER )
{
// Adjust speed if it's time
// Scale is next think time
if ( client_time > pTemp->entity.baseline.scale )
{
// Show Sparks
gEngfuncs.pEfxAPI->R_SparkEffect( pTemp->entity.origin, 8, -200, 200 );
// Reduce life
pTemp->entity.baseline.framerate -= 0.1;
if ( pTemp->entity.baseline.framerate <= 0.0 )
{
pTemp->die = client_time;
}
else
{
// So it will die no matter what
pTemp->die = client_time + 0.5;
// Next think
pTemp->entity.baseline.scale = client_time + 0.1;
}
}
}
else if ( pTemp->flags & FTENT_PLYRATTACHMENT )
{
cl_entity_t *pClient;
pClient = gEngfuncs.GetEntityByIndex( pTemp->clientIndex );
VectorAdd( pClient->origin, pTemp->tentOffset, pTemp->entity.origin );
}
else if ( pTemp->flags & FTENT_SINEWAVE )
{
pTemp->x += pTemp->entity.baseline.origin[0] * frametime;
pTemp->y += pTemp->entity.baseline.origin[1] * frametime;
pTemp->entity.origin[0] = pTemp->x + sin( pTemp->entity.baseline.origin[2] + client_time * pTemp->entity.prevstate.frame ) * (10*pTemp->entity.curstate.framerate);
pTemp->entity.origin[1] = pTemp->y + sin( pTemp->entity.baseline.origin[2] + fastFreq + 0.7 ) * (8*pTemp->entity.curstate.framerate);
pTemp->entity.origin[2] += pTemp->entity.baseline.origin[2] * frametime;
}
else if ( pTemp->flags & FTENT_SPIRAL )
{
float s, c;
s = sin( pTemp->entity.baseline.origin[2] + fastFreq );
c = cos( pTemp->entity.baseline.origin[2] + fastFreq );
pTemp->entity.origin[0] += pTemp->entity.baseline.origin[0] * frametime + 8 * sin( client_time * 20 + (int)pTemp );
pTemp->entity.origin[1] += pTemp->entity.baseline.origin[1] * frametime + 4 * sin( client_time * 30 + (int)pTemp );
pTemp->entity.origin[2] += pTemp->entity.baseline.origin[2] * frametime;
}
else
{
for ( i = 0; i < 3; i++ )
pTemp->entity.origin[i] += pTemp->entity.baseline.origin[i] * frametime;
}
if ( pTemp->flags & FTENT_SPRANIMATE )
{
pTemp->entity.curstate.frame += frametime * pTemp->entity.curstate.framerate;
if ( pTemp->entity.curstate.frame >= pTemp->frameMax )
{
pTemp->entity.curstate.frame = pTemp->entity.curstate.frame - (int)(pTemp->entity.curstate.frame);
if ( !(pTemp->flags & FTENT_SPRANIMATELOOP) )
{
// this animating sprite isn't set to loop, so destroy it.
pTemp->die = client_time;
pTemp = pnext;
continue;
}
}
}
else if ( pTemp->flags & FTENT_SPRCYCLE )
{
pTemp->entity.curstate.frame += frametime * 10;
if ( pTemp->entity.curstate.frame >= pTemp->frameMax )
{
pTemp->entity.curstate.frame = pTemp->entity.curstate.frame - (int)(pTemp->entity.curstate.frame);
}
}
// Experiment
#if 0
if ( pTemp->flags & FTENT_SCALE )
pTemp->entity.curstate.framerate += 20.0 * (frametime / pTemp->entity.curstate.framerate);
#endif
if ( pTemp->flags & FTENT_ROTATE )
{
pTemp->entity.angles[0] += pTemp->entity.baseline.angles[0] * frametime;
pTemp->entity.angles[1] += pTemp->entity.baseline.angles[1] * frametime;
pTemp->entity.angles[2] += pTemp->entity.baseline.angles[2] * frametime;
VectorCopy( pTemp->entity.angles, pTemp->entity.latched.prevangles );
}
if ( pTemp->flags & (FTENT_COLLIDEALL | FTENT_COLLIDEWORLD) )
{
vec3_t traceNormal;
float traceFraction = 1;
if ( pTemp->flags & FTENT_COLLIDEALL )
{
pmtrace_t pmtrace;
physent_t *pe;
gEngfuncs.pEventAPI->EV_SetTraceHull( 2 );
gEngfuncs.pEventAPI->EV_PlayerTrace( pTemp->entity.prevstate.origin, pTemp->entity.origin, PM_STUDIO_BOX, -1, &pmtrace );
if ( pmtrace.fraction != 1 )
{
pe = gEngfuncs.pEventAPI->EV_GetPhysent( pmtrace.ent );
if ( !pmtrace.ent || ( pe->info != pTemp->clientIndex ) )
{
traceFraction = pmtrace.fraction;
VectorCopy( pmtrace.plane.normal, traceNormal );
if ( pTemp->hitcallback )
{
(*pTemp->hitcallback)( pTemp, &pmtrace );
}
}
}
}
else if ( pTemp->flags & FTENT_COLLIDEWORLD )
{
pmtrace_t pmtrace;
gEngfuncs.pEventAPI->EV_SetTraceHull( 2 );
gEngfuncs.pEventAPI->EV_PlayerTrace( pTemp->entity.prevstate.origin, pTemp->entity.origin, PM_STUDIO_BOX | PM_WORLD_ONLY, -1, &pmtrace );
if ( pmtrace.fraction != 1 )
{
traceFraction = pmtrace.fraction;
VectorCopy( pmtrace.plane.normal, traceNormal );
if ( pTemp->flags & FTENT_SPARKSHOWER )
{
// Chop spark speeds a bit more
//
VectorScale( pTemp->entity.baseline.origin, 0.6, pTemp->entity.baseline.origin );
if ( Length( pTemp->entity.baseline.origin ) < 10 )
{
pTemp->entity.baseline.framerate = 0.0;
}
}
if ( pTemp->hitcallback )
{
(*pTemp->hitcallback)( pTemp, &pmtrace );
}
}
}
if ( traceFraction != 1 ) // Decent collision now, and damping works
{
float proj, damp;
// Place at contact point
VectorMA( pTemp->entity.prevstate.origin, traceFraction*frametime, pTemp->entity.baseline.origin, pTemp->entity.origin );
// Damp velocity
damp = pTemp->bounceFactor;
if ( pTemp->flags & (FTENT_GRAVITY|FTENT_SLOWGRAVITY) )
{
damp *= 0.5;
if ( traceNormal[2] > 0.9 ) // Hit floor?
{
if ( pTemp->entity.baseline.origin[2] <= 0 && pTemp->entity.baseline.origin[2] >= gravity*3 )
{
damp = 0; // Stop
pTemp->flags &= ~(FTENT_ROTATE|FTENT_GRAVITY|FTENT_SLOWGRAVITY|FTENT_COLLIDEWORLD|FTENT_SMOKETRAIL);
pTemp->entity.angles[0] = 0;
pTemp->entity.angles[2] = 0;
}
}
}
if (pTemp->hitSound)
{
Callback_TempEntPlaySound(pTemp, damp);
}
if (pTemp->flags & FTENT_COLLIDEKILL)
{
// die on impact
pTemp->flags &= ~FTENT_FADEOUT;
pTemp->die = client_time;
}
else
{
// Reflect velocity
if ( damp != 0 )
{
proj = DotProduct( pTemp->entity.baseline.origin, traceNormal );
VectorMA( pTemp->entity.baseline.origin, -proj*2, traceNormal, pTemp->entity.baseline.origin );
// Reflect rotation (fake)
pTemp->entity.angles[1] = -pTemp->entity.angles[1];
}
if ( damp != 1 )
{
VectorScale( pTemp->entity.baseline.origin, damp, pTemp->entity.baseline.origin );
VectorScale( pTemp->entity.angles, 0.9, pTemp->entity.angles );
}
}
}
}
if ( (pTemp->flags & FTENT_FLICKER) && gTempEntFrame == pTemp->entity.curstate.effects )
{
dlight_t *dl = gEngfuncs.pEfxAPI->CL_AllocDlight (0);
VectorCopy (pTemp->entity.origin, dl->origin);
dl->radius = 60;
dl->color.r = 255;
dl->color.g = 120;
dl->color.b = 0;
dl->die = client_time + 0.01;
}
if ( pTemp->flags & FTENT_SMOKETRAIL )
{
gEngfuncs.pEfxAPI->R_RocketTrail (pTemp->entity.prevstate.origin, pTemp->entity.origin, 1);
}
if ( pTemp->flags & FTENT_GRAVITY )
pTemp->entity.baseline.origin[2] += gravity;
else if ( pTemp->flags & FTENT_SLOWGRAVITY )
pTemp->entity.baseline.origin[2] += gravitySlow;
if ( pTemp->flags & FTENT_CLIENTCUSTOM )
{
if ( pTemp->callback )
{
( *pTemp->callback )( pTemp, frametime, client_time );
}
}
// Cull to PVS (not frustum cull, just PVS)
if ( !(pTemp->flags & FTENT_NOMODEL ) )
{
if ( !Callback_AddVisibleEntity( &pTemp->entity ) )
{
if ( !(pTemp->flags & FTENT_PERSIST) )
{
pTemp->die = client_time; // If we can't draw it this frame, just dump it.
pTemp->flags &= ~FTENT_FADEOUT; // Don't fade out, just die
}
}
}
}
pTemp = pnext;
}
finish:
// Restore state info
gEngfuncs.pEventAPI->EV_PopPMStates();
}
/*
=================
HUD_GetUserEntity
If you specify negative numbers for beam start and end point entities, then
the engine will call back into this function requesting a pointer to a cl_entity_t
object that describes the entity to attach the beam onto.
Indices must start at 1, not zero.
=================
*/
cl_entity_t DLLEXPORT *HUD_GetUserEntity( int index )
{
#if defined( BEAM_TEST )
// None by default, you would return a valic pointer if you create a client side
// beam and attach it to a client side entity.
if ( index > 0 && index <= 1 )
{
return &beams[ index ];
}
else
{
return NULL;
}
#else
return NULL;
#endif
}
| [
"joropito@23c7d628-c96c-11de-a380-73d83ba7c083"
] | [
[
[
1,
977
]
]
] |
982146215b0fc150c902593c18e01aa6ecdcf352 | c2a70374051ef8f96105d65c84023d97c90f4806 | /bin/src/loadBmp/common/plbmpenc.cpp | 270d44da86a135c0bc88652c8639136be2894868 | [] | no_license | haselab-net/SpringheadOne | dcf6f10cb1144b17790a782f519ae25cbe522bb2 | 004335b64ec7bea748ae65a85463c0e85b98edbd | refs/heads/master | 2023-08-04T20:27:17.158435 | 2006-04-15T16:49:35 | 2006-04-15T16:49:35 | 407,701,182 | 1 | 0 | null | null | null | null | MacCentralEurope | C++ | false | false | 5,310 | cpp | /*
/--------------------------------------------------------------------
|
| Windows bitmap file encoder. Encodes 1, 4, 8, 24 and 32 bpp
| bitmaps to a 1, 4, 8 or 24 bpp uncompressed BMP file
|
| Copyright (c) 1996-2002 Ulrich von Zadow
|
\--------------------------------------------------------------------
*/
#include "plstdpch.h"
#include "plbmpenc.h"
#include "plwindefs.h"
#include "plexcept.h"
/////////////////////////////////////////////////////////////////////
// Class functions
PLBmpEncoder::PLBmpEncoder
() : PLPicEncoder()
// Creates an encoder
{
// nothing to do (yet)
}
PLBmpEncoder::~PLBmpEncoder
()
{
// nothing to do (yet)
}
int PLBmpEncoder::GetLineMemNeeded (PLLONG width, PLWORD BitsPerPixel)
{
// Calculate memory per line.
int LineMem = width * BitsPerPixel / 8;
if (BitsPerPixel == 1 && width % 8)
++LineMem;
// DWORD alignment
return ((LineMem + 3) & ~3);
}
void PLBmpEncoder::DoEncode
( PLBmp * pBmp,
PLDataSink * pSink
)
{
int BPP = pBmp->GetBitsPerPixel();
WINBITMAPFILEHEADER BFH;
BFH.bfType = *((PLWORD*)"BM");
BFH.bfReserved1 = 0;
BFH.bfReserved2 = 0;
BFH.bfOffBits = sizeof (WINBITMAPFILEHEADER) +
sizeof (WINBITMAPINFOHEADER);
if (BPP <= 8) // include palette
BFH.bfOffBits += (1 << BPP) * sizeof(WINRGBQUAD);
BFH.bfSize = BFH.bfOffBits;
BFH.bfSize += pBmp->GetHeight()*GetLineMemNeeded(pBmp->GetWidth(), BPP);
pSink->WriteNBytes( sizeof (WINBITMAPFILEHEADER), (PLBYTE *) &BFH);
WINBITMAPINFOHEADER FileBMI;
FileBMI.biSize = sizeof(WINBITMAPINFOHEADER);
FileBMI.biWidth = pBmp->GetWidth ();
FileBMI.biHeight = pBmp->GetHeight ();
FileBMI.biPlanes = 1;
FileBMI.biCompression = BI_RGB;
FileBMI.biSizeImage = 0; // may be 0 for non-compressed files
FileBMI.biXPelsPerMeter = (int)((float)pBmp->GetResolution().x * 39.37f+0.5);
FileBMI.biYPelsPerMeter = (int)((float)pBmp->GetResolution().y * 39.37f+0.5);
FileBMI.biClrUsed = 0;
FileBMI.biClrImportant = 0;
int x,y;
if (BPP <= 8)
{
PLBYTE * pCurLine;
FileBMI.biBitCount = BPP; // not 32...
pSink->WriteNBytes (sizeof (WINBITMAPINFOHEADER), (PLBYTE *) &FileBMI);
// Write Palette
PLPixel32 * pPal = pBmp->GetPalette();
for (int i=0; i<(1<<BPP); i++)
{
pSink->WriteByte (pPal[i].GetB());
pSink->WriteByte (pPal[i].GetG());
pSink->WriteByte (pPal[i].GetR());
pSink->WriteByte (pPal[i].GetA());
}
for (y=FileBMI.biHeight-1; y>=0; y--)
{
pCurLine = pBmp->GetLineArray()[y];
pSink->WriteNBytes (pBmp->GetBytesPerLine(), pCurLine);
int PadBytes = GetLineMemNeeded(pBmp->GetWidth(), BPP)
- pBmp->GetBytesPerLine();
pSink->Skip(PadBytes);
}
}
else
{
PLPixel32 * pCurLine;
FileBMI.biBitCount = 24; // not 32...
pSink->WriteNBytes (sizeof (WINBITMAPINFOHEADER),(PLBYTE *) &FileBMI);
int LinePadding = 4-((FileBMI.biWidth*3)&3);
if (LinePadding == 4)
LinePadding = 0;
for (y=FileBMI.biHeight-1; y>=0; y--)
{
pCurLine = pBmp->GetLineArray32()[y];
for (x=0; x<FileBMI.biWidth; x++)
{
pSink->WriteByte (pCurLine[x].GetB());
pSink->WriteByte (pCurLine[x].GetG());
pSink->WriteByte (pCurLine[x].GetR());
}
pSink->WriteNBytes(LinePadding,(PLBYTE *) " ");
}
}
}
/*
/--------------------------------------------------------------------
|
| $Log: /Project/Springhead/bin/src/loadBmp/common/plbmpenc.cpp $
*
* 1 04/07/12 13:34 Hase
| Revision 1.7 2002/03/31 13:36:41 uzadow
| Updated copyright.
|
| Revision 1.6 2001/10/21 17:12:39 uzadow
| Added PSD decoder beta, removed BPPWanted from all decoders, added PLFilterPixel.
|
| Revision 1.5 2001/10/16 17:12:26 uzadow
| Added support for resolution information (Luca Piergentili)
|
| Revision 1.4 2001/10/06 22:37:08 uzadow
| Linux compatibility.
|
| Revision 1.3 2001/10/06 22:03:26 uzadow
| Added PL prefix to basic data types.
|
| Revision 1.2 2001/10/06 20:44:45 uzadow
| Linux compatibility
|
| Revision 1.1 2001/09/16 19:03:22 uzadow
| Added global name prefix PL, changed most filenames.
|
| Revision 1.8 2001/02/04 14:31:52 uzadow
| Member initialization list cleanup (Erik Hoffmann).
|
| Revision 1.7 2000/12/02 19:52:12 uzadow
| no message
|
| Revision 1.6 2000/12/02 19:50:01 uzadow
| Added Logging.
|
| 31.10.2000 - Josť Miguel Buenaposada
| Corrected the order for writing color channels
| to work with other channels orders.
|
| 27.08.2000 - Martin Skinner
| now uses PLDataSink instead of MFC CFile
| moved to a new class PLBmpEncoder
|
| 11.01.2000 - Michael Salzlechner
| moved code from PLWinBmp to CAfxBmp
|
| 21.01.99 - Added by M.Skinner
| Moved program logic from
| PLWinBmp::SaveAsBmp(const char *) to here
|
\--------------------------------------------------------------------
*/
| [
"jumius@05cee5c3-a2e9-0310-9523-9dfc2f93dbe1"
] | [
[
[
1,
183
]
]
] |
5afbd91665c69e9be74e3d503819091da3d3b46d | 1736474d707f5c6c3622f1cd370ce31ac8217c12 | /Pseudo/CountedPtr.hpp | 9e70ceb5606094e3b1aaeeb590a255cb445a9eef | [] | no_license | arlm/pseudo | 6d7450696672b167dd1aceec6446b8ce137591c0 | 27153e50003faff31a3212452b1aec88831d8103 | refs/heads/master | 2022-11-05T23:38:08.214807 | 2011-02-18T23:18:36 | 2011-02-18T23:18:36 | 275,132,368 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,249 | hpp | // Copyright (c) John Lyon-Smith. All rights reserved.
#pragma once
#include <Pseudo\AutoPtr.hpp>
namespace Pseudo
{
// A class for counted pointer semantics, i.e. it deletes the object to which it
// refers when the last CountedPtr that refers to it is destroyed
template <class T> class CountedPtr
{
private: T* p;
// pointer to the value
private: Int* pCount;
// shared number of owners. It's a pointer because everyone's got to be looking at the same reference!
public: typedef T ElementType;
public: template <class Y> friend class CountedPtr;
// Initialize pointer with existing pointer - requires that the pointer p is a return value of new
public: explicit CountedPtr (T* pOther = 0)
{
p = pOther;
pCount = (pOther != NULL ? PSEUDO_NEW Int(1) : NULL);
}
// copy pointer (one more owner)
public: CountedPtr (CountedPtr<T> const & pOther) : p(pOther.p), pCount(pOther.pCount)
{
++*pCount;
}
public: template<class Y> CountedPtr(CountedPtr<Y> const & p) : p(pOther.p), pCount(p.pCount)
{
++*pCount;
}
public: template<class Y> CountedPtr(AutoPtr<Y> & pOther) : p(pOther.Release()), pCount(PSEUDO_NEW Int(1))
{
}
// destructor (delete value if this was the last owner)
public: ~CountedPtr ()
{
Dispose();
}
// assignment (unshare old and share new value)
public: CountedPtr<T>& operator= (CountedPtr<T> const & pOther)
{
if (this != &pOther)
{
Dispose();
p = pOther.p;
pCount = pOther.pCount;
++*pCount;
}
return *this;
}
// access the value to which the pointer refers
public: T* get_Ptr() const
{
return p;
}
public: T& operator*() const
{
return *p;
}
public: T* operator->() const
{
return p;
}
public: bool operator==(CountedPtr<T> const & pOther)
{
return p == pOther.p;
}
public: bool operator!=(CountedPtr<T> const & pOther)
{
return !(this == pOther);
}
private: void Dispose()
{
if (pCount != NULL && --*pCount == 0)
{
delete pCount;
delete p;
}
}
};
}
| [
"[email protected]"
] | [
[
[
1,
98
]
]
] |
5867a0b2954da4b3be44c629233496bbfabc7bd7 | 8f5d0d23e857e58ad88494806bc60c5c6e13f33d | /Network/cServer.cpp | d73dbbf000da5834578783867f01a4a56206c057 | [] | no_license | markglenn/projectlife | edb14754118ec7b0f7d83bd4c92b2e13070dca4f | a6fd3502f2c2713a8a1a919659c775db5309f366 | refs/heads/master | 2021-01-01T15:31:30.087632 | 2011-01-30T16:03:41 | 2011-01-30T16:03:41 | 1,704,290 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 87 | cpp | #include "cserver.h"
cServer::cServer(void)
{
}
cServer::~cServer(void)
{
}
| [
"[email protected]"
] | [
[
[
1,
9
]
]
] |
5809a04167e682928298ab9ac2fa7ecd42585c7f | 9773c3304eecc308671bcfa16b5390c81ef3b23a | /MDI AIPI V.6.92 2003 ( Correct Save Fired Rules, AM =-1, g_currentLine)/AIPI/AIPI_Engine/Aipi_RETE_TK.h | 81dbeb0e8cd537c6c762ffd62ca0aa076e8210b1 | [] | no_license | 15831944/AiPI-1 | 2d09d6e6bd3fa104d0175cf562bb7826e1ac5ec4 | 9350aea6ac4c7870b43d0a9f992a1908a3c1c4a8 | refs/heads/master | 2021-12-02T20:34:03.136125 | 2011-10-27T00:07:54 | 2011-10-27T00:07:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,108 | h | // Aipi_RETE_TK.h: interface for the CAipi_RETE_TK class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_AIPI_RETE_TK_H__45B40ADC_D670_478D_A69D_22F6BE5354E0__INCLUDED_)
#define AFX_AIPI_RETE_TK_H__45B40ADC_D670_478D_A69D_22F6BE5354E0__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
//// Tokens (TK)
/*
This class represents the Tokens of the Beta Memory.
Tokens are Working Memory elements linked that are inside the Beta Memory
*** Symbols ***
TK = Token
AM = Alpha Memory
BM = Beta Memory
WM = Working Memory
PM = Production Memory
Cond = Condition
I = Identifier (Id)
A = Atribute (Attr)
V = Value (Val)
e = Don`t care
ParentTK = Parent Token
ChildTK = Child Token
*** Function Parameters ***
am = Alpha Memory
bm = Beta Memory
wm = Working Memory
pm = Production Memory
lhs = Left Hand Side Function
cond = Condition
*/
class CAipi_RETE_TK
{
public:
CAipi_RETE_TK();
virtual ~CAipi_RETE_TK();
//Child token is the index of the structure
CAipi_RETE_TK(int parent_tk, int wm, int bm, int sign)
{
m_ParentTk = parent_tk;
m_WM = wm;
m_BM = bm;
m_Sign = sign;
}
inline void CAipi_RETE_TK::setParentTk(int parent_tk)
{
m_ParentTk = parent_tk;
}
inline void CAipi_RETE_TK::setWM(int wm)
{
m_WM = wm;
}
inline void CAipi_RETE_TK::setBM(int bm)
{
m_BM = bm;
}
inline void CAipi_RETE_TK::setSign(int sign)
{
m_Sign = sign;
}
inline int CAipi_RETE_TK::getWM()
{
return m_WM;
}
inline int CAipi_RETE_TK::getBM()
{
return m_BM;
}
inline int CAipi_RETE_TK::getParentTk()
{
return m_ParentTk;
}
inline int CAipi_RETE_TK::getSign()
{
return m_Sign;
}
public:
CAipi_RETE_TK* createTK(int child_tk, int parent_tk, int wm, int bm, int sign);
void addWM_ParentTK(int wm, int parent_tk);
void addWM_ChildTK(int wm, int child_tk);
void addTKParent_TKChild(int parent,int child);
void addTKParent_TKLink(int parent,int link);
void createTKParent_TKLink();
void createTKParent_TKLinkE(int parent_tk);
void fillTK();
void eraseTK(int child_tk);
//Deletes all tokens linked with the parent token
void eraseParent_TKParent_TKLink(int parent_tk);
//Deletes all tokens linked with the child token
int eraseChild_TKParent_TKLink(int child_tk);
void eraseParent_TKParent_TKChild(int parent_tk);
int eraseChild_TKParent_TKChild(int child_tk);
int eraseItemTKParent_TKChild(int parent_tk,int child_tk);
void eraseWMParentTK(int wme);
void eraseWMChildTK(int wme);
int eraseWMParentTKE(int wme, int parent_tk);
int eraseWMChildTKE(int wme, int child_tk);
int eraseWMParentTokenE(int w, int parent_tk);
int eraseWMChildTokenE(int w, int child_tk);
void clearTK();
void clearTKParent_TKLink();
void clearTKParent_TKChild();
void clearWM_ParentTK();
void clearWM_ChildTK();
void clearTKStructs();
int generateTKKey();
int findTKMembers(int child_tk);
int findParentTk(int child_tk);
int findSign(int child_tk);
int findBM(int child_tk);
int findWM(int child_tk);
int findWMParentTK(int tk);
int findWM_ParentTK(int wm);
int findWM_ChildTK(int wm);
int findChild_TKParent_TKChild(int parent_tk);
tstring linkWMEs(int tk);
int searchTKWM(int wm);
int searchTKChildTK(int parent_tk);
int countWM(int wm);
int countWM_ParentTK(int wm);
int countWM_ChildTK(int wm);
int countParentTK(int parent_tk);
int countChildTK(int child_tk);
void printTK();
void printLinkTK();
void printWM_ParentTK();
void printWM_ChildTK();
void printTKParent_TKChild();
void printTKParent_TKLink();
public:
int m_WM;
int m_BM;
int m_ParentTk;
int m_Sign;
};
#endif // !defined(AFX_AIPI_RETE_TK_H__45B40ADC_D670_478D_A69D_22F6BE5354E0__INCLUDED_)
| [
"[email protected]"
] | [
[
[
1,
211
]
]
] |
182c508263488900521f501985ab4e94652ed14b | d37a1d5e50105d82427e8bf3642ba6f3e56e06b8 | /DVR/HaohanITPlayer/public/Common/SysUtils/Seconds.cpp | 0948dcd033a6517172a9b6639dcd4263dcbdcc3b | [] | 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 | UTF-8 | C++ | false | false | 1,163 | cpp | //-----------------------------------------------------------------------------
// Seconds.cpp
// Copyright (c) 1997 - 2004, Haohanit. All rights reserved.
//-----------------------------------------------------------------------------
//SR FS: Reviewed [JAW 20040912]
//SR FS: Reviewed [wwt 20040914]
#include "Seconds.h"
#include "time_utils.h"
//----------------------------------------------------------------------
// Seconds::Seconds typical (and can be default) constructor
//----------------------------------------------------------------------
Seconds::Seconds(double inSeconds, double inEpsilon)
: FuzzyTime(inSeconds, inEpsilon)
{
}
Seconds::Seconds(const std::string &theString, tc_mode timecodePref)
: FuzzyTime(TCString2Seconds(theString, timecodePref))
{
}
void Seconds::GetTCString(std::string & theString, tc_mode timecodePref, bool showOddField /*= true*/) const
{
Seconds2TCString(*this, theString, timecodePref, showOddField);
}
void Seconds::ParseTCString(const std::string &theString, tc_mode timecodePref, bool *pOutSuccess)
{
*this = TCString2Seconds(theString, timecodePref, pOutSuccess);
}
| [
"[email protected]@27769579-7047-b306-4d6f-d36f87483bb3"
] | [
[
[
1,
33
]
]
] |
cb0751f00a8a3b3dbbf6d2a626ef481db34b6c5d | c2a70374051ef8f96105d65c84023d97c90f4806 | /bin/src/loadBmp/common/Filter/plfiltermirror.h | a00374a128c3f5ddbdb3cf23272d1f5c5524385f | [] | no_license | haselab-net/SpringheadOne | dcf6f10cb1144b17790a782f519ae25cbe522bb2 | 004335b64ec7bea748ae65a85463c0e85b98edbd | refs/heads/master | 2023-08-04T20:27:17.158435 | 2006-04-15T16:49:35 | 2006-04-15T16:49:35 | 407,701,182 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,528 | h | /*
/--------------------------------------------------------------------
|
| $Id: plfiltermirror.h,v 1.3 2004/06/15 10:26:13 uzadow Exp $
|
| Copyright (c) 1996-2002 Ulrich von Zadow
| Original code by Richard Hollis
|
\--------------------------------------------------------------------
*/
#ifndef INCL_PLFILTERMIRROR
#define INCL_PLFILTERMIRROR
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
#include "plfilter.h"
//! Creates a mirror image of a bitmap.
class PLFilterMirror: public PLFilter
{
public:
//!
PLFilterMirror();
//!
virtual ~PLFilterMirror();
//!
virtual void Apply(PLBmpBase * pBmpSource, PLBmp * pBmpDest) const;
protected:
};
#endif
/*
/--------------------------------------------------------------------
|
| $Log: /Project/Springhead/bin/src/loadBmp/common/Filter/plfiltermirror.h $
*
* 1 04/07/12 13:34 Hase
| Revision 1.3 2004/06/15 10:26:13 uzadow
| Initial nonfunctioning version of plbmpbase.
|
| Revision 1.2 2002/03/31 13:36:42 uzadow
| Updated copyright.
|
| Revision 1.1 2001/09/16 19:03:23 uzadow
| Added global name prefix PL, changed most filenames.
|
| Revision 1.2 2001/01/15 15:05:31 uzadow
| Added PLBmp::ApplyFilter() and PLBmp::CreateFilteredCopy()
|
| Revision 1.1 2001/01/13 20:06:16 uzadow
| Added Flip and Mirror filters.
|
|
|
\--------------------------------------------------------------------
*/
| [
"jumius@05cee5c3-a2e9-0310-9523-9dfc2f93dbe1"
] | [
[
[
1,
61
]
]
] |
e4b10b023fb6d5bcd17a2f4d19d6092bf5f37d75 | 1e5a2230acf1c2edfe8b9d226100438f9374e98a | /src/gecko-sdk/include/nsXPCOM.h | 8a4fbbbb0bf79998f51b02c5b0e3e57ed4785e57 | [] | no_license | lifanxi/tabimswitch | 258860fea291c935d3630abeb61436e20f5dcd09 | f351fc4b04983e59d1ad2b91b85e396e1f4920ed | refs/heads/master | 2020-05-20T10:53:41.990172 | 2008-10-15T11:15:41 | 2008-10-15T11:15:41 | 32,111,854 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,948 | h | /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** 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.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Benjamin Smedberg <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* either of 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 MPL, 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 MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef nsXPCOM_h__
#define nsXPCOM_h__
// Map frozen functions to private symbol names if not using strict API.
#ifdef MOZILLA_INTERNAL_API
# define NS_InitXPCOM2 NS_InitXPCOM2_P
# define NS_InitXPCOM3 NS_InitXPCOM3_P
# define NS_ShutdownXPCOM NS_ShutdownXPCOM_P
# define NS_GetServiceManager NS_GetServiceManager_P
# define NS_GetComponentManager NS_GetComponentManager_P
# define NS_GetComponentRegistrar NS_GetComponentRegistrar_P
# define NS_GetMemoryManager NS_GetMemoryManager_P
# define NS_NewLocalFile NS_NewLocalFile_P
# define NS_NewNativeLocalFile NS_NewNativeLocalFile_P
# define NS_GetDebug NS_GetDebug_P
# define NS_GetTraceRefcnt NS_GetTraceRefcnt_P
# define NS_Alloc NS_Alloc_P
# define NS_Realloc NS_Realloc_P
# define NS_Free NS_Free_P
#endif
#include "nscore.h"
#include "nsXPCOMCID.h"
class nsAString;
class nsACString;
class nsIModule;
class nsIComponentManager;
class nsIComponentRegistrar;
class nsIServiceManager;
class nsIFile;
class nsILocalFile;
class nsIDirectoryServiceProvider;
class nsIMemory;
class nsIDebug;
class nsITraceRefcnt;
/**
* Every XPCOM component implements this function signature, which is the
* only entrypoint XPCOM uses to the function.
*
* @status FROZEN
*/
typedef nsresult (PR_CALLBACK *nsGetModuleProc)(nsIComponentManager *aCompMgr,
nsIFile* location,
nsIModule** return_cobj);
/**
* Initialises XPCOM. You must call one of the NS_InitXPCOM methods
* before proceeding to use xpcom. The one exception is that you may
* call NS_NewLocalFile to create a nsIFile.
*
* @status FROZEN
*
* @note Use <CODE>NS_NewLocalFile</CODE> or <CODE>NS_NewNativeLocalFile</CODE>
* to create the file object you supply as the bin directory path in this
* call. The function may be safely called before the rest of XPCOM or
* embedding has been initialised.
*
* @param result The service manager. You may pass null.
*
* @param binDirectory The directory containing the component
* registry and runtime libraries;
* or use <CODE>nsnull</CODE> to use the working
* directory.
*
* @param appFileLocationProvider The object to be used by Gecko that specifies
* to Gecko where to find profiles, the component
* registry preferences and so on; or use
* <CODE>nsnull</CODE> for the default behaviour.
*
* @see NS_NewLocalFile
* @see nsILocalFile
* @see nsIDirectoryServiceProvider
*
* @return NS_OK for success;
* NS_ERROR_NOT_INITIALIZED if static globals were not initialized,
* which can happen if XPCOM is reloaded, but did not completly
* shutdown. Other error codes indicate a failure during
* initialisation.
*/
extern "C" NS_COM nsresult
NS_InitXPCOM2(nsIServiceManager* *result,
nsIFile* binDirectory,
nsIDirectoryServiceProvider* appFileLocationProvider);
/**
* Some clients of XPCOM have statically linked components (not dynamically
* loaded component DLLs), which can be passed to NS_InitXPCOM3 using this
* structure.
*
* @status FROZEN
*/
struct nsStaticModuleInfo {
const char *name;
nsGetModuleProc getModule;
};
/**
* Initialises XPCOM with static components. You must call one of the
* NS_InitXPCOM methods before proceeding to use xpcom. The one
* exception is that you may call NS_NewLocalFile to create a nsIFile.
*
* @status FROZEN
*
* @note Use <CODE>NS_NewLocalFile</CODE> or <CODE>NS_NewNativeLocalFile</CODE>
* to create the file object you supply as the bin directory path in this
* call. The function may be safely called before the rest of XPCOM or
* embedding has been initialised.
*
* @param result The service manager. You may pass null.
*
* @param binDirectory The directory containing the component
* registry and runtime libraries;
* or use <CODE>nsnull</CODE> to use the working
* directory.
*
* @param appFileLocationProvider The object to be used by Gecko that specifies
* to Gecko where to find profiles, the component
* registry preferences and so on; or use
* <CODE>nsnull</CODE> for the default behaviour.
*
* @param staticComponents An array of static components. Passing null causes
* default (builtin) components to be registered, if
* present.
* @param componentCount Number of elements in staticComponents
*
* @see NS_NewLocalFile
* @see nsILocalFile
* @see nsIDirectoryServiceProvider
* @see XRE_GetStaticComponents
*
* @return NS_OK for success;
* NS_ERROR_NOT_INITIALIZED if static globals were not initialized,
* which can happen if XPCOM is reloaded, but did not completly
* shutdown. Other error codes indicate a failure during
* initialisation.
*/
extern "C" NS_COM nsresult
NS_InitXPCOM3(nsIServiceManager* *result,
nsIFile* binDirectory,
nsIDirectoryServiceProvider* appFileLocationProvider,
nsStaticModuleInfo const *staticComponents,
PRUint32 componentCount);
/**
* Shutdown XPCOM. You must call this method after you are finished
* using xpcom.
*
* @status FROZEN
*
* @param servMgr The service manager which was returned by NS_InitXPCOM.
* This will release servMgr. You may pass null.
*
* @return NS_OK for success;
* other error codes indicate a failure during initialisation.
*
*/
extern "C" NS_COM nsresult
NS_ShutdownXPCOM(nsIServiceManager* servMgr);
/**
* Public Method to access to the service manager.
*
* @status FROZEN
* @param result Interface pointer to the service manager
*
* @return NS_OK for success;
* other error codes indicate a failure during initialisation.
*
*/
extern "C" NS_COM nsresult
NS_GetServiceManager(nsIServiceManager* *result);
/**
* Public Method to access to the component manager.
*
* @status FROZEN
* @param result Interface pointer to the service
*
* @return NS_OK for success;
* other error codes indicate a failure during initialisation.
*
*/
extern "C" NS_COM nsresult
NS_GetComponentManager(nsIComponentManager* *result);
/**
* Public Method to access to the component registration manager.
*
* @status FROZEN
* @param result Interface pointer to the service
*
* @return NS_OK for success;
* other error codes indicate a failure during initialisation.
*
*/
extern "C" NS_COM nsresult
NS_GetComponentRegistrar(nsIComponentRegistrar* *result);
/**
* Public Method to access to the memory manager. See nsIMemory
*
* @status FROZEN
* @param result Interface pointer to the memory manager
*
* @return NS_OK for success;
* other error codes indicate a failure during initialisation.
*
*/
extern "C" NS_COM nsresult
NS_GetMemoryManager(nsIMemory* *result);
/**
* Public Method to create an instance of a nsILocalFile. This function
* may be called prior to NS_InitXPCOM.
*
* @status FROZEN
*
* @param path
* A string which specifies a full file path to a
* location. Relative paths will be treated as an
* error (NS_ERROR_FILE_UNRECOGNIZED_PATH).
* |NS_NewNativeLocalFile|'s path must be in the
* filesystem charset.
* @param followLinks
* This attribute will determine if the nsLocalFile will auto
* resolve symbolic links. By default, this value will be false
* on all non unix systems. On unix, this attribute is effectively
* a noop.
* @param result Interface pointer to a new instance of an nsILocalFile
*
* @return NS_OK for success;
* other error codes indicate a failure.
*/
extern "C" NS_COM nsresult
NS_NewLocalFile(const nsAString &path,
PRBool followLinks,
nsILocalFile* *result);
extern "C" NS_COM nsresult
NS_NewNativeLocalFile(const nsACString &path,
PRBool followLinks,
nsILocalFile* *result);
/**
* Allocates a block of memory of a particular size. If the memory cannot
* be allocated (because of an out-of-memory condition), null is returned.
*
* @status FROZEN
*
* @param size The size of the block to allocate
* @result The block of memory
* @note This function is thread-safe.
*/
extern "C" NS_COM void*
NS_Alloc(PRSize size);
/**
* Reallocates a block of memory to a new size.
*
* @status FROZEN
*
* @param ptr The block of memory to reallocate. This block must originally
have been allocated by NS_Alloc or NS_Realloc
* @param size The new size. If 0, frees the block like NS_Free
* @result The reallocated block of memory
* @note This function is thread-safe.
*
* If ptr is null, this function behaves like NS_Alloc.
* If s is the size of the block to which ptr points, the first min(s, size)
* bytes of ptr's block are copied to the new block. If the allocation
* succeeds, ptr is freed and a pointer to the new block is returned. If the
* allocation fails, ptr is not freed and null is returned. The returned
* value may be the same as ptr.
*/
extern "C" NS_COM void*
NS_Realloc(void* ptr, PRSize size);
/**
* Frees a block of memory. Null is a permissible value, in which case no
* action is taken.
*
* @status FROZEN
*
* @param ptr The block of memory to free. This block must originally have
* been allocated by NS_Alloc or NS_Realloc
* @note This function is thread-safe.
*/
extern "C" NS_COM void
NS_Free(void* ptr);
/**
* Categories (in the category manager service) used by XPCOM:
*/
/**
* A category which is read after component registration but before
* the "xpcom-startup" notifications. Each category entry is treated
* as the contract ID of a service which implements
* nsIDirectoryServiceProvider. Each directory service provider is
* installed in the global directory service.
*
* @status FROZEN
*/
#define XPCOM_DIRECTORY_PROVIDER_CATEGORY "xpcom-directory-providers"
/**
* A category which is read after component registration but before
* NS_InitXPCOM returns. Each category entry is treated as the contractID of
* a service: each service is instantiated, and if it implements nsIObserver
* the nsIObserver.observe method is called with the "xpcom-startup" topic.
*
* @status FROZEN
*/
#define NS_XPCOM_STARTUP_CATEGORY "xpcom-startup"
/**
* Observer topics (in the observer service) used by XPCOM:
*/
/**
* At XPCOM startup after component registration is complete, the
* following topic is notified. In order to receive this notification,
* component must register their contract ID in the category manager,
*
* @see NS_XPCOM_STARTUP_CATEGORY
* @status FROZEN
*/
#define NS_XPCOM_STARTUP_OBSERVER_ID "xpcom-startup"
/**
* At XPCOM shutdown, this topic is notified. All components must
* release any interface references to objects in other modules when
* this topic is notified.
*
* @status FROZEN
*/
#define NS_XPCOM_SHUTDOWN_OBSERVER_ID "xpcom-shutdown"
/**
* This topic is notified when an entry was added to a category in the
* category manager. The subject of the notification will be the name of
* the added entry as an nsISupportsCString, and the data will be the
* name of the category.
*
* @status FROZEN
*/
#define NS_XPCOM_CATEGORY_ENTRY_ADDED_OBSERVER_ID \
"xpcom-category-entry-added"
/**
* This topic is notified when an entry was removed from a category in the
* category manager. The subject of the notification will be the name of
* the removed entry as an nsISupportsCString, and the data will be the
* name of the category.
*
* @status FROZEN
*/
#define NS_XPCOM_CATEGORY_ENTRY_REMOVED_OBSERVER_ID \
"xpcom-category-entry-removed"
/**
* This topic is notified when an a category was cleared in the category
* manager. The subject of the notification will be the category manager,
* and the data will be the name of the cleared category.
*
* @status FROZEN
*/
#define NS_XPCOM_CATEGORY_CLEARED_OBSERVER_ID "xpcom-category-cleared"
extern "C" NS_COM nsresult
NS_GetDebug(nsIDebug* *result);
extern "C" NS_COM nsresult
NS_GetTraceRefcnt(nsITraceRefcnt* *result);
#endif
| [
"ftofficer.zhangc@237747d1-5336-0410-8d3f-2982d197fc3e"
] | [
[
[
1,
421
]
]
] |
fdedc24fa25f06c8fb8054f402e6685804ee16d1 | ff24756dc4add027f5953a4954a4855d824a5a63 | /CheckBoxList.cpp | 5e9855d8b0dc4d8f02873202252bc2e5f787a91a | [] | no_license | weekydy/molt-asb-bigz-sont-dans-un-bateau | 640b4170b0ed9e07ca08641add9f57198bc2e8a6 | 2f116842bf604125ecbdd10226f79d0b085d0b4f | refs/heads/master | 2021-01-09T21:54:53.848431 | 2010-06-17T07:24:26 | 2010-06-17T07:24:26 | 55,782,366 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,016 | cpp | #include "CheckBoxList.h"
#include <QtGui>
// internal private delegate
class CheckBoxListDelegate : public QItemDelegate
{
public:
CheckBoxListDelegate(QObject *parent = 0) : QItemDelegate(parent){}
QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem &/* option */, const QModelIndex &/* index */) const
{
QCheckBox *editor = new QCheckBox(parent);
return editor;
}
void setEditorData(QWidget *editor, const QModelIndex &index) const
{
QCheckBox *checkBox = static_cast<QCheckBox*>(editor);
checkBox->setText(index.data(Qt::DisplayRole).toString());
checkBox->setChecked(index.data(Qt::UserRole).toBool());
}
/*
void setEditorData(QWidget *editor, const QModelIndex &index) const{
//set editor data
QCheckBox *checkBox = static_cast<QCheckBox*>(editor);
checkBox->setText(index.data(Qt::DisplayRole).toString());
checkBox->setChecked(index.data(Qt::UserRole).toBool());
}*/
void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
QCheckBox *checkBox = static_cast<QCheckBox*>(editor);
//spinBox->interpretText();
bool value = checkBox->isChecked();
QMap<int,QVariant> data;
data.insert(Qt::DisplayRole,checkBox->text());
data.insert(Qt::UserRole,value);
model->setItemData(index, data);
}
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const{
//Get item data
bool value = index.data(Qt::UserRole).toBool();
QString text = index.data(Qt::DisplayRole).toString();
// fill style options with item data
const QStyle *style = QApplication::style();
QStyleOptionButton opt;
opt.state |= value ? QStyle::State_On : QStyle::State_Off;
opt.state |= QStyle::State_Enabled;
opt.text = text;
opt.rect = option.rect;
// draw item data as CheckBox
style->drawControl(QStyle::CE_CheckBox,&opt,painter);
}
/*
void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
//get the value from the editor (CheckBox)
QCheckBox *myEditor = static_cast<QCheckBox*>(editor);
bool value = myEditor->isChecked();
//set model data
QMap<int,QVariant> data;
data.insert(Qt::DisplayRole,myEditor->text());
data.insert(Qt::UserRole,value);
model->setItemData(index,data);
}
*/
void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &/* index */) const
{
editor->setGeometry(option.rect);
}
};
/*
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
//Get item data
bool value = index.data(Qt::UserRole).toBool();
QString text = index.data(Qt::DisplayRole).toString();
// fill style options with item data
const QStyle *style = QApplication::style();
QStyleOptionButton opt;
opt.state |= value ? QStyle::State_On : QStyle::State_Off;
opt.state |= QStyle::State_Enabled;
opt.text = text;
opt.rect = option.rect;
// draw item data as CheckBox
style->drawControl(QStyle::CE_CheckBox,&opt,painter);
}
void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
//get the value from the editor (CheckBox)
QCheckBox *myEditor = static_cast<QCheckBox*>(editor);
bool value = myEditor->isChecked();
//set model data
QMap<int,QVariant> data;
data.insert(Qt::DisplayRole,myEditor->text());
data.insert(Qt::UserRole,value);
model->setItemData(index,data);
}
void setEditorData(QWidget *editor, const QModelIndex &index) const
{
//set editor data
QCheckBox *myEditor = static_cast<QCheckBox*>(editor);
myEditor->setText(index.data(Qt::DisplayRole).toString());
myEditor->setChecked(index.data(Qt::UserRole).toBool());
}
*/
CheckBoxList::CheckBoxList(QWidget *parent) : QComboBox(parent), m_DisplayText(0)
{
// set delegate items view
view()->setItemDelegate(new CheckBoxListDelegate(this));
// Enable editing on items view
view()->setEditTriggers(QAbstractItemView::CurrentChanged);
// set "CheckBoxList::eventFilter" as event filter for items view
view()->viewport()->installEventFilter(this);
// it just cool to have it as defualt ;)
//view()->setAlternatingRowColors(true);
}
CheckBoxList::~CheckBoxList(){}
/*bool CheckBoxList::eventFilter(QObject *object, QEvent *event)
{
// don't close items view after we release the mouse button
// by simple eating MouseButtonRelease in viewport of items view
if(event->type() == QEvent::MouseButtonRelease && object==view()->viewport())
{
return true;
}
return QComboBox::eventFilter(object,event);
}
*/
/*
void CheckBoxList::paintEvent(QPaintEvent *)
{
QStylePainter painter(this);
painter.setPen(palette().color(QPalette::Text));
// draw the combobox frame, focusrect and selected etc.
QStyleOptionComboBox opt;
initStyleOption(&opt);
// if no display text been set , use "..." as default
if(m_DisplayText.isNull())
opt.currentText = "...";
else
opt.currentText = m_DisplayText;
painter.drawComplexControl(QStyle::CC_ComboBox, opt);
// draw the icon and text
painter.drawControl(QStyle::CE_ComboBoxLabel, opt);
}
void CheckBoxList::setDisplayText(QString text)
{
m_DisplayText = text;
}
QString CheckBoxList::getDisplayText() const
{
return m_DisplayText;
}*/
| [
"adrien.gavignet@df1d4e54-f2be-1ee4-b4f2-52395a1b115b"
] | [
[
[
1,
199
]
]
] |
e53c47d9c962975853706e047769da1d73c736b1 | cd0987589d3815de1dea8529a7705caac479e7e9 | /webkit/WebKit/win/WebCache.cpp | 7362d28daa1fedc19c3adf074a269aef1ba306f0 | [
"BSD-2-Clause"
] | permissive | azrul2202/WebKit-Smartphone | 0aab1ff641d74f15c0623f00c56806dbc9b59fc1 | 023d6fe819445369134dee793b69de36748e71d7 | refs/heads/master | 2021-01-15T09:24:31.288774 | 2011-07-11T11:12:44 | 2011-07-11T11:12:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,357 | cpp | /*
* Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. 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 "config.h"
#include "WebKitDLL.h"
#include "WebCache.h"
#include "CFDictionaryPropertyBag.h"
#pragma warning(push, 0)
#include <WebCore/ApplicationCacheStorage.h>
#include <WebCore/Cache.h>
#include <WebCore/CrossOriginPreflightResultCache.h>
#pragma warning(pop)
// WebCache ---------------------------------------------------------------------------
WebCache::WebCache()
: m_refCount(0)
{
gClassCount++;
gClassNameCount.add("WebCache");
}
WebCache::~WebCache()
{
gClassCount--;
gClassNameCount.remove("WebCache");
}
WebCache* WebCache::createInstance()
{
WebCache* instance = new WebCache();
instance->AddRef();
return instance;
}
// IUnknown -------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE WebCache::QueryInterface(REFIID riid, void** ppvObject)
{
*ppvObject = 0;
if (IsEqualGUID(riid, IID_IUnknown))
*ppvObject = static_cast<WebCache*>(this);
else if (IsEqualGUID(riid, IID_IWebCache))
*ppvObject = static_cast<WebCache*>(this);
else
return E_NOINTERFACE;
AddRef();
return S_OK;
}
ULONG STDMETHODCALLTYPE WebCache::AddRef(void)
{
return ++m_refCount;
}
ULONG STDMETHODCALLTYPE WebCache::Release(void)
{
ULONG newRef = --m_refCount;
if (!newRef)
delete(this);
return newRef;
}
// IWebCache ------------------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE WebCache::statistics(
/* [in][out] */ int* count,
/* [retval][out] */ IPropertyBag ** s)
{
if (!count || (s && *count < 4))
return E_FAIL;
*count = 4;
if (!s)
return S_OK;
WebCore::Cache::Statistics stat = WebCore::cache()->getStatistics();
static CFStringRef imagesKey = CFSTR("images");
static CFStringRef stylesheetsKey = CFSTR("style sheets");
static CFStringRef xslKey = CFSTR("xsl");
static CFStringRef scriptsKey = CFSTR("scripts");
#if !ENABLE(XSLT)
const int zero = 0;
#endif
RetainPtr<CFMutableDictionaryRef> dictionary(AdoptCF,
CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
RetainPtr<CFNumberRef> value(AdoptCF, CFNumberCreate(0, kCFNumberIntType, &stat.images.count));
CFDictionaryAddValue(dictionary.get(), imagesKey, value.get());
value.adoptCF(CFNumberCreate(0, kCFNumberIntType, &stat.cssStyleSheets.count));
CFDictionaryAddValue(dictionary.get(), stylesheetsKey, value.get());
#if ENABLE(XSLT)
value.adoptCF(CFNumberCreate(0, kCFNumberIntType, &stat.xslStyleSheets.count));
#else
value.adoptCF(CFNumberCreate(0, kCFNumberIntType, &zero));
#endif
CFDictionaryAddValue(dictionary.get(), xslKey, value.get());
value.adoptCF(CFNumberCreate(0, kCFNumberIntType, &stat.scripts.count));
CFDictionaryAddValue(dictionary.get(), scriptsKey, value.get());
COMPtr<CFDictionaryPropertyBag> propBag = CFDictionaryPropertyBag::createInstance();
propBag->setDictionary(dictionary.get());
s[0] = propBag.releaseRef();
dictionary.adoptCF(CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
value.adoptCF(CFNumberCreate(0, kCFNumberIntType, &stat.images.size));
CFDictionaryAddValue(dictionary.get(), imagesKey, value.get());
value.adoptCF(CFNumberCreate(0, kCFNumberIntType, &stat.cssStyleSheets.size));
CFDictionaryAddValue(dictionary.get(), stylesheetsKey, value.get());
#if ENABLE(XSLT)
value.adoptCF(CFNumberCreate(0, kCFNumberIntType, &stat.xslStyleSheets.size));
#else
value.adoptCF(CFNumberCreate(0, kCFNumberIntType, &zero));
#endif
CFDictionaryAddValue(dictionary.get(), xslKey, value.get());
value.adoptCF(CFNumberCreate(0, kCFNumberIntType, &stat.scripts.size));
CFDictionaryAddValue(dictionary.get(), scriptsKey, value.get());
propBag = CFDictionaryPropertyBag::createInstance();
propBag->setDictionary(dictionary.get());
s[1] = propBag.releaseRef();
dictionary.adoptCF(CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
value.adoptCF(CFNumberCreate(0, kCFNumberIntType, &stat.images.liveSize));
CFDictionaryAddValue(dictionary.get(), imagesKey, value.get());
value.adoptCF(CFNumberCreate(0, kCFNumberIntType, &stat.cssStyleSheets.liveSize));
CFDictionaryAddValue(dictionary.get(), stylesheetsKey, value.get());
#if ENABLE(XSLT)
value.adoptCF(CFNumberCreate(0, kCFNumberIntType, &stat.xslStyleSheets.liveSize));
#else
value.adoptCF(CFNumberCreate(0, kCFNumberIntType, &zero));
#endif
CFDictionaryAddValue(dictionary.get(), xslKey, value.get());
value.adoptCF(CFNumberCreate(0, kCFNumberIntType, &stat.scripts.liveSize));
CFDictionaryAddValue(dictionary.get(), scriptsKey, value.get());
propBag = CFDictionaryPropertyBag::createInstance();
propBag->setDictionary(dictionary.get());
s[2] = propBag.releaseRef();
dictionary.adoptCF(CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
value.adoptCF(CFNumberCreate(0, kCFNumberIntType, &stat.images.decodedSize));
CFDictionaryAddValue(dictionary.get(), imagesKey, value.get());
value.adoptCF(CFNumberCreate(0, kCFNumberIntType, &stat.cssStyleSheets.decodedSize));
CFDictionaryAddValue(dictionary.get(), stylesheetsKey, value.get());
#if ENABLE(XSLT)
value.adoptCF(CFNumberCreate(0, kCFNumberIntType, &stat.xslStyleSheets.decodedSize));
#else
value.adoptCF(CFNumberCreate(0, kCFNumberIntType, &zero));
#endif
CFDictionaryAddValue(dictionary.get(), xslKey, value.get());
value.adoptCF(CFNumberCreate(0, kCFNumberIntType, &stat.scripts.decodedSize));
CFDictionaryAddValue(dictionary.get(), scriptsKey, value.get());
propBag = CFDictionaryPropertyBag::createInstance();
propBag->setDictionary(dictionary.get());
s[3] = propBag.releaseRef();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebCache::empty( void)
{
if (WebCore::cache()->disabled())
return S_OK;
WebCore::cache()->setDisabled(true);
WebCore::cache()->setDisabled(false);
// Empty the application cache.
WebCore::cacheStorage().empty();
// Empty the Cross-Origin Preflight cache
WebCore::CrossOriginPreflightResultCache::shared().empty();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebCache::setDisabled(
/* [in] */ BOOL disabled)
{
WebCore::cache()->setDisabled(!!disabled);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebCache::disabled(
/* [out][retval] */ BOOL* disabled)
{
if (!disabled)
return E_POINTER;
*disabled = WebCore::cache()->disabled();
return S_OK;
}
| [
"[email protected]"
] | [
[
[
1,
235
]
]
] |
6b80e9101f011e40dd51134306ffa97d63e1f049 | 668dc83d4bc041d522e35b0c783c3e073fcc0bd2 | /fbide-vs/wxScintillaCtrl/ScintillaWX.h | 276513bddf80dbe2e4542be90bdacd482ad5a5ac | [] | no_license | albeva/fbide-old-svn | 4add934982ce1ce95960c9b3859aeaf22477f10b | bde1e72e7e182fabc89452738f7655e3307296f4 | refs/heads/master | 2021-01-13T10:22:25.921182 | 2009-11-19T16:50:48 | 2009-11-19T16:50:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,058 | h | ////////////////////////////////////////////////////////////////////////////
// Name: ScintillaWX.h
// Purpose: A wxWidgets implementation of Scintilla. A class derived
// from ScintillaBase that uses the "wx platform" defined in
// PlatWX.cpp. This class is one end of a bridge between
// the wx world and the Scintilla world. It needs a peer
// object of type wxScintillaCtrl to function.
//
// Author: Robin Dunn
//
// Created: 13-Jan-2000
// RCS-ID: $Id: ScintillaWX.h 62259 2009-10-05 14:50:45Z JJ $
// Copyright: (c) 2000 by Total Control Software
// Licence: wxWindows license
/////////////////////////////////////////////////////////////////////////////
#ifndef __ScintillaWX_h__
#define __ScintillaWX_h__
#include "wx/defs.h"
//----------------------------------------------------------------------
#include "../Sdk/Sdk.h"
// #define SDK_DLL
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "CharClassify.h"
#include "XPM.h"
#ifdef SCI_LEXER
#include "SciLexer.h"
#endif
#include "SplitVector.h"
#include "Partitioning.h"
#include "RunStyles.h"
#include "ContractionState.h"
#include "CellBuffer.h"
#include "CallTip.h"
#include "KeyMap.h"
#include "Indicator.h"
#include "LineMarker.h"
#include "Style.h"
#include "ViewStyle.h"
#include "AutoComplete.h"
#include "Decoration.h"
#include "Document.h"
#include "PositionCache.h"
#include "Editor.h"
#include "ScintillaBase.h"
#ifdef __WXMSW__
#include "wx/msw/wrapwin.h" // HBITMAP
#endif
#if wxUSE_DRAG_AND_DROP
#include "wx/timer.h"
#endif
//----------------------------------------------------------------------
class WXDLLIMPEXP_FWD_CORE wxDC;
class SDK_DLL wxScintillaCtrl; // forward
class ScintillaWX;
//----------------------------------------------------------------------
// Helper classes
#if wxUSE_DRAG_AND_DROP
class wxSTCDropTarget : public wxTextDropTarget {
public:
void SetScintilla(ScintillaWX* swx) {
m_swx = swx;
}
bool OnDropText(wxCoord x, wxCoord y, const wxString& data);
wxDragResult OnEnter(wxCoord x, wxCoord y, wxDragResult def);
wxDragResult OnDragOver(wxCoord x, wxCoord y, wxDragResult def);
void OnLeave();
private:
ScintillaWX* m_swx;
};
#endif
//----------------------------------------------------------------------
class ScintillaWX : public ScintillaBase {
public:
ScintillaWX(wxScintillaCtrl* win);
~ScintillaWX();
// base class virtuals
virtual void Initialise();
virtual void Finalise();
virtual void StartDrag();
virtual bool SetIdle(bool on);
virtual void SetTicking(bool on);
virtual void SetMouseCapture(bool on);
virtual bool HaveMouseCapture();
virtual void ScrollText(int linesToMove);
virtual void SetVerticalScrollPos();
virtual void SetHorizontalScrollPos();
virtual bool ModifyScrollBars(int nMax, int nPage);
virtual void Copy();
virtual void Paste();
virtual void CopyToClipboard(const SelectionText &selectedText);
virtual void CreateCallTipWindow(PRectangle rc);
virtual void AddToPopUp(const char *label, int cmd = 0, bool enabled = true);
virtual void ClaimSelection();
virtual sptr_t DefWndProc(unsigned int iMessage,
uptr_t wParam,
sptr_t lParam);
virtual sptr_t WndProc(unsigned int iMessage,
uptr_t wParam,
sptr_t lParam);
virtual void NotifyChange();
virtual void NotifyParent(SCNotification scn);
virtual void CancelModes();
virtual void UpdateSystemCaret();
// Event delegates
void DoPaint(wxDC* dc, wxRect rect);
void DoHScroll(int type, int pos);
void DoVScroll(int type, int pos);
void DoSize(int width, int height);
void DoLoseFocus();
void DoGainFocus();
void DoSysColourChange();
void DoLeftButtonDown(Point pt, unsigned int curTime, bool shift, bool ctrl, bool alt);
void DoLeftButtonUp(Point pt, unsigned int curTime, bool ctrl);
void DoLeftButtonMove(Point pt);
void DoMiddleButtonUp(Point pt);
void DoMouseWheel(int rotation, int delta, int linesPerAction, int ctrlDown, bool isPageScroll);
void DoAddChar(int key);
int DoKeyDown(const wxKeyEvent& event, bool* consumed);
void DoTick() { Tick(); }
void DoOnIdle(wxIdleEvent& evt);
#if wxUSE_DRAG_AND_DROP
bool DoDropText(long x, long y, const wxString& data);
wxDragResult DoDragEnter(wxCoord x, wxCoord y, wxDragResult def);
wxDragResult DoDragOver(wxCoord x, wxCoord y, wxDragResult def);
void DoDragLeave();
#endif
void DoCommand(int ID);
void DoContextMenu(Point pt);
void DoOnListBox();
// helpers
void FullPaint();
bool CanPaste();
bool GetHideSelection() { return hideSelection; }
void DoScrollToLine(int line);
void DoScrollToColumn(int column);
void ClipChildren(wxDC& dc, PRectangle rect);
void SetUseAntiAliasing(bool useAA);
bool GetUseAntiAliasing();
private:
bool capturedMouse;
bool focusEvent;
wxScintillaCtrl* stc;
#if wxUSE_DRAG_AND_DROP
wxSTCDropTarget* dropTarget;
wxDragResult dragResult;
#endif
int wheelRotation;
// For use in creating a system caret
bool HasCaretSizeChanged();
bool CreateSystemCaret();
bool DestroySystemCaret();
#ifdef __WXMSW__
HBITMAP sysCaretBitmap;
int sysCaretWidth;
int sysCaretHeight;
#endif
friend class wxSTCCallTip;
int currentPos;
};
//----------------------------------------------------------------------
#endif
| [
"vongodric@957c6b5c-1c3a-0410-895f-c76cfc11fbc7"
] | [
[
[
1,
204
]
]
] |
3cba50bed5e0255f21363e125834eec36310e2d4 | 9b3df03cb7e134123cf6c4564590619662389d35 | /ObjectOutputStream.cpp | c7745e15ee009f25c0cc57822b9646f6d084b361 | [] | no_license | CauanCabral/Computacao_Grafica | a32aeff2745f40144a263c16483f53db7375c0ba | d8673aed304573415455d6a61ab31b68420b6766 | refs/heads/master | 2016-09-05T16:48:36.944139 | 2010-12-09T19:32:05 | 2010-12-09T19:32:05 | null | 0 | 0 | null | null | null | null | ISO-8859-10 | C++ | false | false | 3,914 | cpp | //[]------------------------------------------------------------------------[]
//| |
//| GVSG Foundation Classes |
//| Version 1.0 |
//| |
//| CopyrightŪ 2007, Paulo Aristarco Pagliosa |
//| All Rights Reserved. |
//| |
//[]------------------------------------------------------------------------[]
//
// OVERVIEW: ObjectOutputStream.cpp
// ========
// Source file for object output streams.
#ifndef __ObjectOutputStream_h
#include "ObjectOutputStream.h"
#endif
using namespace System;
//////////////////////////////////////////////////////////
//
// ObjectOutputStream implementation
// ==================
ObjectOutputStream::ObjectOutputStream(OutputStream* out):
DataOutputStream(/*new BufferedOutputStream*/(out))
//[]---------------------------------------------------[]
//| Constructor |
//[]---------------------------------------------------[]
{
// do nothing
}
void
ObjectOutputStream::writeObject(const Serializable& obj)
//[]---------------------------------------------------[]
//| Write object (ref) |
//[]---------------------------------------------------[]
{
writePrefix(const_cast<Serializable*>(&obj));
writeFields(const_cast<Serializable*>(&obj));
writeSuffix(const_cast<Serializable*>(&obj));
}
void
ObjectOutputStream::writeObject(const Serializable* obj)
//[]---------------------------------------------------[]
//| Write object (prt) |
//[]---------------------------------------------------[]
{
if (obj == 0)
writeInt8(ObjectStream::ptNull);
else
{
int32 index = findObject(const_cast<Serializable*>(obj));
if (index != 0)
{
writeInt8(ObjectStream::ptIndexed);
writeInt32(index);
}
else
{
writeInt8(ObjectStream::ptObject);
writeObject(*obj);
}
}
}
void
ObjectOutputStream::writePrefix(Serializable* obj)
//[]---------------------------------------------------[]
//| Write prefix |
//[]---------------------------------------------------[]
{
writeInt8('[');
int index = findClass(obj);
if (index == 0)
{
registerClass(obj);
writeInt8(ObjectStream::ntClass);
writeString(obj->getClassName());
}
else
{
writeInt8(ObjectStream::ntIndexed);
writeInt32(index);
}
}
void
ObjectOutputStream::writeFields(Serializable* obj)
//[]---------------------------------------------------[]
//| Write fields |
//[]---------------------------------------------------[]
{
Streamer* strmr = getStreamer(*obj);
registerObject(obj);
strmr->write(*this);
delete strmr;
}
void
ObjectOutputStream::writeVirtualBaseObject(const Streamer& strmr)
//[]---------------------------------------------------[]
//| Write virtual base object |
//[]---------------------------------------------------[]
{
Serializable* obj = strmr.getObject();
if (findVB(obj) != 0)
writeInt8(ObjectStream::ptIndexed);
else
{
registerObject((Serializable*)((char*)obj + 1));
writeInt8(ObjectStream::ptObject);
strmr.write(*this);
}
}
void
ObjectOutputStream::writeBaseObject(const Streamer& strmr)
//[]---------------------------------------------------[]
//| Write base object |
//[]---------------------------------------------------[]
{
strmr.write(*this);
}
| [
"[email protected]"
] | [
[
[
1,
132
]
]
] |
0577343c485e601d5f0c4a564deaeb4c2e335bff | 56c792a91c174293c8f848ea5498c1145b4946fe | /rgrow/includes/fltkImageViewerGUI.h | afb5d8e67d65e958a07f4410275a6ce333d1d3ae | [] | no_license | ltflores/csc821a3 | f9e4e1d31eaefaa6246515b444d1a9008d8b8f94 | cc22d481e466172dfdac20366d41a14bf2eb2470 | refs/heads/master | 2020-06-12T18:13:05.260330 | 2011-05-08T22:39:32 | 2011-05-08T22:39:32 | 32,131,514 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,025 | h | // generated by Fast Light User Interface Designer (fluid) version 1.0300
#ifndef fltkImageViewerGUI_h
#define fltkImageViewerGUI_h
#include <FL/Fl.H>
#include <FL/Fl_Double_Window.H>
#include <FL/Fl_Group.H>
#include <FL/Fl_Choice.H>
#include <GLSliceView.h>
#include <FL/Fl_Menu_Bar.H>
#include <FL/Fl_Value_Slider.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Browser.H>
class fltkImageViewerGUI {
public:
fltkImageViewerGUI();
virtual ~fltkImageViewerGUI();
Fl_Double_Window* CreateGUI();
Fl_Double_Window *iviewWindow;
Fl_Group *glWindowGroup;
Fl_Choice *orientationChoice;
private:
void cb_orientationChoice_i(Fl_Choice*, void*);
static void cb_orientationChoice(Fl_Choice*, void*);
static Fl_Menu_Item menu_orientationChoice[];
static Fl_Menu_Item menu_[];
void cb_Value_i(Fl_Menu_*, void*);
static void cb_Value(Fl_Menu_*, void*);
void cb_Log_i(Fl_Menu_*, void*);
static void cb_Log(Fl_Menu_*, void*);
void cb_Opacity_i(Fl_Menu_*, void*);
static void cb_Opacity(Fl_Menu_*, void*);
public:
Fl_Value_Slider *sliceNumberSlider;
private:
void cb_sliceNumberSlider_i(Fl_Value_Slider*, void*);
static void cb_sliceNumberSlider(Fl_Value_Slider*, void*);
public:
Fl_Value_Slider *intensityWindowingMinSlider;
private:
void cb_intensityWindowingMinSlider_i(Fl_Value_Slider*, void*);
static void cb_intensityWindowingMinSlider(Fl_Value_Slider*, void*);
public:
Fl_Value_Slider *intensityWindowingMaxSlider;
private:
void cb_intensityWindowingMaxSlider_i(Fl_Value_Slider*, void*);
static void cb_intensityWindowingMaxSlider(Fl_Value_Slider*, void*);
void cb_Zoom_i(Fl_Button*, void*);
static void cb_Zoom(Fl_Button*, void*);
void cb_Zoom1_i(Fl_Button*, void*);
static void cb_Zoom1(Fl_Button*, void*);
void cb_U_i(Fl_Button*, void*);
static void cb_U(Fl_Button*, void*);
void cb_Reset_i(Fl_Button*, void*);
static void cb_Reset(Fl_Button*, void*);
void cb_R_i(Fl_Button*, void*);
static void cb_R(Fl_Button*, void*);
void cb_L_i(Fl_Button*, void*);
static void cb_L(Fl_Button*, void*);
void cb_D_i(Fl_Button*, void*);
static void cb_D(Fl_Button*, void*);
void cb_Points_i(Fl_Button*, void*);
static void cb_Points(Fl_Button*, void*);
public:
Fl_Double_Window *clickedPointsWindow;
Fl_Browser *clickedPointsBrowser;
private:
void cb_Update_i(Fl_Button*, void*);
static void cb_Update(Fl_Button*, void*);
void cb_Clear_i(Fl_Button*, void*);
static void cb_Clear(Fl_Button*, void*);
void cb_Close_i(Fl_Button*, void*);
static void cb_Close(Fl_Button*, void*);
public:
Fl_Double_Window *overlayOpacityControlWindow;
private:
void cb_Close1_i(Fl_Button*, void*);
static void cb_Close1(Fl_Button*, void*);
public:
Fl_Value_Slider *overlayOpacitySlider;
private:
void cb_overlayOpacitySlider_i(Fl_Value_Slider*, void*);
static void cb_overlayOpacitySlider(Fl_Value_Slider*, void*);
public:
virtual void CreateGLSliceView( Fl_Group *,Fl_Gl_Window * w );
virtual void AddMenuBarOptions(void);
virtual void AddFilterMenuOptions();
virtual void AddFileMenuOptions();
virtual void SetImage( itk::ImageBase<3> * img );
virtual void Show(void);
virtual void Hide(void);
virtual void Update(void);
virtual void Synchronize(void);
virtual void ImageMode(itk::ImageModeType mode);
virtual void SelectSlice(unsigned int);
virtual void SetIntensityWindowingMin(float);
virtual void SetIntensityWindowingMax(float);
virtual void CenterWindow(void);
virtual void ZoomIn(void);
virtual void ZoomOut(void);
virtual void ShiftUp(void);
virtual void ShiftDown(void);
virtual void ShiftLeft(void);
virtual void ShiftRight(void);
virtual void SetOrientation(void);
virtual void ShowClickedPointsWindow(void);
virtual void ClearClickedPoints(void);
virtual void ShowOverlayOpacityControl(void);
virtual void SetOverlayOpacity(float);
virtual void UpdateClickedPoints();
};
#endif
| [
"[email protected]@f99ad3ae-f7c5-c186-d9e4-f786dcd8cbb9"
] | [
[
[
1,
113
]
]
] |
f137fad40a5f73b393d306b7de799afa4b56b2f3 | a1c866c630074029d5bdc632fbcf946ea9a512ab | /Trabalho 2/LAIGtp2/Source/globals.h | 796c1a8681f76eb36c1cc99106edb2d52ab9a113 | [] | no_license | miaosun/laig-072-162 | f08aebf9592bdbe9a57ae2382d03445feffcab89 | b7b5717521cd5c0a52be0ba1293f1e926dfe74c6 | refs/heads/master | 2020-12-24T13:28:03.086329 | 2010-12-21T19:57:44 | 2010-12-21T19:57:44 | 33,734,370 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,912 | h | #include <string>
#include <vector>
#include <glui.h>
using namespace std;
// Apontadores para os principais grupos
// declarados aqui como globais por conveniência
// idealmente tudo seria incluido numa classe
class Global
{
public:
int maxlights;
int maxtextures;
int maxmaterials;
int maxobjects;
string root;
Global()
{
this->maxlights = maxlights;
this->maxtextures = maxtextures;
this->maxmaterials = maxmaterials;
this->maxobjects = maxobjects;
this->root = root;
}
};
class Light
{
public:
string id;
bool enabled;
float ambient[4];
float diffuse[4];
float specular[4];
float position[4];
Light(string id, bool enabled)
{
this->id = id;
this->enabled = enabled;
}
};
class Illumination
{
public:
bool doublesided;
bool local;
float ambient[4];
float backgroud[4];
Illumination(){};
Illumination(bool doublesided, bool local)
{
this->doublesided = doublesided;
this->local = local;
}
};
class Material
{
public:
string id;
float ambient[4];
float diffuse[4];
float specular[4];
float emission[4];
float shininess[1];
Material(){};
Material(string id)
{
this->id = id;
this->shininess[0] = 0;
}
void apply()
{
glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, this->shininess);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, this->specular);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, this->diffuse);
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, this->ambient);
glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, this->emission);
}
};
class Texture
{
public:
string id;
string file;
float length_s;
float length_t;
int n_texture;
Texture(){};
Texture(string id, string file, float length_s, float length_t)
{
this->id = id;
this->file = file;
this->length_s = length_s;
this->length_t = length_t;
}
};
| [
"gasparlafurtado@7f58f83d-947b-b5a6-e802-c2e2e7638ba7",
"miaosun88@7f58f83d-947b-b5a6-e802-c2e2e7638ba7"
] | [
[
[
1,
99
],
[
101,
111
]
],
[
[
100,
100
]
]
] |
b5fcd4f7c0d9d93b0eb587b19ff0593743a2fc28 | 814b49df11675ac3664ac0198048961b5306e1c5 | /Code/Engine/Utilities/include/ComponentInteractive.h | cce15acad28e2484ed088f27ddfb06c01053ceb9 | [] | no_license | Atridas/biogame | f6cb24d0c0b208316990e5bb0b52ef3fb8e83042 | 3b8e95b215da4d51ab856b4701c12e077cbd2587 | refs/heads/master | 2021-01-13T00:55:50.502395 | 2011-10-31T12:58:53 | 2011-10-31T12:58:53 | 43,897,729 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,158 | h | #pragma once
#ifndef __COMPONENT_INTERACTIVE__
#define __COMPONENT_INTERACTIVE__
#include "base.h"
#include "EntityDefines.h"
class CComponentObject3D;
#define RADI_ESFERA_INTERACTUABLES 5.f
#define UPDATE_BILLBOARD_SECONDS 1.f
class CComponentInteractive:
public CBaseComponent
{
public:
~CComponentInteractive() {Done();}
CBaseComponent::Type GetType() {return CBaseComponent::ECT_INTERACTIVE;};
static CBaseComponent::Type GetStaticType() {return CBaseComponent::ECT_INTERACTIVE;};
static CComponentInteractive* AddToEntity(CGameEntity* _pEntity, const string& _szAction);
virtual void ReceiveEvent(const SEvent& _Event);
virtual void Update(float _fDeltaTime);
float m_fBillboardYOffset;
protected:
CComponentInteractive():m_szAction(""),m_bBillboardActive(false),m_fLastUpdate(0),m_pObject3D(0),m_fBillboardYOffset(0) {};
bool Init(CGameEntity* _pEntity, const string& _szAction);
virtual void Release();
private:
void CallAction(int _iCaller);
string m_szAction;
CComponentObject3D * m_pObject3D;
bool m_bBillboardActive;
float m_fLastUpdate;
};
#endif | [
"mudarra@576ee6d0-068d-96d9-bff2-16229cd70485",
"Atridas87@576ee6d0-068d-96d9-bff2-16229cd70485"
] | [
[
[
1,
7
],
[
17,
28
],
[
30,
30
],
[
33,
33
],
[
35,
35
],
[
37,
41
],
[
47,
49
]
],
[
[
8,
16
],
[
29,
29
],
[
31,
32
],
[
34,
34
],
[
36,
36
],
[
42,
46
]
]
] |
4891aabd12b03d29a44042217ad8a78fba9181cb | be7eef50e21e11340134d150f78db8d6f5423e66 | /L3/L3.cpp | 3840d35b529b651459fb531fb4f7ced329d5def6 | [] | no_license | Maciej-Poleski/Algorytmika | 8023aef976c1087e25a4f9079de65769cf690ae3 | 3a3818f82738d9ea42aba24dea89e9280d504f00 | refs/heads/master | 2023-07-06T03:57:54.430947 | 2011-05-26T15:57:11 | 2011-05-26T15:57:11 | 395,015,968 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 265 | cpp | #include <cstdio>
#include <cmath>
int main()
{
int z;
scanf("%d",&z);
while(z--)
{
long long n,w,t;
scanf("%lld",&n);
t=w=sqrt(n);
for(long long i=1;i<=t;++i)
w+=2*((n-i*i)/i);
printf("%lld\n",w);
}
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
18
]
]
] |
8d68be1b6ce51ef32403cabc767c222e295026a6 | a2904986c09bd07e8c89359632e849534970c1be | /topcoder/ChessboardPattern.cpp | 139e43655978e6c0c5a098c3f55a94e1b5e19de4 | [] | no_license | naturalself/topcoder_srms | 20bf84ac1fd959e9fbbf8b82a93113c858bf6134 | 7b42d11ac2cc1fe5933c5bc5bc97ee61b6ec55e5 | refs/heads/master | 2021-01-22T04:36:40.592620 | 2010-11-29T17:30:40 | 2010-11-29T17:30:40 | 444,669 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,579 | cpp | // BEGIN CUT HERE
// END CUT HERE
#line 5 "ChessboardPattern.cpp"
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <map>
#include <utility>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <functional>
#include <sstream>
#include <complex>
#include <stack>
#include <queue>
using namespace std;
#define debug(p) cout << #p << "=" << p << endl;
#define forv(i, v) for (int i = 0; i < (int)(v.size()); ++i)
#define fors(i, s) for (int i = 0; i < (int)(s.length()); ++i)
#define all(a) a.begin(), a.end()
#define pb push_back
class ChessboardPattern {
public:
vector <string> makeChessboard(int rows, int clms) {
vector <string> ret;
for(int i=0;i<rows;i++){
string tmp;
for(int j=0;j<clms;j++){
if((i+j)%2==0){
if(rows%2==0){
tmp += 'X';
}else{
tmp += '.';
}
}else{
if(rows%2==0){
tmp += '.';
}else{
tmp += 'X';
}
}
}
ret.pb(tmp);
}
return ret;
}
};
// BEGIN CUT HERE
namespace moj_harness {
int run_test_case(int);
void run_test(int casenum = -1, bool quiet = false) {
if (casenum != -1) {
if (run_test_case(casenum) == -1 && !quiet) {
cerr << "Illegal input! Test case " << casenum << " does not exist." << endl;
}
return;
}
int correct = 0, total = 0;
for (int i=0;; ++i) {
int x = run_test_case(i);
if (x == -1) {
if (i >= 100) break;
continue;
}
correct += x;
++total;
}
if (total == 0) {
cerr << "No test cases run." << endl;
} else if (correct < total) {
cerr << "Some cases FAILED (passed " << correct << " of " << total << ")." << endl;
} else {
cerr << "All " << total << " tests passed!" << endl;
}
}
template<typename T> ostream& operator<<(ostream &os, const vector<T> &v) { os << "{"; for (typename vector<T>::const_iterator vi=v.begin(); vi!=v.end(); ++vi) { if (vi != v.begin()) os << ","; os << " " << *vi; } os << " }"; return os; }
template<> ostream& operator<<(ostream &os, const vector<string> &v) { os << "{"; for (vector<string>::const_iterator vi=v.begin(); vi!=v.end(); ++vi) { if (vi != v.begin()) os << ","; os << " \"" << *vi << "\""; } os << " }"; return os; }
int verify_case(int casenum, const vector <string> &expected, const vector <string> &received, clock_t elapsed) {
cerr << "Example " << casenum << "... ";
string verdict;
vector<string> info;
char buf[100];
if (elapsed > CLOCKS_PER_SEC / 200) {
sprintf(buf, "time %.2fs", elapsed * (1.0/CLOCKS_PER_SEC));
info.push_back(buf);
}
if (expected == received) {
verdict = "PASSED";
} else {
verdict = "FAILED";
}
cerr << verdict;
if (!info.empty()) {
cerr << " (";
for (int i=0; i<(int)info.size(); ++i) {
if (i > 0) cerr << ", ";
cerr << info[i];
}
cerr << ")";
}
cerr << endl;
if (verdict == "FAILED") {
cerr << " Expected: " << expected << endl;
cerr << " Received: " << received << endl;
}
return verdict == "PASSED";
}
int run_test_case(int casenum) {
switch (casenum) {
case 0: {
int rows = 8;
int columns = 8;
string expected__[] = {"X.X.X.X.", ".X.X.X.X", "X.X.X.X.", ".X.X.X.X", "X.X.X.X.", ".X.X.X.X", "X.X.X.X.", ".X.X.X.X" };
clock_t start__ = clock();
vector <string> received__ = ChessboardPattern().makeChessboard(rows, columns);
return verify_case(casenum, vector <string>(expected__, expected__ + (sizeof expected__ / sizeof expected__[0])), received__, clock()-start__);
}
case 1: {
int rows = 1;
int columns = 20;
string expected__[] = {".X.X.X.X.X.X.X.X.X.X" };
clock_t start__ = clock();
vector <string> received__ = ChessboardPattern().makeChessboard(rows, columns);
return verify_case(casenum, vector <string>(expected__, expected__ + (sizeof expected__ / sizeof expected__[0])), received__, clock()-start__);
}
case 2: {
int rows = 5;
int columns = 1;
string expected__[] = {".", "X", ".", "X", "." };
clock_t start__ = clock();
vector <string> received__ = ChessboardPattern().makeChessboard(rows, columns);
return verify_case(casenum, vector <string>(expected__, expected__ + (sizeof expected__ / sizeof expected__[0])), received__, clock()-start__);
}
case 3: {
int rows = 5;
int columns = 13;
string expected__[] = {".X.X.X.X.X.X.", "X.X.X.X.X.X.X", ".X.X.X.X.X.X.", "X.X.X.X.X.X.X", ".X.X.X.X.X.X." };
clock_t start__ = clock();
vector <string> received__ = ChessboardPattern().makeChessboard(rows, columns);
return verify_case(casenum, vector <string>(expected__, expected__ + (sizeof expected__ / sizeof expected__[0])), received__, clock()-start__);
}
// custom cases
/* case 4: {
int rows = ;
int columns = ;
string expected__[] = ;
clock_t start__ = clock();
vector <string> received__ = ChessboardPattern().makeChessboard(rows, columns);
return verify_case(casenum, vector <string>(expected__, expected__ + (sizeof expected__ / sizeof expected__[0])), received__, clock()-start__);
}*/
/* case 5: {
int rows = ;
int columns = ;
string expected__[] = ;
clock_t start__ = clock();
vector <string> received__ = ChessboardPattern().makeChessboard(rows, columns);
return verify_case(casenum, vector <string>(expected__, expected__ + (sizeof expected__ / sizeof expected__[0])), received__, clock()-start__);
}*/
/* case 6: {
int rows = ;
int columns = ;
string expected__[] = ;
clock_t start__ = clock();
vector <string> received__ = ChessboardPattern().makeChessboard(rows, columns);
return verify_case(casenum, vector <string>(expected__, expected__ + (sizeof expected__ / sizeof expected__[0])), received__, clock()-start__);
}*/
default:
return -1;
}
}
}
int main(int argc, char *argv[]) {
if (argc == 1) {
moj_harness::run_test();
} else {
for (int i=1; i<argc; ++i)
moj_harness::run_test(atoi(argv[i]));
}
}
// END CUT HERE
| [
"shin@CF-7AUJ41TT52JO.(none)"
] | [
[
[
1,
216
]
]
] |
b0066eba04ca4e93aeec69b5a3bb4a00959c9da4 | 25426133cf6405c5cebf4b51c48ff3dce2629ea9 | /engine/engine.cpp | 10ad4cfd18d7742616e11b830bd028518f0b562f | [] | no_license | tolhc1234/openglengine | 456fd5a099b30544af1e338fab289402d2b81341 | 6ed525f9a74235605157e68728e36b8b5291b096 | refs/heads/master | 2021-01-10T02:38:58.457222 | 2010-01-12T20:28:21 | 2010-01-12T20:28:21 | 50,214,430 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,480 | cpp | #include "engine.h"
#include "gl/glut.h"
Engine engine;
gui MainMenu;
int noclip = true;
float temppos[3] = {0,0,20};//temp
//ook temp
particles particleTest(5,100,0.5,50000,temppos,temppos,temppos,1);
void mainMenu(){
if(engine.logic){
GUIList.add(&MainMenu);
engine.dissableLogic();
}
else{
GUIList.remove(&MainMenu);
engine.enableLogic();
}
}
void Engine::init(){
themeInit();
static gui MainMenu("Main Menu",blueWindow);
MainMenu.newElem(new button("exit",Exit));
GUIList.add(&MainMenu);
camera.viewObject(&player);
}
void Engine::update(){
particleTest.update();
GUIList.updateAll();
}
void Engine::dissableLogic(){
engine.logic = false;
}
void Engine::enableLogic(){
engine.logic = true;
}
void Engine::start(){
}
void Engine::render(){
glClearColor (0,0,0,1.0);
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glColor4f(0.4, 0.3, 0.6, 0.55);
camera.update();
glPushMatrix();
renderBullet();
glPopMatrix();
glColor4f(1,0.3,0.3,1);
// light test
float ambient[] = {0.20,0.20,0.20};
float diffuseLight[] = {0.20,0.20,0.60};
float place[] = {10,0,0};
glPushMatrix();
glRotatef(random.gen(0,360),0,1,0);
glTranslatef(100,30,0);
glLightfv(GL_LIGHT0,GL_AMBIENT, ambient);
glLightfv (GL_LIGHT0, GL_DIFFUSE, diffuseLight);
glLightfv (GL_LIGHT0, GL_POSITION, place);
glutSolidCube(5);
glPopMatrix();
static texture test("data//textures//test.bmp");
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, test.ID);
glBegin(GL_QUADS);
glTexCoord2i(0,0);glVertex3f(10,10,20);
glTexCoord2i(1,0);glVertex3f(20,10,20);
glTexCoord2i(1,1);glVertex3f(20,20,20);
glTexCoord2i(0,1);glVertex3f(10,20,20);
glEnd();
glDisable(GL_TEXTURE_2D);
// light test
glutSolidSphere(20,24,48);
glColor4f(0,0,0.4,0.95);
//glRotatef(-xrot,1,0,0);
//glRotatef(-yrot,0,1,0);
//glTranslatef(-camx,-camy,-camz);
glBegin(GL_QUADS);
glVertex3f(10, -30, 40);
glVertex3f(40, -30, 40);
glVertex3f( 40, 30, 40);
glVertex3f( 1, 30, 40);
glEnd();
particleTest.render();
GUIList.renderAll();
}
void Engine::handleMouse(int movedX, int movedY){
}
void handleKey(int ammount,char* keys, bool* status);
{//////////////////////////////////////////////////////////////////////////////////////////////working, this wont compile..
case SDLK_ESCAPE:
mainMenu();
break;
case SDLK_w:
{
std::cout << "ASD\n";
float xrotrad, yrotrad;
yrotrad = (player.directionY / 180 * 3.141592654f);
xrotrad = (player.directionX / 180 * 3.141592654f);
player.posX += float(sin(yrotrad)) * 5;//cscale
player.posY -= float(cos(yrotrad)) * 5;
if(noclip == true)
{
player.posY -= float(sin(xrotrad)) * 5 ;
}
//camz -= 5;
break;
case 's':
{
float xrotrad, yrotrad;
yrotrad = (player.directionY / 180 * 3.141592654f);
xrotrad = (player.directionX / 180 * 3.141592654f);
player.posX -= float(sin(yrotrad)) * 5;//cscale
player.posY += float(cos(yrotrad)) * 5;
if(noclip == true)
{
player.posX += float(sin(xrotrad)) * 5;
}
// camz += 5;
break;
}
case 'd':
{
float yrotrad;
yrotrad = (player.directionY / 180 * 3.141592654f);
player.posX += float(cos(yrotrad)) * 5;
player.posZ += float(sin(yrotrad)) * 5;
//camx += 5;
break;
}
case 'a':
{
float yrotrad;
yrotrad = (player.directionY / 180 * 3.141592654f);
player.posX -= float(cos(yrotrad)) * 5;
player.posZ -= float(sin(yrotrad)) * 5;
// camx -= 5;
break;
}
case '8':
player.directionX -= 1;
if (player.directionX < -360) player.directionX += 360;
break;
case '2':
player.directionX += 1;
if (player.directionX >360) player.directionX -= 360;
break;
case ' ':
player.posY += 5;
break;
case '5':
player.posY -= 5;
break;
case 'e':
addBullet(player.posX, player.posY, player.posZ, player.directionX, player.directionY);
break;
case 'n':
if(noclip == false) noclip = true;
else noclip = false;
break;
/*case 'f':
if(fpsOn == true) fpsOn = false;
else fpsOn = true;
break;
*/
}
}
if(/*guiFocus&&*/(event.key.keysym.unicode & 0x7F) == event.key.keysym.unicode && isascii(event.key.keysym.unicode))
{
if(event.key.keysym.unicode)
GUIList.handleKey(event.key.keysym.unicode);
else
GUIList.handleKey(event.key.keysym.sym);
}
}
}
void events(/*unsigned char key, int x, int y*/)
{
SDL_Event event;
while (SDL_PollEvent(&event)) //Poll our SDL key event for any keystrokes.
{
switch(event.type)
{
case SDL_VIDEORESIZE:
reshape(event.resize.w,event.resize.h);
//screen = SDL_SetVideoMode(getWindowWidth(), getWindowHeight(), 32, SDL_OPENGL | SDL_DOUBLEBUF | SDL_RESIZABLE);
break;
case SDL_QUIT:
mainMenu();
break;
case SDL_MOUSEMOTION :
Mouse.setXY(event.motion.x, event.motion.y);
GUIList.handleMouse(event.button.x, event.button.y,event.type);
break;
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
Mouse.clickHandle(event.button.button , event.type,event.button.x, event.button.y);
break;
case SDL_KEYDOWN:
switch(event.key.keysym.sym){
case SDLK_ESCAPE:
mainMenu();
break;
case SDLK_w:
{
std::cout << "ASD\n";
float xrotrad, yrotrad;
yrotrad = (player.directionY / 180 * 3.141592654f);
xrotrad = (player.directionX / 180 * 3.141592654f);
player.posX += float(sin(yrotrad)) * 5;//cscale
player.posY -= float(cos(yrotrad)) * 5;
if(noclip == true)
{
player.posY -= float(sin(xrotrad)) * 5 ;
}
//camz -= 5;
break;
case 's':
{
float xrotrad, yrotrad;
yrotrad = (player.directionY / 180 * 3.141592654f);
xrotrad = (player.directionX / 180 * 3.141592654f);
player.posX -= float(sin(yrotrad)) * 5;//cscale
player.posY += float(cos(yrotrad)) * 5;
if(noclip == true)
{
player.posX += float(sin(xrotrad)) * 5;
}
// camz += 5;
break;
}
case 'd':
{
float yrotrad;
yrotrad = (player.directionY / 180 * 3.141592654f);
player.posX += float(cos(yrotrad)) * 5;
player.posZ += float(sin(yrotrad)) * 5;
//camx += 5;
break;
}
case 'a':
{
float yrotrad;
yrotrad = (player.directionY / 180 * 3.141592654f);
player.posX -= float(cos(yrotrad)) * 5;
player.posZ -= float(sin(yrotrad)) * 5;
// camx -= 5;
break;
}
case '8':
player.directionX -= 1;
if (player.directionX < -360) player.directionX += 360;
break;
case '2':
player.directionX += 1;
if (player.directionX >360) player.directionX -= 360;
break;
case ' ':
player.posY += 5;
break;
case '5':
player.posY -= 5;
break;
case 'e':
addBullet(player.posX, player.posY, player.posZ, player.directionX, player.directionY);
break;
case 'n':
if(noclip == false) noclip = true;
else noclip = false;
break;
/*case 'f':
if(fpsOn == true) fpsOn = false;
else fpsOn = true;
break;
*/
}
}
if(/*guiFocus&&*/(event.key.keysym.unicode & 0x7F) == event.key.keysym.unicode && isascii(event.key.keysym.unicode))
{
if(event.key.keysym.unicode)
GUIList.handleKey(event.key.keysym.unicode);
else
GUIList.handleKey(event.key.keysym.sym);
}
}
}
} | [
"[email protected]"
] | [
[
[
1,
332
]
]
] |
e97ec3aec64fd6e29d552e7a447d8779f52e02a1 | 4275e8a25c389833c304317bdee5355ed85c7500 | /KylTek/CDeviceHandler.cpp | a9eb82af108a924b0e0d7fc7398a10a484ccd619 | [] | no_license | kumorikarasu/KylTek | 482692298ef8ff501fd0846b5f41e9e411afe686 | be6a09d20159d0a320abc4d947d4329f82d379b9 | refs/heads/master | 2021-01-10T07:57:40.134888 | 2010-07-26T12:10:09 | 2010-07-26T12:10:09 | 55,943,006 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,472 | cpp | #include "Main.h"
#include "CGlobal.h"
#include "CDeviceHandler.h"
//Take out all DX stuff not related with GFX, keyboard...
CDeviceHandler::CDeviceHandler(HINSTANCE hInstance){
m_pD3DInputObject = NULL;
m_pD3DInputDevice = NULL;
m_pD3DMouseDevice = NULL;
DirectInput8Create(hInstance, DIRECTINPUT_VERSION,
IID_IDirectInput8, (void**)&m_pD3DInputObject, NULL);
ZeroMemory(&m_bKeyDown, sizeof(m_bKeyDown));
}
CDeviceHandler::~CDeviceHandler(){
SAFE_RELEASE(m_pD3DInputObject);
SAFE_RELEASE(m_pD3DInputDevice);
SAFE_RELEASE(m_pD3DMouseDevice);
}
HRESULT CDeviceHandler::InitializeMouse(HWND hWnd){
if (FAILED(m_pD3DInputObject->CreateDevice(GUID_SysMouse, &m_pD3DMouseDevice, NULL)))
return false;
if (FAILED(m_pD3DMouseDevice->SetCooperativeLevel(hWnd, DISCL_BACKGROUND |
DISCL_NONEXCLUSIVE)))
return false;
if (FAILED(m_pD3DMouseDevice->SetDataFormat(&c_dfDIMouse)))
return false;
if (FAILED(m_pD3DMouseDevice->Acquire()))
return false;
return true;
}
HRESULT CDeviceHandler::InitializeKeyboard(HWND hWnd){
if (FAILED(m_pD3DInputObject->CreateDevice(GUID_SysKeyboard, &m_pD3DInputDevice, NULL))) return false;
if (FAILED(m_pD3DInputDevice->SetDataFormat( &c_dfDIKeyboard ))) return false;
if (FAILED(m_pD3DInputDevice->SetCooperativeLevel(hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE))) return false;
ZeroMemory(keys, sizeof(keys) );
m_pD3DInputDevice->GetDeviceState( sizeof(keys), keys );
return true;
}
void CDeviceHandler::UpdateKeyboardState(){
if (FAILED(m_pD3DInputDevice->GetDeviceState( sizeof(keys), keys ))){
// If input is lost then acquire and keep trying until we get it back
while( m_pD3DInputDevice->Acquire() == DIERR_INPUTLOST ){
//Do Nothing
}
// Now get them again
m_pD3DInputDevice->GetDeviceState( sizeof(keys), keys );
}
for(UINT a=0;a<256;++a)
if(m_bKeyDown[a] && !KeyDown(a))
m_bKeyDown[a]=false;
}
void CDeviceHandler::UpdateMouseState(){
m_pD3DMouseDevice->GetDeviceState(sizeof(DIMOUSESTATE), (LPVOID)&mouse_state);
for(UINT a=0;a<4;++a)
if(m_bButtonDown[a] && !MouseButtonDown(a))
m_bButtonDown[a]=false;
}
bool CDeviceHandler::KeyDown(){
for(UINT a=0;a<256;++a)
if (keys[a] & 0x80)
return true;
return false;
}
bool CDeviceHandler::KeyDown(UINT Key){
if (keys[Key] & 0x80)
return true;
return false;
}
bool CDeviceHandler::KeyPress(UINT Key){
if(KeyDown(Key) && !m_bKeyDown[Key]){
m_bKeyDown[Key]=true;
return true;
}
return false;
}
bool CDeviceHandler::KeyRelease(UINT Key){
if(!KeyDown(Key) && m_bKeyDown[Key]){
m_bKeyDown[Key]=false;
return true;
}
return false;
}
bool CDeviceHandler::MouseButtonDown(){
for(UINT a=0;a<5;++a)
if(mouse_state.rgbButtons[a])
return true;
return false;
}
bool CDeviceHandler::MouseButtonDown(UINT Button){
if(mouse_state.rgbButtons[Button])return true;
return false;
}
bool CDeviceHandler::MouseButtonPress(UINT Key){
if(MouseButtonDown(Key) && !m_bButtonDown[Key]){
m_bButtonDown[Key]=true;
return true;
}
return false;
}
bool CDeviceHandler::MouseButtonRelease(UINT Key){
if(!MouseButtonDown(Key) && m_bButtonDown[Key]){
m_bButtonDown[Key]=false;
return true;
}
return false;
}
Vector2 CDeviceHandler::MousePos(){
POINT pos;
GetCursorPos(&pos);
return Vector2((float)pos.x + Global->CAMERA.x, (float)pos.y + Global->CAMERA.y);
} | [
"Sean Stacey@localhost"
] | [
[
[
1,
130
]
]
] |
5d8bb9126d660e88bac2d47f18e85838103ac460 | 521721c2e095daf757ad62a267b1c0f724561935 | /bsRayCastUtil.cpp | ecc1e34895ccd630ef8386becd1064695b0de71e | [] | no_license | MichaelSPG/boms | 251922d78f2db85ece495e067bd56a1e9fae14b1 | 23a13010e0aaa79fea3b7cf1b23e2faab02fa5d4 | refs/heads/master | 2021-01-10T16:23:51.722062 | 2011-12-08T00:04:33 | 2011-12-08T00:04:33 | 48,052,727 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,807 | cpp | #include "StdAfx.h"
#include "bsRayCastUtil.h"
#include "bsAssert.h"
#include "bsMath.h"
#include <Physics/Dynamics/World/hkpWorld.h>
void bsRayCastUtil::castRay(const XMVECTOR& origin, const XMVECTOR& destination,
hkpWorld* world, hkpWorldRayCastOutput& hitCollectorOut)
{
BS_ASSERT(world != nullptr);
hkpWorldRayCastInput input;
input.m_from = bsMath::toHK(origin);
input.m_to = bsMath::toHK(destination);
world->lock();
world->castRay(input, hitCollectorOut);
world->unlock();
}
void bsRayCastUtil::castRay(const XMVECTOR& origin, const XMVECTOR& forward, float rayLength,
hkpWorld* world, hkpWorldRayCastOutput& hitCollectorOut, XMVECTOR& destinationOut)
{
BS_ASSERT2(bsMath::approximatelyEqual(XMVectorGetX(XMVector3LengthSq(forward)), 1.0f),
"Forward vector is not normalized.");
//Calculate destination point of ray.
const XMVECTOR destination = XMVectorAdd(origin, XMVectorScale(forward, rayLength));
destinationOut = destination;
return castRay(origin, destination, world, hitCollectorOut);
}
XMVECTOR bsRayCastUtil::screenSpaceToObjectSpace(const XMVECTOR& screenPoint,
const XMFLOAT2& screenSize, const XMMATRIX& projection, const XMMATRIX& view)
{
return XMVector3Unproject(screenPoint,
0.0f, 0.0f,//Only for rendering subsets of viewport.
screenSize.x, screenSize.y,
0.0f, 1.0f,//Range of depth when rendering.
projection, view, XMMatrixIdentity());
}
hkVector4 bsRayCastUtil::getHitPosition(const hkpWorldRayCastInput& input,
const hkpWorldRayCastOutput& output)
{
BS_ASSERT2(output.hasHit(), "Cannot find hit position for outputs with no hit.");
hkVector4 hitPosition;
hitPosition.setInterpolate(input.m_from, input.m_to,
hkSimdReal::convert(output.m_hitFraction));
return hitPosition;
}
| [
"[email protected]"
] | [
[
[
1,
57
]
]
] |
7d1af5d28eafc92fd346190c8ab30d55223bfd42 | 6bdb3508ed5a220c0d11193df174d8c215eb1fce | /Codes/Halak/GameComponentFactory.inl | 87c0be125b60e502dfc9c5623154ea285e357764 | [] | no_license | halak/halak-plusplus | d09ba78640c36c42c30343fb10572c37197cfa46 | fea02a5ae52c09ff9da1a491059082a34191cd64 | refs/heads/master | 2020-07-14T09:57:49.519431 | 2011-07-09T14:48:07 | 2011-07-09T14:48:07 | 66,716,624 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 295 | inl | namespace Halak
{
template <typename T> void GameComponentFactory::AddEntry()
{
struct Create
{
static GameComponent* Do()
{
return new T();
}
};
AddEntry(T::ClassID, &Create::Do);
}
} | [
"[email protected]"
] | [
[
[
1,
15
]
]
] |
997feb7477c46cafee882fba3ad2d1a2afe5997e | cfa6cdfaba310a2fd5f89326690b5c48c6872a2a | /Sources/Server/M-Server Manager/Sources/Util/CustomControl.h | df359da2ff51b9fcb2fc625fb8eda82976e4214d | [] | no_license | asdlei00/project-jb | 1cc70130020a5904e0e6a46ace8944a431a358f6 | 0bfaa84ddab946c90245f539c1e7c2e75f65a5c0 | refs/heads/master | 2020-05-07T21:41:16.420207 | 2009-09-12T03:40:17 | 2009-09-12T03:40:17 | 40,292,178 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 882 | h | /*
Author : ±èÁ¤ÈÆ(Bill) ([email protected])
Release Date : 2009. 04. 15.
Project Name : Custom Control For MFC contorls
Version : 1.00.00
Test PC : CPU - Pentium(R) 4 2.40Ghz, RAM - 1 GB Graphic - Radeon 9600
Test OS : Windows XP Professional + SP3
Test Application : Visual Studio 2008 + SP1
Contents
Custom Control Header
2009 ¨Ï Copyright MIS Corporation. All Rights Reserved.
*/
#pragma once
#define globalData afxGlobalData
/*
Class : ColorListCtrl Class
Release Date : 2008. 04. 15.
Version : 1.00.00
*/
class CColorListCtrl : public CMFCListCtrl
{
virtual COLORREF OnGetCellTextColor(int nRow, int nColum);
virtual COLORREF OnGetCellBkColor(int nRow, int nColum);
virtual HFONT OnGetCellFont(int nRow, int nColum, DWORD dwData = 0);
public:
BOOL m_bColor;
BOOL m_bModifyFont;
}; | [
"[email protected]"
] | [
[
[
1,
38
]
]
] |
b3e756f8a7c2cec8c146d02fe2e4eea9ec704bf0 | accd6e4daa3fc1103c86d245c784182e31681ea4 | /HappyHunter/Core/AnimationController.cpp | 49b795e0b3a5ca4e553a57c38da952ad5f02bc8c | [] | no_license | linfuqing/zero3d | d87ad6cf97069aea7861332a9ab8fc02b016d286 | cebb12c37fe0c9047fb5b8fd3c50157638764c24 | refs/heads/master | 2016-09-05T19:37:56.213992 | 2011-08-04T01:37:36 | 2011-08-04T01:37:36 | 34,048,942 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 6,269 | cpp | #include "StdAfx.h"
#include "AnimationController.h"
using namespace zerO;
CAnimationController::CAnimationController(void) :
CResource(RESOURCE_ANIMATIONCONTROLLER),
m_bPlayAnim(true),
m_pAnimController(NULL),
m_uCurrentTrack(0),
m_fTimeCurrent(0.0f),
m_uPlayTime(0),
m_fFrameTime(0.0f),
m_lfTotalFrameTime(0.0),
m_uControlPlayTime(0)
{
}
CAnimationController::~CAnimationController(void)
{
Destroy();
}
bool CAnimationController::Create(const LPD3DXANIMATIONCONTROLLER pAnimationController)
{
HRESULT hr = pAnimationController->CloneAnimationController(
pAnimationController->GetMaxNumAnimationOutputs(),
pAnimationController->GetMaxNumAnimationSets(),
pAnimationController->GetMaxNumTracks(),
pAnimationController->GetMaxNumEvents(),
&m_pAnimController);
if( FAILED(hr) )
{
DEBUG_WARNING(hr);
return false;
}
return true;
}
bool CAnimationController::Destroy()
{
DEBUG_RELEASE(m_pAnimController);
m_pAnimController = NULL;
return true;
}
bool CAnimationController::Restore()
{
if (m_pAnimController == NULL)
return false;
m_pAnimController->ResetTime();
m_pAnimController->AdvanceTime( m_fTimeCurrent, NULL );
// Initialize current track
if( m_szASName[0] != '\0' )
{
DWORD dwActiveSet = GetAnimIndex( m_szASName );
LPD3DXANIMATIONSET pAS = NULL;
m_pAnimController->GetAnimationSet( dwActiveSet, &pAS );
m_pAnimController->SetTrackAnimationSet( m_uCurrentTrack, pAS );
DEBUG_RELEASE( pAS );
}
m_pAnimController->SetTrackEnable( m_uCurrentTrack, TRUE );
m_pAnimController->SetTrackWeight( m_uCurrentTrack, 1.0f );
m_pAnimController->SetTrackSpeed( m_uCurrentTrack, 1.0f );
return true;
}
bool CAnimationController::Disable()
{
if (m_pAnimController == NULL)
return false;
LPD3DXANIMATIONSET pAS = NULL;
m_pAnimController->GetTrackAnimationSet(m_uCurrentTrack, &pAS);
if( pAS->GetName() )
strcpy( m_szASName, pAS->GetName() );
DEBUG_RELEASE(pAS);
return true;
}
void CAnimationController::Update()
{
FLOAT fElapsedAppTime = ELAPSEDTIME;
if( 0.0f == fElapsedAppTime )
return;
m_fTimeCurrent += fElapsedAppTime;
if (m_bPlayAnim && m_pAnimController != NULL)
{
if(m_uControlPlayTime == 0 || m_uPlayTime < m_uControlPlayTime)
m_pAnimController->AdvanceTime( fElapsedAppTime, NULL );
// 计算动画播放次数
m_fFrameTime += fElapsedAppTime;
if(m_fFrameTime >= m_lfTotalFrameTime)
{
m_fFrameTime = 0.0f;
m_uPlayTime++;
}
}
}
void CAnimationController::SetAnimation( zerO::UINT index, DWORD dwControlPlayTime, bool bSmooth, zerO::FLOAT fSmoothTranstionTime )
{
if( index >= m_pAnimController->GetNumAnimationSets() )
return;
LPD3DXANIMATIONSET pAnimSet = NULL;
m_pAnimController->GetAnimationSet( index, &pAnimSet );
if(pAnimSet)
{
if(!strcmp(m_strNowAnimSetName.c_str(), pAnimSet->GetName()))
return;
m_strNowAnimSetName = pAnimSet->GetName();
}
m_uPlayTime = 0;
m_fFrameTime = 0.0f;
m_uControlPlayTime = dwControlPlayTime;
if( pAnimSet )
{
m_lfTotalFrameTime = pAnimSet->GetPeriod();
if(bSmooth)
AnimationChangeSmooth(pAnimSet, fSmoothTranstionTime);
else
{
DWORD dwNewTrack = 0;
m_pAnimController->SetTrackAnimationSet( dwNewTrack, pAnimSet );
m_pAnimController->SetTrackEnable( dwNewTrack, TRUE );
}
pAnimSet->Release();
}
}
void CAnimationController::SetAnimationByName( LPSTR pName, DWORD dwControlPlayTime, bool bSmooth, zerO::FLOAT fSmoothTranstionTime )
{
if(m_pAnimController == NULL)
return;
if(!strcmp(m_strNowAnimSetName.c_str(), pName))
return;
m_strNowAnimSetName = pName;
m_uPlayTime = 0;
m_fFrameTime = 0.0f;
m_uControlPlayTime = dwControlPlayTime;
LPD3DXANIMATIONSET pAnimSet = NULL;
m_pAnimController->SetTrackPosition(0, 0.0);
m_pAnimController->GetAnimationSetByName( pName, &pAnimSet );
if( pAnimSet )
{
m_lfTotalFrameTime = pAnimSet->GetPeriod();
if(bSmooth)
AnimationChangeSmooth(pAnimSet, fSmoothTranstionTime);
else
{
DWORD dwNewTrack = 0;
m_pAnimController->SetTrackAnimationSet( dwNewTrack, pAnimSet );
m_pAnimController->SetTrackEnable( dwNewTrack, TRUE );
}
pAnimSet->Release();
}
}
void CAnimationController::AnimationChangeSmooth(LPD3DXANIMATIONSET pAnimSet, zerO::FLOAT fSmoothTranstionTime)
{
DWORD dwNewTrack = ( m_uCurrentTrack == 0 ? 1 : 0 );
m_pAnimController->SetTrackAnimationSet( dwNewTrack, pAnimSet );
m_pAnimController->UnkeyAllTrackEvents( m_uCurrentTrack );
m_pAnimController->UnkeyAllTrackEvents( dwNewTrack );
m_pAnimController->KeyTrackEnable( m_uCurrentTrack, FALSE, m_fTimeCurrent + fSmoothTranstionTime );
m_pAnimController->KeyTrackSpeed( m_uCurrentTrack, 0.0f, m_fTimeCurrent, fSmoothTranstionTime, D3DXTRANSITION_LINEAR );
m_pAnimController->KeyTrackWeight( m_uCurrentTrack, 0.0f, m_fTimeCurrent, fSmoothTranstionTime, D3DXTRANSITION_LINEAR );
m_pAnimController->SetTrackEnable( dwNewTrack, TRUE );
m_pAnimController->KeyTrackSpeed( dwNewTrack, 1.0f, m_fTimeCurrent, fSmoothTranstionTime, D3DXTRANSITION_LINEAR );
m_pAnimController->KeyTrackWeight( dwNewTrack, 1.0f, m_fTimeCurrent, fSmoothTranstionTime, D3DXTRANSITION_LINEAR );
m_uCurrentTrack = dwNewTrack;
}
zerO::UINT CAnimationController::GetPlayTime()
{
// 如果没有动画控制器,则默认播放了一次
if(m_pAnimController == NULL)
m_uPlayTime = 1;
return m_uPlayTime;
}
zerO::UINT CAnimationController::GetAnimIndex( char sString[] )
{
HRESULT hr;
LPD3DXANIMATIONSET pAS;
zerO::UINT dwRet = 0xffffffff;
for( zerO::UINT i = 0; i < m_pAnimController->GetNumAnimationSets(); ++ i )
{
hr = m_pAnimController->GetAnimationSet( i, & pAS );
if( FAILED( hr ) )
continue;
if( pAS->GetName() &&
!strncmp( pAS->GetName(), sString, min( strlen( pAS->GetName() ), strlen( sString ) ) ) )
{
dwRet = i;
pAS->Release();
break;
}
pAS->Release();
}
return dwRet;
}
bool CAnimationController::CanPlay(LPSTR pName, DWORD count)
{
if (strcmp(m_strNowAnimSetName.c_str(), pName) == 0
|| GetPlayTime() >= count)
return true;
return false;
} | [
"[email protected]"
] | [
[
[
1,
242
]
]
] |
4d8fb96d011690205aefa035e7adc72067d443b8 | 45229380094a0c2b603616e7505cbdc4d89dfaee | /lstm/bioinf/lstm/stdafx.cpp | d1bfd88cfca22006a00c1a1080ad23d62ac14656 | [] | no_license | xcud/msrds | a71000cc096723272e5ada7229426dee5100406c | 04764859c88f5c36a757dbffc105309a27cd9c4d | refs/heads/master | 2021-01-10T01:19:35.834296 | 2011-11-04T09:26:01 | 2011-11-04T09:26:01 | 45,697,313 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 291 | cpp | // stdafx.cpp : source file that includes just the standard includes
// lstm.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"perpet99@cc61708c-8d4c-0410-8fce-b5b73d66a671"
] | [
[
[
1,
8
]
]
] |
c01d8a420abc8409d923a61176a822ca405a4214 | bc262760d6268bb7786949c472f9639066a019fa | /layer.h | 7361b03d58e16f89f395016cfb0a050018e10e3e | [] | no_license | Juzezhang/MC-Boost | 0108234a1b5af1c0e4985ac2292b38566619b647 | bcb67c391a63af7a7baa24f4e9050c52659786c5 | refs/heads/master | 2021-05-27T19:40:48.914994 | 2011-09-22T12:02:18 | 2011-09-22T12:02:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,024 | h | // Defines attributes of a layer.
#ifndef LAYER_H
#define LAYER_H
#include "absorber.h"
#include "coordinates.h"
#include <vector>
class Layer
{
public:
Layer(double mu_a, double mu_s, double ref_index, double anisotropy,
double depth_start, double depth_end);
~Layer(void);
// Returns the absorption coefficient of the layer.
double getAbsorpCoeff(void) const {return mu_a;}
// Returns the absorption coeffiecient of the layer based on the photon's coordinates
// Checks are made to see if the photon has made it's way into an absorber as well.
double getAbsorpCoeff(const boost::shared_ptr<Vector3d> photonVector);
// Returns the scattering coefficient of the layer.
double getScatterCoeff(void) const {return mu_s;}
double getScatterCoeff(const boost::shared_ptr<Vector3d> photonVector);
// Returns total interaction coefficient (mu_a + mu_s).
double getTotalAttenuationCoeff(void) const {return mu_t;}
double getTotalAttenuationCoeff(const boost::shared_ptr<Vector3d> photonVector);
// Return the albedo
double getAlbedo(void) const {return albedo;}
// Return the anisotropy of the layer.
double getAnisotropy(void) {return g;}
double getAnisotropy(const boost::shared_ptr<Vector3d> photonVector);
// Return the impedance of the layer.
double getImpedance(void) {return impedance;}
double getDepthStart(void) const {return depth_start;}
double getDepthEnd(void) const {return depth_end;}
// Return the refractive index of the layer.
double getRefractiveIndex(void) const {return refractive_index;}
double getRefractiveIndex(const boost::shared_ptr<Vector3d> photonVector);
void setAbsorpCoeff(const double mu_a);
void setScatterCoeff(const double mu_s);
void updateAlbedo();
void addAbsorber(Absorber * a);
void updateAbsorbedWeightByAbsorber(const boost::shared_ptr<Vector3d> currLocation, const double absorbed);
// Iterate over all absorbers and write their data out to file.
void writeAbsorberData(void);
// Return the absorber at this location 'currLocation' in the medium.
Absorber * getAbsorber(const boost::shared_ptr<Vector3d> currLocation);
private:
// Anisotropy factor.
double g;
// Absorption coefficient
double mu_a;
// Scattering coefficient
double mu_s;
// Transmission coefficient
double mu_t;
// The refractive index of the layer
double refractive_index;
// The width of the layer.
//double radial_size;
// z-coordinate value at which the layer starts.
double depth_start;
// z-coordinate value at which the layer ends.
double depth_end;
// Albedo of the layer.
double albedo;
// The impedance of the layer.
double impedance;
// A vector that holds all the abosrbers in this layer.
std::vector<Absorber *> p_absorbers;
};
#endif // end LAYER_H
| [
"[email protected]"
] | [
[
[
1,
108
]
]
] |
11b03b5c2ac34be4a0dfcf7e695c5564c9bba93e | 3449de09f841146a804930f2a51ccafbc4afa804 | /C++/FluidSystem/src/FluidSystem.h | 8d0ba80bb0ca2a689f66ddc3c9e85ca197f5c704 | [] | no_license | davies/daviescode | 0c244f4aebee1eb909ec3de0e4e77db3a5bbacee | bb00ee0cfe5b7d5388485c59211ebc9ba2d6ecbd | refs/heads/master | 2020-06-04T23:32:27.360979 | 2007-08-19T06:31:49 | 2007-08-19T06:31:49 | 32,641,672 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,379 | h | // FluidSystem.h : main header file for the FLUIDSYSTEM application
//
#if !defined(AFX_FLUIDSYSTEM_H__AB31DD2E_1B8E_48CC_BD9B_EBECC729EB15__INCLUDED_)
#define AFX_FLUIDSYSTEM_H__AB31DD2E_1B8E_48CC_BD9B_EBECC729EB15__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "resource.h" // main symbols
/////////////////////////////////////////////////////////////////////////////
// CFluidSystemApp:
// See FluidSystem.cpp for the implementation of this class
//
class CFluidSystemApp : public CWinApp
{
public:
CFluidSystemApp();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CFluidSystemApp)
public:
virtual BOOL InitInstance();
//}}AFX_VIRTUAL
// Implementation
//{{AFX_MSG(CFluidSystemApp)
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_FLUIDSYSTEM_H__AB31DD2E_1B8E_48CC_BD9B_EBECC729EB15__INCLUDED_)
| [
"davies.liu@32811f3b-991a-0410-9d68-c977761b5317"
] | [
[
[
1,
49
]
]
] |
5ed03523b08fbd61df20141720091a8bbfb5a4a5 | bf19f77fdef85e76a7ebdedfa04a207ba7afcada | /NewAlpha/TMNT Tactics Tech Demo/Source/Ninja.cpp | 85e243477a7b3af1c7dee9a0a3af6a7d513d2989 | [] | no_license | marvelman610/tmntactis | 2aa3176d913a72ed985709843634933b80d7cb4a | a4e290960510e5f23ff7dbc1e805e130ee9bb57d | refs/heads/master | 2020-12-24T13:36:54.332385 | 2010-07-12T08:08:12 | 2010-07-12T08:08:12 | 39,046,976 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,379 | cpp | ////////////////////////////////////////////////////////
// File Name : "Ninja.cpp"
//
// Author : Matthew Di Matteo (MD)
//
// Purpose : To provide a game object to be used as an emeny
// against the user during the game.
////////////////////////////////////////////////////////
#include "Ninja.h"
#include "Assets.h"
#include <cmath>
#include "MessageSystem.h"
#include "ObjectManager.h"
#include "BattleMap.h"
#include "BitmapFont.h"
CNinja::CNinja(void)
{
SetType( OBJECT_NINJA );
m_nAttack = 0;
m_nDefend = 0;
m_nLowHealth = 0;
m_nInRange = 0;
SetBaseAP(16);
SetCurrAP(16);
SetHealthMax(100);
SetHealth(100);
SetVelX(100.0f);
SetVelY(50.0f);
SetLevel(1);
SetStrength(10);
SetDefense(5);
SetAccuracy(10);
SetSpeed(5);
SetRange(2);
SetExperience(0);
m_pPlayer = CPlayer::GetInstance();
m_pTile = CBattleMap::GetInstance()->GetTiles();
m_pBattleMap = CBattleMap::GetInstance();
m_bAttackBool = false;
m_nDamage = 0;
m_nAttacksSoFar = 0;
m_nTotalAttacks = 0;
m_pBitmapFont = CBitmapFont::GetInstance();
}
CNinja::~CNinja(void)
{
for(int j = 0; j < (int)this->GetAnimations().size(); j++)
this->GetAnimations()[j].Unload();
}
void CNinja::AI()
{
//get current x and y tile position then get the x and y tile positions
//of each turtle then set the m_nInRange to however many tiles apart the closest turtle is
m_nInRange = 20;
SetCurrAP(16);
m_nAttacksSoFar = 0;
m_bMovingDone = false;
int distToMikey = abs(m_pPlayer->GetTurtles()[MIKEY]->GetMapCoord().x - GetMapCoord().x) +
abs( m_pPlayer->GetTurtles()[MIKEY]->GetMapCoord().y - GetMapCoord().y);
int distToLeo = abs( m_pPlayer->GetTurtles()[LEONARDO]->GetMapCoord().x - GetMapCoord().x) +
abs(m_pPlayer->GetTurtles()[LEONARDO]->GetMapCoord().y - GetMapCoord().y );
int distToDon = abs(m_pPlayer->GetTurtles()[DONATELLO]->GetMapCoord().x - GetMapCoord().x ) +
abs(m_pPlayer->GetTurtles()[DONATELLO]->GetMapCoord().y - GetMapCoord().y );
int distToRaph = abs(m_pPlayer->GetTurtles()[RAPHAEL]->GetMapCoord().x - GetMapCoord().x ) +
abs(m_pPlayer->GetTurtles()[RAPHAEL]->GetMapCoord().y - GetMapCoord().y );
if( m_pPlayer->GetTurtles()[MIKEY]->GetAlive() == false)
distToMikey = 1000;
if(m_pPlayer->GetTurtles()[LEONARDO]->GetAlive() == false)
distToLeo = 1000;
if( m_pPlayer->GetTurtles()[DONATELLO]->GetAlive() == false)
distToDon = 1000;
if( m_pPlayer->GetTurtles()[RAPHAEL]->GetAlive() == false)
distToRaph = 1000;
if( m_pPlayer->GetTurtles()[MIKEY]->GetAlive() == true)
{
if(distToMikey < distToLeo)
{
if(distToMikey < distToDon)
{
if(distToMikey <= distToRaph)
{
m_nInRange = distToMikey;
m_nXChange = m_pPlayer->GetTurtles()[MIKEY]->GetMapCoord().x - GetMapCoord().x;
m_nYChange = m_pPlayer->GetTurtles()[MIKEY]->GetMapCoord().y - GetMapCoord().y ;
m_nTurtle = MIKEY;
}
}
}
}
if( m_pPlayer->GetTurtles()[LEONARDO]->GetAlive() == true)
{
if(distToLeo < distToMikey)
{
if(distToLeo < distToDon)
{
if(distToLeo <= distToRaph)
{
m_nInRange = distToLeo;
m_nXChange = m_pPlayer->GetTurtles()[LEONARDO]->GetMapCoord().x - GetMapCoord().x;
m_nYChange = m_pPlayer->GetTurtles()[LEONARDO]->GetMapCoord().y - GetMapCoord().y;
m_nTurtle = LEONARDO;
}
}
}
}
if( m_pPlayer->GetTurtles()[DONATELLO]->GetAlive() == true)
{
if(distToDon < distToMikey)
{
if(distToDon < distToLeo)
{
if(distToDon <= distToRaph)
{
m_nInRange = distToDon;
m_nXChange = m_pPlayer->GetTurtles()[DONATELLO]->GetMapCoord().x - GetMapCoord().x;
m_nYChange = m_pPlayer->GetTurtles()[DONATELLO]->GetMapCoord().y - GetMapCoord().y;
m_nTurtle = DONATELLO;
}
}
}
}
if( m_pPlayer->GetTurtles()[RAPHAEL]->GetAlive() == true)
{
if(distToRaph < distToMikey)
{
if(distToRaph < distToLeo)
{
if(distToRaph <= distToDon)
{
m_nInRange = distToRaph;
m_nXChange = m_pPlayer->GetTurtles()[RAPHAEL]->GetMapCoord().x - GetMapCoord().x ;
m_nYChange = m_pPlayer->GetTurtles()[RAPHAEL]->GetMapCoord().y - GetMapCoord().y;
m_nTurtle = RAPHAEL;
}
}
}
}
//map point to set
POINT mapPt;
POINT begin = GetMapCoord();
POINT end;
if(m_nTurtle <= -1)
m_nTurtle = 0;
mapPt.x = -1; mapPt.y = -1;
if (m_nInRange > 8)
m_nInRange = 20;
switch(m_nInRange)
{
//next to turtle
case 20:
{
// should never get here
// need to do something..like move instead of ending turn
// find a tile to move to that's valid
CTile* tiles = m_pBattleMap->GetTiles();
// loop until a valid tile is found
// find a valid map coord
while (true)
{
int change = Random(1, 4);//rand() % 4 - (-4+1) - 4;
end.x = begin.x + change;
change = Random(1, 4);//rand() % (4 - (-4+1) - 4);
end.y = begin.y + change;
if (end.x > 1 && end.y > 1 && end.x < m_pBattleMap->GetNumCols() && end.y < m_pBattleMap->GetNumRows() &&
tiles[end.y*m_pBattleMap->GetNumCols()+end.x].Flag() == FLAG_NONE
&& end.x != begin.x && end.y != begin.y)
break; // found a valid tile
}
m_bMoving = true;
FindPath(begin,end);
}
break;
//one tile away from turtle
case 1:
{
SetCurrAnim(4);
m_nTotalAttacks = 4;
CBattleMap::GetInstance()->UpdatePositions();
m_bAttackBool = true; m_bMoving = false; m_bMovingDone = true;
}
break;
//two tiles away from turtle 1 out of range
case 2:
{
//move in 1 tile (2ap)
switch(abs(m_nXChange))
{
case 0:
mapPt.x = GetMapCoord().x;
//if(x == 0) y == 2
if(m_nYChange > 0)
mapPt.y = GetMapCoord().y + (m_nYChange -1);
else
mapPt.y = GetMapCoord().y + (m_nYChange +1);
break;
case 1:
mapPt.x = GetMapCoord().x + m_nXChange;
mapPt.y = GetMapCoord().y;
break;
case 2:
if(m_nXChange > 0)
{
mapPt.x = GetMapCoord().x + (m_nXChange -1);
mapPt.y = GetMapCoord().y;
}
else
{
mapPt.x = GetMapCoord().x + (m_nXChange +1);
mapPt.y = GetMapCoord().y;
}
break;
}
end = mapPt;
m_bMoving = true;
FindPath(begin, end);
}
break;
//three tiles, move in two tiles
case 3:
{
//move in two tiles(4ap)
switch(abs(m_nXChange))
{
case 0://if x = 0, y = 3
if(m_nYChange > 0)
{
mapPt.x = GetMapCoord().x;
mapPt.y = GetMapCoord().y + (m_nYChange -1);
}
else
{
mapPt.x = GetMapCoord().x;
mapPt.y = GetMapCoord().y + (m_nYChange +1);
}
break;
case 1://if x = 1, y = 2
mapPt.x = GetMapCoord().x;
mapPt.y = GetMapCoord().y + m_nYChange;
break;
case 2://if x = 2, y = 1
mapPt.x = GetMapCoord().x + m_nXChange;
mapPt.y = GetMapCoord().y;
break;
case 3://if x = 3, y = 0
if(m_nXChange > 0)
{
mapPt.x = GetMapCoord().x + (m_nXChange -1);
mapPt.y = GetMapCoord().y;
}
else
{
mapPt.x = GetMapCoord().x + (m_nXChange +1);
mapPt.y = GetMapCoord().y;
}
break;
}
end = mapPt;
m_bMoving = true;
FindPath(begin, end);
}
break;
//four tiles, move in three tiles
case 4:
{
//move in three tiles(6ap)
switch(abs(m_nXChange))
{
case 0://if x = 0, y = 4
if(m_nYChange > 0)
{
mapPt.x = GetMapCoord().x;
mapPt.y = GetMapCoord().y + (m_nYChange -1);
}
else
{
mapPt.x = GetMapCoord().x;
mapPt.y = GetMapCoord().y + (m_nYChange +1);
}
break;
case 1://if x1 y3
mapPt.x = GetMapCoord().x;
mapPt.y = GetMapCoord().y + m_nYChange;
break;
case 2://if x2 y2
mapPt.x = GetMapCoord().x + m_nXChange;
if(m_nYChange >0)
mapPt.y = GetMapCoord().y + (m_nYChange -1);
else
mapPt.y = GetMapCoord().y + (m_nYChange +1);
break;
case 3://if x3 y1
mapPt.x = GetMapCoord().x + m_nXChange;
mapPt.y = GetMapCoord().y;
break;
case 4://if x4 y0
if(m_nXChange > 0)
mapPt.x = GetMapCoord().x + (m_nXChange -1);
else
mapPt.x = GetMapCoord().x + (m_nXChange +1);
mapPt.y = GetMapCoord().y;
break;
}
end = mapPt;
m_bMoving = true;
FindPath(begin, end);
}
break;
//five tiles, move four
case 5:
{
//move four tiles(8ap)
switch(abs(m_nXChange))
{
case 0://if x0 y5
if(m_nYChange > 0)
mapPt.y = GetMapCoord().y + (m_nYChange -1);
else
mapPt.y = GetMapCoord().y + (m_nYChange +1);
mapPt.x = GetMapCoord().x;
break;
case 1://if x1 y4
mapPt.x = GetMapCoord().x;
mapPt.y = GetMapCoord().y + m_nYChange;
break;
case 2://if x2 y3
mapPt.x = GetMapCoord().x + m_nXChange;
if(m_nYChange > 0)
mapPt.y = GetMapCoord().y + (m_nYChange -1);
else
mapPt.y = GetMapCoord().y + (m_nYChange +1);
break;
case 3://if x3 y2
mapPt.y = GetMapCoord().y + m_nYChange;
if(m_nXChange > 0)
mapPt.x = GetMapCoord().x + (m_nXChange -1);
else
mapPt.x = GetMapCoord().x + (m_nXChange +1);
break;
case 4://if x4 y1
mapPt.y = GetMapCoord().y;
mapPt.x = GetMapCoord().x + m_nXChange;
break;
case 5://if x5 y0
if(m_nXChange > 0)
mapPt.x = GetMapCoord().x + (m_nXChange -1);
else
mapPt.x = GetMapCoord().x + (m_nXChange +1);
mapPt.y = GetMapCoord().y;
break;
}
end = mapPt;
m_bMoving = true;
FindPath(begin, end);
}
break;
//six tiles, move five
case 6:
{
//move 5 tiles(10ap)
switch(abs(m_nXChange))
{
case 0://if x0 y6
if(m_nYChange > 0)
mapPt.y = GetMapCoord().y + (m_nYChange -1);
else
mapPt.y = GetMapCoord().y + (m_nYChange -1);
mapPt.x = GetMapCoord().x;
break;
case 1://if x1 y5
mapPt.x = GetMapCoord().x;
mapPt.y = GetMapCoord().y + m_nYChange;
break;
case 2://if x2 y4
mapPt.x = GetMapCoord().x + m_nXChange;
if(m_nYChange > 0)
mapPt.y = GetMapCoord().y + (m_nYChange -1);
else
mapPt.y = GetMapCoord().y + (m_nYChange +1);
break;
case 3://if x3 y3
mapPt.x = GetMapCoord().x + m_nXChange;
if(m_nYChange > 0)
mapPt.y = GetMapCoord().y + (m_nYChange -1);
else
mapPt.y = GetMapCoord().y + (m_nYChange +1);
break;
case 4://if x4 y2
mapPt.y = GetMapCoord().y + m_nYChange;
if(m_nXChange > 0)
mapPt.x = GetMapCoord().x + (m_nXChange -1);
else
mapPt.x = GetMapCoord().x + (m_nXChange +1);
break;
case 5://if x5 y1
mapPt.y = GetMapCoord().y;
mapPt.x = GetMapCoord().x + m_nXChange;
break;
case 6://if x6 y0
mapPt.y = GetMapCoord().y;
if(m_nXChange > 0)
mapPt.x = GetMapCoord().x + (m_nXChange -1);
else
mapPt.x = GetMapCoord().x + (m_nXChange +1);
break;
}
end = mapPt;
m_bMoving = true;
FindPath(begin, end);
}
break;
//7 tiles, move 6
case 7:
{
//move 6 tiles(12ap)
switch(abs(m_nXChange))
{
case 0://if x0 y7
if(m_nYChange > 0)
mapPt.y = GetMapCoord().y + (m_nYChange -1);
else
mapPt.y = GetMapCoord().y + (m_nYChange +1);
mapPt.x = GetMapCoord().x;
break;
case 1://if x1 y6
mapPt.x = GetMapCoord().x;
mapPt.y = GetMapCoord().y + m_nYChange;
break;
case 2://if x2 y5
mapPt.x = GetMapCoord().x + m_nXChange;
if(m_nYChange > 0)
mapPt.y = GetMapCoord().y + (m_nYChange -1);
else
mapPt.y = GetMapCoord().y + (m_nYChange +1);
break;
case 3://if x3 y4
mapPt.x = GetMapCoord().x + m_nXChange;
if(m_nYChange > 0)
mapPt.y = GetMapCoord().y + (m_nYChange -1);
else
mapPt.y = GetMapCoord().y + (m_nYChange +1);
break;
case 4://if x4 y3
mapPt.y = GetMapCoord().y + m_nYChange;
if(m_nXChange > 0)
mapPt.x = GetMapCoord().x + (m_nXChange -1);
else
mapPt.x = GetMapCoord().x + (m_nXChange +1);
break;
case 5://if x5 y2
mapPt.y = GetMapCoord().y + m_nYChange;
if(m_nXChange > 0)
mapPt.x = GetMapCoord().x + (m_nXChange -1);
else
mapPt.x = GetMapCoord().x + (m_nXChange +1);
break;
case 6://if x6 y1
mapPt.y = GetMapCoord().y;
mapPt.x = GetMapCoord().x + m_nXChange;
break;
case 7://if x7 y0
mapPt.y = GetMapCoord().y;
if(m_nXChange > 0)
mapPt.x = GetMapCoord().x + (m_nXChange -1);
else
mapPt.x = GetMapCoord().x + (m_nXChange +1);
break;
}
end = mapPt;
m_bMoving = true;
FindPath(begin, end);
}
break;
//8 tiles, move 7
case 8:
{
//move 7 tiles(14ap)
switch(abs(m_nXChange))
{
case 0://if x0 y8
if(m_nYChange > 0)
mapPt.y = GetMapCoord().y + (m_nYChange -1);
else
mapPt.y = GetMapCoord().y + (m_nYChange +1);
mapPt.x = GetMapCoord().x;
break;
case 1://if x1 y7
mapPt.x = GetMapCoord().x;
mapPt.y = GetMapCoord().y + m_nYChange;
break;
case 2://if x2 y6
mapPt.x = GetMapCoord().x + m_nXChange;
if(m_nYChange > 0)
mapPt.y = GetMapCoord().y + (m_nYChange -1);
else
mapPt.y = GetMapCoord().y + (m_nYChange +1);
break;
case 3://if x3 y5
mapPt.x = GetMapCoord().x + m_nXChange;
if(m_nYChange > 0)
mapPt.y = GetMapCoord().y + (m_nYChange -1);
else
mapPt.y = GetMapCoord().y + (m_nYChange +1);
break;
case 4://if x4 y4
mapPt.x = GetMapCoord().x + m_nXChange;
if(m_nYChange > 0)
mapPt.y = GetMapCoord().y + (m_nYChange -1);
else
mapPt.y = GetMapCoord().y + (m_nYChange +1);
break;
case 5://if x5 y3
mapPt.y = GetMapCoord().y + m_nYChange;
if(m_nXChange > 0)
mapPt.x = GetMapCoord().x + (m_nXChange -1);
else
mapPt.x = GetMapCoord().x + (m_nXChange +1);
break;
case 6://if x6 y2
mapPt.y = GetMapCoord().y + m_nYChange;
if(m_nXChange > 0)
mapPt.x = GetMapCoord().x + (m_nXChange -1);
else
mapPt.x = GetMapCoord().x + (m_nXChange +1);
break;
case 7://if x7 y1
mapPt.x = GetMapCoord().x + m_nXChange;
mapPt.y = GetMapCoord().y;
break;
case 8://if x8 y0
if(m_nXChange > 0)
mapPt.x = GetMapCoord().x + (m_nXChange -1);
else
mapPt.x = GetMapCoord().x + (m_nXChange +1);
mapPt.y = GetMapCoord().y;
break;
}
end = mapPt;
m_bMoving = true;
FindPath(begin, end);
}
break;
default:
{
//end turn
switch(abs(m_nXChange))
{
case 0:
mapPt.x = GetMapCoord().x;
if(m_nYChange > 0)
mapPt.y = GetMapCoord().y + 8;
else
mapPt.y = GetMapCoord().y - 8;
break;
case 1:
mapPt.x = GetMapCoord().x + m_nXChange;
if(m_nYChange > 0)
mapPt.y = GetMapCoord().y + 7;
else
mapPt.y = GetMapCoord().y - 7;
break;
case 2:
mapPt.x = GetMapCoord().x + m_nXChange;
if(m_nYChange > 0)
mapPt.y = GetMapCoord().y + 6;
else
mapPt.y = GetMapCoord().y - 6;
break;
case 3:
mapPt.x = GetMapCoord().x + m_nXChange;
if(m_nYChange > 0)
mapPt.y = GetMapCoord().y + 5;
else
mapPt.y = GetMapCoord().y - 5;
break;
case 4:
mapPt.x = GetMapCoord().x + m_nXChange;
if(m_nYChange > 0)
mapPt.y = GetMapCoord().y + 4;
else
mapPt.y = GetMapCoord().y - 4;
break;
case 5:
mapPt.x = GetMapCoord().x + m_nXChange;
if(m_nYChange > 0)
mapPt.y = GetMapCoord().y + 3;
else
mapPt.y = GetMapCoord().y - 3;
break;
case 6:
mapPt.x = GetMapCoord().x + m_nXChange;
if(m_nYChange > 0)
mapPt.y = GetMapCoord().y + 2;
else
mapPt.y = GetMapCoord().y - 2;
break;
case 7:
mapPt.x = GetMapCoord().x + m_nXChange;
if(m_nYChange > 0)
mapPt.y = GetMapCoord().y + 1;
else
mapPt.y = GetMapCoord().y - 1;
break;
case 8:
mapPt.y = GetMapCoord().y;
if(m_nXChange > 0)
mapPt.x = GetMapCoord().x + 8;
else
mapPt.x = GetMapCoord().x - 8;
break;
}
if(mapPt.x > -1 && mapPt.y > -1)
{
end = mapPt;
//m_bMoving = true;
FindPath(begin, end);
}
else
{
CBattleMap::GetInstance()->SetTurn(true);
}
}
break;
}
}
///////////////////////////////////////////////////////////////////////////////
// Function: FindPath
//
// Purpose: To find a path to get to the turtles
///////////////////////////////////////////////////////////////////////////////
void CNinja::FindPath(POINT begin, POINT end)
{
SetCurrAnim(0);
m_bMovingDone = false;
m_vPath.clear();
POINT ptCurr = begin; // begin point
POINT ptTarget = end; // end point
int range = GetCurrAP(); // max distance movable
int pathWeight = 0;
vector<int> pathX;
vector<int> pathY;
int oldX = ptCurr.x;
int oldY = ptCurr.y;
int nNumCols = CBattleMap::GetInstance()->GetNumCols();
while (true)
{
if (pathX.size() > 0 && ptCurr.x == pathX[pathX.size()-1] && ptCurr.y == pathY[pathX.size()-1])
{ pathWeight = 10000; break; }
if (pathWeight-4 > -1)
{
if ( (ptCurr.x == pathX[pathWeight-4]) && (ptCurr.y == pathY[pathWeight-4]) )
{ pathWeight = 10000; break; }
}
if (pathWeight-1 > -1)
{
pathX.push_back(ptCurr.x);
pathY.push_back(ptCurr.y);
m_vPath.push_back(ptCurr);
oldX = pathX[pathWeight-1];
oldY = pathY[pathWeight-1];
}
++pathWeight;
if (pathWeight*2 > GetCurrAP())
break;
if (ptTarget.x == ptCurr.x && ptTarget.y == ptCurr.y)
break;
if (pathWeight > nNumCols)
{pathWeight = 10000; break;}
if (pathX.size() > 1)
{
if (ptCurr.x < ptTarget.x && (oldX != ptCurr.x + 1) && ptCurr.x+1 != pathX[pathX.size()-2] &&
m_pTile[ptCurr.y * nNumCols + (ptCurr.x+1)].Flag() == FLAG_NONE &&
!CBattleMap::GetInstance()->CheckTileOccupied(ptCurr.y * nNumCols + (ptCurr.x+1)))
{ ++ptCurr.x; continue; }
if (ptCurr.x > ptTarget.x && (oldX != ptCurr.x - 1) && ptCurr.x-1 != pathX[pathX.size()-2] &&
m_pTile[ptCurr.y * nNumCols + (ptCurr.x-1)].Flag() == FLAG_NONE &&
!CBattleMap::GetInstance()->CheckTileOccupied(ptCurr.y * nNumCols + (ptCurr.x-1)))
{ --ptCurr.x; continue; }
if (ptCurr.y < ptTarget.y && (oldY != ptCurr.y + 1) && ptCurr.y+1 != pathY[pathX.size()-2] &&
m_pTile[(ptCurr.y+1) * nNumCols + ptCurr.x].Flag() == FLAG_NONE &&
!CBattleMap::GetInstance()->CheckTileOccupied((ptCurr.y+1) * nNumCols + ptCurr.x))
{ ++ptCurr.y; continue; }
if (ptCurr.y > ptTarget.y && (oldY != ptCurr.y - 1) && ptCurr.y-1 != pathY[pathX.size()-2] &&
m_pTile[(ptCurr.y-1) * nNumCols + ptCurr.x].Flag() == FLAG_NONE &&
!CBattleMap::GetInstance()->CheckTileOccupied((ptCurr.y-1) * nNumCols + ptCurr.x))
{ --ptCurr.y; continue; }
}
else
{
if (ptCurr.x < ptTarget.x && (oldX != ptCurr.x + 1) &&
m_pTile[ptCurr.y * nNumCols + (ptCurr.x+1)].Flag() == FLAG_NONE &&
!CBattleMap::GetInstance()->CheckTileOccupied(ptCurr.y * nNumCols + (ptCurr.x+1)))
{ ++ptCurr.x; continue; }
if (ptCurr.x > ptTarget.x && (oldX != ptCurr.x - 1) &&
m_pTile[ptCurr.y * nNumCols + (ptCurr.x-1)].Flag() == FLAG_NONE &&
!CBattleMap::GetInstance()->CheckTileOccupied(ptCurr.y * nNumCols + (ptCurr.x-1)))
{ --ptCurr.x; continue; }
if (ptCurr.y < ptTarget.y && (oldY != ptCurr.y + 1) &&
m_pTile[(ptCurr.y+1) * nNumCols + ptCurr.x].Flag() == FLAG_NONE &&
!CBattleMap::GetInstance()->CheckTileOccupied((ptCurr.y+1) * nNumCols + ptCurr.x))
{ ++ptCurr.y; continue; }
if (ptCurr.y > ptTarget.y && (oldY != ptCurr.y - 1) &&
m_pTile[(ptCurr.y-1) * nNumCols + ptCurr.x].Flag() == FLAG_NONE &&
!CBattleMap::GetInstance()->CheckTileOccupied((ptCurr.y-1) * nNumCols + ptCurr.x))
{ --ptCurr.y; continue; }
}
if (ptCurr.x == ptTarget.x)
{
if (oldX != ptCurr.x+1 && m_pTile[ptCurr.y * nNumCols + ptCurr.x+1].Flag() == FLAG_NONE &&
!CBattleMap::GetInstance()->CheckTileOccupied(ptCurr.y * nNumCols + ptCurr.x+1) )
{ ++ptCurr.x; continue; }
if (oldX != ptCurr.x-1 && m_pTile[ptCurr.y * nNumCols + ptCurr.x-1].Flag() == FLAG_NONE &&
!CBattleMap::GetInstance()->CheckTileOccupied(ptCurr.y * nNumCols + ptCurr.x-1))
{ --ptCurr.x; continue; }
}
else if (ptCurr.y == ptTarget.y)
{
if (oldY != ptCurr.y+1 && m_pTile[(ptCurr.y+1) * nNumCols + ptCurr.x].Flag() == FLAG_NONE &&
!CBattleMap::GetInstance()->CheckTileOccupied((ptCurr.y+1) * nNumCols + ptCurr.x))
{ ++ptCurr.y; continue; }
if (oldY != ptCurr.y-1 && m_pTile[(ptCurr.y-1) * nNumCols + ptCurr.x].Flag() == FLAG_NONE &&
!CBattleMap::GetInstance()->CheckTileOccupied((ptCurr.y-1) * nNumCols + ptCurr.x))
{ --ptCurr.y; continue; }
}
if ( (ptCurr.x > ptTarget.x) && (oldX != ptCurr.x+1) && m_pTile[ptCurr.y * nNumCols + (ptCurr.x+1)].Flag() == FLAG_NONE &&
!CBattleMap::GetInstance()->CheckTileOccupied(ptCurr.y * nNumCols + (ptCurr.x+1)))
{++ptCurr.x; continue;}
else if (oldX != ptCurr.x-1 && m_pTile[ptCurr.y * nNumCols + (ptCurr.x-1)].Flag() == FLAG_NONE &&
!CBattleMap::GetInstance()->CheckTileOccupied(ptCurr.y * nNumCols + (ptCurr.x-1)))
{--ptCurr.x; continue;}
if ( (ptCurr.y > ptTarget.y) && (oldY != ptCurr.y+1) && m_pTile[(ptCurr.y+1) * nNumCols + ptCurr.x].Flag() == FLAG_NONE &&
!CBattleMap::GetInstance()->CheckTileOccupied((ptCurr.y+1) * nNumCols + ptCurr.x))
{++ptCurr.y; continue;}
else if (oldY != ptCurr.y-1 && m_pTile[(ptCurr.y-1) * nNumCols + ptCurr.x].Flag() == FLAG_NONE &&
!CBattleMap::GetInstance()->CheckTileOccupied((ptCurr.y-1) * nNumCols + ptCurr.x))
{--ptCurr.y; continue;}
pathWeight = 10000; break;
}
if (m_vPath.size() > 0)
{
m_ptStartXY.x = GetPosX();
m_ptStartXY.y = GetPosY();
for (unsigned int i = 0; i < m_vPath.size(); ++i)
m_pTile[m_vPath[i].y * nNumCols + m_vPath[i].x].SetAlpha(199);
}
}
///////////////////////////////////////////////////////////////////////////////
// Function: Update
//
// Purpose: To update the ninja information
///////////////////////////////////////////////////////////////////////////////
void CNinja::Update(float fElapsedTime)
{
bool bTimerDone = m_Timer.Update(fElapsedTime);
m_vAnimations[m_nCurrAnimation].Update(fElapsedTime);
// a ninja needs to be moved...execute the animation and position change over time
if (m_bMoving && !m_bMovingDone)
{
if(GetCurrAnim()->IsAnimationPlaying() && GetCurrAnim()->GetCurrAnimFrame() != 1 && GetCurrAnim()->GetCurrAnimFrame() != 2)
GetCurrAnim()->Stop();
if (m_vPath.size() > 0)
{
// grab the next move and take it out of the vector..if the previous move is complete
POINT newPoint = m_vPath[0];
// set up variables
POINT currPoint= GetMapCoord();
MY_POINT_FLOAT currPos;
currPos.x = GetPosX(); currPos.y = GetPosY();
// NORTHWEST
if ( newPoint.x < currPoint.x && abs(m_ptStartXY.x - currPos.x) < 32 && abs(m_ptStartXY.y - currPos.y) < 16)
{
if(!GetCurrAnim()->IsAnimationPlaying())
SetCurrAnim(2);
SetCurrAnimFacing(false);
currPos.x -= GetVelX() * fElapsedTime;
currPos.y -= GetVelY() * fElapsedTime;
SetPosPtF(currPos);
}
// SOUTHEAST
else if ( newPoint.x > currPoint.x && abs(m_ptStartXY.x - currPos.x) < 32 && abs(m_ptStartXY.y - currPos.y) < 16)
{
if(!GetCurrAnim()->IsAnimationPlaying())
SetCurrAnim(1);
SetCurrAnimFacing(true);
currPos.x += GetVelX() * fElapsedTime;
currPos.y += GetVelY() * fElapsedTime;
SetPosPtF(currPos);
}
// NORTHEAST
if ( newPoint.y < currPoint.y && abs(m_ptStartXY.x - currPos.x) < 32 && abs(m_ptStartXY.y - currPos.y) < 16)
{
if(!GetCurrAnim()->IsAnimationPlaying())
SetCurrAnim(2);
SetCurrAnimFacing(true);
currPos.y -= GetVelY() * fElapsedTime;
currPos.x += GetVelX() * fElapsedTime;
SetPosPtF(currPos);
}
// SOUTHWEST
else if ( newPoint.y > currPoint.y && abs(m_ptStartXY.x - currPos.x) < 32 && abs(m_ptStartXY.y - currPos.y) < 16)
{
if(!GetCurrAnim()->IsAnimationPlaying())
SetCurrAnim(1);
SetCurrAnimFacing(false);
currPos.y += GetVelY() * fElapsedTime;
currPos.x -= GetVelX() * fElapsedTime;
SetPosPtF(currPos);
}
// check to see if this current tile move is complete
if ( abs(m_ptStartXY.x - currPos.x) >= 32 && abs(m_ptStartXY.y - currPos.y) >= 16)
{
vector<POINT>::iterator first = m_vPath.begin();
m_vPath.erase(first);
SetCurrTile(newPoint, CBattleMap::GetInstance()->GetOffsetX(), CBattleMap::GetInstance()->GetOffsetY(), CBattleMap::GetInstance()->GetTileWidth(),
CBattleMap::GetInstance()->GetTileHeight(), CBattleMap::GetInstance()->GetNumCols());
DecrementCurrAP(2);
m_nInRange--;
m_ptStartXY.x = GetPosX();
m_ptStartXY.y = GetPosY();
if (m_vPath.size() == 0)
m_bMovingDone = true;
if(m_nInRange == 1 && GetCurrAP() >=4)
{
m_bMovingDone = true;
if( GetCurrAP() == 4)
m_nTotalAttacks = 1;
else if( GetCurrAP() >= 8 && GetCurrAP() < 12)
m_nTotalAttacks = 2;
else if(GetCurrAP() >= 12)
m_nTotalAttacks = 3;
SetCurrAnim(4);
m_bAttackBool = true; m_bMoving = false;
m_Timer.StartTimer(0.25f);
}
}
}
}
if (m_bMovingDone)// movement and attack MUST be done by this point
{
//attack check
if (m_bAttackBool == true)
{
if(!m_vAnimations[4].IsAnimationPlaying() /*&& m_Timer.GetElapsed() > 1.0f*/)
{
CBattleMap::GetInstance()->PlaySFX(CAssets::GetInstance()->aBMninjaAttackSnd);
m_nDamage = this->GetStrength() * (this->GetAccuracy()/ (m_pPlayer->GetTurtles()[m_nTurtle]->GetDefense() + m_pPlayer->GetTurtles()[m_nTurtle]->GetCurrWeapon()->GetDefense()));
m_nDamage += rand() % (5 - (-4)) -5;
m_pPlayer->GetTurtles()[m_nTurtle]->SetHealth(m_pPlayer->GetTurtles()[m_nTurtle]->GetHealth() - m_nDamage);
m_pPlayer->GetTurtles()[m_nTurtle]->AddDamageRecieved(m_nDamage);
SetCurrAnim(4);
//m_Timer.StartTimer(1.5f);
m_nAttacksSoFar++;
m_pBattleMap->PlaySFX(CAssets::GetInstance()->aBMpainSnd);
}
else if(m_nAttacksSoFar >= m_nTotalAttacks)
{
SetCurrAnim(0);
//m_Timer.StartTimer(1.0f);
m_bMoving = m_bAttackBool = m_bMovingDone = false;
CBattleMap::GetInstance()->SetTurn(true);
}
//end of attack
}
else
{
if(GetCurrAnim()->IsAnimationPlaying() && GetCurrAnim()->GetCurrAnimFrame() != 4)
SetCurrAnim(0);
m_bMoving = m_bAttackBool = false;
if (m_nAttacksSoFar >= m_nTotalAttacks)
{
CBattleMap::GetInstance()->UpdatePositions();
CBattleMap::GetInstance()->NinjaMoveComplete();
SetCurrAnim(0);
m_bMovingDone = false;
CBattleMap::GetInstance()->SetTurn(true);
}
CBattleMap::GetInstance()->SetTurn(true);
}
}
// //attack check
// if (m_bAttackBool == true)
// {
// if(!m_vAnimations[4].IsAnimationPlaying() /*&& m_Timer.GetElapsed() > 1.0f*/)
// {
// CBattleMap::GetInstance()->PlaySFX(CAssets::GetInstance()->aBMninjaAttackSnd);
//
// m_nDamage = this->GetStrength() * (this->GetAccuracy()/ (m_pPlayer->GetTurtles()[m_nTurtle]->GetDefense() + m_pPlayer->GetTurtles()[m_nTurtle]->GetCurrWeapon()->GetDefense()));
// m_nDamage += rand() % (5 - (-4)) -5;
//
// m_pPlayer->GetTurtles()[m_nTurtle]->SetHealth(m_pPlayer->GetTurtles()[m_nTurtle]->GetHealth() - m_nDamage);
//
// m_pPlayer->GetTurtles()[m_nTurtle]->AddDamageRecieved(m_nDamage);
//
// SetCurrAnim(4);
// //m_Timer.StartTimer(1.5f);
//
// m_nAttacksSoFar++;
// }
// else if(m_nAttacksSoFar >= m_nTotalAttacks)
// {
// SetCurrAnim(0);
// //m_Timer.StartTimer(1.0f);
// m_bAttackBool = false;
// CBattleMap::GetInstance()->SetTurn(true);
// }
// }
if(GetHealth() <= 0)
{
int type = rand() % 5;
if(type < 3) MessageSystem::GetInstance()->SendMsg(new CCreateItem(this));
else if (type < 4) MessageSystem::GetInstance()->SendMsg(new CCreateWeapon(this));
return;
}
if( GetExperience() >= (100 * GetLevel()) ) // each level requires lvl * 100 xp
{
SetExperience( GetExperience() - (100* GetLevel()) );
CBase::SetLevel(GetLevel()+1);
SetHealthMax((int)((float)GetMaxHealth() * 1.25f));
SetHealth((int)GetMaxHealth());
//SetBaseAP(GetBaseAP()+2);
SetBaseAP(16);
SetStrength( (int)( (float)GetStrength() * 1.2f ) );
SetDefense( (int) ( (float)GetDefense() * 1.2f ) );
SetAccuracy( (int) ( (float)GetAccuracy() * 1.2f ) );
SetSpeed( (int) ( (float)GetSpeed() * 1.2f ) );
}
}
void CNinja::Render()
{
m_vAnimations[m_nCurrAnimation].Render((int)GetPosX()+m_vAnimations[0].GetFrames()[0].nAnchorX, (int)GetPosY()+m_vAnimations[0].GetFrames()[0].nAnchorY, GetPosZ(), 1, m_dwColor);
if(m_bAttackBool && m_nDamage != 0)
{
int offset = (int)(m_Timer.GetElapsed()*20.0f )-15;
m_pBitmapFont->ChangeBMFont(CAssets::GetInstance()->aBitmapFontBubblyID,16,15,20);
int nXP = 10;
//ninja xp
char tempXP[16];
sprintf_s(tempXP, "+%i", nXP);
m_pBitmapFont->DrawString(tempXP,(int)GetPosX()+5,(int)GetPosY()-offset,0.4f,0.9f,D3DCOLOR_XRGB(255,255,0));
//player damage
char tempDmg[16];
sprintf_s(tempDmg, "-%i", m_nDamage);
m_pBitmapFont->DrawString(tempDmg,(int)m_pPlayer->GetTurtles()[m_nTurtle]->GetPosX()+5, (int)m_pPlayer->GetTurtles()[m_nTurtle]->GetPosY()-offset,0.3f,0.9f,D3DCOLOR_XRGB(255,0,0));
m_pBitmapFont->Reset();
}
}
void CNinja::SetLevel(int nLevel)
{
nLevel--;
SetExperience(0);
CBase::SetLevel(nLevel+1);
//SetBaseAP( GetBaseAP() + (nLevel*2)-2 );
SetBaseAP( 16 );
SetHealthMax((int) ((float)GetMaxHealth() + (26 * nLevel)) );
SetStrength( (int) ((float)GetStrength() + (1 * nLevel)) );
SetDefense( (int) ((float)GetDefense() + (0.5f * nLevel)) );
SetAccuracy( (int) ((float)GetAccuracy() + (1 * nLevel)) );
SetHealth((int)GetMaxHealth());
} | [
"AllThingsCandid@7dc79cba-3e6d-11de-b8bc-ddcf2599578a",
"jsierra099@7dc79cba-3e6d-11de-b8bc-ddcf2599578a",
"marvelman610@7dc79cba-3e6d-11de-b8bc-ddcf2599578a"
] | [
[
[
1,
11
],
[
13,
14
],
[
17,
35
],
[
37,
39
],
[
41,
45
],
[
48,
48
],
[
56,
65
],
[
68,
68
],
[
71,
71
],
[
73,
80
],
[
83,
83
],
[
85,
85
],
[
87,
87
],
[
89,
89
],
[
93,
93
],
[
95,
95
],
[
97,
97
],
[
99,
99
],
[
110,
110
],
[
112,
112
],
[
114,
114
],
[
116,
116
],
[
127,
127
],
[
129,
129
],
[
131,
131
],
[
133,
133
],
[
144,
144
],
[
146,
146
],
[
148,
148
],
[
150,
150
],
[
159,
160
],
[
164,
165
],
[
168,
193
],
[
196,
196
],
[
201,
202
],
[
218,
218
],
[
223,
223
],
[
230,
230
],
[
233,
234
],
[
237,
237
],
[
249,
249
],
[
252,
252
],
[
266,
266
],
[
269,
269
],
[
277,
278
],
[
281,
281
],
[
298,
298
],
[
301,
302
],
[
313,
313
],
[
324,
324
],
[
327,
327
],
[
347,
347
],
[
354,
354
],
[
365,
365
],
[
372,
372
],
[
375,
375
],
[
391,
391
],
[
402,
402
],
[
409,
409
],
[
416,
416
],
[
427,
427
],
[
430,
430
],
[
432,
433
],
[
439,
439
],
[
490,
490
],
[
492,
492
],
[
501,
501
],
[
559,
559
],
[
561,
561
],
[
637,
637
],
[
646,
647
],
[
656,
656
],
[
660,
660
],
[
666,
666
],
[
670,
671
],
[
690,
690
],
[
693,
730
],
[
734,
735
],
[
737,
738
],
[
743,
744
],
[
746,
747
],
[
751,
752
],
[
754,
755
],
[
758,
759
],
[
761,
762
],
[
771,
771
],
[
779,
780
],
[
783,
785
],
[
854,
855
],
[
859,
859
],
[
868,
869
],
[
872,
879
],
[
881,
881
],
[
883,
884
],
[
886,
886
],
[
888,
888
],
[
890,
891
],
[
893,
901
],
[
904,
906
],
[
912,
919
],
[
922,
949
],
[
951,
953
],
[
955,
963
],
[
965,
965
],
[
969,
976
],
[
981,
981
],
[
990,
990
],
[
995,
995
],
[
1013,
1013
]
],
[
[
12,
12
],
[
15,
15
],
[
36,
36
],
[
46,
47
],
[
49,
49
],
[
66,
67
],
[
69,
70
],
[
72,
72
],
[
81,
82
],
[
84,
84
],
[
86,
86
],
[
88,
88
],
[
90,
92
],
[
94,
94
],
[
96,
96
],
[
98,
98
],
[
100,
109
],
[
111,
111
],
[
113,
113
],
[
115,
115
],
[
117,
126
],
[
128,
128
],
[
130,
130
],
[
132,
132
],
[
134,
143
],
[
145,
145
],
[
147,
147
],
[
149,
149
],
[
151,
158
],
[
161,
163
],
[
166,
166
],
[
194,
195
],
[
197,
198
],
[
203,
217
],
[
219,
222
],
[
224,
229
],
[
231,
232
],
[
235,
236
],
[
238,
248
],
[
250,
251
],
[
253,
265
],
[
267,
268
],
[
270,
276
],
[
279,
280
],
[
282,
297
],
[
299,
300
],
[
303,
312
],
[
314,
323
],
[
325,
326
],
[
328,
346
],
[
348,
353
],
[
355,
364
],
[
366,
371
],
[
373,
374
],
[
376,
390
],
[
392,
401
],
[
403,
408
],
[
410,
415
],
[
417,
426
],
[
428,
429
],
[
431,
431
],
[
434,
438
],
[
440,
489
],
[
491,
491
],
[
493,
500
],
[
502,
558
],
[
560,
560
],
[
562,
636
],
[
638,
645
],
[
648,
654
],
[
657,
659
],
[
661,
665
],
[
667,
669
],
[
672,
689
],
[
691,
692
],
[
731,
733
],
[
736,
736
],
[
739,
742
],
[
745,
745
],
[
748,
750
],
[
753,
753
],
[
756,
757
],
[
760,
760
],
[
763,
770
],
[
772,
778
],
[
786,
786
],
[
790,
801
],
[
806,
812
],
[
816,
822
],
[
827,
833
],
[
838,
853
],
[
856,
856
],
[
858,
858
],
[
862,
862
],
[
870,
871
],
[
880,
880
],
[
882,
882
],
[
885,
885
],
[
887,
887
],
[
889,
889
],
[
892,
892
],
[
902,
903
],
[
950,
950
]
],
[
[
16,
16
],
[
40,
40
],
[
50,
55
],
[
167,
167
],
[
199,
200
],
[
655,
655
],
[
781,
782
],
[
787,
789
],
[
802,
805
],
[
813,
815
],
[
823,
826
],
[
834,
837
],
[
857,
857
],
[
860,
861
],
[
863,
867
],
[
907,
911
],
[
920,
921
],
[
954,
954
],
[
964,
964
],
[
966,
968
],
[
977,
980
],
[
982,
989
],
[
991,
994
],
[
996,
1012
]
]
] |
41b0a50fc5a174e3334b64d64760f679544095e2 | 4fc5ea796f7a695498250913453fab1f2b7e8baa | /src/projectmanager.h | 51f33e01ba396feabd00e41afabeee11f9d7c97a | [] | no_license | apavelm/qsqldesigner | ed5522a99b499fe8082dc917f23a2fd08bdeae0a | 90ceff97249456d826901ac772ef3e9983fe8dcb | refs/heads/master | 2016-09-06T18:27:08.716947 | 2010-12-21T13:11:59 | 2010-12-21T13:11:59 | 32,121,169 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,698 | h | /***************************************************************************
* Copyright (C) 2010 by Pavel Andreev *
* Mail: apavelm on gmail point com ([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 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, you can read it *
* here <http://www.gnu.org/licenses/>, or write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef PROJECTMANAGER_H
#define PROJECTMANAGER_H
#include <QtCore/QList>
#include <QtCore/QObject>
#include "singleton.h"
#include "sqldesignerproject.h"
class ProjectManager: public QObject, public Singleton<ProjectManager>
{
Q_OBJECT
public:
PSqlDesignerProject currentProject();
QList<QString> projectNames() const;
private:
friend class Singleton<ProjectManager>;
ProjectManager();
virtual ~ProjectManager();
QList<SharedSqlDesignerProject> m_projectList;
QString m_currentProjectName;
QString defaultProjectName(const QString projectName = tr("Untitled"));
public slots:
void newProject(const QString& projectName, const QString& dbmsType);
void openProject(const QString& fileName);
void closeProject(const QString& projectName = QString());
void closeAllProjects();
void setCurrentProject(const QString& projectName);
signals:
void currentProjectChanged(QString);
};
#define PROJECTMANAGER ProjectManager::getInstance()
#define CURRENTPROJECT ProjectManager::getInstance()->currentProject()
#endif // PROJECTMANAGER_H
| [
"[email protected]@b976079f-fb2a-2d15-3876-d33d174e65f6"
] | [
[
[
1,
61
]
]
] |
78cc4d9b5090f91dc7bbb96eb861af9fdf14eec5 | a405cf24ef417f6eca00c688ceb9008d80f84e1a | /trunk/DataObject.h | 366de530f4b1131309b32084b56cad4cd768dff6 | [] | no_license | BackupTheBerlios/nassiplugin-svn | 186ac2b1ded4c0bf7994e6309150aa23bc70b644 | abd9d809851d58d7206008b470680a23d0548ef6 | refs/heads/master | 2020-06-02T21:23:32.923994 | 2010-02-23T21:37:37 | 2010-02-23T21:37:37 | 40,800,406 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,315 | h | #ifdef __GNUG__
// #pragma interface
#endif
#ifndef __DATAOBJECT_H__
#define __DATAOBJECT_H__
#include <wx/dataobj.h>
static const wxChar *NassiFormatId = _T("NassiDataFormat");
class NassiView;
class NassiBrick;
class NassiDataObject : public wxDataObject
{
public:
NassiDataObject(NassiBrick *brick, NassiView *view, wxString strc = _T("X"), wxString strs = _T("case :") );
virtual ~NassiDataObject();
NassiBrick *GetBrick(void);
wxString GetText(wxInt32 n = 0);
virtual wxDataFormat GetPreferredFormat(Direction dir) const;
virtual size_t GetFormatCount(Direction dir) const;
virtual void GetAllFormats(wxDataFormat *formats, Direction dir) const;
virtual size_t GetDataSize(const wxDataFormat& format) const;
virtual bool SetData(const wxDataFormat& format, size_t len, const void *buf);
virtual bool GetDataHere(const wxDataFormat& format, void *pBuf)const;
bool HasBrick();
private:
NassiDataObject(const NassiDataObject &p);
NassiDataObject &operator=(const NassiDataObject &rhs);
private:
wxDataFormat m_format;
wxBitmapDataObject m_dobjBitmap;
NassiBrick *m_firstbrick;
bool m_hasBitmap;
wxString m_caseSource, m_caseComment;
};
#endif
| [
"danselmi@1ca45b2e-1973-0410-a226-9012aad761af"
] | [
[
[
1,
42
]
]
] |
0d29918020078fbab925ea969b82fe0b24a6a84c | 8bbbcc2bd210d5608613c5c591a4c0025ac1f06b | /nes/mapper/068.cpp | 694a348d9af8c8b16eab2c715eb43abd8e196570 | [] | no_license | PSP-Archive/NesterJ-takka | 140786083b1676aaf91d608882e5f3aaa4d2c53d | 41c90388a777c63c731beb185e924820ffd05f93 | refs/heads/master | 2023-04-16T11:36:56.127438 | 2008-12-07T01:39:17 | 2008-12-07T01:39:17 | 357,617,280 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,511 | cpp |
/////////////////////////////////////////////////////////////////////
// Mapper 68
void NES_mapper68_Init()
{
g_NESmapper.Reset = NES_mapper68_Reset;
g_NESmapper.MemoryWrite = NES_mapper68_MemoryWrite;
}
void NES_mapper68_Reset()
{
// set CPU bank pointers
g_NESmapper.set_CPU_banks4(0,1,g_NESmapper.num_8k_ROM_banks-2,g_NESmapper.num_8k_ROM_banks-1);
g_NESmapper.Mapper68.regs[0] = 0;
g_NESmapper.Mapper68.regs[1] = 0;
g_NESmapper.Mapper68.regs[2] = 0;
g_NESmapper.Mapper68.regs[3] = 0;
}
void NES_mapper68_MemoryWrite(uint32 addr, uint8 data)
{
switch(addr & 0xF000)
{
case 0x8000:
{
g_NESmapper.set_PPU_bank0(data*2+0);
g_NESmapper.set_PPU_bank1(data*2+1);
}
break;
case 0x9000:
{
g_NESmapper.set_PPU_bank2(data*2+0);
g_NESmapper.set_PPU_bank3(data*2+1);
}
break;
case 0xA000:
{
g_NESmapper.set_PPU_bank4(data*2+0);
g_NESmapper.set_PPU_bank5(data*2+1);
}
break;
case 0xB000:
{
g_NESmapper.set_PPU_bank6(data*2+0);
g_NESmapper.set_PPU_bank7(data*2+1);
}
break;
case 0xC000:
{
g_NESmapper.Mapper68.regs[2] = data;
NES_mapper68_SyncMirror();
}
break;
case 0xD000:
{
g_NESmapper.Mapper68.regs[3] = data;
NES_mapper68_SyncMirror();
}
break;
case 0xE000:
{
g_NESmapper.Mapper68.regs[0] = (data & 0x10) >> 4;
g_NESmapper.Mapper68.regs[1] = data & 0x03;
NES_mapper68_SyncMirror();
}
break;
case 0xF000:
{
g_NESmapper.set_CPU_bank4(data*2);
g_NESmapper.set_CPU_bank5(data*2+1);
}
break;
}
}
void NES_mapper68_SyncMirror()
{
if(g_NESmapper.Mapper68.regs[0])
{
if (g_NESmapper.Mapper68.regs[1] == 0)
{
g_NESmapper.set_PPU_bank8(g_NESmapper.Mapper68.regs[2] + 0x80); // + 0x20000
g_NESmapper.set_PPU_bank9(g_NESmapper.Mapper68.regs[3] + 0x80);
g_NESmapper.set_PPU_bank10(g_NESmapper.Mapper68.regs[2] + 0x80);
g_NESmapper.set_PPU_bank11(g_NESmapper.Mapper68.regs[3] + 0x80);
}
else if (g_NESmapper.Mapper68.regs[1] == 1)
{
g_NESmapper.set_PPU_bank8(g_NESmapper.Mapper68.regs[2] + 0x80);
g_NESmapper.set_PPU_bank9(g_NESmapper.Mapper68.regs[2] + 0x80);
g_NESmapper.set_PPU_bank10(g_NESmapper.Mapper68.regs[3] + 0x80);
g_NESmapper.set_PPU_bank11(g_NESmapper.Mapper68.regs[3] + 0x80);
}
else if (g_NESmapper.Mapper68.regs[1] == 2)
{
g_NESmapper.set_PPU_bank8(g_NESmapper.Mapper68.regs[2] + 0x80);
g_NESmapper.set_PPU_bank9(g_NESmapper.Mapper68.regs[2] + 0x80);
g_NESmapper.set_PPU_bank10(g_NESmapper.Mapper68.regs[2] + 0x80);
g_NESmapper.set_PPU_bank11(g_NESmapper.Mapper68.regs[2] + 0x80);
}
else if (g_NESmapper.Mapper68.regs[1] == 3)
{
g_NESmapper.set_PPU_bank8(g_NESmapper.Mapper68.regs[3] + 0x80);
g_NESmapper.set_PPU_bank9(g_NESmapper.Mapper68.regs[3] + 0x80);
g_NESmapper.set_PPU_bank10(g_NESmapper.Mapper68.regs[3] + 0x80);
g_NESmapper.set_PPU_bank11(g_NESmapper.Mapper68.regs[3] + 0x80);
}
}
else
{
if (g_NESmapper.Mapper68.regs[1] == 0)
{
g_NESmapper.set_mirroring2(NES_PPU_MIRROR_VERT);
}
else if (g_NESmapper.Mapper68.regs[1] == 1)
{
g_NESmapper.set_mirroring2(NES_PPU_MIRROR_HORIZ);
}
else if (g_NESmapper.Mapper68.regs[1] == 2)
{
g_NESmapper.set_mirroring(0,0,0,0);
}
else if (g_NESmapper.Mapper68.regs[1] == 3)
{
g_NESmapper.set_mirroring(1,1,1,1);
}
}
}
/////////////////////////////////////////////////////////////////////
| [
"takka@e750ed6d-7236-0410-a570-cc313d6b6496"
] | [
[
[
1,
138
]
]
] |
6fa348feb75f4ba424734948e5d5b285e7345b8e | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Targets/WayFinder/symbian/CommunicationWizardBase.h | 1be93adb9e3b8694a9f38b9b5311e2b3dc3551fa | [
"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 | 13,913 | h | /*
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.
*/
#ifndef COMMUNICATION_WIZARD_GENERIC_H
#define COMMUNICATION_WIZARD_GENERIC_H
#include <e32base.h>
#include <badesca.h>
#include "ContactBkObserver.h" // ContactBkEngineObserver
#include "SmsHandlerObserver.h" // SmsHandlerObserver
#include "EventGenerator.h" // EventGenerator
#include "GuiProt/GuiProtMessageSender.h" // GuiProtMessageReceiver
#include "GuiProt/ServerEnums.h"
#include <vector>
namespace isab{
class Favorite;
class GuiFavorite;
class GetFavoritesReplyMess;
class GetFavoritesAllDataReplyMess;
class GetFavoriteInfoReplyMess;
class AdditionalInfo;
}
enum TWizardSteps {
EWhatToSend = 100,
EValidateContentChoice,
EGetSelectedFavorite,
ESendAs,
EHowToAddRecipient,
EAddRecipient,
EShowSelectedContact,
EStoreContactDetail,
EValidateManualInput,
ESubject,
EFormatMessage,
EConfirmation,
ESendMessage,
EQuit,
};
enum TWizContent
{
EWfCurRoute,
EWfGpsPosition,
EWfMapPosition,
EWfCurDestination,
EWfFavorite,
EWfNotSpecified
};
enum TWizTransmitAS
{
EWfSMS,
EWfEmail,
EWfMMS
};
enum THowToAddRecipient
{
EFromPhoneBook,
EEnterManually
};
enum TDialogTypeEvent
{
ESubjectDialog,
ENonValidPhoneNbrDialog,
ENonValidEmailDialog,
EContactBookBusyDialog
};
/**
* Class that lets a user send a wayfinder sms or a mail
* containing a route or a destinatin etc. It is built
* up to be a wizard, the user is able to go back and
* forward through the wizard that is built up by dialogs.
* This class handles the logic, switching between the different
* steps in the wizard etc. The subclasses displays all the dialogs.
*/
class CCommunicationWizardBase : public CBase,
public GuiProtMessageReceiver,
public MSmsHandlerObserver,
public MContactBkObserver
{
protected:
CCommunicationWizardBase(class GuiProtMessageSender& aSender);
public:
virtual ~CCommunicationWizardBase();
/**
* The initial phase for the wizard, gets called when
* the wizard is to be launched. By defined aPreDefinedContent
* with a value other than EWfNotSpecified the wizard becomes
* context sensitive. The wizard the skipps the "What to send"
* step and jump right to the next step.
* @param aPreDefinedContent, if set to other value then EWfNotSpecified
* the wizard will skipp "What to send".
* If this step is wanted then don't specify
* a value for this though it is defaulted to
* EWfNotSpecified.
*/
void StartWizardL(TWizContent aPreDefinedContent = EWfNotSpecified,
isab::Favorite* aFavorite = NULL);
/**
* Generates av event.
* @param aEvent The event to be generated.
*/
void GenerateEvent(enum TWizardSteps aEvent);
/**
* Handles the generated event.
* @param eEvent The event to be handled.
*/
void HandleGeneratedEventL(enum TWizardSteps aEvent);
public: // From base classes
/**
* From MContactBkEngineObserver
*/
void ContactBkSearchDone(TInt aError);
void ContactBkInUse();
/**
* From MSmsHandlerObserver
*/
void SmsSent(TInt aStatus, TInt aCount, TInt aNbrSent);
void SmsReceived(class CSmsParser* aSmsParser, TInt32 aMsvId);
/**
* From GuiProtMessageReceiver
*/
virtual bool GuiProtReceiveMessage(isab::GuiProtMess* mess);
protected:
/**
* If user selected to send a favorite we need to ask the
* server for it, if not just generate an event and move on.
*/
void ValidateContentChoiceL();
/**
* Validates the manually entered phone number.
*/
void ValidatePhoneNbrL();
/**
* Validates the manually entered email adress.
*/
void ValidateEmailAdressL();
/**
* Resets, deletes and allocates the iContentArray.
* @param aNbrIndex The granularity of the array.
*/
void ResetContentArray(TUint aNbrIndex);
/**
* Asks nav2 about all information about a specific favorite.
*/
void GetSelectedFavoriteL();
/**
* Formates the message to be sent.
* @aMessage The variable holding the formated message when done.
*/
void FormatMessageL(HBufC*& aMessage);
/**
* Sends the message, email/sms.
*/
void SendMessageL();
/**
* Cleans up
*/
void CleanUp();
protected: // Struct holding the data to be sent
/**
* Struct that holds information about the message
* that is about to be sent.
*/
struct TWizardData
{
/// The content, route/destination etc.
enum TWizContent iContent;
/// How to send the message, sms/email.
enum TWizTransmitAS iTransmitAs;
/// Objecttype, needed when formating the message.
enum isab::GuiProtEnums::ObjectType iObjectType;
/// The recipient, phone nbr.
TBuf<256> iSmsRecipient;
/// The recipient, email adress.
TBuf<256> iEmailRecipient;
/// The formated message to be sent.
HBufC* iMessage;
/// The resource id of the user text that should
/// be a part of the message.
TInt iPersonalMessageId;
/// Signature, the personal message converted to a char*.
char* iSignature;
};
protected: // Pure virtual functions
/**
* Displays a list of the content that is possible to send.
*/
virtual void ShowWhatToSendDialogL() = 0;
/**
* Displays a list of all the stored favorites.
* @param aMessage A message from server/nav2 that contains all
* favorites in a vector.
*/
virtual void ShowFavoriteListL(isab::GetFavoritesReplyMess* aMessage) = 0;
/**
* Displays a list of how the selcted content should be sent.
*/
virtual void ShowSendAsDialogL() = 0;
/**
* List that lets the user select how to add the recipient,
* from the contact book or manually.
*/
virtual void ShowHowToAddRecipientDialogL() = 0;
/**
* Dialog that lets the user enter a phone number or
* email adress.
*/
virtual void ShowEnterManuallyDialogL() = 0;
/**
* Displays all contact info for a selected contact.
*/
virtual void ShowContactDetailsDialogL() = 0;
/**
* Dislplays a dialog that lets the user confirm that en email/sms
* is going to be sent.
*/
virtual void ShowConfirmationDialogL() = 0;
/**
* Dislplays a dialog.
* @param aNextEvent The event to be triggered when user presses
* the left soft key.
* @param aBackEvent The event to be triggered when user presses
* the right soft key.
* @param aHeader The id for the title.
* @param aText The id for the text to be displayed in the body.
* @param aResourceId The resource id for the dialog to be displayed.
*/
virtual void ShowGenericInfoDialogL(TWizardSteps aNextEvent,
TWizardSteps aBackEvent,
TDialogTypeEvent aEvent) = 0;
/**
* Displays dialog, if aError is KErrNone the dialog displays
* a list of contacts. If not KErrNone an error dialog should
* be displayed.
*/
virtual void ShowContactBookDialogL() = 0;
/**
* Called by super class when ContactBkInUse is called
* by the ContactBkEngine.
*/
virtual void ShowContactBookBusyDialogL() = 0;
/**
* Information dialog displaying information about the sms that has
* been sent.
* @param aStatus, KErrNone if successful otherwise one of the other system
* panic codes.
* @param aCount, Total number of emails to be sent.
* @param aNbrSent, The number of emails sent.
*/
virtual void ShowSmsSentDialogL(TInt aStatus, TInt aCount, TInt aNbrSent) = 0;
/**
* Returns the current origin.
* @return Current origin.
*/
virtual TPoint GetOrigin() = 0;
/**
* Returns the current destination.
* @return Current destination.
*/
virtual TPoint GetDestination() = 0;
/**
* Returns the current position.
* @return Current position.
*/
virtual TPoint GetCurrentPosition() = 0;
/**
* Returns the name of the current destination.
* @return Name of the current destination.
*/
virtual const TDesC& GetCurrentRouteDestinationName() = 0;
/**
* Get the coordinate of the current postion in the map.
* @return The map position.
*/
virtual TPoint GetCoordinate() = 0;
/**
* Gets the id of the current route.
* @return The id of the current route.
*/
virtual TInt64 GetRouteId() = 0;
/**
* Calls wayfinder appui to send a GuiProtMess
* to nav2.
* @param aMessage, The message to send to nav2.
*/
virtual void SendMessageL(isab::GuiProtMess* aMessage) = 0;
/**
* Allocates the message to be sent, body in the sms.
*/
virtual void SetSignatureL() = 0;
/**
* Allocates a text from the resources and appends
* it to the iCOntentArray.
* @param aResourceId The resource id to be added to the array.
*/
virtual void AddItemToContentArray(TInt aResourceId) = 0;
/**
* Validates a phone nbr.
* @param aPhoneNbr, the phone nbr to validate.
* @return, True if the phone nbr is valid
* False if not.
*/
virtual TBool IsValidPhoneNumber(const TDesC& aPhoneNbr) = 0;
/**
* Returns the text that is displayed in the blue note.
* @return The info text that is displayed in the blue note in the map.
*/
virtual const char* GetMapMoverInfoText() = 0;
/**
* Function letting the sub class know that a sms is about
* to be sent. Good when wanting to display an info message.
*/
virtual void SmsAboutToBeSent() = 0;
protected:
typedef CEventGenerator<CCommunicationWizardBase, enum TWizardSteps>
CCommunicationWizardGenerator;
/// Event generator, used to generate event
CCommunicationWizardGenerator* iEventGenerator;
/// Used to send sms.
class MSmsHandler* iSmsHandler;
/// Used to get contacts from the contact book.
class CContactBkEngine* iContactBkEngine;
/// Used to send messages to Nav2.
class GuiProtMessageSender& iSender;
/// Stores information about the selected favorite to be send.
isab::Favorite* iFavorite;
/// Holds all stored favorites.
std::vector<isab::GuiFavorite*> iFavVector;
/// Used to display data in all the list dialogs.
CDesCArray* iContentArray;
/// Holds data about the wizard/message to be sent
TWizardData iWizardData;
/// Used when formating a wayfinder sms.
static const uint8 SmsStringDelimiter;
/// Holds the index for the selected content to be sent.
TInt iContentSelection;
/// Holds the index for the selected format to send the message in.
TInt iTransmitAsSelection;
/// Holds the index for the selected way to add the recipient.
TInt iHowToAddRecSelection;
/// Holds the index for the selected favorite to be send.
TInt iFavoriteSelection;
/// Holds the index for the selected contact.
TInt iContactSelection;
/// Holds the index for the selected cantact detail.
TInt iContactDetailSelection;
/// Acts like a map between the data in contentArray and TWizContent,
/// makes it possible to set the content dynamically
TInt* iContentMapArray;
/// Array containing resource ids for personal message, the message
/// depens on what to send.
RArray<TInt> iPersonalMessageIds;
/// This is set when calling StartWizardL with a type of message as
/// parameter. By doing this we get a context sensitive wizard,
/// this means that the what to send dialog is skipped.
TWizContent iPreDefinedContent;
};
#endif
| [
"[email protected]"
] | [
[
[
1,
427
]
]
] |
1d42509544c0f83cd63264c8cdd8bcd13e937c81 | 08cad47ac3b88c5decfef2020197a633c802985a | /src/toko/mtoko.cpp | 6be618f87420ef3e96a9bbb356770b49db493c99 | [] | no_license | dieend/opeh | 6a6f270dd1168a3d37c8cf4072c173d40e9b601c | 8582f6c9675a2276ce48391223149ae89ae9e250 | refs/heads/master | 2016-09-06T17:18:37.859721 | 2011-04-08T11:59:09 | 2011-04-08T11:59:09 | 32,120,494 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 129 | cpp | #include "toko.h"
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
Toko T;
T.listItem();
}
| [
"[email protected]@88d9ccb5-13cd-afb7-92b0-0a47c0cce1aa"
] | [
[
[
1,
12
]
]
] |
c3b31cb00457820dc48f14bc39aada3ff1d8f31c | e2e49023f5a82922cb9b134e93ae926ed69675a1 | /tools/utilcpp/include/utilcpp/Assert.hpp | b05d69f35075d0f32da7a4ef694cf3b1fb58e422 | [] | no_license | invy/mjklaim-freewindows | c93c867e93f0e2fe1d33f207306c0b9538ac61d6 | 30de8e3dfcde4e81a57e9059dfaf54c98cc1135b | refs/heads/master | 2021-01-10T10:21:51.579762 | 2011-12-12T18:56:43 | 2011-12-12T18:56:43 | 54,794,395 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,831 | hpp | #ifndef HGUARD_UTILCPP_ASSERT_HPP__
#define HGUARD_UTILCPP_ASSERT_HPP__
#pragma once
#include <exception>
#include "utilcpp/HardConfig.hpp"
#include "utilcpp/Log.hpp"
#define UTILCPP_DEBUGBREAK ::__debugbreak() // is it crossplatform?
#if UTILCPP_ASSERTIONS_LOG_ON == 1
#define UTILCPP_ASSERTIONS_LOG( expression__, message__ ) \
UTILCPP_LOG_ERROR << "\n#############################################" \
<< "\n#### Assertion Failed! : " << #expression__ \
<< "\n## Function : " << __FUNCTION__ \
<< "\n## File : " << __FILE__ \
<< "\n## Line : " << __LINE__ \
<< "\n##" \
<< "\n## Message : \n\t\t" << message__ \
<< "\n##" \
<< "\n#############################################\n\n";
#else
#define UTILCPP_ASSERTIONS_LOG( expression__, message__ )
#endif
#if UTILCPP_ASSERTIONS_DEBUGBREAK_ON == 1
#define UTILCPP_ASSERTIONS_DEBUGBREAK UTILCPP_DEBUGBREAK
#else
#define UTILCPP_ASSERTIONS_DEBUGBREAK
#endif
#if UTILCPP_ASSERTIONS_CRASH_ON == 1
#define UTILCPP_ASSERTIONS_CRASH std::terminate()
#else
#define UTILCPP_ASSERTIONS_CRASH
#endif
#define UTILCPP_ASSERTION_IMPLEMENTATION( expression__, message__ ) \
UTILCPP_ASSERTIONS_LOG( expression__, message__ ); \
UTILCPP_ASSERTIONS_DEBUGBREAK; \
UTILCPP_ASSERTIONS_CRASH;
#if UTILCPP_ASSERTIONS_ON == 1
#define UTILCPP_ASSERT( expression__, message__ ) if( !(expression__) ) { UTILCPP_ASSERTION_IMPLEMENTATION( expression__, message__ ); }
#define UTILCPP_ASSERT_NULL( expression__ ) UTILCPP_ASSERT( !(expression__), #expression__ " IS NOT NULL! It should be!" )
#define UTILCPP_ASSERT_NOT_NULL( expression__ ) UTILCPP_ASSERT( expression__, #expression__ " IS NULL! It shouldn't be!" )
#define UTILCPP_ASSERT_IMPOSSIBLE( message__ ) UTILCPP_ASSERTION_IMPLEMENTATION( "IMPOSSIBLE!!!", message__ )
#else
#define UTILCPP_ASSERT( expression__, message__ )
#define UTILCPP_ASSERT_NULL( expression__ )
#define UTILCPP_ASSERT_NOT_NULL( expression__ )
#define UTILCPP_ASSERT_IMPOSSIBLE( message__ )
#endif
/////////////////////////////////////////////
// some utility macros
/// Use this macro in functions wich implementation will be written later.
#define UTILCPP_NOT_IMPLEMENTED_YET \
UTILCPP_LOG_ERROR << "\n##########################################" \
<< "\n## !!!! NOT IMPLEMENTED YET !!! " \
<< "\n## Function : " << __FUNCTION__ \
<< "\n## File : " << __FILE__ \
<< "\n## Line : " << __LINE__ \
<< "\n##########################################\n" \
; \
UTILCPP_DEBUGBREAK
/// Use this macro when you just want to remember to implement a function before compiling
#define UTILCPP_DO_IT_NOW static_assert( false, "NOT IMPLEMENTED : DO IT NOW!" )
#endif
| [
"klaim@localhost"
] | [
[
[
1,
83
]
]
] |
b0b6a5480edadc4180bbc1250f9188cb71680d1b | fac8de123987842827a68da1b580f1361926ab67 | /inc/physics/Physics/Dynamics/Common/hkpMaterial.h | 6d79bdd8c314eb9998756af543e9a5ecf998cf89 | [] | no_license | blockspacer/transporter-game | 23496e1651b3c19f6727712a5652f8e49c45c076 | 083ae2ee48fcab2c7d8a68670a71be4d09954428 | refs/heads/master | 2021-05-31T04:06:07.101459 | 2009-02-19T20:59:59 | 2009-02-19T20:59:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,101 | h | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HK_DYNAMICS2_MATERIAL_H
#define HK_DYNAMICS2_MATERIAL_H
extern const hkClass hkpMaterialClass;
/// hkMaterials allow you to add extra information to collision detection results, such as friction and restitution values.
class hkpMaterial
{
public:
HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_DYNAMICS, hkpMaterial );
HK_DECLARE_REFLECTION();
/// Constructor initialises friction to .5 and restitution to .4.
inline hkpMaterial();
//
// Friction and Restitution
//
/// Returns the friction coefficient (dynamic and static).
inline hkReal getFriction() const;
/// Returns the default restitution.
// restitution = bounciness (1 should give object all its energy back, 0 means it just sits there, etc.).
inline hkReal getRestitution() const;
/// Sets the friction coefficient. Note: Setting this will not update existing contact information.
inline void setFriction( hkReal newFriction );
/// Sets the restitution coefficient. Note: Setting this will not update existing contact information.
inline void setRestitution( hkReal newRestitution );
/// This returns the default way to combine two friction values.
/// We take the geometric mean ( sqrt (frictionA * frictionB) )
static inline hkReal HK_CALL getCombinedFriction( hkReal frictionA, hkReal frictionB);
/// This returns the default way to combine two restitution values.
/// We take the geometric mean ( sqrt (restitutionA * restitutionB) )
static inline hkReal HK_CALL getCombinedRestitution( hkReal restitutionA, hkReal restitutionB);
//
// Response type
//
/// A list of some response types as initially set up by the hkpWorld constructor,
/// which can be overridden. The default behavior is that a higher ResponseType
/// overrides a lower ResponseType. For instance, RESPONSE_NONE will have a higher
/// priority than RESPONSE_SIMPLE_CONTACT.
enum ResponseType
{
///
RESPONSE_INVALID,
/// Do normal collision resolution.
RESPONSE_SIMPLE_CONTACT,
/// Just do some reporting. No collision resolution is performed, but the collision
/// listener functions are called.
RESPONSE_REPORTING,
/// Do nothing, ignore all the results.
RESPONSE_NONE,
///
RESPONSE_MAX_ID
};
/// Get the response type. See the description of hkRepsonseType for details.
inline void setResponseType( enum hkpMaterial::ResponseType t );
/// Set the response type. See the description of hkRepsonseType for details.
inline enum hkpMaterial::ResponseType getResponseType() const;
private:
hkEnum<ResponseType,hkInt8> m_responseType;
hkReal m_friction;
hkReal m_restitution;
public:
hkpMaterial( class hkFinishLoadedObjectFlag flag ) { }
};
#include <Physics/Dynamics/Common/hkpMaterial.inl>
#endif // HK_DYNAMICS2_MATERIAL_H
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529)
*
* Confidential Information of Havok. (C) Copyright 1999-2008
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at
* www.havok.com/tryhavok
*
*/
| [
"uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4"
] | [
[
[
1,
111
]
]
] |
4fe6b5dbb0ec2d7c71eac8ecbac4ce1a30d738b4 | 3ea8b8900d21d0113209fd02bd462310bd0fce83 | /packmethod.cpp | 38e547adf0da7e1e83571d75aca51118fa9faf18 | [] | no_license | LazurasLong/bgmlib | 56958b7dffd98d78f99466ce37c4abaddc7da5b1 | a9d557ea76a383fae54dc3729aaea455c258777a | refs/heads/master | 2022-12-04T02:58:36.450986 | 2011-08-16T17:44:46 | 2011-08-16T17:44:46 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 5,997 | cpp | // Music Room BGM Library
// ----------------------
// packmethod.cpp - Pack Method Base Class
// ----------------------
// "©" Nmlgc, 2010-2011
#include "platform.h"
#include <FXFile.h>
#include <FXDir.h>
#include "list.h"
#include "config.h"
#include "infostruct.h"
#include "bgmlib.h"
#include "ui.h"
#include "packmethod.h"
#ifdef SUPPORT_VORBIS_PM
#include <FXPath.h>
#include "utils.h"
#include "libvorbis.h"
#endif
// Pack Methods
// ------------
PackMethod::PackMethod()
{
ID = -1;
ADD_THIS(BGMLib::PM, PackMethod);
}
bool PackMethod::PF_PGI_BGMFile(ConfigFile& NewGame, GameInfo* GI)
{
NewGame.GetValue("game", "bgmfile", TYPE_STRING, &GI->BGMFile);
PMGame.Add(&GI);
return true;
}
// Scans for GameInfo::BGMFile in [Path]
GameInfo* PackMethod::PF_Scan_BGMFile(const FXString& Path)
{
GameInfo* NewGame = NULL;
FXString* Files = NULL;
FXint FileCount = 0;
ListEntry<GameInfo*>* CurGame = PMGame.First();
while(CurGame)
{
NewGame = CurGame->Data;
FileCount = FXDir::listFiles(Files, Path, NewGame->BGMFile, FXDir::NoDirs | FXDir::CaseFold | FXDir::HiddenFiles);
SAFE_DELETE_ARRAY(Files);
if((FileCount > 0) && BGMFile_Check(NewGame))
{
return NewGame;
}
CurGame = CurGame->Next();
}
return NULL;
}
#ifdef SUPPORT_VORBIS_PM
// Scans for original and Vorbis versions of GameInfo::BGMFile in [Path]
GameInfo* PackMethod::PF_Scan_BGMFile_Vorbis(const FXString& Path)
{
GameInfo* NewGame = NULL;
FXString* Files = NULL;
FXint FileCount = 0;
FXString Search, Ext;
bool TrgVorbis, Found;
// ov_open can be a quite expensive operation when dealing with mulitple bitstreams,
// so we're always keeping the last loaded file open, until the scan file name changes
FXString LastSearchFN, LastVorbisFN;
OggVorbis_File VF;
memset(&VF, 0, sizeof(OggVorbis_File));
ListEntry<GameInfo*>* CurGame = PMGame.First();
while(CurGame)
{
NewGame = CurGame->Data;
TrgVorbis = Found = false;
if(NewGame->BGMFile != LastSearchFN)
{
SAFE_DELETE_ARRAY(Files);
Search = replaceExtension(NewGame->BGMFile, "*");
FileCount = FXDir::listFiles(Files, Path, Search, FXDir::NoDirs | FXDir::CaseFold | FXDir::HiddenFiles);
LastSearchFN = NewGame->BGMFile;
}
for(ushort c = 0; c < FileCount; c++)
{
Ext = FXPath::extension(Files[c]);
Found = BGMFile_Check_Vorbis(NewGame, Files[c], Ext, LastVorbisFN, &TrgVorbis, &VF);
if(Found)
{
// NewGame->BGMFile = Files[c]; // Moved to DiskFN, we should not change that value
NewGame->Vorbis = TrgVorbis; // Let's cache the target Vorbis flag there...
// Immediately return when we found a matching .dat file (because it will be lossless!)
if(!TrgVorbis) break;
}
}
if(Found) break;
CurGame = CurGame->Next();
NewGame = NULL;
}
SAFE_DELETE_ARRAY(Files);
ov_clear(&VF);
return NewGame;
}
// Helper function test-opening a new Vorbis file
bool PackMethod::PF_Scan_TestVorbis(OggVorbis_File* VF, const FXString& FN)
{
// File handle has to be static because vorbisfile will crash on ov_clear if it's already freed
// And since we always close it here, nothing will leak
static FXFile F;
int Ret;
ov_clear(VF);
F.open(FN);
Ret = ov_test_callbacks(&F, VF, NULL, 0, OV_CALLBACKS_FXFILE);
// VF now has everything we want, so we can close already
F.close();
return Ret == 0;
}
#endif
// Reads necessary track data from an archive file based on it's extension.
// Sets track start/end values and returns true if [AudioExt], or calls MetaData function below and returns false on [MetaExt].
TrackInfo* PackMethod::PF_TD_ParseArchiveFile(GameInfo *GI, FXFile& In, const FXString &_FN, const FXString &AudioExt, const FXString &MetaExt, const ulong &CFPos, const ulong &CFSize)
{
ListEntry<TrackInfo>* CurTrack;
TrackInfo* Track;
FXString FNExt = _FN.after('.');
FXString FN = _FN.before('.');
CurTrack = GI->Track.First();
while(CurTrack)
{
Track = &CurTrack->Data;
if((Track->NativeFN) == FN)
{
if(FNExt == AudioExt) AudioData(GI, In, CFPos, CFSize, Track);
else if(FNExt == MetaExt) MetaData(GI, In, CFPos, CFSize, Track);
return Track;
}
else CurTrack = CurTrack->Next();
}
return NULL;
}
void PackMethod::AudioData(GameInfo* GI, FXFile& In, const ulong& Pos, const ulong& Size, TrackInfo* TI)
{
TI->Start[0] = TI->Start[1] = Pos;
TI->FS = Size;
}
bool PackMethod::Dump(GameInfo* GI, FXFile& In, const ulong& Pos, const ulong& Size, const FXString& DumpFN, volatile FXulong* p)
{
FXFile Dec;
if(!Dec.open(DumpFN, FXIO::Writing))
{
BGMLib::UI_Error("Couldn't open temporary Vorbis file!\nExtraction from this game won't be possible...\n");
return false;
}
char* DecBuf = new char[Size];
DecryptFile(GI, In, DecBuf, Pos, Size, p);
Dec.writeBlock(DecBuf, Size);
SAFE_DELETE_ARRAY(DecBuf);
Dec.close();
return true;
}
FXString PackMethod::DiskFN(GameInfo* GI, TrackInfo* TI)
{
return GI->BGMFile;
}
FXString PackMethod::PMInfo(GameInfo* GI)
{
return FXString("To get the original music files as used by the game without re-encoding,\n"
"select the OGG format, a loop count of 1, and 0 second fades.");
}
// ------------
// PM_None
// -------
bool PM_None::ParseGameInfo(ConfigFile&, GameInfo*) {return true;}
bool PM_None::ParseTrackInfo(ConfigFile&, GameInfo*, ConfigParser*, TrackInfo*) {return false;}
GameInfo* PM_None::Scan(const FXString&) {return NULL;}
FXString PM_None::DiskFN(GameInfo*, TrackInfo*) {return "";}
void PM_None::DisplayName(FXString& Name, GameInfo*) {Name.append(" (tagging only)");}
// -------
PackMethod* BGMLib::FindPM(const short& PMID)
{
ListEntry<PackMethod*>* CurPM = PM.First();
while(CurPM)
{
if(CurPM->Data->GetID() == PMID) return CurPM->Data;
CurPM = CurPM->Next();
}
// return &PM_None::Inst();
return NULL;
}
| [
"[email protected]"
] | [
[
[
1,
221
]
]
] |
69c7bd1cd965f02254a581c91f299a119a698a99 | 3bfe835203f793ee00bdf261c26992b1efea69ed | /fall08/cs460/project/cs460_1/Vertex.h | 752d89204d29737c3791c8b6819a70be12e984a1 | [] | no_license | yxrkt/DigiPen | 0bdc1ed3ee06e308b4942a0cf9de70831c65a3d3 | e1bb773d15f63c88ab60798f74b2e424bcc80981 | refs/heads/master | 2020-06-04T20:16:05.727685 | 2009-11-18T00:26:56 | 2009-11-18T00:26:56 | 814,145 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 996 | h | #pragma once
#include <d3dx9.h>
#include <vector>
#define D3DFVF_COLOREDVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1)
class ColoredVertex
{
public:
ColoredVertex( float _x = 0, float _y = 0, float _z = 0,
DWORD _color = D3DCOLOR_XRGB( 0, 255, 0 ), float _u = 0.f, float _v = 0.f )
: x( _x ), y( _y ), z( _z ), color( _color ), u( _u ), v( _v ) {}
ColoredVertex( const D3DXVECTOR3 &rhs )
: x( rhs.x ), y( rhs.y ), z( rhs.z ), color( D3DCOLOR_XRGB( 255, 255, 255 ) ), u( 0.f ), v( 0.f ) {}
bool operator ==( const ColoredVertex &rhs )
{
return !memcmp( this, &rhs, sizeof( ColoredVertex ) );
}
LPD3DXVECTOR3 ToLPD3DXVECTOR3() const
{
return (LPD3DXVECTOR3)this;
};
float x, y, z;
D3DCOLOR color;
float u, v;
};
typedef std::vector< ColoredVertex > VertVec;
typedef VertVec::iterator VertVecIt;
typedef VertVec::const_iterator VertVecItC;
| [
"[email protected]"
] | [
[
[
1,
34
]
]
] |
a95981336eb63860bfbe31b15f03e8251ae4ce72 | a92598d0a8a2e92b424915d2944212f2f13e7506 | /PtRPG/libs/cocos2dx/include/CCLabelBMFont.h | f6fd02eee10dc48e6d43e9a05102a6b98811a725 | [
"MIT"
] | permissive | peteo/RPG_Learn | 0cc4facd639bd01d837ac56cf37a07fe22c59211 | 325fd1802b14e055732278f3d2d33a9577608c39 | refs/heads/master | 2021-01-23T11:07:05.050645 | 2011-12-12T08:47:27 | 2011-12-12T08:47:27 | 2,299,148 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,168 | h | /****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga Inc.
http://www.cocos2d-x.org
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.
Use any of these editors to generate BMFonts:
http://glyphdesigner.71squared.com/ (Commercial, Mac OS X)
http://www.n4te.com/hiero/hiero.jnlp (Free, Java)
http://slick.cokeandcode.com/demos/hiero.jnlp (Free, Java)
http://www.angelcode.com/products/bmfont/ (Free, Windows only)
****************************************************************************/
#ifndef __CCBITMAP_FONT_ATLAS_H__
#define __CCBITMAP_FONT_ATLAS_H__
#include "CCSpriteBatchNode.h"
namespace cocos2d{
struct _KerningHashElement;
/**
@struct ccBMFontDef
BMFont definition
*/
typedef struct _BMFontDef {
//! ID of the character
unsigned int charID;
//! origin and size of the font
CCRect rect;
//! The X amount the image should be offset when drawing the image (in pixels)
int xOffset;
//! The Y amount the image should be offset when drawing the image (in pixels)
int yOffset;
//! The amount to move the current position after drawing the character (in pixels)
int xAdvance;
} ccBMFontDef;
/** @struct ccBMFontPadding
BMFont padding
@since v0.8.2
*/
typedef struct _BMFontPadding {
/// padding left
int left;
/// padding top
int top;
/// padding right
int right;
/// padding bottom
int bottom;
} ccBMFontPadding;
enum {
// how many characters are supported
kCCBMFontMaxChars = 2048, //256,
};
/** @brief CCBMFontConfiguration has parsed configuration of the the .fnt file
@since v0.8
*/
class CC_DLL CCBMFontConfiguration : public CCObject
{
// XXX: Creating a public interface so that the bitmapFontArray[] is accesible
public://@public
//! The characters building up the font
ccBMFontDef m_pBitmapFontArray[kCCBMFontMaxChars];
//! FNTConfig: Common Height
unsigned int m_uCommonHeight;
//! Padding
ccBMFontPadding m_tPadding;
//! atlas name
std::string m_sAtlasName;
//! values for kerning
struct _KerningHashElement *m_pKerningDictionary;
public:
CCBMFontConfiguration()
: m_uCommonHeight(0)
, m_pKerningDictionary(NULL)
{}
virtual ~CCBMFontConfiguration();
char * description();
/** allocates a CCBMFontConfiguration with a FNT file */
static CCBMFontConfiguration * configurationWithFNTFile(const char *FNTfile);
/** initializes a BitmapFontConfiguration with a FNT file */
bool initWithFNTfile(const char *FNTfile);
private:
void parseConfigFile(const char *controlFile);
void parseCharacterDefinition(std::string line, ccBMFontDef *characterDefinition);
void parseInfoArguments(std::string line);
void parseCommonArguments(std::string line);
void parseImageFileName(std::string line, const char *fntFile);
void parseKerningCapacity(std::string line);
void parseKerningEntry(std::string line);
void purgeKerningDictionary();
};
/** @brief CCLabelBMFont is a subclass of CCSpriteSheet.
Features:
- Treats each character like a CCSprite. This means that each individual character can be:
- rotated
- scaled
- translated
- tinted
- chage the opacity
- It can be used as part of a menu item.
- anchorPoint can be used to align the "label"
- Supports AngelCode text format
Limitations:
- All inner characters are using an anchorPoint of (0.5f, 0.5f) and it is not recommend to change it
because it might affect the rendering
CCLabelBMFont implements the protocol CCLabelProtocol, like CCLabel and CCLabelAtlas.
CCLabelBMFont has the flexibility of CCLabel, the speed of CCLabelAtlas and all the features of CCSprite.
If in doubt, use CCLabelBMFont instead of CCLabelAtlas / CCLabel.
Supported editors:
http://glyphdesigner.71squared.com/ (Commercial, Mac OS X)
http://www.n4te.com/hiero/hiero.jnlp (Free, Java)
http://slick.cokeandcode.com/demos/hiero.jnlp (Free, Java)
http://www.angelcode.com/products/bmfont/ (Free, Windows only)
@since v0.8
*/
class CC_DLL CCLabelBMFont : public CCSpriteBatchNode, public CCLabelProtocol, public CCRGBAProtocol
{
/** conforms to CCRGBAProtocol protocol */
CC_PROPERTY(GLubyte, m_cOpacity, Opacity)
/** conforms to CCRGBAProtocol protocol */
CC_PROPERTY(ccColor3B, m_tColor, Color)
/** conforms to CCRGBAProtocol protocol */
CC_PROPERTY(bool, m_bIsOpacityModifyRGB, IsOpacityModifyRGB)
protected:
// string to render
std::string m_sString;
CCBMFontConfiguration *m_pConfiguration;
public:
CCLabelBMFont()
: m_cOpacity(0)
, m_bIsOpacityModifyRGB(false)
, m_sString("")
, m_pConfiguration(NULL)
{}
virtual ~CCLabelBMFont();
/** Purges the cached data.
Removes from memory the cached configurations and the atlas name dictionary.
@since v0.99.3
*/
static void purgeCachedData();
/** creates a bitmap font altas with an initial string and the FNT file */
static CCLabelBMFont * labelWithString(const char *str, const char *fntFile);
/** init a bitmap font altas with an initial string and the FNT file */
bool initWithString(const char *str, const char *fntFile);
/** updates the font chars based on the string to render */
void createFontChars();
// super method
virtual void setString(const char *label);
virtual const char* getString(void);
virtual void setCString(const char *label);
virtual void setAnchorPoint(CCPoint var);
virtual CCRGBAProtocol* convertToRGBAProtocol() { return (CCRGBAProtocol*)this; }
virtual CCLabelProtocol* convertToLabelProtocol() { return (CCLabelProtocol*)this; }
#if CC_LABELBMFONT_DEBUG_DRAW
virtual void draw();
#endif // CC_LABELBMFONT_DEBUG_DRAW
private:
char * atlasNameFromFntFile(const char *fntFile);
int kerningAmountForFirst(unsigned short first, unsigned short second);
};
/** Free function that parses a FNT file a place it on the cache
*/
CC_DLL CCBMFontConfiguration * FNTConfigLoadFile( const char *file );
/** Purges the FNT config cache
*/
CC_DLL void FNTConfigRemoveCache( void );
}// namespace cocos2d
#endif //__CCBITMAP_FONT_ATLAS_H__
| [
"[email protected]"
] | [
[
[
1,
202
]
]
] |
65a6632c9dd5f6e7402813a056794b3afed1ca0a | 22d9640edca14b31280fae414f188739a82733e4 | /Code/VTK/include/vtk-5.2/vtkPKdTree.h | 5de1b5eeac1e0042c2f6aa6af1e15b149846bb4d | [] | 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 | 16,730 | h | /*=========================================================================
Program: Visualization Toolkit
Module: $RCSfile: vtkPKdTree.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.
=========================================================================*/
/*----------------------------------------------------------------------------
Copyright (c) Sandia Corporation
See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
----------------------------------------------------------------------------*/
// .NAME vtkPKdTree - Build a k-d tree decomposition of a list of points.
//
// .SECTION Description
// Build, in parallel, a k-d tree decomposition of one or more
// vtkDataSets distributed across processors. We assume each
// process has read in one portion of a large distributed data set.
// When done, each process has access to the k-d tree structure,
// can obtain information about which process contains
// data for each spatial region, and can depth sort the spatial
// regions.
//
// This class can also assign spatial regions to processors, based
// on one of several region assignment schemes. By default
// a contiguous, convex region is assigned to each process. Several
// queries return information about how many and what cells I have
// that lie in a region assigned to another process.
//
// .SECTION See Also
// vtkKdTree
#ifndef __vtkPKdTree_h
#define __vtkPKdTree_h
#include "vtkKdTree.h"
class vtkMultiProcessController;
class vtkCommunicator;
class vtkSubGroup;
class vtkIntArray;
class vtkKdNode;
class VTK_PARALLEL_EXPORT vtkPKdTree : public vtkKdTree
{
public:
vtkTypeRevisionMacro(vtkPKdTree, vtkKdTree);
void PrintSelf(ostream& os, vtkIndent indent);
void PrintTiming(ostream& os, vtkIndent indent);
void PrintTables(ostream& os, vtkIndent indent);
static vtkPKdTree *New();
// Description:
// Build the spatial decomposition. Call this explicitly
// after changing any parameters affecting the build of the
// tree. It must be called by all processes in the parallel
// application, or it will hang.
void BuildLocator();
// Description:
// Get the total number of cells distributed across the data
// files read by all processes. You must have called BuildLocator
// before calling this method.
vtkIdType GetTotalNumberOfCells(){return this->TotalNumCells;}
// Description:
// Create tables of counts of cells per process per region.
// These tables can be accessed with queries like
// "HasData", "GetProcessCellCountForRegion", and so on.
// You must have called BuildLocator() beforehand. This
// method must be called by all processes or it will hang.
// Returns 1 on error, 0 when no error.
int CreateProcessCellCountData();
// Description:
// A convenience function which compiles the global
// bounds of the data arrays across processes.
// These bounds can be accessed with
// "GetCellArrayGlobalRange" and "GetPointArrayGlobalRange".
// This method must be called by all processes or it will hang.
// Returns 1 on error, 0 when no error.
int CreateGlobalDataArrayBounds();
// Description:
// Set/Get the communicator object
void SetController(vtkMultiProcessController *c);
vtkGetObjectMacro(Controller, vtkMultiProcessController);
// Description:
// The PKdTree class can assign spatial regions to processors after
// building the k-d tree, using one of several partitioning criteria.
// These functions Set/Get whether this assignment is computed.
// The default is "Off", no assignment is computed. If "On", and
// no assignment scheme is specified, contiguous assignment will be
// computed. Specifying an assignment scheme (with AssignRegions*())
// automatically turns on RegionAssignment.
vtkGetMacro(RegionAssignment, int);
static const int NoRegionAssignment;
static const int ContiguousAssignment;
static const int UserDefinedAssignment;
static const int RoundRobinAssignment;
// Description:
// Assign spatial regions to processes via a user defined map.
// The user-supplied map is indexed by region ID, and provides a
// process ID for each region.
int AssignRegions(int *map, int numRegions);
// Description:
// Let the PKdTree class assign a process to each region in a
// round robin fashion. If the k-d tree has not yet been
// built, the regions will be assigned after BuildLocator executes.
int AssignRegionsRoundRobin();
// Description:
// Let the PKdTree class assign a process to each region
// by assigning contiguous sets of spatial regions to each
// process. The set of regions assigned to each process will
// always have a union that is a convex space (a box).
// If the k-d tree has not yet been built, the regions
// will be assigned after BuildLocator executes.
int AssignRegionsContiguous();
// Description:
// Writes the list of region IDs assigned to the specified
// process. Regions IDs start at 0 and increase by 1 from there.
// Returns the number of regions in the list.
int GetRegionAssignmentList(int procId, vtkIntArray *list);
// Description:
// The k-d tree spatial regions have been assigned to processes.
// Given a point on the boundary of one of the regions, this
// method creates a list of all processes whose region
// boundaries include that point. This may be required when
// looking for processes that have cells adjacent to the cells
// of a given process.
void GetAllProcessesBorderingOnPoint(float x, float y, float z,
vtkIntArray *list);
// Description:
// Returns the ID of the process assigned to the region.
int GetProcessAssignedToRegion(int regionId);
// Description:
// Returns 1 if the process has data for the given region,
// 0 otherwise.
int HasData(int processId, int regionId);
// Description:
// Returns the number of cells the specified process has in the
// specified region.
int GetProcessCellCountForRegion(int processId, int regionId);
// Description:
// Returns the total number of processes that have data
// falling within this spatial region.
int GetTotalProcessesInRegion(int regionId);
// Description:
// Adds the list of processes having data for the given
// region to the supplied list, returns the number of
// processes added.
int GetProcessListForRegion(int regionId, vtkIntArray *processes);
// Description:
// Writes the number of cells each process has for the region
// to the supplied list of length len. Returns the number of
// cell counts written. The order of the cell counts corresponds
// to the order of process IDs in the process list returned by
// GetProcessListForRegion.
int GetProcessesCellCountForRegion(int regionId, int *count, int len);
// Description:
// Returns the total number of spatial regions that a given
// process has data for.
int GetTotalRegionsForProcess(int processId);
// Description:
// Adds the region IDs for which this process has data to
// the supplied vtkIntArray. Retruns the number of regions.
int GetRegionListForProcess(int processId, vtkIntArray *regions);
// Description:
// Writes to the supplied integer array the number of cells this
// process has for each region. Returns the number of
// cell counts written. The order of the cell counts corresponds
// to the order of region IDs in the region list returned by
// GetRegionListForProcess.
int GetRegionsCellCountForProcess(int ProcessId, int *count, int len);
// Description:
// After regions have been assigned to processes, I may want to know
// which cells I have that are in the regions assigned to a particular
// process.
//
// This method takes a process ID and two vtkIdLists. It
// writes to the first list the IDs of the cells
// contained in the process' regions. (That is, their cell
// centroid is contained in the region.) To the second list it
// write the IDs of the cells which intersect the process' regions
// but whose cell centroid lies elsewhere.
//
// The total number of cell IDs written to both lists is returned.
// Either list pointer passed in can be NULL, and it will be ignored.
// If there are multiple data sets, you must specify which data set
// you wish cell IDs for.
//
// The caller should delete these two lists when done. This method
// uses the cell lists created in vtkKdTree::CreateCellLists().
// If the cell lists for the process' regions do not exist, this
// method will first build the cell lists for all regions by calling
// CreateCellLists(). You must remember to DeleteCellLists() when
// done with all calls to this method, as cell lists can require a
// great deal of memory.
vtkIdType GetCellListsForProcessRegions(int ProcessId, int set,
vtkIdList *inRegionCells, vtkIdList *onBoundaryCells);
vtkIdType GetCellListsForProcessRegions(int ProcessId, vtkDataSet *set,
vtkIdList *inRegionCells, vtkIdList *onBoundaryCells);
vtkIdType GetCellListsForProcessRegions(int ProcessId,
vtkIdList *inRegionCells,
vtkIdList *onBoundaryCells);
// Description:
// DO NOT CALL. Deprecated in VTK 5.2. Use ViewOrderAllProcessesInDirection
// or ViewOrderAllProcessesFromPosition.
VTK_LEGACY(int DepthOrderAllProcesses(double *directionOfProjection,
vtkIntArray *orderedList));
// Description:
// Return a list of all process in order from front to back given a
// vector direction of projection. Use this to do visibility sorts
// in parallel projection mode.
int ViewOrderAllProcessesInDirection(const double directionOfProjection[3],
vtkIntArray *orderedList);
// Description:
// Return a list of all processes in order from front to back given a
// camera position. Use this to do visibility sorts in perspective
// projection mode.
int ViewOrderAllProcessesFromPosition(const double cameraPosition[3],
vtkIntArray *orderedList);
// Description:
// An added feature of vtkPKdTree is that it will calculate the
// the global range of field arrays across all processes. You
// call CreateGlobalDataArrayBounds() to do this calculation.
// Then the following methods return the ranges.
// Returns 1 on error, 0 otherwise.
int GetCellArrayGlobalRange(const char *name, float range[2]);
int GetPointArrayGlobalRange(const char *name, float range[2]);
int GetCellArrayGlobalRange(const char *name, double range[2]);
int GetPointArrayGlobalRange(const char *name, double range[2]);
int GetCellArrayGlobalRange(int arrayIndex, double range[2]);
int GetPointArrayGlobalRange(int arrayIndex, double range[2]);
int GetCellArrayGlobalRange(int arrayIndex, float range[2]);
int GetPointArrayGlobalRange(int arrayIndex, float range[2]);
protected:
vtkPKdTree();
~vtkPKdTree();
void SingleProcessBuildLocator();
int MultiProcessBuildLocator(double *bounds);
private:
int RegionAssignment;
vtkMultiProcessController *Controller;
vtkSubGroup *SubGroup;
static char *StrDupWithNew(const char *s);
int NumProcesses;
int MyId;
// basic tables - each region is the responsibility of one process, but
// one process may be assigned many regions
int *RegionAssignmentMap; // indexed by region ID
int RegionAssignmentMapLength;
int **ProcessAssignmentMap; // indexed by process ID
int *NumRegionsAssigned; // indexed by process ID
int UpdateRegionAssignment();
// basic tables reflecting the data that was read from disk
// by each process
char *DataLocationMap; // by process, by region
int *NumProcessesInRegion; // indexed by region ID
int **ProcessList; // indexed by region ID
int *NumRegionsInProcess; // indexed by process ID
int **RegionList; // indexed by process ID
vtkIdType **CellCountList; // indexed by region ID
double *CellDataMin; // global range for data arrays
double *CellDataMax;
double *PointDataMin;
double *PointDataMax;
char **CellDataName;
char **PointDataName;
int NumCellArrays;
int NumPointArrays;
// distribution of indices for select operation
int BuildGlobalIndexLists(vtkIdType ncells);
vtkIdType *StartVal;
vtkIdType *EndVal;
vtkIdType *NumCells;
vtkIdType TotalNumCells;
// local share of points to be partitioned, and local cache
int WhoHas(int pos);
int _whoHas(int L, int R, int pos);
float *GetLocalVal(int pos);
float *GetLocalValNext(int pos);
void SetLocalVal(int pos, float *val);
void ExchangeVals(int pos1, int pos2);
void ExchangeLocalVals(int pos1, int pos2);
float *PtArray;
float *PtArray2;
float *CurrentPtArray;
float *NextPtArray;
int PtArraySize;
int *SelectBuffer;
// Parallel build of k-d tree
int AllCheckForFailure(int rc, const char *where, const char *how);
void AllCheckParameters();
double *VolumeBounds();
int DivideRegion(vtkKdNode *kd, int L, int level, int tag);
int BreadthFirstDivide(double *bounds);
void enQueueNode(vtkKdNode *kd, int L, int level, int tag);
int Select(int dim, int L, int R);
void _select(int L, int R, int K, int dim);
void DoTransfer(int from, int to, int fromIndex, int toIndex, int count);
int *PartitionAboutMyValue(int L, int R, int K, int dim);
int *PartitionAboutOtherValue(int L, int R, float T, int dim);
int *PartitionSubArray(int L, int R, int K, int dim, int p1, int p2);
int CompleteTree();
#ifdef YIELDS_INCONSISTENT_REGION_BOUNDARIES
void RetrieveData(vtkKdNode *kd, int *buf);
#else
void ReduceData(vtkKdNode *kd, int *sources);
void BroadcastData(vtkKdNode *kd);
#endif
float *DataBounds(int L, int K, int R);
void GetLocalMinMax(int L, int R, int me, float *min, float *max);
static int FillOutTree(vtkKdNode *kd, int level);
static int ComputeDepth(vtkKdNode *kd);
static void PackData(vtkKdNode *kd, double *data);
static void UnpackData(vtkKdNode *kd, double *data);
static void CheckFixRegionBoundaries(vtkKdNode *tree);
// list management
int AllocateDoubleBuffer();
void FreeDoubleBuffer();
void SwitchDoubleBuffer();
int AllocateSelectBuffer();
void FreeSelectBuffer();
void InitializeGlobalIndexLists();
int AllocateAndZeroGlobalIndexLists();
void FreeGlobalIndexLists();
void InitializeRegionAssignmentLists();
int AllocateAndZeroRegionAssignmentLists();
void FreeRegionAssignmentLists();
void InitializeProcessDataLists();
int AllocateAndZeroProcessDataLists();
void FreeProcessDataLists();
void InitializeFieldArrayMinMax();
int AllocateAndZeroFieldArrayMinMax();
void FreeFieldArrayMinMax();
void ReleaseTables();
// Assigning regions to processors
void AddProcessRegions(int procId, vtkKdNode *kd);
void BuildRegionListsForProcesses();
// Gather process/region data totals
int *CollectLocalRegionProcessData();
int BuildRegionProcessTables();
int BuildFieldArrayMinMax();
void AddEntry(int *list, int len, int id);
#ifdef VTK_USE_64BIT_IDS
void AddEntry(vtkIdType *list, int len, vtkIdType id);
#endif
static int BinarySearch(vtkIdType *list, int len, vtkIdType which);
static int FindNextLocalArrayIndex(const char *n, const char **names, int len, int start=0);
vtkPKdTree(const vtkPKdTree&); // Not implemented
void operator=(const vtkPKdTree&); // Not implemented
};
#endif
| [
"nnsmit@9b22acdf-97ab-464f-81e2-08fcc4a6931f"
] | [
[
[
1,
430
]
]
] |
708dd246dd1b77495f502d7134b816e36b554d4a | 9c62af23e0a1faea5aaa8dd328ba1d82688823a5 | /rl/branches/persistence2/engine/script/include/MapLoader.h | a6d970125d60c486ce45411081a302bfac5d04f1 | [
"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 | 3,216 | h | /* 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.
*/
#ifndef __MapLoader_H__
#define __MapLoader_H__
#include "ScriptPrerequisites.h"
#include <list>
#include "XmlProcessor.h"
#include "ContentLoader.h"
#include "MessagePump.h"
#include "CoreMessages.h"
namespace rl {
typedef MessageType<RLMSG_SCENE_CHANGE_REQUESTED, Ogre::StringVector> MessageType_SceneChangeRequested;
class AbstractMapNodeProcessor;
class ProgressWindow;
class _RlScriptExport MapLoader : public ContentLoader, protected XmlProcessor
{
public:
static const CeGuiString PROPERTY_ACTIVEMAPS;
MapLoader();
MapLoader(const Ogre::String& resourceGroup);
~MapLoader();
/** Loads a Rastullahs Lockenpracht map
*
* @param mapresource the name of the map file resource
* @param loadGameObjects set <code>false</code> if the MapLoader should not load the GameObjects of the map file (e.g. when loading a saved game)
*/
void loadContent();
void unloadContent();
void setDefaultMaps(Ogre::StringVector maps);
void loadMap(const Ogre::String& mapresource, bool loadGameObjects = true);
void loadScene(Ogre::StringVector mapsresources, bool loadGameObjects = true);
void unloadAllMaps(bool removeGameObjects); /// @todo
void requestSceneChange(Ogre::StringVector mapsresources);
const CeGuiString getClassName() const;
const Property getProperty(const CeGuiString& key) const;
void setProperty(const CeGuiString& key, const Property& value);
PropertyKeys getAllPropertyKeys() const;
private:
std::list<AbstractMapNodeProcessor*> mNodeProcessors;
Ogre::SceneNode* mRootSceneNode;
/// Alle statischen GeometrieNodes
Ogre::String mResourceGroup;
ProgressWindow* mPercentageWindow;
Ogre::StringVector mLoadedMaps;
Ogre::StringVector mPrevLoadedMaps;
Ogre::StringVector mDefaultMaps;
void setRootSceneNode(Ogre::SceneNode* node);
void processSceneNodes(XERCES_CPP_NAMESPACE::DOMElement* nodesElem, bool loadGameObjects);
void setLoadingPercentage(Ogre::Real percentage, const Ogre::String& text = "");
bool changeScene(Ogre::StringVector mapsresources);
void initialize(const Ogre::String& resourceGroup);
MessagePump::ScopedConnection RequestedSceneChangeConnection;
};
} // namespace rl
#endif //__MapLoader_H__
| [
"timm@4c79e8ff-cfd4-0310-af45-a38c79f83013"
] | [
[
[
1,
87
]
]
] |
30468b7348e17d92987af859c7e8a175445c74a6 | fbe2cbeb947664ba278ba30ce713810676a2c412 | /iptv_root/skin_lite/src/SkinLite/SendFilesFrame.cpp | 876d9352a7740c2f9ac45cc748b9b2d7f51ee0b3 | [] | no_license | abhipr1/multitv | 0b3b863bfb61b83c30053b15688b070d4149ca0b | 6a93bf9122ddbcc1971dead3ab3be8faea5e53d8 | refs/heads/master | 2020-12-24T15:13:44.511555 | 2009-06-04T17:11:02 | 2009-06-04T17:11:02 | 41,107,043 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,613 | cpp | /////////////////////////////////////////////////////////////////////////////
// Name: SendFilesFrame.cpp
// Purpose:
// Author:
// Modified by:
// Created: 19/05/2008 09:50:49
// RCS-ID:
// Copyright:
// Licence:
/////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#include "wx/filename.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include "SendFilesFrame.h"
#include "MessageDialog.h"
#include "SkinLite.h"
/*!
* SendFilesFrame type definition
*/
IMPLEMENT_CLASS( SendFilesFrame, wxFrame )
/*!
* SendFilesFrame event table definition
*/
BEGIN_EVENT_TABLE( SendFilesFrame, wxFrame )
EVT_BUTTON( ID_SENDFILESFRAME_BTN_SEARCHFILE, SendFilesFrame::OnBtnSearchFileClick )
EVT_BUTTON( ID_SENDFILESFRAME_BTN_SEND, SendFilesFrame::OnBtnSendClick )
EVT_BUTTON( ID_SENDFILESFRAME_BTN_CANCEL, SendFilesFrame::OnBtnCancelClick )
EVT_TEXT(ID_SENDFILESFRAME_TXT_FILENAME, SendFilesFrame::OnTxtFileNameChange)
EVT_CLOSE(SendFilesFrame::OnClose)
EVT_TIMER( wxID_ANY, SendFilesFrame::OnTimer )
END_EVENT_TABLE()
/** SendFilesFrame default constructor.
*
*/
SendFilesFrame::SendFilesFrame()
{
Init();
}
/** SendFilesFrame constructor.
* @param[in] parent. Parent window.
* @param[in] iface. Interface with application.
* @param[in] id. Window id. Default SYMBOL_SENDFILESFRAME_IDNAME.
* @param[in] caption. Window caption. Default SYMBOL_SENDFILESFRAME_TITLE.
* @param[in] pos. Window position. Default SYMBOL_SENDFILESFRAME_POSITION.
* @param[in] size. Window size. Default SYMBOL_SENDFILESFRAME_SIZE.
* @param[in] style. Window style. Default SYMBOL_SENDFILESFRAME_STYLE.
*/
SendFilesFrame::SendFilesFrame( wxWindow* parent, AppInterface* iface, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
Init();
m_appInterface = iface;
Create( parent, id, caption, pos, size, style );
}
/** SendFilesFrame creator.
* @param[in] parent. Parent window.
* @param[in] id. Window id. Default SYMBOL_SENDFILESFRAME_IDNAME.
* @param[in] caption. Window caption. Default SYMBOL_SENDFILESFRAME_TITLE.
* @param[in] pos. Window position. Default SYMBOL_SENDFILESFRAME_POSITION.
* @param[in] size. Window size. Default SYMBOL_SENDFILESFRAME_SIZE.
* @param[in] style. Window style. Default SYMBOL_SENDFILESFRAME_STYLE.
*/
bool SendFilesFrame::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
wxFrame::Create( parent, id, caption, pos, size, style );
SetMinSize(SYMBOL_SENDFILESFRAME_SIZE);
CreateControls();
SessionWindow *sessionWnd = ((SessionWindow *)GetParent());
SkinLite *skinLite = (SkinLite *)(sessionWnd->GetParent());
skinLite->ChangeSendFilesExistsStatus(true);
sessionWnd->DisableSendPlaylist();
return true;
}
/** SendFilesFrame destructor.
*
*/
SendFilesFrame::~SendFilesFrame()
{
SessionWindow *sessionWnd = ((SessionWindow *)GetParent());
SkinLite *skinLite = (SkinLite *)(sessionWnd->GetParent());
skinLite->ChangeSendFilesExistsStatus(false);
if (skinLite->CheckSessionWindowExists())
sessionWnd->EnableSendPlaylist();
}
/*!
* Member initialisation
*/
void SendFilesFrame::Init()
{
m_whiteboardTransmissionEnabled = false;
m_mainVertSizer = NULL;
m_mainPanel = NULL;
m_mainPanelVertSizer = NULL;
m_fileGroupBoxSizer = NULL;
m_lblFileName = NULL;
m_fileNameSizer = NULL;
m_txtFileName = NULL;
m_btnSearchFile = NULL;
m_statusTransferGroupBoxSizer = NULL;
m_transferLabelsGridSizer = NULL;
m_lblFileSizeCaption = NULL;
m_lblFileSizeLength = NULL;
m_lblSentCaption = NULL;
m_lblSentPercentual = NULL;
m_lblSentBytesCaption = NULL;
m_lblSentBytesLength = NULL;
m_lblRemainingTimeTransferCaption = NULL;
m_lblRemainingTimeTransfer = NULL;
m_lblBitrateCaption = NULL;
m_lblBitrate = NULL;
m_gaugeTransferFile = NULL;
m_recoverTransferGridSizer = NULL;
m_lblRecoveredCaption = NULL;
m_lblRecoveredPercentual = NULL;
m_lblReamainingTimeRecoveredCaption = NULL;
m_lblRemainingTimeRecovered = NULL;
m_gaugeRecovered = NULL;
m_transferCtrlSizer = NULL;
m_btnSend = NULL;
m_btnCancel = NULL;
m_StatisticGroupBoxSizer = NULL;
m_statisticGridSizer = NULL;
m_lblStatisticSentCaption = NULL;
m_lblStatisticSent = NULL;
m_lblStatisticCancelledCaption = NULL;
m_lblStatisticCancelled = NULL;
m_lblStatisticReceivedCaption = NULL;
m_lblStatisticReceived = NULL;
m_lblStatisticToReceiveCaption = NULL;
m_lblStatisticToReceive = NULL;
m_mediaId = 0;
m_sendFinished = true;
m_totalLostPackets = 0;
m_isTotalLostPackets = false;
m_isRecoverPhase = false;
m_beginningTransmission = false;
m_toReceive = 0;
m_sent = 0;
m_cancelled = 0;
m_received = 0;
m_filePath = wxEmptyString;
m_lastPacket = 0;
m_currentPacket = 0;
m_timer.SetOwner(this);
m_timer.Start(TIMER_INTERVAL);
m_timer.Stop();
}
/*!
* Control creation for SendFilesFrame
*/
void SendFilesFrame::CreateControls()
{
SendFilesFrame* itemFrame1 = this;
m_mainVertSizer = new wxBoxSizer(wxVERTICAL);
itemFrame1->SetSizer(m_mainVertSizer);
m_mainPanel = new wxPanel( itemFrame1, ID_SENDFILESFRAME_MAINPANEL, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER|wxTAB_TRAVERSAL );
m_mainVertSizer->Add(m_mainPanel, 1, wxGROW, 5);
m_mainPanelVertSizer = new wxBoxSizer(wxVERTICAL);
m_mainPanel->SetSizer(m_mainPanelVertSizer);
m_animatedGif.LoadFile(SENDFILESFRAME_ANIMATEDSENDGIF);
m_sendAnimatedGif = new wxAnimationCtrl(m_mainPanel, wxID_ANY, m_animatedGif);
m_mainPanelVertSizer->Add(m_sendAnimatedGif, 0, wxALIGN_CENTER_HORIZONTAL, 5);
m_fileGroupBoxSizer = new wxStaticBox(m_mainPanel, wxID_ANY, wxEmptyString);
wxStaticBoxSizer* itemStaticBoxSizer5 = new wxStaticBoxSizer(m_fileGroupBoxSizer, wxVERTICAL);
m_mainPanelVertSizer->Add(itemStaticBoxSizer5, 0, wxGROW|wxALL, 5);
m_lblFileName = new wxStaticText( m_mainPanel, wxID_STATIC, SENDFILESFRAME_LBL_FILENAME_LABEL, wxDefaultPosition, wxDefaultSize, 0 );
itemStaticBoxSizer5->Add(m_lblFileName, 0, wxALIGN_LEFT|wxLEFT|wxRIGHT|wxTOP, 5);
m_fileNameSizer = new wxBoxSizer(wxHORIZONTAL);
itemStaticBoxSizer5->Add(m_fileNameSizer, 0, wxGROW|wxLEFT|wxRIGHT|wxBOTTOM, 5);
m_txtFileName = new wxTextCtrl( m_mainPanel, ID_SENDFILESFRAME_TXT_FILENAME, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
m_fileNameSizer->Add(m_txtFileName, 1, wxALIGN_CENTER_VERTICAL|wxRIGHT|wxTOP|wxBOTTOM, 5);
m_btnSearchFile = new wxButton( m_mainPanel, ID_SENDFILESFRAME_BTN_SEARCHFILE, SENDFILESFRAME_BTN_SEARCH_LABEL, wxDefaultPosition, wxDefaultSize, 0 );
m_fileNameSizer->Add(m_btnSearchFile, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_statusTransferGroupBoxSizer = new wxStaticBox(m_mainPanel, wxID_ANY, wxEmptyString);
wxStaticBoxSizer* itemStaticBoxSizer10 = new wxStaticBoxSizer(m_statusTransferGroupBoxSizer, wxVERTICAL);
m_mainPanelVertSizer->Add(itemStaticBoxSizer10, 0, wxGROW|wxALL, 5);
m_transferLabelsGridSizer = new wxGridSizer(5, 5, 0, 0);
itemStaticBoxSizer10->Add(m_transferLabelsGridSizer, 0, wxGROW|wxALL, 5);
m_lblFileSizeCaption = new wxStaticText( m_mainPanel, wxID_STATIC, SENDFILESFRAME_LBL_FILESIZE_CAPTION, wxDefaultPosition, wxDefaultSize, 0 );
m_transferLabelsGridSizer->Add(m_lblFileSizeCaption, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_lblFileSizeLength = new wxStaticText( m_mainPanel, wxID_STATIC, wxT("0.00 KB"), wxDefaultPosition, wxDefaultSize, 0 );
m_transferLabelsGridSizer->Add(m_lblFileSizeLength, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_transferLabelsGridSizer->Add(5, 5, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_transferLabelsGridSizer->Add(5, 5, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_transferLabelsGridSizer->Add(5, 5, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_lblSentCaption = new wxStaticText( m_mainPanel, wxID_STATIC, SENDFILESFRAME_LBL_FILESENT_CAPTION, wxDefaultPosition, wxDefaultSize, 0 );
m_transferLabelsGridSizer->Add(m_lblSentCaption, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_lblSentPercentual = new wxStaticText( m_mainPanel, wxID_STATIC, wxT("0 %"), wxDefaultPosition, wxDefaultSize, 0 );
m_transferLabelsGridSizer->Add(m_lblSentPercentual, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_transferLabelsGridSizer->Add(5, 5, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_lblSentBytesCaption = new wxStaticText( m_mainPanel, wxID_STATIC, SENDFILESFRAME_LBL_FILESENTBYTES_CAPTION, wxDefaultPosition, wxDefaultSize, 0 );
m_transferLabelsGridSizer->Add(m_lblSentBytesCaption, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_lblSentBytesLength = new wxStaticText( m_mainPanel, wxID_STATIC, wxT("0.00 KB"), wxDefaultPosition, wxDefaultSize, 0 );
m_transferLabelsGridSizer->Add(m_lblSentBytesLength, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_lblRemainingTimeTransferCaption = new wxStaticText( m_mainPanel, wxID_STATIC, SENDFILESFRAME_LBL_REMAININGTIME_CAPTION, wxDefaultPosition, wxDefaultSize, 0 );
m_transferLabelsGridSizer->Add(m_lblRemainingTimeTransferCaption, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_lblRemainingTimeTransfer = new wxStaticText( m_mainPanel, wxID_STATIC, wxT("00:00:00"), wxDefaultPosition, wxDefaultSize, 0 );
m_transferLabelsGridSizer->Add(m_lblRemainingTimeTransfer, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_transferLabelsGridSizer->Add(5, 5, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_lblBitrateCaption = new wxStaticText( m_mainPanel, wxID_STATIC, SENDFILESFRAME_LBL_BITRATE_CAPTION, wxDefaultPosition, wxDefaultSize, 0 );
m_transferLabelsGridSizer->Add(m_lblBitrateCaption, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_lblBitrate = new wxStaticText( m_mainPanel, wxID_STATIC, wxT("0 kB/s"), wxDefaultPosition, wxDefaultSize, 0 );
m_transferLabelsGridSizer->Add(m_lblBitrate, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_gaugeTransferFile = new wxGauge( m_mainPanel, ID_SENDFILESFRAME_GAUGE_TRANSFERFILE, 100, wxDefaultPosition, wxDefaultSize, wxGA_HORIZONTAL );
m_gaugeTransferFile->SetValue(0);
itemStaticBoxSizer10->Add(m_gaugeTransferFile, 0, wxGROW|wxALL, 5);
m_recoverTransferGridSizer = new wxGridSizer(2, 2, 0, 0);
itemStaticBoxSizer10->Add(m_recoverTransferGridSizer, 0, wxALIGN_LEFT|wxALL, 5);
m_lblRecoveredCaption = new wxStaticText( m_mainPanel, wxID_STATIC, SENDFILESFRAME_LBL_RECOVERED_CAPTION, wxDefaultPosition, wxDefaultSize, 0 );
m_recoverTransferGridSizer->Add(m_lblRecoveredCaption, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_lblRecoveredPercentual = new wxStaticText( m_mainPanel, wxID_STATIC, wxT("0 %"), wxDefaultPosition, wxDefaultSize, 0 );
m_recoverTransferGridSizer->Add(m_lblRecoveredPercentual, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_lblReamainingTimeRecoveredCaption = new wxStaticText( m_mainPanel, wxID_STATIC, SENDFILESFRAME_LBL_REMAININGTIMERECOVERED_CAPTION, wxDefaultPosition, wxDefaultSize, 0 );
m_recoverTransferGridSizer->Add(m_lblReamainingTimeRecoveredCaption, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_lblRemainingTimeRecovered = new wxStaticText( m_mainPanel, wxID_STATIC, wxT("00:00:00"), wxDefaultPosition, wxDefaultSize, 0 );
m_recoverTransferGridSizer->Add(m_lblRemainingTimeRecovered, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_gaugeRecovered = new wxGauge( m_mainPanel, ID_SENDFILESFRAME_GAUGE_RECOVERED, 100, wxDefaultPosition, wxDefaultSize, wxGA_HORIZONTAL );
m_gaugeRecovered->SetValue(0);
itemStaticBoxSizer10->Add(m_gaugeRecovered, 0, wxGROW|wxALL, 5);
m_transferCtrlSizer = new wxBoxSizer(wxHORIZONTAL);
itemStaticBoxSizer10->Add(m_transferCtrlSizer, 0, wxALIGN_LEFT|wxRIGHT|wxTOP|wxBOTTOM, 5);
m_btnSend = new wxButton( m_mainPanel, ID_SENDFILESFRAME_BTN_SEND, SENDFILESFRAME_BTN_SEND_LABEL, wxDefaultPosition, wxDefaultSize, 0 );
m_transferCtrlSizer->Add(m_btnSend, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_btnSend->Disable();
m_btnCancel = new wxButton( m_mainPanel, ID_SENDFILESFRAME_BTN_CANCEL, SENDFILESFRAME_BTN_CANCEL_LABEL, wxDefaultPosition, wxDefaultSize, 0 );
m_transferCtrlSizer->Add(m_btnCancel, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_btnCancel->Disable();
////Cancel button was hidden for send release
//m_btnCancel->Hide();
m_StatisticGroupBoxSizer = new wxStaticBox(m_mainPanel, wxID_ANY, wxEmptyString);
wxStaticBoxSizer* itemStaticBoxSizer37 = new wxStaticBoxSizer(m_StatisticGroupBoxSizer, wxVERTICAL);
m_mainPanelVertSizer->Add(itemStaticBoxSizer37, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5);
m_statisticGridSizer = new wxGridSizer(4, 4, 0, 0);
itemStaticBoxSizer37->Add(m_statisticGridSizer, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5);
m_lblStatisticSentCaption = new wxStaticText( m_mainPanel, wxID_STATIC, SENDFILESFRAME_LBL_STATISTICSENT_CAPTION, wxDefaultPosition, wxDefaultSize, 0 );
m_statisticGridSizer->Add(m_lblStatisticSentCaption, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_lblStatisticSent = new wxStaticText( m_mainPanel, wxID_STATIC, wxT("0"), wxDefaultPosition, wxDefaultSize, 0 );
m_statisticGridSizer->Add(m_lblStatisticSent, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_lblStatisticCancelledCaption = new wxStaticText( m_mainPanel, wxID_STATIC, SENDFILESFRAME_LBL_STATISTICCANCELLED_CAPTION, wxDefaultPosition, wxDefaultSize, 0 );
m_statisticGridSizer->Add(m_lblStatisticCancelledCaption, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_lblStatisticCancelled = new wxStaticText( m_mainPanel, wxID_STATIC, wxT("0"), wxDefaultPosition, wxDefaultSize, 0 );
m_statisticGridSizer->Add(m_lblStatisticCancelled, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_lblStatisticReceivedCaption = new wxStaticText( m_mainPanel, wxID_STATIC, SENDFILESFRAME_LBL_STATISTICRECEIVED_CAPTION, wxDefaultPosition, wxDefaultSize, 0 );
m_statisticGridSizer->Add(m_lblStatisticReceivedCaption, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_lblStatisticReceived = new wxStaticText( m_mainPanel, wxID_STATIC, wxT("0"), wxDefaultPosition, wxDefaultSize, 0 );
m_statisticGridSizer->Add(m_lblStatisticReceived, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_lblStatisticToReceiveCaption = new wxStaticText( m_mainPanel, wxID_STATIC, SENDFILESFRAME_LBL_STATISTICTORECEIVE_CAPTION, wxDefaultPosition, wxDefaultSize, 0 );
m_statisticGridSizer->Add(m_lblStatisticToReceiveCaption, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_lblStatisticToReceive = new wxStaticText( m_mainPanel, wxID_STATIC, wxT("0"), wxDefaultPosition, wxDefaultSize, 0 );
m_statisticGridSizer->Add(m_lblStatisticToReceive, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_mainVertSizer->Fit(this);
}
/*!
* Should we show tooltips?
*/
bool SendFilesFrame::ShowToolTips()
{
return true;
}
/*!
* Get bitmap resources
*/
wxBitmap SendFilesFrame::GetBitmapResource( const wxString& name )
{
// Bitmap retrieval
wxUnusedVar(name);
return wxNullBitmap;
}
/*!
* Get icon resources
*/
wxIcon SendFilesFrame::GetIconResource( const wxString& name )
{
// Icon retrieval
wxUnusedVar(name);
return wxNullIcon;
}
/*!
* wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_SENDFILESFRAME_BTN_SEARCHFILE
*/
void SendFilesFrame::OnBtnSearchFileClick( wxCommandEvent& event )
{
wxString wildcard;
#ifdef WIN32 // "All files" means "*.*" in Windows, "*" in other systems
wildcard = _("All files|*.*");
#else
wildcard = _("All files|*");
#endif // WIN32
wxFileDialog fileDialog(this, SENDFILESFRAME_DLG_CHOOSEFILE_LABEL, wxEmptyString, wxEmptyString, wildcard, wxFD_OPEN|wxFD_FILE_MUST_EXIST);
if (fileDialog.ShowModal() == wxID_OK)
{
m_txtFileName->SetValue(fileDialog.GetPath());
}
}
void SendFilesFrame::OnClose(wxCloseEvent &event)
{
wxCHECK_RET(m_appInterface, wxT("SendFilesFrame::OnClose(): I need AppInterface to work!!"));
if (event.CanVeto())
{
if (!m_sendFinished)
{
int ret = OnFileTransferCancelSendFile();
if (ret == SENDFILESFRAME_RET_ONCANCEL_OK)
{
this->Destroy();
}
else if (ret == SENDFILESFRAME_RET_ONCANCEL_CANCELERROR)
{
wxMessageBox(_("any files being sent."), wxMessageBoxCaptionStr, 4|wxCENTRE, this);
}
}
else
{
this->Destroy();
}
}
else
{
if(!m_sendFinished)
m_appInterface->FileTransferCancelTransmission(m_mediaId);
this->Destroy();
}
}
/*!
* wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_SENDFILESFRAME_BTN_SEND
*/
void SendFilesFrame::OnBtnSendClick( wxCommandEvent& event )
{
wxCHECK_RET(m_appInterface, wxT("SendFilesFrame::OnBtnSendClick( wxCommandEvent& event ): No AppInterface!!"));
m_filePath = m_txtFileName->GetValue();
// Check if file exists and we have permission to read
if(wxFile::Exists(m_filePath))
{
if(!wxFile::Access(m_filePath, wxFile::read))
{
wxMessageBox(_("You do not have permission to access this file."), wxMessageBoxCaptionStr, 4|wxCENTRE, this);
return;
}
}
else
{
wxMessageBox(_("This file don't exist."), wxMessageBoxCaptionStr, 4|wxCENTRE, this);
return;
}
//wxMessageBox(m_filePath);
wxFileName file = wxFileName(m_filePath);
unsigned long fileSize = file.GetSize().ToULong();
const Channel *channel = m_appInterface->GetCurrentChannel();
//Get channel bitrate
Mode mode;
ModeList modeList = channel->GetModeList();
modeList.FindMode(IRM_MODE_CHANNEL_BITRATE, mode);
long bitrate;
mode.GetParameter().ToLong(&bitrate);
OnFileTransferSendFile(channel->GetName(), m_filePath, fileSize, bitrate);
}
/*!
* wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_SENDFILESFRAME_BTN_CANCEL
*/
void SendFilesFrame::OnBtnCancelClick( wxCommandEvent& event )
{
int ret = OnFileTransferCancelSendFile();
if (ret == SENDFILESFRAME_RET_ONCANCEL_OK)
{
m_btnSend->Enable();
m_btnCancel->Disable();
m_btnSearchFile->Enable();
m_txtFileName->Enable();
m_sendAnimatedGif->Stop();
InitializeAllFields();
}
else if (ret == SENDFILESFRAME_RET_ONCANCEL_CANCELERROR)
{
m_btnSend->Enable();
m_btnCancel->Disable();
m_btnSearchFile->Enable();
m_txtFileName->Enable();
m_sendAnimatedGif->Stop();
InitializeAllFields();
wxMessageBox(_("any files being sent."), wxMessageBoxCaptionStr, 4|wxCENTRE, this);
}
}
/** Cancel send file.
* @return SENDFILESFRAME_RET_ONCANCEL_OK. Send file was cancelled successfully.
* @return SENDFILESFRAME_RET_ONCANCEL_CANCELERROR. Send file couldn't cancelled.
* @return SENDFILESFRAME_RET_ONCANCEL_CANCELABORT. Send file cancel was aborted.
*/
int SendFilesFrame::OnFileTransferCancelSendFile()
{
//wxCHECK_RET(m_appInterface, wxT("SendFilesFrame::OnFileTransferCancelSendFile(): I need AppInterface to work!!"));
MessageDialog cancelDlg(this,_("Cancel"), _("Do you want cancel send file?"));
if (cancelDlg.ShowModal() == ID_MESSAGEDIALOG_BTN_YES)
{
bool ret = m_appInterface->FileTransferCancelTransmission(m_mediaId);
if (ret)
return SENDFILESFRAME_RET_ONCANCEL_OK; //SendFiles cancel successfull
else
return SENDFILESFRAME_RET_ONCANCEL_CANCELERROR; //Can't cancel SendFiles
}
return SENDFILESFRAME_RET_ONCANCEL_CANCELABORT; //Abort cancel SendFiles
}
void SendFilesFrame::OnTxtFileNameChange(wxCommandEvent &event)
{
wxString str = event.GetString();
if (str != wxEmptyString)
m_btnSend->Enable();
else
m_btnSend->Disable();
}
void SendFilesFrame::OnTimer( wxTimerEvent& event )
{
if (!m_isRecoverPhase)
{
unsigned long bytesPerSecond = m_packetSize * ((m_currentPacket - m_lastPacket)*1000/TIMER_INTERVAL);
unsigned long timeLeft = 0;
if(bytesPerSecond != 0)
timeLeft = (m_fileSize - (m_currentPacket * m_packetSize))/bytesPerSecond;
wxString label;
SizeToSizeLabel(bytesPerSecond, label);
label += wxT("/s");
m_lblBitrate->SetLabel(label);
wxTimeSpan timeLeftTS = wxTimeSpan::Seconds(timeLeft);
m_lblRemainingTimeTransfer->SetLabel(timeLeftTS.Format());
m_lastPacket = m_currentPacket;
}
else
{
unsigned long bytesPerSecond = ((m_packetSize/* * m_totalLostPackets*/)*1000/TIMER_INTERVAL);
unsigned long timeLeft = 0;
if(bytesPerSecond != 0)
timeLeft = ((m_totalLostPackets - m_lostPackets) * m_packetSize) / bytesPerSecond;
wxTimeSpan timeLeftLP = wxTimeSpan::Seconds(timeLeft);
m_lblRemainingTimeRecovered->SetLabel(timeLeftLP.Format());
}
}
/** Start whiteBoard file transmission.
* @param[in] filePath. Whiteboard path.
*/
void SendFilesFrame::StartWhiteboardFileTransmission(const wxString &filePath)
{
if(filePath == wxEmptyString)
return;
m_filePath = filePath;
m_txtFileName->SetValue(m_filePath);
//if(m_btnSend->IsEnabled())
{
m_whiteboardTransmissionEnabled = true;
wxCommandEvent e;
this->OnBtnSendClick(e);
}
}
/** Begin send file trasmission.
* @param[in] channel. Channel to send file.
* @param[in] filePath. File path.
* @param[in] filPath. File path.
* @param[in] fileSize. File size.
* @param[in] bitrate. Transmission Bitrate.
*/
void SendFilesFrame::OnFileTransferSendFile(const wxString &channel, const wxString &filePath, unsigned long fileSize, unsigned bitRate)
{
InitializeAllFields();
wxCHECK_RET(m_appInterface, wxT("SendFilesFrame::OnFileTransferSendBegin(): No AppInterface!!"));
m_fileSize = fileSize;
wxString label;
SizeToSizeLabel(fileSize, label);
m_lblFileSizeLength->SetLabel(label);
//Checks if the user has media voice
if (m_appInterface->GetCurrentChannelUser()->HasMediaVoice())
{
if(m_whiteboardTransmissionEnabled)
{
if (m_appInterface->FileTransferBeginWhiteboardTransmission(channel, filePath, fileSize, bitRate))
{
m_btnSend->Disable();
m_btnCancel->Enable();
m_btnSearchFile->Disable();
m_txtFileName->Disable();
m_timer.Start();
}
else
{
m_btnSend->Enable();
m_btnCancel->Disable();
m_btnSearchFile->Enable();
m_txtFileName->Enable();
m_timer.Stop();
}
}
else
{
if (m_appInterface->FileTransferBeginTransmission(channel, filePath, fileSize, bitRate))
{
m_btnSend->Disable();
m_btnCancel->Enable();
m_btnSearchFile->Disable();
m_txtFileName->Disable();
m_timer.Start();
}
else
{
m_btnSend->Enable();
m_btnCancel->Disable();
m_btnSearchFile->Enable();
m_txtFileName->Enable();
m_timer.Stop();
}
}
}
else
wxMessageBox(_("User don't have voice"), wxMessageBoxCaptionStr, 4|wxCENTRE, this);
}
/** Updates the progress of send.
* @param[in] currentPacketIndex. Index of the current packet sent.
* @param[in] lastPacketIndex. last packet to send.
*/
void SendFilesFrame::OnFileTransferSendProgress(unsigned long currentPacketIndex, unsigned long lastPacketIndex)
{
if (m_isTotalLostPackets)
{
m_packetSize = (float)m_fileSize / (float)lastPacketIndex;
m_isTotalLostPackets = false;
}
if (m_beginningTransmission)
{
m_sendAnimatedGif->Play();
m_beginningTransmission = false;
}
// Save current packet to use in timer
m_currentPacket = currentPacketIndex;
wxString label;
if(currentPacketIndex != lastPacketIndex)
SizeToSizeLabel(currentPacketIndex * m_packetSize, label);
else
SizeToSizeLabel(m_fileSize, label);
m_lblSentBytesLength->SetLabel(label);
float percentage = ((float)(currentPacketIndex)/(float)(lastPacketIndex))*100.0f;
label.Printf(wxT("%.2f%%"), percentage);
m_lblSentPercentual->SetLabel(label);
m_gaugeTransferFile->SetValue((int)percentage);
}
/** Begin show the progress of lost packets upload.
* @param[in] lostPacket. Number of lost packets.
*/
void SendFilesFrame::OnFileTransferSendLostPacket(unsigned long lostPackets, unsigned long lostPacketsTotal)
{
wxString label;
m_totalLostPackets = lostPacketsTotal;
m_lostPackets = lostPackets;
float percentage = (((float)(lostPackets)/(float)(lostPacketsTotal)))*100.0f;
label.Printf(wxT("%.2f%%"), percentage);
m_lblRecoveredPercentual->SetLabel(label);
m_gaugeRecovered->SetValue((int)percentage);
}
/** Informs thats file came to at end.
*
*/
void SendFilesFrame::OnFileTransferSendEof()
{
m_isTotalLostPackets = true;
m_isRecoverPhase = true;
}
/** Show thats the send ocurred successfully.
*
*/
void SendFilesFrame::OnFileTransferSendSuccess()
{
m_sendFinished = true;
m_sendAnimatedGif->Stop();
m_timer.Stop();
m_btnSend->Enable();
m_btnCancel->Disable();
m_btnSearchFile->Enable();
m_txtFileName->Enable();
m_sendAnimatedGif->Stop();
InitializeAllFields();
if(!m_whiteboardTransmissionEnabled)
wxMessageBox(_("File transfer send successfull."), wxMessageBoxCaptionStr, 4|wxCENTRE, this);
else
{
m_whiteboardTransmissionEnabled = false;
Close();
}
}
/** Initaialize all dialog fields.
* Private method.
*/
void SendFilesFrame::InitializeAllFields()
{
m_sendFinished = true;
m_beginningTransmission = true;
m_totalLostPackets = 0;
m_isTotalLostPackets = true;
m_isRecoverPhase = false;
m_gaugeTransferFile->SetValue(0);
m_gaugeRecovered->SetValue(0);
m_cancelled = 0;
m_toReceive = 0;
m_received = 0;
m_sent = 0;
m_lblSentPercentual->SetLabel(wxT("0 %"));
m_lblSentBytesLength->SetLabel(wxT("0.00 KB"));
m_lblRemainingTimeTransfer->SetLabel(wxT("00:00:00"));
m_lblBitrate->SetLabel(wxT("0 bytes/s"));
m_lblRecoveredPercentual->SetLabel(wxT("0 %"));
m_lblRemainingTimeRecovered->SetLabel(wxT("00:00:00"));
m_lblStatisticCancelled->SetLabel(wxString::Format(wxT("%d"), m_cancelled));
m_lblStatisticReceived->SetLabel(wxString::Format(wxT("%d"), m_received));
m_lblStatisticSent->SetLabel(wxString::Format(wxT("%d"), m_sent));
m_lblStatisticToReceive->SetLabel(wxString::Format(wxT("%d"), m_toReceive));
}
/** Show thats an error ocurred with send.
*
*/
void SendFilesFrame::OnFileTransferSendError()
{
m_sendFinished = true;
m_sendAnimatedGif->Stop();
//Checks if the user has media voice
if (!m_appInterface->GetCurrentChannelUser()->HasMediaVoice())
wxMessageBox(wxString::Format(_("File transfer Send error.\n%s lost voice."),m_appInterface->GetCurrentUser()->GetNickName().c_str()), wxMessageBoxCaptionStr, wxICON_ERROR|wxCENTRE, this);
else
wxMessageBox(_("File transfer Send error."), wxMessageBoxCaptionStr, wxICON_ERROR|wxCENTRE, this);
m_whiteboardTransmissionEnabled = false;
Close();
}
/** Show thats file send began.
*
*/
void SendFilesFrame::OnFileTranferSendBegin(long mediaId)
{
m_mediaId = mediaId;
m_sendFinished = false;
}
/** Informs that a new receiver entered.
* @param[in] mediaId. Media id of the new receiver.
*/
void SendFilesFrame::OnFileTransferSendReceiverNew(long mediaId)
{
m_sent++;
UpdateToReceiveStatistic();
}
/** Informs that a receiver cancelled the transmission.
* @param[in] mediaId. Media id of the receiver.
*/
void SendFilesFrame::OnFileTransferSendReceiverCancel(long mediaId)
{
m_cancelled++;
UpdateToReceiveStatistic();
}
/** Informs that a receiver terminate of download.
* @param[in] mediaId. Media id of the receiver.
*/
void SendFilesFrame::OnFileTransferSendReceiverEnd(long mediaId)
{
m_received++;
UpdateToReceiveStatistic();
}
/** Updates the number of users receivers statistics.
* Private method.
*/
void SendFilesFrame::UpdateToReceiveStatistic()
{
m_toReceive = m_sent - m_cancelled - m_received;
m_lblStatisticCancelled->SetLabel(wxString::Format(wxT("%d"), m_cancelled));
m_lblStatisticReceived->SetLabel(wxString::Format(wxT("%d"), m_received));
m_lblStatisticSent->SetLabel(wxString::Format(wxT("%d"), m_sent));
m_lblStatisticToReceive->SetLabel(wxString::Format(wxT("%d"), m_toReceive));
}
/** Receive the size of file and devolve your respective string in bytes, Kbytes, MBytes or GBytes.
* @param[in] size. File Size.
* @param[out] label. String containing the size in format described above.
* Private method.
*/
void SendFilesFrame::SizeToSizeLabel(unsigned long size, wxString &label)
{
// show in GBytes
if((size/1073741824) > 0)
{
label.Printf(wxT("%d.%d GB"), size/1073741824, ((size*100)/1073741824)%100);
return;
}
// show in MBytes
if((size/1048576) > 0)
{
label.Printf(wxT("%d.%d MB"), size/1048576, ((size*100)/1048576)%100);
return;
}
// show in KBytes
if((size/1024) > 0)
{
label.Printf(wxT("%d.%d kB"), size/1024, ((size*10)/1024)%10);
return;
}
// show in bytes
label.Printf(wxT("%d Bytes"), size);
return;
}
| [
"heineck@c016ff2c-3db2-11de-a81c-fde7d73ceb89"
] | [
[
[
1,
855
]
]
] |
6685a834ae197b6fb03982c566d588765b596d56 | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/Dependencies/Xerces/include/xercesc/validators/DTD/DTDAttDef.hpp | 6b2abfbf3f3bae09602a082e71e5a0be9c71fad7 | [] | 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 | 5,516 | hpp | /*
* Copyright 1999-2000,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: DTDAttDef.hpp 191054 2005-06-17 02:56:35Z jberry $
*/
#if !defined(DTDATTDEF_HPP)
#define DTDATTDEF_HPP
#include <xercesc/framework/XMLAttDef.hpp>
XERCES_CPP_NAMESPACE_BEGIN
//
// This class is a derivative of the core XMLAttDef class. This class adds
// any DTD specific data members and provides DTD specific implementations
// of any underlying attribute def virtual methods.
//
// In the DTD we don't do namespaces, so the attribute names are just the
// QName literally from the DTD. This is what we return as the full name,
// which is what is used to key these in any name keyed collections.
//
class VALIDATORS_EXPORT DTDAttDef : public XMLAttDef
{
public :
// -----------------------------------------------------------------------
// Constructors and Destructors
// -----------------------------------------------------------------------
DTDAttDef(MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);
DTDAttDef
(
const XMLCh* const attName
, const XMLAttDef::AttTypes type = CData
, const XMLAttDef::DefAttTypes defType = Implied
, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager
);
DTDAttDef
(
const XMLCh* const attName
, const XMLCh* const attValue
, const XMLAttDef::AttTypes type
, const XMLAttDef::DefAttTypes defType
, const XMLCh* const enumValues = 0
, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager
);
~DTDAttDef();
// -----------------------------------------------------------------------
// Implementation of the XMLAttDef interface
// -----------------------------------------------------------------------
virtual const XMLCh* getFullName() const;
//does nothing currently
virtual void reset() {};
// -----------------------------------------------------------------------
// Getter methods
// -----------------------------------------------------------------------
unsigned int getElemId() const;
/**
* @deprecated
**/
virtual const XMLCh* getDOMTypeInfoName() const;
/**
* @deprecated
**/
virtual const XMLCh* getDOMTypeInfoUri() const;
// -----------------------------------------------------------------------
// Setter methods
// -----------------------------------------------------------------------
void setElemId(const unsigned int newId);
void setName(const XMLCh* const newName);
/***
* Support for Serialization/De-serialization
***/
DECL_XSERIALIZABLE(DTDAttDef)
private :
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
DTDAttDef(const DTDAttDef &);
DTDAttDef& operator = (const DTDAttDef&);
// -----------------------------------------------------------------------
// Private data members
//
// fElemId
// This is the id of the element (the id is into the element decl
// pool) of the element this attribute def said it belonged to.
// This is used later to link back to the element, mostly for
// validation purposes.
//
// fName
// This is the name of the attribute. Since we don't do namespaces
// in the DTD, its just the fully qualified name.
// -----------------------------------------------------------------------
unsigned int fElemId;
XMLCh* fName;
};
// ---------------------------------------------------------------------------
// DTDAttDef: Implementation of the XMLAttDef interface
// ---------------------------------------------------------------------------
inline const XMLCh* DTDAttDef::getFullName() const
{
return fName;
}
// ---------------------------------------------------------------------------
// DTDAttDef: Getter methods
// ---------------------------------------------------------------------------
inline unsigned int DTDAttDef::getElemId() const
{
return fElemId;
}
inline const XMLCh* DTDAttDef::getDOMTypeInfoName() const
{
return getAttTypeString(getType(), getMemoryManager());
}
inline const XMLCh* DTDAttDef::getDOMTypeInfoUri() const
{
return 0;
}
// ---------------------------------------------------------------------------
// DTDAttDef: Setter methods
// ---------------------------------------------------------------------------
inline void DTDAttDef::setElemId(const unsigned int newId)
{
fElemId = newId;
}
XERCES_CPP_NAMESPACE_END
#endif
| [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
] | [
[
[
1,
161
]
]
] |
9f665955c15411dcdfa3f7d9def74a0bc6a52c8d | f89e32cc183d64db5fc4eb17c47644a15c99e104 | /pcsx2-rr/pcsx2/gui/Dialogs/GameDatabaseDialog.cpp | c286e3387f0f507b01d5c77c325675cc0b4aec3a | [] | 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 | 1,113 | 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 "ConfigurationDialog.h"
#include "Panels/ConfigurationPanels.h"
Dialogs::GameDatabaseDialog::GameDatabaseDialog(wxWindow* parent)
: BaseConfigurationDialog( parent, AddAppName(_("Game Database - %s")), 580 )
{
ScopedBusyCursor busy( Cursor_ReallyBusy );
*this += new Panels::GameDatabasePanel(this);
AddOkCancel();
}
| [
"koeiprogenitor@bfa1b011-20a7-a6e3-c617-88e5d26e11c5"
] | [
[
[
1,
28
]
]
] |
824a45c547f0f7947b51956d3d5fc2f19852850e | e3520ab4a2904f7ac4b76537faaa566a670b7ef2 | /src/HashAlgorithm.cpp | 72c78f3f40a9010bdfa645831f8958a9c9f0ed6f | [] | no_license | WilliamsCompanies/linuxrainbowcrack | 6850a9db97b722185b780ed6e95923f04988e5da | 73101acb84c2555839c04a12267f71cfb614512a | refs/heads/master | 2016-08-04T22:37:01.224726 | 2011-04-07T12:34:55 | 2011-04-07T12:34:55 | 33,197,850 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,979 | cpp | /*
RainbowCrack - a general propose implementation of Philippe Oechslin's faster time-memory trade-off technique.
Copyright (C) Zhu Shuanglei <[email protected]>
*/
#include "HashAlgorithm.h"
#include <unistd.h>
#include <string.h>
#include <openssl/des.h>
#include <openssl/md5.h>
#include <openssl/sha.h>
#ifdef _WIN32
#pragma comment(lib, "libeay32.lib")
#endif
void HashCrypt(unsigned char* pPlain, int nPlainLen, unsigned char* pHash)
{
unsigned char *realPlain;
unsigned char realSalt[2];
realSalt[0] = pPlain[0];
realSalt[1] = pPlain[1];
realPlain = pPlain;
realPlain += 2;
pPlain += 2;
pPlain[nPlainLen-2]=0x00;
memcpy(pHash, DES_crypt((const char*)realPlain, (const char*)realSalt), 13);
}
void setup_des_key(unsigned char key_56[], des_key_schedule &ks)
{
des_cblock key;
key[0] = key_56[0];
key[1] = (key_56[0] << 7) | (key_56[1] >> 1);
key[2] = (key_56[1] << 6) | (key_56[2] >> 2);
key[3] = (key_56[2] << 5) | (key_56[3] >> 3);
key[4] = (key_56[3] << 4) | (key_56[4] >> 4);
key[5] = (key_56[4] << 3) | (key_56[5] >> 5);
key[6] = (key_56[5] << 2) | (key_56[6] >> 6);
key[7] = (key_56[6] << 1);
//des_set_odd_parity(&key);
des_set_key(&key, ks);
}
void HashLM(unsigned char* pPlain, int nPlainLen, unsigned char* pHash)
{
/*
unsigned char data[7] = {0};
memcpy(data, pPlain, nPlainLen > 7 ? 7 : nPlainLen);
*/
int i;
for (i = nPlainLen; i < 7; i++)
pPlain[i] = 0;
static unsigned char magic[] = {0x4B, 0x47, 0x53, 0x21, 0x40, 0x23, 0x24, 0x25};
des_key_schedule ks;
//setup_des_key(data, ks);
setup_des_key(pPlain, ks);
des_ecb_encrypt((des_cblock*)magic, (des_cblock*)pHash, ks, DES_ENCRYPT);
}
void HashMD5(unsigned char* pPlain, int nPlainLen, unsigned char* pHash)
{
MD5(pPlain, nPlainLen, pHash);
}
void HashSHA1(unsigned char* pPlain, int nPlainLen, unsigned char* pHash)
{
SHA1(pPlain, nPlainLen, pHash);
}
| [
"kalgecin@81ab7593-b10c-351d-e91d-7834c5017167"
] | [
[
[
1,
72
]
]
] |
ddca836203c65b3bcde662252797c69c356a1d6d | 709cd826da3ae55945fd7036ecf872ee7cdbd82a | /Term/WildMagic2/Source/Intersection/WmlIntrUtilityTri3.cpp | 40cfe458cd409c37b6c1b525220dc28d74475b2c | [] | no_license | argapratama/kucgbowling | 20dbaefe1596358156691e81ccceb9151b15efb0 | 65e40b6f33c5511bddf0fa350c1eefc647ace48a | refs/heads/master | 2018-01-08T15:27:44.784437 | 2011-06-19T15:23:39 | 2011-06-19T15:23:39 | 36,738,655 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,403 | cpp | // Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2003. All Rights Reserved
//
// The Wild Magic Library (WML) source code is supplied under the terms of
// the license agreement http://www.magic-software.com/License/WildMagic.pdf
// and may not be copied or disclosed except in accordance with the terms of
// that agreement.
#include "WmlIntrUtilityTri3.h"
#include "WmlIntrUtilityLin3.h"
using namespace Wml;
//----------------------------------------------------------------------------
template <class Real>
void Wml::TriProjection (const Vector3<Real>& rkD, const Vector3<Real> akV[3],
Real& rfMin, Real& rfMax)
{
Real afDot[3] = { rkD.Dot(akV[0]), rkD.Dot(akV[1]), rkD.Dot(akV[2]) };
rfMin = afDot[0];
rfMax = rfMin;
if ( afDot[1] < rfMin )
rfMin = afDot[1];
else if ( afDot[1] > rfMax )
rfMax = afDot[1];
if ( afDot[2] < rfMin )
rfMin = afDot[2];
else if ( afDot[2] > rfMax )
rfMax = afDot[2];
}
//----------------------------------------------------------------------------
template <class Real>
void Wml::GetTriConfiguration (const Vector3<Real>& rkAxis,
const Vector3<Real> akU[3], ContactConfig<Real>& rkConfig)
{
// find projections of vertices onto potential separating axis
Real fD0 = rkAxis.Dot(akU[0]);
Real fD1 = rkAxis.Dot(akU[1]);
Real fD2 = rkAxis.Dot(akU[2]);
// explicit sort of vertices to construct a ContactConfig
if ( fD0 <= fD1 )
{
if ( fD1 <= fD2 ) // D0 <= D1 <= D2
{
if ( fD0 != fD1 )
{
if ( fD1 != fD2 )
rkConfig.m_kMap = m111;
else
rkConfig.m_kMap = m12;
}
else // ( D0 == D1 )
{
if ( fD1 != fD2 )
rkConfig.m_kMap = m21;
else
rkConfig.m_kMap = m3;
}
rkConfig.m_aiIndex[0] = 0;
rkConfig.m_aiIndex[1] = 1;
rkConfig.m_aiIndex[2] = 2;
rkConfig.m_fMin = fD0;
rkConfig.m_fMax = fD2;
}
else if ( fD0 <= fD2 ) // D0 <= D2 < D1
{
if ( fD0 != fD2 )
{
rkConfig.m_kMap = m111;
rkConfig.m_aiIndex[0] = 0;
rkConfig.m_aiIndex[1] = 2;
rkConfig.m_aiIndex[2] = 1;
}
else
{
rkConfig.m_kMap = m21;
rkConfig.m_aiIndex[0] = 2;
rkConfig.m_aiIndex[1] = 0;
rkConfig.m_aiIndex[2] = 1;
}
rkConfig.m_fMin = fD0;
rkConfig.m_fMax = fD1;
}
else // D2 < D0 <= D1
{
if ( fD0 != fD1 )
rkConfig.m_kMap = m111;
else
rkConfig.m_kMap = m12;
rkConfig.m_aiIndex[0] = 2;
rkConfig.m_aiIndex[1] = 0;
rkConfig.m_aiIndex[2] = 1;
rkConfig.m_fMin = fD2;
rkConfig.m_fMax = fD1;
}
}
else if ( fD2 <= fD1 ) // D2 <= D1 < D0
{
if ( fD2 != fD1 )
{
rkConfig.m_kMap = m111;
rkConfig.m_aiIndex[0] = 2;
rkConfig.m_aiIndex[1] = 1;
rkConfig.m_aiIndex[2] = 0;
}
else
{
rkConfig.m_kMap = m21;
rkConfig.m_aiIndex[0] = 1;
rkConfig.m_aiIndex[1] = 2;
rkConfig.m_aiIndex[2] = 0;
}
rkConfig.m_fMin = fD2;
rkConfig.m_fMax = fD0;
}
else if ( fD2 <= fD0 ) // D1 < D2 <= D0
{
if ( fD2 != fD0 )
rkConfig.m_kMap = m111;
else
rkConfig.m_kMap = m12;
rkConfig.m_aiIndex[0] = 1;
rkConfig.m_aiIndex[1] = 2;
rkConfig.m_aiIndex[2] = 0;
rkConfig.m_fMin = fD1;
rkConfig.m_fMax = fD0;
}
else // D1 < D0 < D2
{
rkConfig.m_kMap = m111;
rkConfig.m_aiIndex[0] = 1;
rkConfig.m_aiIndex[1] = 0;
rkConfig.m_aiIndex[2] = 2;
rkConfig.m_fMin = fD1;
rkConfig.m_fMax = fD2;
}
}
//----------------------------------------------------------------------------
template <class Real>
void Wml::FindContactSetColinearLineTri (const Vector3<Real> akU[2],
const Vector3<Real> akV[3], int& riQuantity, Vector3<Real>* akP)
{
// The potential intersection is initialized to the line segment and then
// clipped against the three sides of the tri
riQuantity = 2;
memcpy(akP,akU,2*sizeof(Vector3<Real>));
Vector3<Real> akSide[3] =
{
akV[1] - akV[0],
akV[2] - akV[1],
akV[0] - akV[2]
};
Vector3<Real> kN = akSide[0].Cross(akSide[1]);
for (int i = 0; i < 3; i++)
{
// normal pointing inside the triangle
Vector3<Real> kSideN = kN.Cross(akSide[i]);
Real fConstant = kSideN.Dot(akV[i]);
ClipConvexPolygonAgainstPlane(kSideN,fConstant,riQuantity,akP);
}
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// explicit instantiation
//----------------------------------------------------------------------------
namespace Wml
{
template WML_ITEM void TriProjection<float> (const Vector3<float>&,
const Vector3<float>[3], float&, float&);
template WML_ITEM void GetTriConfiguration<float> (
const Vector3<float>&, const Vector3<float>[3], ContactConfig<float>&);
template WML_ITEM void FindContactSetColinearLineTri<float> (
const Vector3<float>[2], const Vector3<float>[3], int&,
Vector3<float>*);
template WML_ITEM void TriProjection<double> (const Vector3<double>&,
const Vector3<double>[3], double&, double&);
template WML_ITEM void GetTriConfiguration<double> (
const Vector3<double>&, const Vector3<double>[3], ContactConfig<double>&);
template WML_ITEM void FindContactSetColinearLineTri<double> (
const Vector3<double>[2], const Vector3<double>[3], int&,
Vector3<double>*);
}
//----------------------------------------------------------------------------
| [
"[email protected]"
] | [
[
[
1,
196
]
]
] |
ab0c06664b9f397d057eefaf07ab79980e245b43 | 22438bd0a316b62e88380796f0a8620c4d129f50 | /libs/napl/wav.cpp | d0d83d39d11aee403fe95ed835a4f4ada15e26cc | [
"BSL-1.0"
] | permissive | DannyHavenith/NAPL | 1578f5e09f1b825f776bea9575f76518a84588f4 | 5db7bf823bdc10587746d691cb8d94031115b037 | refs/heads/master | 2021-01-20T02:17:01.186461 | 2010-11-26T22:26:25 | 2010-11-26T22:26:25 | 1,856,141 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,582 | cpp | ////////////////////////////////////////////////////////////////
//
// Wav.cpp - definition of WAV-file functions
//
#include "stdafx.h"
#include "wav.h"
bool WAVHeader::Stream( FILE *file, const direction &d)
{
return le_stream( file, ckID, d) &&
le_stream( file, ckSize, d);
};
bool FormatChunk::Stream( FILE *file, const direction &d)
{
bool bResult =
le_stream( file, header, d) &&
le_stream( file, format, d) &&
le_stream( file, nChannels, d) &&
le_stream( file, sampleRate, d) &&
le_stream( file, bytesPerSecond, d) &&
le_stream( file, blockAlign, d) &&
le_stream( file, bitsPerSample, d);
if (bResult)
{
fseek( file, header.ckSize - 16, SEEK_CUR);
}
return bResult;
}
bool WAVDataChunk::Stream( FILE *file, const direction &d)
{
if ( le_stream( file, header, d))
{
dataoffset = ftell( file);
// create a more flexible read:
// if the data chunk size is zero, it might be that some writing program crashed before it
// could write the chunk length to the file. To handle this type of data, we assume that the
// rest of the file is the data chunk, but only IF the ckSize is zero...
if ( header.ckSize == 0)
{
fseek( file, 0, SEEK_END);
header.ckSize = ftell( file) - dataoffset;
fseek( file, dataoffset, SEEK_SET);
}
return true;
}
else
return false;
}
block_producer *WAVFile::MakeBlockProducer( const char *filename)
{
stream_header h;
FILE *fp;
fp = fopen( filename, "rb");
if (!fp) return NULL;
Stream( fp, input());
GetStreamHeader( h);
return new file_block_producer( fp, h, dataChunk.GetDataOffset());
};
bool WAVFile::Stream( FILE *file, const direction &d)
{
return
le_stream( file, header, d) &&
le_stream( file, ID, d) &&
le_stream( file, formatChunk, d) &&
le_stream( file, dataChunk, d);
}
void wav_block_sink::Start()
{
if (m_pProducer)
{
stream_header h;
m_pProducer->GetStreamHeader( h);
m_FileObj->SetStreamHeader( h);
m_FileObj->Stream( m_pFile, streamable::output());
fseek( m_pFile, m_FileObj->dataChunk.GetDataOffset(), SEEK_SET);
m_pProducer->RequestBlock( *this, 0, h.numframes);
};
}
void wav_block_sink::ReceiveBlock( const sample_block &b)
{
fwrite( b.m_start, 1, b.m_end - b.m_start, m_pFile);
};
wav_block_sink::~wav_block_sink()
{
fclose( m_pFile);
}
block_sink *WAVFile::MakeBlockSink( const char *filename)
{
FILE *fp;
fp = fopen( filename, "wb");
if (!fp) return NULL;
return new wav_block_sink( fp, *this);
}
| [
"[email protected]"
] | [
[
[
1,
114
]
]
] |
03e886b6e9e7d7da772cf74565030da4ff7bf0fb | 28aa891f07cc2240c771b5fb6130b1f4025ddc84 | /src/pbr_ctrl/rpc_ctrl.cpp | 671e42cdfd583ca013312df8886c6263b9950732 | [] | no_license | Hincoin/mid-autumn | e7476d8c9826db1cc775028573fc01ab3effa8fe | 5271496fb820f8ab1d613a1c2355504251997fef | refs/heads/master | 2021-01-10T19:17:01.479703 | 2011-12-19T14:32:51 | 2011-12-19T14:32:51 | 34,730,620 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 241 | cpp | #include <fstream>
#include "rpc_ctrl.hpp"
namespace ma{
namespace rpc{
namespace s2ctrl{
void write_image(std::string file,std::string data)
{
std::ofstream out(file.c_str(),std::ios::out);
out<<data;
}
}
}
}
| [
"luozhiyuan@ea6f400c-e855-0410-84ee-31f796524d81"
] | [
[
[
1,
16
]
]
] |
b9314a1bdf8ca6395a8a811fabb6929107fdec9f | 27651c3f5f829bff0720d7f835cfaadf366ee8fa | /QBluetooth/Connection/SerialPort/Client/QBtSerialPortClient_win32.h | f7c5d72685e1139da627b7d1f88ce43c4883c4a7 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | cpscotti/Push-Snowboarding | 8883907e7ee2ddb9a013faf97f2d9673b9d0fad5 | cc3cc940292d6d728865fe38018d34b596943153 | refs/heads/master | 2021-05-27T16:35:49.846278 | 2011-07-08T10:25:17 | 2011-07-08T10:25:17 | 1,395,155 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,672 | h | /*
* QBtSerialPortClient_win32.h
*
*
* Author: Ftylitakis Nikolaos
*
* 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 QBTSERIALPORTCLIENT_WIN32_H_
#define QBTSERIALPORTCLIENT_WIN32_H_
#include "./QBtSerialPortClient.h"
#include "../../WinSerialPort/Tserial_event.h"
#include <QBtAuxFunctions.h>
class QBtSerialPortClientPrivate
{
public:
QBtSerialPortClientPrivate(QBtSerialPortClient* publicClass);
~QBtSerialPortClientPrivate();
bool IsConnected();
void Disconnect();
/**
* Connect()
* Connect to the server
* INFO: if remoteService has no handle information then the classId
* field is used to connect. (Tested class id working QBtConstants::SerialPort)
*
* @param remoteDevice the remote server to connect to
* @param remoteServive the remote service of the server
*/
void Connect(const QBtDevice& remoteDevice, const QBtService& remoteService);
void SendData(const QString& data);
void SendData(const QByteArray& data);
private:
/**
* PLugInCommPort()
* Plug in a virtual comm port given by the OS.
* This comm port will be used later on to communicate.
*/
bool PLugInCommPort();
void DeinitializeCommPort();
/*
* ConnectBtSerialPortProfile_Handle()
* This function is called when remoteService has a valid handle.
* and the connecting port.
*/
bool ConnectBtSerialPortProfile_Handle();
/*
* ConnectBtSerialPortProfile_ServClass()
* Used when the only info provided about the service is its class
* and the connecting port.
*/
bool ConnectBtSerialPortProfile_ServClass();
bool InitializeSerialPortHandle();
void CloseSerialPortHandle();
static void SerialEventManager(uint32 object, uint32 event);
void SerialCallback(Tserial_event *com_source, uint32 event);
private:
// the server device info
QString incomingDataBuffer;
BTUINT32 OSComPort;
HANDLE serialHandle;
QBtDevice* server;
QBtService* connectingService;
BTCONNHDL connectionHandle;
Tserial_event *com;
// Qt parent public class
QBtSerialPortClient* p_ptr;
};
#endif /* QBTSERIALPORTCLIENT_WIN32_H_ */
| [
"cpscotti@c819a03f-852d-4de4-a68c-c3ac47756727"
] | [
[
[
1,
92
]
]
] |
4347826fdbdf9e9588538f08e3634a8bb88703a9 | df5277b77ad258cc5d3da348b5986294b055a2be | /ChatServer/WindowsLibrary/FileDialogs.cpp | f18e0251f66c2464102ddcf8085bd35e7f72a655 | [] | no_license | beentaken/cs260-last2 | 147eaeb1ab15d03c57ad7fdc5db2d4e0824c0c22 | 61b2f84d565cc94a0283cc14c40fb52189ec1ba5 | refs/heads/master | 2021-03-20T16:27:10.552333 | 2010-04-26T00:47:13 | 2010-04-26T00:47:13 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 6,503 | cpp | /**************************************************************************************************/
/*!
@file FileDialogs.cpp
@author Robert Onulak
@author Justin Keane
@par email: robert.onulak@@digipen.edu
@par email: justin.keane@@digipen.edu
@par Course: CS260
@par Assignment #3
----------------------------------------------------------------------------------------------------
@attention © Copyright 2010: DigiPen Institute of Technology (USA). All Rights Reserved.
*/
/**************************************************************************************************/
#include "FileDialogs.hpp"
/**************************************************************************************************/
/**************************************************************************************************/
OpenFileDialog::OpenFileDialog( HWND hWnd ) : hWnd_(hWnd)
{
SecureZeroMemory( &ofn_, sizeof(ofn_) );
SecureZeroMemory( &filename_, sizeof(filename_) );
// Get the current directory of our process.
char current_dir[MAX_PATH];
GetCurrentDirectory( sizeof(current_dir), current_dir );
SetDirectory( current_dir );
ofn_.lStructSize = sizeof(ofn_);
ofn_.hwndOwner = hWnd;
ofn_.lpstrFilter = "All Files (*.*)\0*.*\0";
ofn_.lpstrFile = filename_;
ofn_.nMaxFile = MAX_PATH;
ofn_.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_NOCHANGEDIR;
}
/**************************************************************************************************/
/**************************************************************************************************/
BOOL OpenFileDialog::OpenFile( void )
{
// Have the user open a file for us to load.
BOOL result = GetOpenFileName( &ofn_ );
return result;
}
/**************************************************************************************************/
/**************************************************************************************************/
BOOL OpenFileDialog::OpenFile( const std::string &filename )
{
if ( filename.size() < MAX_PATH )
{
strcpy( filename_, filename.c_str() );
return OpenFile();
}
else
{
return FALSE;
}
}
/**************************************************************************************************/
/**************************************************************************************************/
void OpenFileDialog::SetDirectory( const std::string &directory )
{
dir_ = directory;
ofn_.lpstrInitialDir = dir_.c_str();
}
/**************************************************************************************************/
/**************************************************************************************************/
void OpenFileDialog::SetRelativeDir( const std::string &relative_dir )
{
dir_ = dir_ + ("\\" + relative_dir);
ofn_.lpstrInitialDir = dir_.c_str();
}
/**************************************************************************************************/
/**************************************************************************************************/
const char* OpenFileDialog::GetFileName( void )
{
return ofn_.lpstrFile;
}
/**************************************************************************************************/
/**************************************************************************************************/
const char* OpenFileDialog::GetFileTitle( void )
{
return ofn_.lpstrFileTitle;
}
/**************************************************************************************************/
/**************************************************************************************************/
SaveFileDialog::SaveFileDialog( HWND hWnd ) : hWnd_(hWnd)
{
SecureZeroMemory( &ofn_, sizeof(ofn_) );
SecureZeroMemory( &filename_, sizeof(filename_) );
// Get the current directory of our process.
char current_dir[MAX_PATH];
GetCurrentDirectory( sizeof(current_dir), current_dir );
SetDirectory( current_dir );
ofn_.lStructSize = sizeof(ofn_);
ofn_.hwndOwner = hWnd_;
ofn_.lpstrFilter = "All Files (*.*)\0*.*\0";
ofn_.lpstrFile = filename_;
ofn_.nMaxFile = MAX_PATH;
ofn_.Flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_NOCHANGEDIR;
}
/**************************************************************************************************/
/**************************************************************************************************/
BOOL SaveFileDialog::SaveFile( void )
{
// Have the user open a file for us to load.
BOOL result = GetSaveFileName( &ofn_ );
return result;
}
/**************************************************************************************************/
/**************************************************************************************************/
BOOL SaveFileDialog::SaveFile( const std::string &filename )
{
if ( filename.size() < MAX_PATH )
{
strcpy( filename_, filename.c_str() );
return SaveFile();
}
else
{
return FALSE;
}
}
/**************************************************************************************************/
/**************************************************************************************************/
void SaveFileDialog::SetDirectory( const std::string &directory )
{
dir_ = directory;
ofn_.lpstrInitialDir = dir_.c_str();
}
/**************************************************************************************************/
/**************************************************************************************************/
void SaveFileDialog::SetRelativeDir( const std::string &relative_dir )
{
dir_ = dir_ + ("\\" + relative_dir);
ofn_.lpstrInitialDir = dir_.c_str();
}
/**************************************************************************************************/
/**************************************************************************************************/
const char* SaveFileDialog::GetFileName( void )
{
return ofn_.lpstrFile;
}
/**************************************************************************************************/
/**************************************************************************************************/
const char* SaveFileDialog::GetFileTitle( void )
{
return ofn_.lpstrFile;
}
| [
"rziugy@af704e40-745a-32bd-e5ce-d8b418a3b9ef"
] | [
[
[
1,
175
]
]
] |
d9bf23860019d8a4c83504a3c8cc2ba5f1724e1a | cdd3d4c40db6a0eee7ad679f57adc2b5d1159349 | /src/vars.h | 3612f7fd706274c893468f5a6735ce34e0070da6 | [] | no_license | golanlevin/GMLStenciler | 4227fc348f6a1de4c3c4a651ab5caa68bbfe4934 | dfac16a260b71da0c4cb01c1b12547dbe5fedfd7 | refs/heads/master | 2021-01-01T16:50:16.519166 | 2010-07-04T22:19:39 | 2010-07-04T22:19:39 | 752,227 | 6 | 1 | null | 2014-03-02T20:39:14 | 2010-07-01T20:57:49 | C++ | UTF-8 | C++ | false | false | 630 | h | #ifndef _VARS
#define _VARS
#include "string.h"
class vars {
public:
void setupDefault();
//location for drawing.
float xLoc;
float yLoc;
int controlWidth;
int controlHeight;
float thickness;
float contourThickness;
float threshold;
float scaleFactor;
bool thickenOn;//holds whether or not the Graffiti is thickened.
bool contoursOn;
bool save;
bool showHoles;
char* fileName;
bool fileChanged;
bool bFileLoaded;
//variables for bridge types
bool findClosestBridge;
bool highestBridge;
bool lowestBridge;
bool leftMostBridge;
bool rightMostBridge;
};
#endif | [
"[email protected]"
] | [
[
[
1,
40
]
]
] |
6c9d3844cea8768e9e4b13ae0c0385970a7613cd | 6d680e20e4a703f0aa0d4bb5e50568143241f2d5 | /src/MobiHealth/ui_ErrorForm.h | 29ea28ff8d8fb909f025fb5c8ef64a5826b97ae1 | [] | no_license | sirnicolaz/MobiHealt | f7771e53a4a80dcea3d159eca729e9bd227e8660 | bbfd61209fb683d5f75f00bbf81b24933922baac | refs/heads/master | 2021-01-20T12:21:17.215536 | 2010-04-21T14:21:16 | 2010-04-21T14:21:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,393 | h | /********************************************************************************
** Form generated from reading UI file 'ErrorForm.ui'
**
** Created: Sun Apr 11 11:47:50 2010
** by: Qt User Interface Compiler version 4.6.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_ERRORFORM_H
#define UI_ERRORFORM_H
#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QHeaderView>
#include <QtGui/QWidget>
QT_BEGIN_NAMESPACE
class Ui_ErrorFormClass
{
public:
void setupUi(QWidget *ErrorFormClass)
{
if (ErrorFormClass->objectName().isEmpty())
ErrorFormClass->setObjectName(QString::fromUtf8("ErrorFormClass"));
ErrorFormClass->resize(400, 300);
retranslateUi(ErrorFormClass);
QMetaObject::connectSlotsByName(ErrorFormClass);
} // setupUi
void retranslateUi(QWidget *ErrorFormClass)
{
ErrorFormClass->setWindowTitle(QApplication::translate("ErrorFormClass", "ErrorForm", 0, QApplication::UnicodeUTF8));
} // retranslateUi
};
namespace Ui {
class ErrorFormClass: public Ui_ErrorFormClass {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_ERRORFORM_H
| [
"[email protected]"
] | [
[
[
1,
50
]
]
] |
3621147b4df2685434929efd9018322c742b8585 | ffe0a7d058b07d8f806d610fc242d1027314da23 | /V3e/dummy/IRCClient.cpp | 3cc94f2c9c72e711ffde897af47b600a854af80e | [] | no_license | Cybie/mangchat | 27bdcd886894f8fdf2c8956444450422ea853211 | 2303d126245a2b4778d80dda124df8eff614e80e | refs/heads/master | 2016-09-11T13:03:57.386786 | 2009-12-13T22:09:37 | 2009-12-13T22:09:37 | 32,145,077 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,076 | cpp | #include "IRCClient.h"
#include "IRCCmd.h"
#include "IRCFunc.h"
void IRCClient::run()
{
bActive = true;
while(this->bActive)
{
Sock.Connect("127.0.0.1", 6667);
Sock.Send("PASS CYMC");
Sock.Send("NICK CYMC");
Sock.Send("USER CYMC Cybrax VisualDreams :MangChat 3.01 (C) Cybrax");
int nRecv = 1;
while(nRecv && this->bActive)
{
char Buffer[BUFFER_SIZE + 1];
memset(Buffer, 0, BUFFER_SIZE + 1);
nRecv = Sock._Recv(Buffer, BUFFER_SIZE);
//Buffer[nRecv] = '\0';
while(char *pch = strstr(Buffer, "\r\n"))
{
*pch = '\0';
Handle_IRC(Buffer);
strcpy(Buffer, pch + 2);
}
}
Sock.Close();
}
}
void IRCClient::Handle_IRC(char *line)
{
if(!strncmp(line, "ERROR", 5))
return;
else if(!strncmp(line, "PING", 4))
{
char *pong = strstr (line, "PING");
strncpy(pong, "PONG", 4);
this->Sock.Send(pong);
}
else if(line[0] == ':')
{
line += 1;
IRCMsg msg(this);
//printf("%s\n", line);
// Raw line for debug
msg.data = new char[strlen(line) + 1];
strcpy(msg.data, line);
// Get the chat text first, after first occurence of :
// So we can split by " " without messing up chat
if(char *chat = strchr(line, ':'))
{
chat += 1;
msg.chat = new char[strlen(chat) + 1];
strcpy(msg.chat, chat);
}
char *pch = NULL;
char *ident = pch = Parse(line, " ", true);
// Full Ident
msg.ident = new char[strlen(ident)+1];
strcpy(msg.ident, ident);
// Command
msg.cmd = Parse(pch);
// Channel
msg.channel = Parse(pch);
// Extra1
msg.extra1 = Parse(pch);
// Extra2
msg.extra2 = Parse(pch);
// Nick
msg.nick = Parse(ident, "!", true);
// User/Host
msg.user = Parse(ident, "@");
if(msg.user == "")
{
msg.user = msg.nick;
msg.host = msg.nick;
}
else
msg.host = Parse(ident, "@");
IRCCmd CMD(&msg);
if(!strcmp(msg.cmd, "001"))
CMD.OnConnect();
else if(!strcmp(msg.cmd, "002"))
CMD.OnRFC(/*Host info*/);
else if(!strcmp(msg.cmd, "003"))
CMD.OnRFC(/*Server info*/);
else if(!strcmp(msg.cmd, "251"))
CMD.OnRFC(/*Online Users*/);
else if(!strcmp(msg.cmd, "252"))
CMD.OnRFC(/*Online Operators*/);
else if(!strcmp(msg.cmd, "252"))
CMD.OnRFC(/*Online Channels*/);
else if(!strcmp(msg.cmd, "255"))
CMD.OnRFC(/*Clients/Servers*/);
else if(!strcmp(msg.cmd, "265"))
CMD.OnRFC(/*Local Users*/);
else if(!strcmp(msg.cmd, "266"))
CMD.OnRFC(/*Global Users*/);
else if(!strcmp(msg.cmd, "332"))
CMD.OnRFC(/*Channel Topic*/);
else if(!strcmp(msg.cmd, "353"))
CMD.OnRFC(/*Channel Users start*/);
else if(!strcmp(msg.cmd, "366"))
CMD.OnRFC(/*Channel Users end*/);
else if(!strcmp(msg.cmd, "372"))
CMD.OnRFC(/*MOTD Start*/);
else if(!strcmp(msg.cmd, "367"))
CMD.OnRFC(/*MOTD End*/);
else if(!strcmp(msg.cmd, "433"))
CMD.OnNickTaken();
else if(!strcmp(msg.cmd, "439"))
CMD.OnRFC(/*Processing Connection*/);
else if(!strcmp(msg.cmd, "PRIVMSG"))
CMD.OnPrivMsg();
else if(!strcmp(msg.cmd, "NOTICE"))
CMD.OnNotice();
else if(!strcmp(msg.cmd, "JOIN"))
CMD.OnJoin();
else if(!strcmp(msg.cmd, "PART"))
CMD.OnPart();
else if(!strcmp(msg.cmd, "NICK"))
CMD.OnNick();
else if(!strcmp(msg.cmd, "KICK"))
CMD.OnKick();
else if(!strcmp(msg.cmd, "MODE"))
CMD.OnMode();
else if(!strcmp(msg.cmd, "QUIT"))
CMD.OnQuit();
else if(!strcmp(msg.cmd, "SQUIT"))
CMD.OnQuit();
else if(!strcmp(msg.cmd, "USER"))
CMD.OnDefault();
else if(!strcmp(msg.cmd, "TOPIC"))
CMD.OnDefault();
else if(!strcmp(msg.cmd, "NAMES"))
CMD.OnDefault();
else if(!strcmp(msg.cmd, "INVITE"))
CMD.OnDefault();
else if(!strcmp(msg.cmd, "VERSION"))
CMD.OnDefault();
else
CMD.OnDefault();
}
}
IClient *IRCClient::GetUser(char *username)
{
for(std::list<IClient *>::iterator i=UserList.begin(); i!=UserList.end();i++)
{
if(!strcmp(username, (*i)->user))
return (*i);
}
return NULL;
}
| [
"cybraxcyberspace@dfcbb000-c142-0410-b1aa-f54c88fa44bd"
] | [
[
[
1,
165
]
]
] |
e4bb5e89915ec25b138f4bdd288c5881347bd791 | ad80c85f09a98b1bfc47191c0e99f3d4559b10d4 | /code/src/terrain/nflatterrain_render.cc | 842e291365cbc224bccaf8ed0a7ccfeb01f88051 | [] | 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 | 11,143 | cc | #define N_IMPLEMENTS nFlatTerrainNode
//-------------------------------------------------------------------
// nflatterrain_render.cc
// (C) 2000 A.Weissflog
//-------------------------------------------------------------------
#include "gfx/ngfxserver.h"
#include "misc/nquickwatch.h"
#include "terrain/nflatterrainnode.h"
#include "terrain/quadtree.h"
#include "kernel/ntimeserver.h"
#include "gfx/nvertexbuffer.h"
#include "gfx/nindexbuffer.h"
#include "gfx/nscenegraph2.h"
#include "gfx/npixelshader.h"
//-------------------------------------------------------------------
/**
Initialize vertex buffer to keep data for NUM_TRIANGLES.
26-Mar-00 floh created
*/
//-------------------------------------------------------------------
void nFlatTerrainNode::init_vbuffer(void)
{
n_assert(!this->ref_ibuf.isvalid());
this->dyn_vb.Initialize((N_VT_COORD|N_VT_NORM|N_VT_UV0|N_VT_UV1),0);
int num_indices = 0;
nIndexBuffer *ibuf = this->ref_gs->FindIndexBuffer("nterrainnode_ibuf");
if (ibuf) {
num_indices = ibuf->GetNumIndices();
} else {
ibuf = this->ref_gs->NewIndexBuffer("nterrainnode_ibuf");
num_indices = this->dyn_vb.GetNumVertices();
// round down to multiple of 3
num_indices = (num_indices / 3) * 3;
ibuf->Begin(N_IBTYPE_WRITEONLY, N_PTYPE_TRIANGLE_LIST,num_indices);
int i;
for (i=0; i<num_indices; i++) {
ibuf->Index(i, i);
}
ibuf->End();
}
this->num_triangles = num_indices / 3;
n_assert(this->num_triangles > 0);
n_assert(ibuf);
this->ref_ibuf = ibuf;
}
//-------------------------------------------------------------------
/**
Render current vbuffer, swap current vbuffer, initialize
new current vbuffer, increment render pass ID.
27-Mar-00 floh created
07-Oct-00 floh rewritten for ndynmeshnode
18-Oct-00 floh + rewritten to ndynvertexbuffer
*/
//-------------------------------------------------------------------
void nFlatTerrainNode::swap_vbuffer(void)
{
// render the current vbuffer, swap to other vbuffer
this->cur_vb = this->dyn_vb.Swap(this->cur_vertex,this->cur_triangle*3);
// prepare for new render pass
this->render_pass++;
if (this->render_pass==0) this->render_pass=1;
this->cur_vertex = 0;
this->cur_triangle = 0;
this->coord = this->cur_vb->coord_ptr;
this->norm = this->cur_vb->norm_ptr;
this->stride = this->cur_vb->stride4;
int i;
for (i=0; i<N_MAXNUM_TEXCOORDS; i++) {
this->uv[i] = this->cur_vb->uv_ptr[i];
}
}
//-------------------------------------------------------------------
/**
27-Mar-00 floh created
05-Apr-00 floh if clip_enable, set up a clipping plane
11-Apr-00 floh removed clip plane
*/
//-------------------------------------------------------------------
void nFlatTerrainNode::BeginRender(void)
{
// n_assert(this->tmp_sgnode_ptr);
nSceneGraph2 *sg = this->ref_sceneGraph.get();
this->render_pass++;
if (this->render_pass==0) this->render_pass=1;
this->cur_vb = this->dyn_vb.Begin(this->ref_ibuf.get(),
sg->GetPixelShader(),
sg->GetTextureArray());
this->ref_ibuf->Lock();
this->cur_vertex = 0;
this->cur_triangle = 0;
this->coord = (float *) this->cur_vb->coord_ptr;
this->norm = (float *) this->cur_vb->norm_ptr;
this->stride = this->cur_vb->stride4;
int i;
for (i=0; i<N_MAXNUM_TEXCOORDS; i++) {
this->uv[i] = this->cur_vb->uv_ptr[i];
}
this->in_render = true;
}
//-------------------------------------------------------------------
/**
27-Mar-00 floh created
05-Apr-00 floh if clip_enable, turn off clip plane
17-Oct-00 floh + rewritten to ndynvertexbuffer
*/
//-------------------------------------------------------------------
void nFlatTerrainNode::EndRender(void)
{
this->dyn_vb.End(this->cur_vertex,this->cur_triangle*3);
this->ref_ibuf->Unlock();
this->in_render = false;
}
//-------------------------------------------------------------------
/**
@brief Perform view frustum culling for a bounding box.
Expects this->vp_matrix to be valid (updated inside Compute()).
28-Mar-00 floh created
*/
//-------------------------------------------------------------------
Clip::Visibility nFlatTerrainNode::CullBox(const bbox3_qs *bbox)
{
int or_code = 0;
int and_code = ~0;
int i;
float min_x = bbox->vmin.x * this->vertex_radius;
float min_y = bbox->vmin.y * this->vertex_radius;
float min_z = bbox->vmin.z * this->vertex_radius;
float max_x = bbox->vmax.x * this->vertex_radius;
float max_y = bbox->vmax.y * this->vertex_radius;
float max_z = bbox->vmax.z * this->vertex_radius;
vector4 v0(0.0f,0.0f,0.0f,1.0f);
vector4 v1(0.0f,0.0f,0.0f,1.0f);
for (i=0; i<8; i++) {
v0.w = 1.0f;
if (i & 1) v0.x = max_x;
else v0.x = min_x;
if (i & 2) v0.y = max_y;
else v0.y = min_y;
if (i & 4) v0.z = max_z;
else v0.z = min_z;
v1 = this->vp_matrix * v0;
int clip = 0;
if (v1.x < -v1.w) clip |= CLIP_LEFT;
else if (v1.x > v1.w) clip |= CLIP_RIGHT;
if (v1.y < -v1.w) clip |= CLIP_TOP;
else if (v1.y > v1.w) clip |= CLIP_BOTTOM;
if (v1.z < -v1.w) clip |= CLIP_NEAR;
else if (v1.z > v1.w) clip |= CLIP_FAR;
and_code &= clip;
or_code |= clip;
}
if (and_code != 0) {
return Clip::NOT_VISIBLE;
} else if (or_code == 0) {
return Clip::NO_CLIP;
} else {
return Clip::SOME_CLIP;
}
}
//-------------------------------------------------------------------
/**
18-Apr-00 floh created
*/
//-------------------------------------------------------------------
void nFlatTerrainNode::RenderBox(bbox3_qs *box)
{
nRState rs;
nGfxServer *gs = this->ref_gs.get();
rs.Set(N_RS_LIGHTING,N_FALSE); gs->SetState(rs);
vector3 v0(box->vmin * this->vertex_radius);
vector3 v1(box->vmax * this->vertex_radius);
gs->Begin(N_PTYPE_LINE_LIST);
gs->Rgba(1.0f,0.0f,1.0f,1.0f);
gs->Coord(v0.x,v0.y,v0.z); gs->Coord(v1.x,v0.y,v0.z);
gs->Coord(v1.x,v0.y,v0.z); gs->Coord(v1.x,v1.y,v0.z);
gs->Coord(v1.x,v1.y,v0.z); gs->Coord(v0.x,v1.y,v0.z);
gs->Coord(v0.x,v1.y,v0.z); gs->Coord(v0.x,v0.y,v0.z);
gs->Coord(v0.x,v0.y,v1.z); gs->Coord(v1.x,v0.y,v1.z);
gs->Coord(v1.x,v0.y,v1.z); gs->Coord(v1.x,v1.y,v1.z);
gs->Coord(v1.x,v1.y,v1.z); gs->Coord(v0.x,v1.y,v1.z);
gs->Coord(v0.x,v1.y,v1.z); gs->Coord(v0.x,v0.y,v1.z);
gs->Coord(v0.x,v0.y,v0.z); gs->Coord(v0.x,v0.y,v1.z);
gs->Coord(v1.x,v0.y,v0.z); gs->Coord(v1.x,v0.y,v1.z);
gs->Coord(v1.x,v1.y,v0.z); gs->Coord(v1.x,v1.y,v1.z);
gs->Coord(v0.x,v1.y,v0.z); gs->Coord(v0.x,v1.y,v1.z);
gs->End();
rs.Set(N_RS_LIGHTING,N_TRUE); gs->SetState(rs);
}
//-------------------------------------------------------------------
/**
26-Apr-00 floh created
*/
//-------------------------------------------------------------------
void nFlatTerrainNode::visualize(void)
{
nGfxServer *gs = this->ref_gs.get();
nRState rs;
rs.Set(N_RS_LIGHTING,N_FALSE); gs->SetState(rs);
// visualize last line of intersection
vector3 v0 = this->iline.va();
vector3 v1 = this->iline.vb();
gs->Begin(N_PTYPE_LINE_LIST);
gs->Rgba(1.0f,0.0f,0.0f,1.0f);
gs->Coord(v0.x,v0.y,v0.z); gs->Coord(v1.x,v1.y,v1.z);
// visualize last point of intersection
vector3 v2 = this->iposition;
gs->Rgba(0.0f,0.0f,1.0f,1.0f);
gs->Coord(v2.x-1.0f, v2.y, v2.z); gs->Coord(v2.x+1.0f, v2.y, v2.z);
gs->Coord(v2.x, v2.y-1.0f, v2.z); gs->Coord(v2.x, v2.y+1.0f, v2.z);
gs->Coord(v2.x, v2.y, v2.z-1.0f); gs->Coord(v2.x, v2.y, v2.z+1.0f);
// visualize normal of intersection
v0 = this->iposition;
v1 = v0 + this->itriangle.normal();
gs->Rgba(1.0f,1.0f,0.0f,1.0f);
gs->Coord(v0.x,v0.y,v0.z); gs->Coord(v1.x,v1.y,v1.z);
gs->End();
rs.Set(N_RS_LIGHTING,N_TRUE); gs->SetState(rs);
}
//-------------------------------------------------------------------
/**
26-Mar-00 floh created
28-Mar-00 floh + compute vp_matrix
06-Jun-00 floh + additional bounding box culling check
before Update() is culled.
*/
//-------------------------------------------------------------------
void nFlatTerrainNode::Compute(nSceneGraph2 *sg)
{
n_assert(sg);
nVisNode::Compute(sg);
nGfxServer *gs = this->ref_gs.get();
// compute viewer position in local quadtree coordinate space
vector3 v0;
matrix44 imv;
gs->GetMatrix(N_MXM_MODELVIEW,imv);
imv.invert();
v0.set(imv.M41,imv.M42,imv.M43);
v0.x /= this->vertex_radius;
v0.y /= this->vertex_radius;
v0.z /= this->vertex_radius;
vector3 vwr_loc(v0.x,v0.y,v0.z);
// update vp matrix (used in CullBox())
matrix44 mvm;
matrix44 pm;
gs->GetMatrix(N_MXM_MODELVIEW,mvm);
gs->GetMatrix(N_MXM_PROJECTION,pm);
this->vp_matrix = mvm * pm;
// demand create vertex buffers
if (!this->dyn_vb.IsValid()) {
this->init_vbuffer();
}
// (re)load height map?
if (this->map_dirty) {
// make sure everything is loaded...
if (this->map_dirty) this->load_map();
}
if (this->first_run) {
// Run the update function a few times before we start rendering
// to disable unnecessary quadsquares, so the first frame won't
// be overloaded with tons of triangles.
int i;
for (i = 0; i < 10; i++) {
this->root_node->Update(this,this->root_corner_data,vwr_loc,this->detail);
}
this->first_run = false;
}
// If either of these are set, we need to reconsider
// our edges before we continue
if (this->e_weld || this->s_weld)
this->WeldAux();
// cull nodes and render
Clip::Visibility vis;
vis = this->CullBox(this->root_node->bbox);
if (vis != Clip::NOT_VISIBLE) {
this->p_update->Start();
this->root_node->Update(this,this->root_corner_data,vwr_loc,this->detail);
this->p_update->Stop();
this->p_render->Start();
// backup the pixel shader's layer 0 texture so that we can
// restore it after rendering
this->root_node->Render(this,this->root_corner_data);
this->p_render->Stop();
}
// visualize stuff
// this->visualize();
}
//-------------------------------------------------------------------
// EOF
//-------------------------------------------------------------------
| [
"plushe@411252de-2431-11de-b186-ef1da62b6547"
] | [
[
[
1,
331
]
]
] |
4ac73dd7fc89c8764c949e146b4eaa8be9bf6ebd | 45c0d7927220c0607531d6a0d7ce49e6399c8785 | /GlobeFactory/src/ui/ui_window.cc | 6497139db6254aa4e52f0dc6564fa1eee068459e | [] | no_license | wavs/pfe-2011-scia | 74e0fc04e30764ffd34ee7cee3866a26d1beb7e2 | a4e1843239d9a65ecaa50bafe3c0c66b9c05d86a | refs/heads/master | 2021-01-25T07:08:36.552423 | 2011-01-17T20:23:43 | 2011-01-17T20:23:43 | 39,025,134 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,625 | cc | #include "ui_window.hh"
#include "../gfx/gfx_engine.hh"
#include "../gfx/renderer_2D.hh"
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
UIWindow::UIWindow(const Vector2f& parPosition, const Vector2f& parSize, float parBarSize)
: UIContainer(parPosition, parSize),
MBarSize(parBarSize),
MIsSelected(false)
{
LOG_ASSERT(parBarSize < parSize.y());
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
UIWindow::~UIWindow()
{
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
UIWindow* UIWindow::Clone() const
{
UIWindow* wind = new UIWindow(MPosition, MSize, MBarSize);
const_foreach(child, MChilds)
wind->AddComponent((*child)->Clone());
return wind;
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void UIWindow::Draw(const UIDrawingContext& parContext)
{
BB2f bbWind(MPosition, MPosition + MSize - Vector2f(0.f, MBarSize));
BB2f bbBar(MPosition + Vector2f(0.f, MSize.y() - MBarSize), MPosition + MSize);
GfxEngine::get()->GetPostRender2D()->DrawQuad(bbBar, BaseColor::BLUEVIOLET);
GfxEngine::get()->GetPostRender2D()->DrawQuad(bbWind, BaseColor::GHOSTWHITE);
UIContainer::Draw(parContext);
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void UIWindow::OnMouseMove(const Vector2f& parPosition)
{
if (MIsSelected)
{
MPosition += parPosition - MLastMousePosition;
}
else
UIContainer::OnMouseMove(parPosition);
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void UIWindow::OnMouseOn(const Vector2f& parPosition)
{
UIContainer::OnMouseOn(parPosition);
MIsSelected = false;
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void UIWindow::OnMouseOut()
{
if (MIsSelected)
{
Vector2f lmp = GetAbsPosition() + MLastMousePosition;
Vector2f mp = InputMng::get()->GetMousePosition();
Vector2f delta = mp - lmp;
MPosition += delta;
}
else
UIContainer::OnMouseOut();
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
bool UIWindow::OnMouseDown()
{
if (MLastMousePosition.y() > (MSize.y() - MBarSize))
{
MIsSelected = true;
}
else
UIContainer::OnMouseDown();
LOG_ASSERT(MParent != NULL);
if (MParent != NULL)
MParent->PutFront(this);
return true;
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
bool UIWindow::OnMouseUp()
{
MIsSelected = false;
UIContainer::OnMouseUp();
return true;
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
| [
"creteur.c@8e971d8e-9cf3-0c36-aa0f-a7c54ab41ffc"
] | [
[
[
1,
119
]
]
] |
a9c58b31bb017f65a4cba2014b99850b3df014bb | db3bc5e0550abf83819e70e1bc4f554e97da0b41 | /Scene.h | 92fb6f3a345b62ec3fd0dcd7aae2d4fbc939540d | [] | no_license | jiwonkim/Basic-Ray-Tracer | 019ee02ad59eab8366ece4f552cff8aeed53fcbc | eea6df78c8a6049a264b8af4679c4df84469dc82 | refs/heads/master | 2021-01-15T11:18:30.921793 | 2011-12-30T01:27:15 | 2011-12-30T01:27:15 | 3,072,017 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,636 | h | #ifndef SCENE_H
#define SCENE_H
#include "Camera.h"
#include "Intersection.h"
#include "ImagePlane.h"
#include "CircleLight.h"
#include "LineLight.h"
#include "AmbientLight.h"
#include "DirectionalLight.h"
#include "PointLight.h"
#include "EnvironmentLight.h"
#include "Shape.h"
#include "Ray.h"
#include "Material.h"
#include "SceneObject.h"
#include "st.h"
#include <cstdlib>
class Scene
{
public:
Scene(std::string sceneFilename);
void Render();
private:
/** Parsing helpers **/
void Parse(std::string sceneFilename);
void BeganParsing();
void FinishedParsing();
void ParsedCamera(const STPoint3& eye, const STVector3& up, const STPoint3& lookAt, float fovy, float aspect);
void ParsedOutput(int imgWidth, int imgHeight, const std::string& outputFilename);
void ParsedBounceDepth(int depth);
void ParsedShadowBias(float bias);
void ParsedPushMatrix();
void ParsedPopMatrix();
void ParsedRotate(float rx, float ry, float rz);
void ParsedScale(float sx, float sy, float sz);
void ParsedTranslate(float tx, float ty, float tz);
void ParsedSphere(const STPoint3& center, float radius);
void ParsedTriangle(const STPoint3& v1, const STPoint3& v2, const STPoint3& v3);
void ParsedLineLight(const STPoint3& start, const STPoint3& end, const STColor3f& intensity, const int numSamples);
void ParsedCircleLight(const STPoint3& center, const STVector3& radiusVector_x, const STVector3& radiusVector_y, const STColor3f &intensity, int numLines);
void ParsedEnvironmentLight(const std::string filename, STColor3f &intensity);
void ParsedAmbientLight(const STColor3f& col);
void ParsedPointLight(const STPoint3& loc, const STColor3f& col);
void ParsedDirectionalLight(const STVector3& dir, const STColor3f& col);
void ParsedMaterial(const STColor3f& amb, const STColor3f& diff, const STColor3f& spec, const STColor3f& mirr, float shine);
/** Ray tracing helpers **/
Intersection *FindIntersection(Ray ray);
STColor3f RecursivelyRayTrace(Intersection *hit, STColor3f &color, int bounce);
STColor3f FindColorAt(Intersection *hit);
void FindReachableLights(Intersection *hit, std::vector<Light *> &reachable);
/** CS 148 TODO: Add instance vars to store camera, lights, objects, etc. **/
ImagePlane imageplane;
Camera camera;
Material material;
int width, height;
float bounce_depth, shadow_bias;
std::vector<AmbientLight *> ambient_lights;
std::vector<Light *> lights;
EnvironmentLight *environment_light;
std::vector<SceneObject> objects;
std::vector<STTransform4> matrix_stack;
};
#endif SCENE_H
| [
"[email protected]"
] | [
[
[
1,
75
]
]
] |
0c559469dbc5d4c0ac454ab08209ff0e7e8c6d4a | 3b73ab901549ae9b19a9af1e757ad862bb026f10 | /src/Sonido.cpp | 04f0149817cffaffb30c4b52b434b08a642c8d9f | [] | no_license | morghan/PuzzleGame | dc7f154d26c0fa8d42b173a5f2f70d080065e70e | 63952325b1ceff43752c80ef9bef43963962ff1f | refs/heads/master | 2016-09-06T12:02:34.700300 | 2011-11-18T05:39:12 | 2011-11-18T05:39:12 | 2,799,913 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 711 | cpp | #include "../include/Sonido.h"
Sonido::Sonido()
{
// engine=createIrrKlangDevice();
}
void Sonido::drop()
{
engine->drop();
}
void Sonido::agregarSonido(std::string variable,const ik_c8* valor)
{
sonidos[variable]=new Reproduccion(engine->addSoundSourceFromFile(valor));
}
void Sonido::reproducirSonido(std::string variable)
{
Reproduccion* rep=sonidos[variable];
rep->sonido=engine->play2D(rep->source,false,false,true,true);
}
void Sonido::pararSonido(std::string variable)
{
Reproduccion* rep=sonidos[variable];
rep->sonido->stop();
}
void Sonido::setVolumen(std::string variable,float volumen)
{
Reproduccion* rep=sonidos[variable];
rep->sonido->setVolume(volumen);
}
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
4
],
[
6,
31
]
],
[
[
5,
5
]
]
] |
3a0cd71fdfa5f0b3a0d557c8d4574307139eb380 | e8b8c5d9510b267e41c496024f7f439d1aff1618 | /Pieces/JPiece.h | 8b184ee7299c8f91125d6147afa678e8f588680e | [] | no_license | Archetype/milkblocks | b80250cb5820188a16df73d528f80e3523d129b0 | 28ee5a44e5afc2440b77feec77202b310f395361 | refs/heads/master | 2021-01-19T21:29:05.453990 | 2011-07-12T02:44:59 | 2011-07-12T02:44:59 | 1,030,899 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 273 | h | #ifndef _JPIECE_H_
#define _JPIECE_H_
#ifndef _PIECE_H_
#include "piece.h"
#endif
class JPiece : public Piece
{
protected:
char* RotationGrid();
int States();
int Size();
public:
JPiece( Grid* grid ) : Piece( grid ) { Initialize(); }
};
#endif | [
"[email protected]"
] | [
[
[
1,
18
]
]
] |
753b48a10b5759aa1a24a325ab790a5480429c8c | 5fb9b06a4bf002fc851502717a020362b7d9d042 | /developertools/GumpEditor-0.32/diagram/MainFrm.cpp | 48c34504820b1fb83365bfb914f5af65ac17aa77 | [] | no_license | bravesoftdz/iris-svn | 8f30b28773cf55ecf8951b982370854536d78870 | c03438fcf59d9c788f6cb66b6cb9cf7235fbcbd4 | refs/heads/master | 2021-12-05T18:32:54.525624 | 2006-08-21T13:10:54 | 2006-08-21T13:10:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,153 | cpp | // MainFrm.cpp : implementation of the CMainFrame class
//
#include "stdafx.h"
#include "DialogEditorDemo.h"
#include "MainFrm.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CMainFrame
IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd)
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
//{{AFX_MSG_MAP(CMainFrame)
ON_WM_CREATE()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
static UINT indicators[] =
{
ID_SEPARATOR, // status line indicator
ID_INDICATOR_CAPS,
ID_INDICATOR_NUM,
ID_INDICATOR_SCRL,
};
/////////////////////////////////////////////////////////////////////////////
// CMainFrame construction/destruction
CMainFrame::CMainFrame()
{
}
CMainFrame::~CMainFrame()
{
}
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
return -1;
if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP
| CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
!m_wndToolBar.LoadToolBar(IDR_MAINFRAME))
{
TRACE0("Failed to create toolbar\n");
return -1; // fail to create
}
if (!m_wndStatusBar.Create(this) ||
!m_wndStatusBar.SetIndicators(indicators,
sizeof(indicators)/sizeof(UINT)))
{
TRACE0("Failed to create status bar\n");
return -1; // fail to create
}
m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
EnableDocking(CBRS_ALIGN_ANY);
DockControlBar(&m_wndToolBar);
return 0;
}
BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
if( !CFrameWnd::PreCreateWindow(cs) )
return FALSE;
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// CMainFrame diagnostics
#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
CFrameWnd::AssertValid();
}
void CMainFrame::Dump(CDumpContext& dc) const
{
CFrameWnd::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CMainFrame message handlers
| [
"sience@a725d9c3-d2eb-0310-b856-fa980ef11a19"
] | [
[
[
1,
100
]
]
] |
05174e746deca8609e6065c75b60291b110f7c6f | 68282fb4d720ff76e2414a2646c8c5d2bb5aef2b | /vsoz/fn71112/best_first_search.h | e051520f153c2feddb9438f49d6c080ae34e05e7 | [] | no_license | marvellouz/fmi_projects | d0e67a1386c059bf5edadc3bd0336c12e7f4117b | b25b679e411456e91d2002b7e2c3be10b519b519 | refs/heads/master | 2021-01-17T14:00:24.529519 | 2011-10-24T18:00:54 | 2011-10-24T18:00:54 | 486,223 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,552 | h | #ifndef BEST_FIRST_SEARCH_H
#define BEST_FIRST_SEARCH_H
#include "logger.h"
#include "graph.h"
#include "path.h"
#include "beam_search.h"
//You may need additional includes here
namespace vss {
/*!Performs an informed BestFirstSearch on a given version space graph.
\note The BestFirstSearch algorithm uses a fringe of paths, which are sorted according to the
heuristic evaluation of their last node. At each iteration of the search algorithm,
the best path is chosen for expansion.
\tparam Data The type of data held in the version space graph, i.e. the data representing
a state of the version space.
\param g Graph on which the serarch will be performed.
\param from Identity of the vertix from which a path is searched.
\param to Identity of the vertix to which a path is searched.
\param heuristicsFn Pointer to function that gives the heuristic evaluation of a
given vertix in the given graph.
\return Empty path if none of the two vertices is in the graph or there is no path begining
in 'from' and ending in 'to', otherwise the first path found by the algorithm is returned,
along with its cost (in this case the heuristic evaluation of the path's last vertix).
*/
template <class Data>
PathWithCost bestFirstSearch(Graph<Data> const& g, std::string const& from, std::string const& to,
double (*heuristicsFn)(Graph<Data> const& g, std::string const& v))
{
return beamSearch(g, from, to, heuristicsFn, -1);
}
}
#endif //BEST_FIRST_SEARCH_H
| [
"[email protected]"
] | [
[
[
1,
40
]
]
] |
774e965c867e7800935bb774616ca22ba4c6b8fa | 2627604c0d9ffa5e5fea160c874428ffa67c1076 | /convert_to_adj_lists.cpp | 0764cca20a909330f93ac2b9ac744566080d00e9 | [] | no_license | mvlevin/linkageclustering | c9e1b7ff9342dc3105b6851ac5fbbb8869714100 | 32c86863aa1bc8c28e0a6d690033b23732967084 | refs/heads/master | 2016-08-04T07:03:07.636936 | 2010-05-13T13:31:37 | 2010-05-13T13:31:37 | 32,219,956 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,715 | cpp | #include <cmath>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <map>
#include <sstream>
#include <vector>
using namespace std;
size_t AddName(const string& name, map<string, size_t>* ids, size_t* id_count, FILE* ids_file) {
map<string, size_t>::const_iterator it = ids->find(name);
if (it == ids->end()) {
size_t new_id = *id_count;
(*ids)[name] = new_id;
++(*id_count);
fprintf(ids_file, "%s %u\n", name.c_str(), new_id);
return new_id;
} else {
return it->second;
}
}
void ConvertToAdjLists(
const char* input_filename,
map<string, size_t>* ids,
size_t* id_count,
vector< vector< pair<size_t, size_t> > >* adj_lists) {
freopen(input_filename, "r", stdin);
FILE* ids_file = fopen("ids.txt", "w");
if (!ids_file) {
cerr << "Couldn't open file ids.txt to write down ids" << endl;
abort();
}
*id_count = 0;
int lines_read = 0;
while (!feof(stdin)) {
char buffer[1000];
// From
scanf("%s", buffer);
size_t from = AddName(buffer, ids, id_count, ids_file);
// To
scanf("%s", buffer);
size_t to = AddName(buffer, ids, id_count, ids_file);
double initial_weight;
scanf("%lf\n", &initial_weight);
size_t weight = floor(initial_weight * 10000 + 1e-8);
if (adj_lists->size() < *id_count) {
adj_lists->resize(*id_count);
}
adj_lists->at(from).push_back(make_pair(to, weight));
adj_lists->at(to).push_back(make_pair(from, weight));
++lines_read;
if (lines_read % 10000 == 0) {
cerr << "Read " << lines_read << " lines" << endl;
}
}
fclose(ids_file);
}
void WriteDown(const char* filename, const vector< vector< pair<size_t, size_t> > >& adj_lists) {
FILE* output = fopen(filename, "w");
if (!output) {
cerr << "Couldn't open file " << filename << " to write down the adjacency lists" << endl;
abort();
}
fprintf(output, "%u\n", adj_lists.size());
for (size_t row = 0; row < adj_lists.size(); ++row) {
fprintf(output, "%u", adj_lists[row].size());
for (size_t column = 0; column < adj_lists[row].size(); ++column) {
fprintf(output, " %u %u", adj_lists[row][column].first, adj_lists[row][column].second);
}
fprintf(output, "\n");
}
fclose(output);
}
int main(int argc, char** argv) {
if (argc != 3) {
cerr << "Usage: convert_to_adj_lists input_filename output_filename" << endl;
return -1;
}
map<string, size_t> ids;
size_t id_count = 0;
vector< vector< pair<size_t, size_t> > > adj_lists;
ConvertToAdjLists(argv[1], &ids, &id_count, &adj_lists);
WriteDown(argv[2], adj_lists);
return 0;
}
| [
"mlevin@localhost",
"mlevin@mlevin-ub"
] | [
[
[
1,
2
],
[
4,
88
]
],
[
[
3,
3
],
[
89,
89
]
]
] |
bd10963fef99b26f7818eefb22c52de6d383860c | 2b80036db6f86012afcc7bc55431355fc3234058 | /src/cube/MetadataFilterController.cpp | 1f7e6f9c53edbe4ccabfe907a42f8761ed68ae45 | [
"BSD-3-Clause"
] | permissive | leezhongshan/musikcube | d1e09cf263854bb16acbde707cb6c18b09a0189f | e7ca6a5515a5f5e8e499bbdd158e5cb406fda948 | refs/heads/master | 2021-01-15T11:45:29.512171 | 2011-02-25T14:09:21 | 2011-02-25T14:09:21 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 5,719 | cpp | //////////////////////////////////////////////////////////////////////////////
//
// License Agreement:
//
// The following are Copyright © 2007, Casey Langen
//
// Sources and Binaries of: mC2, win32cpp
//
// 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 author nor the names of other 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 "pch.hpp"
#include <cube/MetadataFilterController.hpp>
#include <cube/MetadataFilterModel.hpp>
#include <cube/BrowseController.hpp>
#include <core/Common.h>
#include <win32cpp/RedrawLock.hpp>
//////////////////////////////////////////////////////////////////////////////
using namespace musik::cube;
//////////////////////////////////////////////////////////////////////////////
// MetadataFilterController
//////////////////////////////////////////////////////////////////////////////
/*ctor*/ MetadataFilterController::MetadataFilterController(
ListView& listView,
const uistring& metadataKey,
BrowseController *browseController)
: listView(listView)
, metadataKey(metadataKey)
, parent(browseController)
, selectionDisabled(false)
{
this->metadataKeyA = musik::core::ConvertUTF8(this->metadataKey);
this->model.reset(new MetadataFilterModel(this));
this->listView.Handle()
? this->OnViewCreated(&listView)
: this->listView.Created.connect(this, &MetadataFilterController::OnViewCreated);
this->listView.SelectionChanged.connect(this, &MetadataFilterController::OnSelectionChanged);
}
void MetadataFilterController::OnSelectionChanged(ListView* listView)
{
if(!this->selectionDisabled){
win32cpp::ListView::RowIndexList selectedRows(this->listView.SelectedRows());
musik::core::MetadataValueVector &metadata = ((MetadataFilterModel*)this->model.get())->metadataFiltered;
this->parent->selectionQuery.ClearMetadata(this->metadataKeyA.c_str());
bool firstRowSelected(false);
for(win32cpp::ListView::RowIndexList::iterator row=selectedRows.begin();row!=selectedRows.end() && !firstRowSelected;++row){
if((*row)==0){
firstRowSelected = true;
}else{
if((*row)<=metadata.size()){
this->parent->selectionQuery.SelectMetadata(this->metadataKeyA.c_str(),metadata[(*row)-1]->id);
}
}
}
// Check if first row is selected, then clear the list
if(firstRowSelected){
this->parent->selectionQuery.ClearMetadata(this->metadataKeyA.c_str());
}
this->parent->SendQuery();
}
}
void MetadataFilterController::OnViewCreated(Window* window)
{
this->listView.SetScrollBarVisibility(HorizontalScrollBar, false);
typedef ListView::Column Column;
Size clientSize = this->listView.ClientSize();
this->mainColumn = Column::Create(this->metadataKey.c_str(), clientSize.width);
//
this->listView.AddColumn(this->mainColumn);
this->listView.EnableColumnResizing(false);
this->listView.SetModel(this->model);
//
int itemHeight = this->listView.RowHeight();
this->listView.SetRowHeight(max(itemHeight, 17));
this->listView.Resized.connect(
this, &MetadataFilterController::OnResized);
this->listView.Char.connect(this,&MetadataFilterController::OnChar);
}
void MetadataFilterController::OnResized(Window* window, Size size)
{
this->listView.SetColumnWidth(this->mainColumn, this->listView.ClientSize().width);
}
void MetadataFilterController::OnChar(Window* window,VirtualKeyCode keyCode, KeyEventFlags keyFlags){
if(keyCode){
win32cpp::RedrawLock drawLock(window);
this->selectionDisabled=true;
((MetadataFilterModel*)this->model.get())->OnChar((wchar_t)keyCode);
this->selectionDisabled=false;
this->OnSelectionChanged(&this->listView);
}
}
void MetadataFilterController::SelectAllFiltered(int rows){
std::vector<int> selectRows;
for(int i(1);i<rows;++i){
selectRows.push_back(i);
}
this->listView.SelectRows(selectRows);
}
| [
"onnerby@6a861d04-ae47-0410-a6da-2d49beace72e",
"bjorn.olievier@6a861d04-ae47-0410-a6da-2d49beace72e"
] | [
[
[
1,
10
],
[
12,
16
],
[
19,
20
],
[
24,
24
],
[
36,
41
],
[
44,
59
],
[
61,
62
],
[
65,
67
],
[
69,
69
],
[
72,
75
],
[
77,
77
],
[
79,
79
],
[
81,
95
],
[
97,
147
]
],
[
[
11,
11
],
[
17,
18
],
[
21,
23
],
[
25,
35
],
[
42,
43
],
[
60,
60
],
[
63,
64
],
[
68,
68
],
[
70,
71
],
[
76,
76
],
[
78,
78
],
[
80,
80
],
[
96,
96
]
]
] |
352f64aa33760e2176a94b4b920e7f117709565e | bdb8fc8eb5edc84cf92ba80b8541ba2b6c2b0918 | /TPs CPOO/Gareth & Maxime/Projet/CanonNoir_Moteur_C++/fichiers/EtatDepot.h | 4485699053005d490af6233519569179a5d12875 | [] | no_license | Issam-Engineer/tp4infoinsa | 3538644b40d19375b6bb25f030580004ed4a056d | 1576c31862ffbc048890e72a81efa11dba16338b | refs/heads/master | 2021-01-10T17:53:31.102683 | 2011-01-27T07:46:51 | 2011-01-27T07:46:51 | 55,446,817 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 536 | h | /**
*\file EtatDepot.h
*\brief file which contains function declarations and attributes of the EtatDepot class
*\author Maxime HAVEZ
*\author Gareth THIVEUX
*\version 1.0
*/
#ifndef ETATDEPOT_H
#define ETATDEPOT_H
#include "Etat.h"
class EtatDepot : public Etat
{
public :
/**
*\fn void execute()
*\brief Function which executes the current state
*/
virtual void execute();
/**
*\fn EtatDepos(MoteurJeu * m)
*\brief default constructor
*/
EtatDepot(MoteurJeu * m);
};
#endif
| [
"havez.maxime.01@9f3b02c3-fd90-5378-97a3-836ae78947c6",
"garethiveux@9f3b02c3-fd90-5378-97a3-836ae78947c6"
] | [
[
[
1,
1
],
[
7,
8
],
[
12,
19
],
[
21,
26
],
[
28,
28
]
],
[
[
2,
6
],
[
9,
11
],
[
20,
20
],
[
27,
27
],
[
29,
30
]
]
] |
3f91d67fb08759c87b8fb94954f11d0a341a5e66 | 388a262c60d0334096836741276e81ee0bff8ae6 | /code/BaseTypes/BaseTypes.h | 45fad3374bd21d435b5a07c92d68337f7769ea99 | [] | no_license | charliep/Earlham-Smoke | 7278976edf0e7df7877722da6f2a649ad5e307b7 | 8757761fb4e02e2f0868142788d413ba68ccbbb6 | refs/heads/master | 2021-01-06T20:42:38.361713 | 2010-03-26T14:36:02 | 2010-03-26T14:36:02 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,413 | h | // Copyright © 2008-2009 Intel Corporation
// All Rights Reserved
//
// Permission is granted to use, copy, distribute and prepare derivative works of this
// software for any purpose and without fee, provided, that the above copyright notice
// and this statement appear in all copies. Intel makes no representations about the
// suitability of this software for any purpose. THIS SOFTWARE IS PROVIDED "AS IS."
// INTEL SPECIFICALLY DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, AND ALL LIABILITY,
// INCLUDING CONSEQUENTIAL AND OTHER INDIRECT DAMAGES, FOR THE USE OF THIS SOFTWARE,
// INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PROPRIETARY RIGHTS, AND INCLUDING THE
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Intel does not
// assume any responsibility for any errors which may appear in this software nor any
// responsibility to update it.
#pragma once
// Disabling the warning for using the non-standard scope operator with enums.
#ifdef _MSC_VER
#endif
#include <vector>
#include <queue>
#include <list>
#include <map>
#include <string>
#include "Defines.h"
#include "DataTypes.h"
#include "Debug.h"
#include "Errors.h"
#include "Assert.h"
#include "Math.h"
//#include "MathX.h"
#include "Singleton.h"
#include "UnitAllocator.h"
//#include "ArrayList.h"
//#include "List.h"
//#include "RedBlackTree.h"
#include "Synchronization.h"
| [
"samuel@Chumbo.(none)"
] | [
[
[
1,
39
]
]
] |
3c49ce26bbe654eddbd95c5b32f87ea89d8f4600 | 279b68f31b11224c18bfe7a0c8b8086f84c6afba | /playground/shelta/obsolete/findik-poc-2/connection.hpp | 8d5ee4beb1ddca91cf9852409db0bc1b142555be | [] | no_license | bogus/findik | 83b7b44b36b42db68c2b536361541ee6175bb791 | 2258b3b3cc58711375fe05221588d5a068da5ea8 | refs/heads/master | 2020-12-24T13:36:19.550337 | 2009-08-16T21:46:57 | 2009-08-16T21:46:57 | 32,120,100 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,906 | hpp | #ifndef FINDIK_IO_CONNECTION_HPP
#define FINDIK_IO_CONNECTION_HPP
#include <boost/asio.hpp>
#include <boost/array.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include "reply.hpp"
#include "request.hpp"
#include "request_handler_.hpp"
#include "request_parser.hpp"
namespace findik {
namespace io {
/// Represents a single connection from a client.
class connection
: public boost::enable_shared_from_this<connection>,
private boost::noncopyable
{
public:
/// Construct a connection with the given io_service.
explicit connection(boost::asio::io_service& io_service,
request_handler& handler);
/// Get the socket associated with the connection.
boost::asio::ip::tcp::socket& socket();
/// Start the first asynchronous operation for the connection.
void start();
private:
/// Handle completion of a read operation.
void handle_read(const boost::system::error_code& e,
std::size_t bytes_transferred);
/// Handle completion of a write operation.
void handle_write(const boost::system::error_code& e);
/// Strand to ensure the connection's handlers are not called concurrently.
boost::asio::io_service::strand strand_;
/// Socket for the connection.
boost::asio::ip::tcp::socket socket_;
/// The handler used to process the incoming request.
request_handler& request_handler_;
/// Buffer for incoming data.
boost::array<char, 8192> buffer_;
/// The incoming request.
request request_;
/// The parser for the incoming request.
request_parser request_parser_;
/// The reply to be sent back to the client.
reply reply_;
boost::asio::streambuf response_;
};
typedef boost::shared_ptr<connection> connection_ptr;
} // namespace server3
} // namespace http
#endif // FINDIK_IO_CONNECTION_HPP
| [
"shelta@d40773b4-ada0-11de-b0a2-13e92fe56a31"
] | [
[
[
1,
69
]
]
] |
b17f9b871d927fa4804f62449cf5d1f26f95c438 | 11da90929ba1488c59d25c57a5fb0899396b3bb2 | /Src/TextRenderer.cpp | 2e3d4b02f4abb46cef3a1a3afa5249d23b6dcc37 | [] | no_license | danste/ars-framework | 5e7864630fd8dbf7f498f58cf6f9a62f8e1d95c6 | 90f99d43804d3892432acbe622b15ded6066ea5d | refs/heads/master | 2022-11-11T15:31:02.271791 | 2005-10-17T15:37:36 | 2005-10-17T15:37:36 | 263,623,421 | 0 | 0 | null | 2020-05-13T12:28:22 | 2020-05-13T12:28:21 | null | UTF-8 | C++ | false | false | 13,748 | cpp | #include <TextRenderer.hpp>
#include <Application.hpp>
#include <68k/Hs.h>
static void ShowSelectionPopupMenu(const Point& point, const String& text, void* context)
{
TextRenderer* renderer = static_cast<TextRenderer*>(context);
if (NULL == renderer->selectionMenuModelBuilder)
return;
if (frmInvalidObjectId == renderer->selectionMenuId)
return;
PopupMenuModel* model = renderer->selectionMenuModelBuilder(text);
PopupMenu menu(*renderer->form());
menu.setModel(model);
menu.hyperlinkHandler = renderer->hyperlinkHandler();
menu.popup(renderer->selectionMenuId, point);
}
TextRenderer::RenderingErrorListener::~RenderingErrorListener() {}
TextRenderer::TextRenderer(Form& form, ScrollBar* scrollBar):
FormGadget(form),
scrollBar_(scrollBar),
drawingWindow_(NULL),
drawingWindowIsOffscreen_(false),
lastRenderingError_(errNone),
renderingErrorListener_(NULL),
scheduledScrollDirection_(scheduledScrollAbandoned),
selectionMenuModelBuilder(NULL),
selectionMenuId(frmInvalidObjectId)
{
setInteractionBehavior(
behavMouseSelection
| behavUpDownScroll
| behavHyperlinkNavigation
// | behavDoubleClickSelection
| behavMenuBarCopyButton
);
definition_.setupSelectionClickHandler(ShowSelectionPopupMenu, this);
}
TextRenderer::~TextRenderer() {
if (drawingWindowIsOffscreen_)
disposeOffscreenWindow();
}
void TextRenderer::checkDrawingWindow()
{
Form* form = this->form();
Rect bounds;
form->bounds(bounds);
if (NULL != drawingWindow_ && drawingWindowBounds_ == bounds)
return;
if (drawingWindowIsOffscreen_)
disposeOffscreenWindow();
if (NULL == drawingWindow_)
{
assert(!drawingWindowIsOffscreen_);
drawingWindow_ = form->windowHandle(); // WinGetDrawWindow(); // form->windowHandle();
drawingWindowBounds_ = bounds;
Err error;
WinHandle offscreenWindow = WinCreateOffscreenWindow(bounds.width(), bounds.height(), nativeFormat, &error);
if (NULL != offscreenWindow)
{
Graphics formWindow(drawingWindow_);
drawingWindow_ = offscreenWindow;
drawingWindowIsOffscreen_ = true;
Graphics offscreen(offscreenWindow);
this->bounds(bounds);
// bounds.explode(1, 1, -2, -2);
formWindow.copyArea(bounds, offscreen, bounds.topLeft());
}
}
assert(NULL != drawingWindow_);
}
void TextRenderer::updateForm(Graphics& graphics)
{
if (!drawingWindowIsOffscreen_)
return;
Rect bounds;
this->bounds(bounds);
//bounds.explode(1, 1, -2, -2);
Graphics formWindow(form()->windowHandle()); //form()->windowHandle(); WinGetDrawWindow()
graphics.copyArea(bounds, formWindow, bounds.topLeft());
}
void TextRenderer::drawProxy()
{
if (!visible())
return;
if (form()->application().runningOnTreo600() && hasFocus())
drawFocusRing();
checkDrawingWindow();
{
Graphics graphics(drawingWindow_);
{
ActivateGraphics activate(graphics);
handleDraw(graphics);
}
if (errNone == lastRenderingError_)
updateForm(graphics);
}
fireDrawCompleted();
if (errNone == lastRenderingError_ && NULL != scrollBar_)
doUpdateScrollbar();
if (errNone != lastRenderingError_ && NULL != renderingErrorListener_)
renderingErrorListener_->handleRenderingError(*this, lastRenderingError_);
}
void TextRenderer::calculateLayout()
{
Graphics formWindow(form()->windowHandle());
Rect bounds;
this->bounds(bounds);
definition_.calculateLayout(formWindow, bounds);
}
void TextRenderer::drawRendererInBounds(Graphics& graphics, const Rect& bounds)
{
lastRenderingError_ = definition_.render(graphics, bounds, false);
}
void TextRenderer::handleDraw(Graphics& graphics)
{
Rect bounds;
this->bounds(bounds);
bounds.explode(1, 1, -2, -2);
drawRendererInBounds(graphics, bounds);
}
void TextRenderer::scroll(WinDirectionType direction, uint_t items, ScrollbarUpdateOption update)
{
if (0 == items)
return;
int i = items;
if (winUp == direction)
i = -i;
checkDrawingWindow();
{
Graphics graphics(drawingWindow_);
{
ActivateGraphics activate(graphics);
definition_.scroll(graphics, i);
}
if (errNone == lastRenderingError_)
updateForm(graphics);
}
fireDrawCompleted();
if (errNone == lastRenderingError_ && updateScrollbar == update && NULL != scrollBar_)
doUpdateScrollbar();
if (errNone != lastRenderingError_ && NULL != renderingErrorListener_)
renderingErrorListener_->handleRenderingError(*this, lastRenderingError_);
}
void TextRenderer::doUpdateScrollbar()
{
assert(NULL != scrollBar_);
if (visibleLinesCount() == linesCount())
scrollBar_->hide();
else
{
uint_t visible = visibleLinesCount();
uint_t total = linesCount();
uint_t top = topLine();
scrollBar_->setPosition(top, 0, total - visible, visible);
scrollBar_->show();
scrollBar_->draw();
}
}
bool TextRenderer::handleEvent(EventType& event)
{
bool handled = false;
switch (event.eType)
{
case penMoveEvent:
case penUpEvent:
handled = handleMouseEvent(event);
break;
case nilEvent:
handleNilEvent();
break;
default:
handled = FormGadget::handleEvent(event);
}
return handled;
}
bool TextRenderer::handleEnter(const EventType& event)
{
focus();
return handleMouseEvent(event);
}
bool TextRenderer::handleMouseEvent(const EventType& event)
{
UInt16 tapCount = 0;
Point p(event.screenX, event.screenY);
Rect bounds;
this->bounds(bounds);
bounds.explode(1, 1, -2, -2);
if (penUpEvent == event.eType)
tapCount = event.tapCount;
if (p && bounds)
scheduledScrollDirection_ = scheduledScrollAbandoned;
else if (p.x >= bounds.x() && p.x < bounds.x() + bounds.width())
{
UInt32 time = TimGetTicks();
if (scheduledScrollAbandoned == scheduledScrollDirection_)
{
if (p.y < bounds.y())
scheduledScrollDirection_ = scheduledScrollUp;
else
scheduledScrollDirection_ = scheduledScrollDown;
scheduledNilEventTicks_ = time + form()->application().ticksPerSecond()/7;
EvtSetNullEventTick(scheduledNilEventTicks_);
}
else if (time >= scheduledNilEventTicks_)
{
EvtSetNullEventTick(time+1);
}
}
else
scheduledScrollDirection_ = scheduledScrollAbandoned;
checkDrawingWindow();
{
bool update;
Graphics graphics(drawingWindow_);
{
ActivateGraphics activate(graphics);
update = definition_.extendSelection(graphics, p, tapCount);
}
if (update)
updateForm(graphics);
}
fireDrawCompleted();
return true;
}
bool TextRenderer::handleScrollRepeat(const EventType& event)
{
if (NULL == scrollBar_ || event.data.sclRepeat.scrollBarID != scrollBar_->id())
return false;
int items = event.data.sclRepeat.newValue - event.data.sclRepeat.value;
WinDirectionType dir = winDown;
if (0 > items)
{
items = -items;
dir = winUp;
}
scroll(dir, items, updateScrollbarNot);
return true;
}
void TextRenderer::disposeOffscreenWindow()
{
assert(drawingWindowIsOffscreen_);
assert(NULL != drawingWindow_);
WinDeleteWindow(drawingWindow_, false);
drawingWindowIsOffscreen_ = false;
drawingWindow_ = NULL;
}
void TextRenderer::notifyHide()
{
if (drawingWindowIsOffscreen_)
disposeOffscreenWindow();
}
void TextRenderer::handleNilEvent()
{
if (scheduledScrollAbandoned == scheduledScrollDirection_)
return;
UInt32 time = TimGetTicks();
if (time < scheduledNilEventTicks_)
{
EvtSetNullEventTick(scheduledNilEventTicks_);
return;
}
WinDirectionType dir = winUp;
int i = -1;
if (scheduledScrollDown == scheduledScrollDirection_)
{
dir = winDown;
i = 1;
}
scheduledNilEventTicks_ = time + form()->application().ticksPerSecond()/7;
EvtSetNullEventTick(scheduledNilEventTicks_);
checkDrawingWindow();
Graphics graphics(drawingWindow_);
{
bool update;
{
ActivateGraphics activate(graphics);
definition_.scroll(graphics, i);
Rect bounds;
this->bounds(bounds);
bounds.explode(1, 1, -2, -2);
Point p(bounds.topLeft());
if (winDown == dir)
p += bounds.extent_();
update = definition_.extendSelection(graphics, p, 0);
}
if (update)
updateForm(graphics);
}
fireDrawCompleted();
if (NULL != scrollBar_)
doUpdateScrollbar();
}
bool TextRenderer::handleNavigatorKey(Definition::NavigatorKey navKey)
{
bool handled = false;
{
checkDrawingWindow();
Graphics graphics(drawingWindow_);
{
ActivateGraphics activate(graphics);
handled = definition_.navigatorKey(graphics, navKey);
}
updateForm(graphics);
}
fireDrawCompleted();
if (handled && NULL != scrollBar_)
doUpdateScrollbar();
return handled;
}
bool TextRenderer::handleKeyDownEvent(const EventType& event)
{
if (form()->application().runningOnTreo600() && !hasFocus())
return false;
bool fieldHasFocus = false;
UInt16 index = FrmGetFocus(*form());
if (noFocus != index && frmFieldObj == FrmGetObjectType(*form(), index))
fieldHasFocus = true;
Definition::NavigatorKey key = Definition::NavigatorKey(-1);
Form& form = *this->form();
if (form.fiveWayUpPressed(&event) || chrUpArrow == event.data.keyDown.chr)
key = Definition::navKeyUp;
else if (form.fiveWayDownPressed(&event) || chrDownArrow == event.data.keyDown.chr)
key = Definition::navKeyDown;
else if (!fieldHasFocus && (form.fiveWayLeftPressed(&event) || chrLeftArrow == event.data.keyDown.chr))
key = Definition::navKeyLeft;
else if (!fieldHasFocus && (form.fiveWayRightPressed(&event) || chrRightArrow == event.data.keyDown.chr))
key = Definition::navKeyRight;
else if (form.fiveWayCenterPressed(&event) || chrLineFeed == event.data.keyDown.chr)
key = Definition::navKeyCenter;
if (Definition::NavigatorKey(-1) == key)
return false;
return handleNavigatorKey(key);
}
void TextRenderer::drawFocusRing()
{
assert(hasFocus());
assert(form()->application().runningOnTreo600());
Rect rect;
bounds(rect);
if (NULL != scrollBar_)
{
rect += scrollBar_->bounds();
}
Err error = HsNavDrawFocusRing(*form(), id(), hsNavFocusRingNoExtraInfo, &rect.native(), hsNavFocusRingStyleSquare, false);
assert(errNone == error);
}
void TextRenderer::removeFocusRing()
{
FormGadget::removeFocusRing();
}
bool TextRenderer::copySelectionOrAll() const
{
String text;
definition_.selectionOrAllToText(text);
if (text.empty())
return false;
ClipboardAddItem(clipboardText, text.data(), text.length());
return true;
}
bool TextRenderer::handleMenuCmdBarOpen(EventType& event)
{
if (!usesMenuBarCopyButton())
return false;
if (!visible())
return false;
if (!definition_.hasSelection())
return false;
UInt16 focus = FrmGetFocus(*form());
if (noFocus != focus)
{
FormObjectKind kind = FrmGetObjectType(*form(), focus);
if (frmFieldObj == kind || frmTableObj == kind)
return false;
}
// if (!hasFocus())
// return false;
event.data.menuCmdBarOpen.preventFieldButtons = true;
Err error = MenuCmdBarAddButton(menuCmdBarOnLeft, BarCopyBitmap, menuCmdBarResultMenuItem, sysEditMenuCopyCmd, "Copy");
return false;
}
bool TextRenderer::handleMenuEvent(const EventType& event)
{
if (sysEditMenuCopyCmd != event.data.menu.itemID)
return false;
if (!usesMenuBarCopyButton())
return false;
if (!visible())
return false;
if (!definition_.hasSelection())
return false;
UInt16 focus = FrmGetFocus(*form());
if (noFocus != focus)
{
FormObjectKind kind = FrmGetObjectType(*form(), focus);
if (frmFieldObj == kind || frmTableObj == kind)
return false;
}
return copySelectionOrAll();
}
bool TextRenderer::handleEventInForm(EventType& event)
{
bool handled = false;
switch (event.eType)
{
case menuCmdBarOpenEvent:
handled = handleMenuCmdBarOpen(event);
break;
case menuEvent:
handled = handleMenuEvent(event);
break;
case keyDownEvent:
handled = handleKeyDownEvent(event);
break;
case sclRepeatEvent:
handleScrollRepeat(event);
break;
}
return handled;
}
| [
"andrzejc@10a9aba9-86da-0310-ac04-a2df2cc00fd9",
"kjk@10a9aba9-86da-0310-ac04-a2df2cc00fd9"
] | [
[
[
1,
379
],
[
381,
382
],
[
384,
428
],
[
430,
454
]
],
[
[
380,
380
],
[
383,
383
],
[
429,
429
]
]
] |
47892c5ff65de95d8752134528cf529b95876233 | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/xercesc++/2.6.0/src/xercesc/com/XMLHTTPRequest.cpp | 2a58ef5cb3fe9aae51d0c814f4cd55e500ade8fe | [
"Apache-2.0"
] | permissive | andyburke/bitflood | dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf | fca6c0b635d07da4e6c7fbfa032921c827a981d6 | refs/heads/master | 2016-09-10T02:14:35.564530 | 2011-11-17T09:51:49 | 2011-11-17T09:51:49 | 2,794,411 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,473 | cpp | /*
* Copyright 1999-2000,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Log: XMLHTTPRequest.cpp,v $
* Revision 1.2 2004/09/08 13:55:36 peiyongz
* Apache License Version 2.0
*
* Revision 1.1.1.1 2002/02/01 22:21:42 peiyongz
* sane_include
*
* Revision 1.3 2000/06/03 00:29:03 andyh
* COM Wrapper changes from Curt Arnold
*
* Revision 1.2 2000/03/30 02:00:09 abagchi
* Initial checkin of working code with Copyright Notice
*
*/
#include "stdafx.h"
#include "xml4com.h"
#include "XMLHttpRequest.h"
#include "XMLDOMDocument.h"
// I need to make sure the file is registered with long filenames
HRESULT WINAPI CXMLHttpRequest::UpdateRegistry(BOOL bRegister)
{
USES_CONVERSION;
TCHAR file[MAX_PATH];
if (::GetModuleFileName(_Module.m_hInst, file, MAX_PATH)) {
WIN32_FIND_DATA d;
memset(&d,0,sizeof(WIN32_FIND_DATA));
HANDLE h = FindFirstFile(file,&d);
if (h != INVALID_HANDLE_VALUE) {
TCHAR *name = _tcsrchr(file,_T('\\'));
TCHAR newFile[MAX_PATH] = _T("");
_tcsncpy(newFile,file,name-file);
_tcscat(newFile,_T("\\"));
_tcscat(newFile,d.cFileName);
FindClose(h);
_ATL_REGMAP_ENTRY regmap[2] = {{NULL,NULL},{NULL,NULL}};
regmap[0].szKey = OLESTR("XMLMODULE");
regmap[0].szData = T2OLE(newFile);
return _Module.UpdateRegistryFromResource((UINT) IDR_XMLHTTPREQUEST, bRegister,regmap);
}
}
return E_FAIL;
}
CXMLHttpRequest::CXMLHttpRequest()
:m_pOnReadyStateChange (NULL)
,m_bAbort (false)
,m_hThread (NULL)
,m_lReadyState (0)
,m_bAsync (false)
,m_Method (_T(""))
,m_HostName (_T(""))
,m_Port (INTERNET_DEFAULT_HTTP_PORT)
,m_URLPath (_T(""))
,m_User (_T(""))
,m_Password (_T(""))
,m_dwStatus (0)
,m_StatusText (_T(""))
,m_ResponseHeaders (_T(""))
,m_HwndParent (NULL)
,m_pBody (NULL)
,m_lBodyLength (0)
,m_pResponseBody (NULL)
,m_lResponseBodyLength (0)
,m_Error (_T(""))
,m_bSuccess (true)
{
}
HRESULT CXMLHttpRequest::FinalConstruct()
{
// create monitor window
RECT rc;
memset(&rc,0,sizeof(RECT));
if (NULL == Create(NULL, rc, _T("XML HTTP Request Monitor Window"), 0))
return E_FAIL;
return S_OK;
}
void CXMLHttpRequest::FinalRelease()
{
if (NULL != m_hThread) {
m_bAbort = true;
::WaitForSingleObject(m_hThread, INFINITE);
::CloseHandle(m_hThread);
m_hThread = NULL;
}
if (m_pOnReadyStateChange != NULL) {
m_pOnReadyStateChange->Release();
m_pOnReadyStateChange = NULL;
}
DestroyWindow();
delete [] m_pBody;
m_pBody = NULL;
m_lBodyLength = 0;
delete [] m_pResponseBody;
m_pResponseBody = NULL;
m_lResponseBodyLength = 0;
}
LRESULT CXMLHttpRequest::OnReadyStateChange(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
ATLTRACE(_T("CXMLHttpRequest::OnReadyStateChange\n"));
bHandled = TRUE;
m_lReadyState = wParam;
if (NULL != m_pOnReadyStateChange) {
CComVariant varResult;
DISPPARAMS disp = { NULL, NULL, 0, 0 };
m_pOnReadyStateChange->Invoke(DISPID_VALUE, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &disp, &varResult, NULL, NULL);
}
return 1L;
}
STDMETHODIMP CXMLHttpRequest::InterfaceSupportsErrorInfo(REFIID riid)
{
if (IsEqualGUID(IID_IXMLHttpRequest,riid))
return S_OK;
return S_FALSE;
}
STDMETHODIMP CXMLHttpRequest::open(BSTR bstrMethod, BSTR bstrUrl,VARIANT varAsync,VARIANT bstrUser,VARIANT bstrPassword)
{
ATLTRACE(_T("CXMLHttpRequest::open\n"));
// do not open if there is a send active
if (NULL != m_hThread) {
DWORD exitCode = 0;
BOOL rc = ::GetExitCodeThread(m_hThread, &exitCode);
if (!rc || STILL_ACTIVE == exitCode)
return E_FAIL;
::CloseHandle(m_hThread);
m_hThread = NULL;
}
if (V_VT(&varAsync) != VT_BOOL)
return E_INVALIDARG;
_bstr_t method = bstrMethod;
if (0 == method.length())
return E_INVALIDARG;
_bstr_t url = bstrUrl;
if (0 == url.length())
return E_INVALIDARG;
TCHAR hostName[INTERNET_MAX_PATH_LENGTH] = _T("");
TCHAR strPathName[INTERNET_MAX_PATH_LENGTH] = _T("");
URL_COMPONENTS urlComponents;
memset(&urlComponents, 0, sizeof(URL_COMPONENTS));
urlComponents.dwStructSize = sizeof(URL_COMPONENTS);
urlComponents.lpszHostName = hostName;
urlComponents.dwHostNameLength = INTERNET_MAX_PATH_LENGTH;
urlComponents.lpszUrlPath = strPathName;
urlComponents.dwUrlPathLength = INTERNET_MAX_PATH_LENGTH;
if (!InternetCrackUrl(url, url.length(), 0, &urlComponents))
return E_INVALIDARG;
m_Method = method;
m_HostName = hostName;
if (urlComponents.nPort != 0)
m_Port = urlComponents.nPort;
m_URLPath = strPathName;
m_bAsync = (VARIANT_TRUE == V_BOOL(&varAsync)) ? true : false;
if (VT_BSTR == V_VT(&bstrUser))
m_User = V_BSTR(&bstrUser);
else
m_User = _T("");
if (VT_BSTR == V_VT(&bstrPassword) && m_User.length() > 0)
m_Password = V_BSTR(&bstrPassword);
else
m_Password = _T("");
return S_OK;
}
STDMETHODIMP CXMLHttpRequest::setRequestHeader(BSTR bstrHeader, BSTR bstrValue)
{
ATLTRACE(_T("CXMLHttpRequest::setRequestHeader\n"));
if (NULL == bstrHeader || NULL == bstrValue)
return E_INVALIDARG;
// check if there is a send active
if (NULL != m_hThread) {
DWORD exitCode = 0;
BOOL rc = ::GetExitCodeThread(m_hThread, &exitCode);
if (!rc || STILL_ACTIVE == exitCode)
return E_PENDING;
::CloseHandle(m_hThread);
m_hThread = NULL;
}
m_RequestHeaderMap.Remove(bstrHeader);
m_RequestHeaderMap.Add(bstrHeader,bstrValue);
return S_OK;
}
STDMETHODIMP CXMLHttpRequest::getResponseHeader(BSTR bstrHeader, BSTR * pbstrValue)
{
ATLTRACE(_T("CXMLHttpRequest::getResponseHeader\n"));
if (NULL == pbstrValue)
return E_POINTER;
*pbstrValue = NULL;
if (NULL == bstrHeader)
return E_INVALIDARG;
// check if there is a send active
if (NULL != m_hThread) {
DWORD exitCode = 0;
BOOL rc = ::GetExitCodeThread(m_hThread, &exitCode);
if (!rc || STILL_ACTIVE == exitCode)
return E_PENDING;
::CloseHandle(m_hThread);
m_hThread = NULL;
}
if (0 == m_ResponseHeaders.length())
return S_FALSE;
_bstr_t value;
_bstr_t header(bstrHeader);
header += _T(": ");
_tcslwr(header);
TCHAR *pHeaders = new TCHAR[m_ResponseHeaders.length() + sizeof(TCHAR)];
_tcscpy(pHeaders,m_ResponseHeaders);
_tcslwr(pHeaders);
TCHAR *pStart = _tcsstr(pHeaders,header);
if (pStart) {
pStart += header.length();
TCHAR *pEnd = _tcsstr(pStart,_T("\r\n"));
if (pEnd) {
TCHAR *pHeader = new TCHAR[pEnd-pStart + sizeof(TCHAR)];
_tcsncpy(pHeader,static_cast<LPCTSTR> (m_ResponseHeaders) + (pStart-pHeaders),pEnd-pStart);
value = pHeader;
delete [] pHeader;
}
}
delete[] pHeaders;
if (0 == value.length())
return S_FALSE;
*pbstrValue = value.copy();
return S_OK;
}
STDMETHODIMP CXMLHttpRequest::getAllResponseHeaders(BSTR * pbstrHeaders)
{
ATLTRACE(_T("CXMLHttpRequest::getAllResponseHeaders\n"));
if (NULL == pbstrHeaders)
return E_POINTER;
*pbstrHeaders = NULL;
if (NULL == pbstrHeaders)
return E_INVALIDARG;
// check if there is a send active
if (NULL != m_hThread) {
DWORD exitCode = 0;
BOOL rc = ::GetExitCodeThread(m_hThread, &exitCode);
if (!rc || STILL_ACTIVE == exitCode)
return E_PENDING;
::CloseHandle(m_hThread);
m_hThread = NULL;
}
*pbstrHeaders = m_ResponseHeaders.copy();
return S_OK;
}
STDMETHODIMP CXMLHttpRequest::send(VARIANT varBody)
{
ATLTRACE(_T("CXMLHttpRequest::send\n"));
if (V_VT(&varBody) != VT_BSTR &&
V_VT(&varBody) != VT_DISPATCH &&
V_VT(&varBody) != (VT_ARRAY | VT_VARIANT) &&
V_VT(&varBody) != (VT_ARRAY | VT_UI1) &&
V_VT(&varBody) != VT_UNKNOWN)
return E_INVALIDARG;
// do not start another thread if there is another active
if (NULL != m_hThread) {
DWORD exitCode = 0;
BOOL rc = ::GetExitCodeThread(m_hThread, &exitCode);
if (!rc || STILL_ACTIVE == exitCode)
return E_PENDING;
::CloseHandle(m_hThread);
m_hThread = NULL;
}
HRESULT hr = S_OK;
m_bSuccess = true;
m_bAbort = false;
delete [] m_pBody;
m_pBody = NULL;
m_lBodyLength = 0;
delete [] m_pResponseBody;
m_pResponseBody = NULL;
m_lResponseBodyLength = 0;
m_dwStatus = 0;
m_StatusText = _T("");
m_ResponseHeaders = _T("");
if (V_VT(&varBody) == VT_BSTR) {
_bstr_t body = V_BSTR(&varBody);
m_lBodyLength = body.length() + 1;
m_pBody = new BYTE[m_lBodyLength];
memset(m_pBody,0,m_lBodyLength);
memcpy(m_pBody,static_cast<char*> (body),body.length());
}
else
if (V_VT(&varBody) == VT_UNKNOWN) {
CComQIPtr<IStream,&IID_IStream> pS(V_UNKNOWN(&varBody));
if (!pS)
return E_INVALIDARG;
CComBSTR b;
hr = b.ReadFromStream(pS);
if (S_OK != hr)
return hr;
_bstr_t body = b;
m_lBodyLength = body.length() + 1;
m_pBody = new BYTE[m_lBodyLength];
memset(m_pBody,0,m_lBodyLength);
memcpy(m_pBody,static_cast<char*> (body),body.length());
}
else
if (V_VT(&varBody) == VT_DISPATCH) {
CComQIPtr<IXMLDOMDocument,&IID_IXMLDOMDocument> pDoc(V_DISPATCH(&varBody));
if (!pDoc)
return E_INVALIDARG;
BSTR b = NULL;
hr = pDoc->get_xml(&b);
if (S_OK != hr)
return hr;
_bstr_t body = b;
::SysFreeString(b);
m_lBodyLength = body.length() + 1;
m_pBody = new BYTE[m_lBodyLength];
memset(m_pBody,0,m_lBodyLength);
memcpy(m_pBody,static_cast<char*> (body),body.length());
}
else
if (V_VT(&varBody) == (VT_ARRAY | VT_VARIANT)) {
SAFEARRAY *pArray = reinterpret_cast<SAFEARRAY *> (varBody.byref);
if (NULL == pArray)
return E_INVALIDARG;
long lLBoundVar = 0;
long lUBoundVar = 0;
UINT dims = ::SafeArrayGetDim(pArray);
if (dims == 0)
return E_INVALIDARG;
hr = ::SafeArrayGetLBound(pArray, dims, &lLBoundVar);
if (S_OK != hr)
return hr;
hr = ::SafeArrayGetUBound(pArray, dims, &lUBoundVar);
if (S_OK != hr)
return hr;
if (lUBoundVar >= lLBoundVar) {
VARIANT *pIndex = NULL;
hr = ::SafeArrayAccessData(pArray, reinterpret_cast<void **> (&pIndex));
if (S_OK != hr)
return hr;
m_lBodyLength = lUBoundVar-lLBoundVar+1;
m_pBody = new BYTE[m_lBodyLength];
for (long i = 0; i <= lUBoundVar-lLBoundVar; ++i) {
VARIANT var = pIndex[i];
if (V_VT(&var) != VT_UI1) {
hr = E_INVALIDARG;
break;
}
m_pBody[i] = V_UI1(&var);
}
::SafeArrayUnaccessData(pArray);
if (S_OK != hr) {
delete [] m_pBody;
m_pBody = NULL;
m_lBodyLength = 0;
return hr;
}
}
}
else
if (V_VT(&varBody) == (VT_ARRAY | VT_UI1)) {
SAFEARRAY *pArray = reinterpret_cast<SAFEARRAY *> (varBody.byref);
if (NULL == pArray)
return E_INVALIDARG;
long lLBoundVar = 0;
long lUBoundVar = 0;
UINT dims = ::SafeArrayGetDim(pArray);
if (dims == 0)
return E_INVALIDARG;
hr = ::SafeArrayGetLBound(pArray, dims, &lLBoundVar);
if (S_OK != hr)
return hr;
hr = ::SafeArrayGetUBound(pArray, dims, &lUBoundVar);
if (S_OK != hr)
return hr;
if (lUBoundVar >= lLBoundVar) {
BYTE *pIndex = NULL;
hr = ::SafeArrayAccessData(pArray, reinterpret_cast<void **> (&pIndex));
if (S_OK != hr)
return hr;
m_lBodyLength = lUBoundVar-lLBoundVar+1;
m_pBody = new BYTE[m_lBodyLength];
for (long i = 0; i <= lUBoundVar-lLBoundVar; ++i)
m_pBody[i] = pIndex[i];
::SafeArrayUnaccessData(pArray);
}
}
m_HwndParent = GetParentWindow();
UINT nthreadID = 0;
m_hThread = reinterpret_cast<HANDLE> (_beginthreadex(NULL,
0,
CXMLHttpRequest::SendThread,
(void *) this,
0,
&nthreadID));
if (NULL == m_hThread)
return E_FAIL;
if (m_bAsync)
return S_OK;
bool bWait = true;
while (bWait) {
DWORD dwEvt = MsgWaitForMultipleObjects(1,&m_hThread,FALSE,INFINITE,QS_ALLINPUT);
switch(dwEvt) {
case WAIT_OBJECT_0:
bWait = false;
break;
case WAIT_OBJECT_0 + 1:
{
MSG msg;
while(::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) {
if (WM_CLOSE == msg.message || WM_QUIT == msg.message) {
bWait = false;
m_bAbort = true;
break;
}
else {
PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
break;
}
default:
m_bAbort = true;
bWait = false;
break;
}
}
return S_OK;
}
UINT APIENTRY CXMLHttpRequest::SendThread(void *pParm)
{
ATLTRACE(_T("CXMLHttpRequest::SendThread\n"));
CXMLHttpRequest *pCtx = reinterpret_cast<CXMLHttpRequest *> (pParm);
if (NULL == pCtx)
return 0;
HINTERNET hOpen = NULL;
HINTERNET hConnect = NULL;
HINTERNET hRequest = NULL;
hOpen = InternetOpen(_T("XMLHTTP/1.0"),INTERNET_OPEN_TYPE_PRECONFIG,
NULL,NULL,0);
if (NULL == hOpen) {
DWORD res = GetLastError();
pCtx->m_Error = CXMLHttpRequest::GetErrorMsg(res);
pCtx->m_bSuccess = false;
}
if (!pCtx->m_bAbort && pCtx->m_bSuccess) {
if (INTERNET_INVALID_STATUS_CALLBACK == InternetSetStatusCallback(hOpen,
CXMLHttpRequest::InternetStatusCallback)) {
pCtx->m_Error = _T("Invalid Internet Status Callback function.");
pCtx->m_bSuccess = false;
}
}
bool bPromptForAuthentication = true;
if (!pCtx->m_bAbort && pCtx->m_bSuccess) {
LPTSTR lpszUserName = NULL;
LPTSTR lpszPassword = NULL;
if (pCtx->m_User.length() > 0) {
bPromptForAuthentication = false;
lpszUserName = pCtx->m_User;
if (pCtx->m_Password.length() > 0)
lpszPassword = pCtx->m_Password;
}
hConnect = InternetConnect(hOpen,pCtx->m_HostName,pCtx->m_Port,lpszUserName,lpszPassword,
INTERNET_SERVICE_HTTP,0,reinterpret_cast<DWORD> (pCtx));
if (NULL == hConnect) {
DWORD res = GetLastError();
pCtx->m_Error = CXMLHttpRequest::GetErrorMsg(res);
pCtx->m_bSuccess = false;
}
}
if (!pCtx->m_bAbort && pCtx->m_bSuccess) {
DWORD dwFlags = (443 == pCtx->m_Port) ? INTERNET_FLAG_SECURE : 0;
dwFlags |= INTERNET_FLAG_NO_CACHE_WRITE;
hRequest = HttpOpenRequest(hConnect,pCtx->m_Method,
pCtx->m_URLPath,NULL,NULL,NULL,
dwFlags,reinterpret_cast<DWORD> (pCtx));
if (NULL == hRequest) {
DWORD res = GetLastError();
pCtx->m_bSuccess = false;
pCtx->m_Error = CXMLHttpRequest::GetErrorMsg(res);
}
}
BOOL rc = TRUE;
if (!pCtx->m_bAbort && pCtx->m_bSuccess && pCtx->m_RequestHeaderMap.GetSize() > 0) {
_bstr_t requestHeaders;
for (int i = 0 ; i < pCtx->m_RequestHeaderMap.GetSize(); ++i) {
requestHeaders += pCtx->m_RequestHeaderMap.GetKeyAt(i);
requestHeaders += _T(": ");
requestHeaders += pCtx->m_RequestHeaderMap.GetValueAt(i);
requestHeaders += _T("\r\n");
}
rc = HttpAddRequestHeaders(hRequest,requestHeaders,-1,HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE);
if (!rc) {
DWORD res = GetLastError();
pCtx->m_bSuccess = false;
pCtx->m_Error = CXMLHttpRequest::GetErrorMsg(res);
}
}
DWORD dwLen = 0;
DWORD dwError = ERROR_SUCCESS;
do {
if (!pCtx->m_bAbort && pCtx->m_bSuccess) {
rc = HttpSendRequest(hRequest,NULL,0,pCtx->m_pBody,pCtx->m_lBodyLength);
if (!rc) {
DWORD res = GetLastError();
pCtx->m_bSuccess = false;
pCtx->m_Error = CXMLHttpRequest::GetErrorMsg(res);
break;
}
}
if (!pCtx->m_bAbort && pCtx->m_bSuccess) {
dwLen = sizeof(DWORD);
rc = HttpQueryInfo(hRequest,
HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER,
&pCtx->m_dwStatus,&dwLen,NULL);
if (!rc) {
DWORD res = GetLastError();
pCtx->m_bSuccess = false;
pCtx->m_Error = CXMLHttpRequest::GetErrorMsg(res);
break;
}
}
if (!pCtx->m_bAbort && pCtx->m_bSuccess &&
bPromptForAuthentication &&
(HTTP_STATUS_PROXY_AUTH_REQ == pCtx->m_dwStatus ||
HTTP_STATUS_DENIED == pCtx->m_dwStatus))
dwError = InternetErrorDlg(pCtx->m_HwndParent,
hRequest,
ERROR_INTERNET_INCORRECT_PASSWORD,
FLAGS_ERROR_UI_FILTER_FOR_ERRORS |
FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS |
FLAGS_ERROR_UI_FLAGS_GENERATE_DATA,
NULL);
else
break;
} while (ERROR_INTERNET_FORCE_RETRY == dwError &&
!pCtx->m_bAbort && pCtx->m_bSuccess);
if (!pCtx->m_bAbort && pCtx->m_bSuccess) {
dwLen = 1024;
TCHAR *pBuff = new TCHAR[dwLen];
rc = HttpQueryInfo(hRequest,HTTP_QUERY_RAW_HEADERS_CRLF,pBuff,&dwLen,NULL);
if (!rc) {
DWORD res = GetLastError();
if (ERROR_INSUFFICIENT_BUFFER == res) {
delete [] pBuff;
pBuff = new TCHAR[dwLen];
rc = HttpQueryInfo(hRequest,HTTP_QUERY_RAW_HEADERS_CRLF,pBuff,&dwLen,NULL);
if (!rc) {
res = GetLastError();
pCtx->m_bSuccess = false;
pCtx->m_Error = CXMLHttpRequest::GetErrorMsg(res);
}
}
else {
pCtx->m_bSuccess = false;
pCtx->m_Error = CXMLHttpRequest::GetErrorMsg(res);
}
}
if (rc)
pCtx->m_ResponseHeaders = pBuff;
delete [] pBuff;
}
if (!pCtx->m_bAbort && pCtx->m_bSuccess) {
dwLen = 1024;
TCHAR *pBuff = new TCHAR[dwLen];
rc = HttpQueryInfo(hRequest,HTTP_QUERY_STATUS_TEXT,pBuff,&dwLen,NULL);
if (!rc) {
DWORD res = GetLastError();
if (ERROR_INSUFFICIENT_BUFFER == res) {
delete [] pBuff;
pBuff = new TCHAR[dwLen];
rc = HttpQueryInfo(hRequest,HTTP_QUERY_STATUS_TEXT,pBuff,&dwLen,NULL);
if (!rc)
_tcscpy(pBuff,_T("Unknown"));
}
else
_tcscpy(pBuff,_T("Unknown"));
}
pCtx->m_StatusText = pBuff;
delete [] pBuff;
if (HTTP_STATUS_OK != pCtx->m_dwStatus) {
TCHAR errBuff[MAX_PATH] = _T("");
wsprintf(errBuff,_T("HTTP Status Code: %d, Reason: "),pCtx->m_dwStatus);
pCtx->m_Error = errBuff;
pCtx->m_Error += pCtx->m_StatusText;
pCtx->m_bSuccess = false;
}
}
if (!pCtx->m_bAbort && pCtx->m_bSuccess) {
PBYTE buffer[255];
DWORD dwRead = 0;
delete [] pCtx->m_pResponseBody;
pCtx->m_pResponseBody = NULL;
pCtx->m_lResponseBodyLength = 0;
while (rc = InternetReadFile(hRequest,buffer,255,&dwRead)) {
if (!rc || pCtx->m_bAbort || 0 == dwRead)
break;
PBYTE tmp = new BYTE[pCtx->m_lResponseBodyLength + dwRead];
if (pCtx->m_pResponseBody) {
memcpy(tmp,pCtx->m_pResponseBody,pCtx->m_lResponseBodyLength);
delete [] pCtx->m_pResponseBody;
}
memcpy(tmp+pCtx->m_lResponseBodyLength,buffer,dwRead);
pCtx->m_pResponseBody = tmp;
pCtx->m_lResponseBodyLength += dwRead;
}
if (!rc) {
DWORD res = GetLastError();
pCtx->m_Error = _T("Error reading response: ") + CXMLHttpRequest::GetErrorMsg(res);
pCtx->m_bSuccess = false;
}
}
if (hRequest != NULL)
InternetCloseHandle(hRequest);
if (hConnect != NULL)
InternetCloseHandle(hConnect);
if (hOpen)
InternetCloseHandle(hOpen);
if (!pCtx->m_bAbort && pCtx->m_bAsync)
::PostMessage(pCtx->m_hWnd,MSG_READY_STATE_CHANGE,4,0);
return 0;
}
HWND CXMLHttpRequest::GetParentWindow()
{
HWND hWnd = GetDesktopWindow();
CComPtr<IServiceProvider> pSP;
HRESULT hr = GetSite(IID_IServiceProvider, reinterpret_cast<LPVOID *> (&pSP));
if (S_OK != hr)
return hWnd;
CComPtr<IWebBrowser2> pWB;
hr = pSP->QueryService(SID_SWebBrowserApp,IID_IWebBrowser2,
reinterpret_cast<LPVOID *> (&pWB));
if (S_OK != hr)
return hWnd;
long lWnd = 0;
hr = pWB->get_HWND(&lWnd);
if (S_OK != hr)
return hWnd;
return reinterpret_cast<HWND> (lWnd);
}
void CALLBACK CXMLHttpRequest::InternetStatusCallback(HINTERNET hInternet,
DWORD dwContext,
DWORD dwInternetStatus,
LPVOID lpvStatusInformation,
DWORD dwStatusInformationLength)
{
ATLTRACE(_T("CXMLHttpRequest::InternetStatusCallback - dwInternetStatus %d\n"),dwInternetStatus);
}
STDMETHODIMP CXMLHttpRequest::abort()
{
ATLTRACE(_T("CXMLHttpRequest::abort\n"));
m_bAbort = true;
return S_OK;
}
STDMETHODIMP CXMLHttpRequest::get_status(long * plStatus)
{
ATLTRACE(_T("CXMLHttpRequest::get_status\n"));
if (NULL == plStatus)
return E_POINTER;
*plStatus = 0;
// check if there is a send active
if (NULL != m_hThread) {
DWORD exitCode = 0;
BOOL rc = ::GetExitCodeThread(m_hThread, &exitCode);
if (!rc || STILL_ACTIVE == exitCode)
return E_PENDING;
::CloseHandle(m_hThread);
m_hThread = NULL;
}
*plStatus = m_dwStatus;
return S_OK;
}
STDMETHODIMP CXMLHttpRequest::get_statusText( BSTR * pbstrStatus)
{
ATLTRACE(_T("CXMLHttpRequest::get_statusText\n"));
if (NULL == pbstrStatus)
return E_POINTER;
*pbstrStatus = NULL;
// check if there is a send active
if (NULL != m_hThread) {
DWORD exitCode = 0;
BOOL rc = ::GetExitCodeThread(m_hThread, &exitCode);
if (!rc || STILL_ACTIVE == exitCode)
return E_PENDING;
::CloseHandle(m_hThread);
m_hThread = NULL;
}
*pbstrStatus = m_StatusText.copy();
return S_OK;
}
STDMETHODIMP CXMLHttpRequest::get_responseXML(IDispatch **ppBody)
{
ATLTRACE(_T("CXMLHttpRequest::get_responseXML\n"));
if (NULL == ppBody)
return E_POINTER;
*ppBody = NULL;
// check if there is a send active
if (NULL != m_hThread) {
DWORD exitCode = 0;
BOOL rc = ::GetExitCodeThread(m_hThread, &exitCode);
if (!rc || STILL_ACTIVE == exitCode)
return E_PENDING;
::CloseHandle(m_hThread);
m_hThread = NULL;
}
BSTR text = NULL;
HRESULT hr = get_responseText(&text);
if (S_OK != hr || NULL == text)
return hr;
CXMLDOMDocumentObj *pObj = NULL;
hr = CXMLDOMDocumentObj::CreateInstance(&pObj);
if (S_OK == hr) {
pObj->AddRef();
VARIANT_BOOL isSuccessful = VARIANT_FALSE;
hr = pObj->loadXML(text, &isSuccessful);
if (S_OK == hr && VARIANT_TRUE == isSuccessful) {
*ppBody = pObj;
(*ppBody)->AddRef();
}
pObj->Release();
}
::SysFreeString(text);
return hr;
}
STDMETHODIMP CXMLHttpRequest::get_responseText(BSTR *pVal)
{
ATLTRACE(_T("CXMLHttpRequest::get_responseText\n"));
if (NULL == pVal)
return E_POINTER;
*pVal = NULL;
// check if there is a send active
if (NULL != m_hThread) {
DWORD exitCode = 0;
BOOL rc = ::GetExitCodeThread(m_hThread, &exitCode);
if (!rc || STILL_ACTIVE == exitCode)
return E_PENDING;
::CloseHandle(m_hThread);
m_hThread = NULL;
}
if (NULL == m_pResponseBody)
return S_OK;
TCHAR *psz = new TCHAR[m_lResponseBodyLength+1];
ZeroMemory(psz,m_lResponseBodyLength+1);
CopyMemory(psz,m_pResponseBody,m_lResponseBodyLength);
*pVal = SysAllocStringByteLen(psz,m_lResponseBodyLength);
delete [] psz;
return S_OK;
}
STDMETHODIMP CXMLHttpRequest::get_responseBody(VARIANT *pVal)
{
ATLTRACE(_T("CXMLHttpRequest::get_responseBody\n"));
if (NULL == pVal)
return E_POINTER;
::VariantInit(pVal);
V_VT(pVal) = VT_NULL;
// check if there is a send active
if (NULL != m_hThread) {
DWORD exitCode = 0;
BOOL rc = ::GetExitCodeThread(m_hThread, &exitCode);
if (!rc || STILL_ACTIVE == exitCode)
return E_PENDING;
::CloseHandle(m_hThread);
m_hThread = NULL;
}
if (NULL == m_pResponseBody)
return S_OK;
return CXMLHttpRequest::InitializeVarFromByte(*pVal, m_pResponseBody,m_lResponseBodyLength);
}
STDMETHODIMP CXMLHttpRequest::get_responseStream(VARIANT *pVal)
{
ATLTRACE(_T("CXMLHttpRequest::get_responseStream\n"));
if (NULL == pVal)
return E_POINTER;
::VariantInit(pVal);
V_VT(pVal) = VT_NULL;
// check if there is a send active
if (NULL != m_hThread) {
DWORD exitCode = 0;
BOOL rc = ::GetExitCodeThread(m_hThread, &exitCode);
if (!rc || STILL_ACTIVE == exitCode)
return E_PENDING;
::CloseHandle(m_hThread);
m_hThread = NULL;
}
if (NULL == m_pResponseBody)
return S_OK;
//Create an IStream from global memory
CComPtr<IStream> pStm;
HRESULT hr = CreateStreamOnHGlobal(NULL, TRUE, &pStm);
if (S_OK != hr)
return hr;
hr = pStm->Write(m_pResponseBody, m_lResponseBodyLength, NULL);
if (S_OK != hr)
return hr;
LARGE_INTEGER dlibMove;
memset(&dlibMove,0,sizeof(LARGE_INTEGER));
hr = pStm->Seek(dlibMove,STREAM_SEEK_SET,NULL);
if (S_OK != hr)
return hr;
V_VT(pVal) = VT_UNKNOWN;
V_UNKNOWN(pVal) = pStm.Detach();
return S_OK;
}
STDMETHODIMP CXMLHttpRequest::get_readyState(long *pVal)
{
ATLTRACE(_T("CXMLHttpRequest::get_readyState\n"));
if (NULL == pVal)
return E_POINTER;
*pVal = m_lReadyState;
return S_OK;
}
STDMETHODIMP CXMLHttpRequest::put_onreadystatechange(IDispatch * pReadyStateSink)
{
ATLTRACE(_T("CXMLHttpRequest::put_onreadystatechange\n"));
if (m_pOnReadyStateChange != NULL) {
m_pOnReadyStateChange->Release();
m_pOnReadyStateChange = NULL;
}
m_pOnReadyStateChange = pReadyStateSink;
if (m_pOnReadyStateChange != NULL)
m_pOnReadyStateChange->AddRef();
return S_OK;
}
_bstr_t CXMLHttpRequest::GetErrorMsg(DWORD rc)
{
_bstr_t msg(_T(""));
TCHAR *lpBuffer = NULL;
if (ERROR_INTERNET_EXTENDED_ERROR == rc) {
DWORD dwError = 0;
DWORD dwLength = 0;
InternetGetLastResponseInfo (&dwError, NULL, &dwLength);
if (dwLength > 0) {
lpBuffer = (TCHAR *) LocalAlloc(LPTR,dwLength);
if (!lpBuffer) {
msg = _T("Unable to allocate memory to display Internet extended error: ");
rc = GetLastError();
}
else {
if (!InternetGetLastResponseInfo(&dwError,lpBuffer,&dwLength)) {
msg = _T("Unable to get Internet extended error: ");
rc = GetLastError();
LocalFree(lpBuffer);
}
else {
int len = lstrlen(lpBuffer);
for (int i=0; i < len; ++i) {
if (_istcntrl(lpBuffer[i]))
lpBuffer[i] = _T(' ');
}
msg = lpBuffer;
LocalFree(lpBuffer);
return msg;
}
}
}
}
lpBuffer = NULL;
HMODULE hModule = NULL; // default to system source
if (rc >= INTERNET_ERROR_BASE)
hModule = LoadLibraryEx(_T("wininet.dll"),NULL,LOAD_LIBRARY_AS_DATAFILE);
::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_FROM_SYSTEM |
((hModule != NULL) ? FORMAT_MESSAGE_FROM_HMODULE : 0),
hModule,
rc,
MAKELANGID(LANG_NEUTRAL, SUBLANG_SYS_DEFAULT),
(LPTSTR)&lpBuffer, 0, NULL);
if (lpBuffer) {
int len = lstrlen(lpBuffer);
for (int i=0; i < len; ++i) {
if (_istcntrl(lpBuffer[i]))
lpBuffer[i] = _T(' ');
}
}
msg += lpBuffer;
LocalFree(lpBuffer);
if (hModule != NULL)
FreeLibrary(hModule);
return msg;
}
HRESULT CXMLHttpRequest::InitializeVarFromByte(VARIANT &varOut, const PBYTE pByte, long lSize)
{
::VariantInit(&varOut);
V_VT(&varOut) = VT_NULL;
HRESULT hr = S_OK;
SAFEARRAYBOUND rgsabound[1];
rgsabound[0].cElements = lSize;
rgsabound[0].lLbound = 0;
SAFEARRAY *psa = ::SafeArrayCreate( VT_VARIANT, 1, rgsabound);
if (psa == NULL)
return E_FAIL;
if (pByte != NULL) {
long ix[1];
for (ULONG i = 0; i < rgsabound[0].cElements; ++i) {
ix[0] = i;
VARIANT var;
::VariantInit(&var);
V_VT(&var) = VT_UI1;
V_UI1(&var) = pByte[i];
hr = ::SafeArrayPutElement(psa, ix, &var);
if (S_OK != hr) {
::SafeArrayDestroy(psa);
break;
}
}
}
if (S_OK == hr) {
V_VT(&varOut) = VT_ARRAY | VT_VARIANT;
V_ARRAY(&varOut) = psa;
}
return hr;
} | [
"[email protected]"
] | [
[
[
1,
1107
]
]
] |
8c692f19ea4048100f0d8154c6b52274933f3094 | d397b0d420dffcf45713596f5e3db269b0652dee | /src/Axe/ConnectionCache.cpp | 40b4eb4843975e33a4b74df57c8ab7fd8bf79abd | [] | no_license | irov/Axe | 62cf29def34ee529b79e6dbcf9b2f9bf3709ac4f | d3de329512a4251470cbc11264ed3868d9261d22 | refs/heads/master | 2021-01-22T20:35:54.710866 | 2010-09-15T14:36:43 | 2010-09-15T14:36:43 | 85,337,070 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,715 | cpp | # include "pch.hpp"
# include <Axe/ConnectionCache.hpp>
# include <Axe/Connection.hpp>
# include <Axe/ServantConnection.hpp>
# include <Axe/ProxyConnectionProvider.hpp>
namespace Axe
{
//////////////////////////////////////////////////////////////////////////
ConnectionCache::ConnectionCache( const ConnectionProviderPtr & _provider )
: m_provider(_provider)
{
}
//////////////////////////////////////////////////////////////////////////
void ConnectionCache::addAdapterConnection( std::size_t _adapterId, const ConnectionPtr & _connection )
{
m_adapterConnections.insert( std::make_pair(_adapterId, _connection) );
}
//////////////////////////////////////////////////////////////////////////
const ConnectionPtr & ConnectionCache::getAdapterConnection( std::size_t _adapterId )
{
TMapAdapterConnections::const_iterator it_found = m_adapterConnections.find( _adapterId );
if( it_found == m_adapterConnections.end() )
{
ConnectionPtr connection = m_provider->createAdapterConnection( _adapterId );
it_found = m_adapterConnections.insert( std::make_pair(_adapterId, connection) ).first;
}
return it_found->second;
}
//////////////////////////////////////////////////////////////////////////
void ConnectionCache::addServantConnection( const std::string & _name, const ConnectionPtr & _connection )
{
m_servantConnections.insert( std::make_pair(_name, _connection) );
}
//////////////////////////////////////////////////////////////////////////
const ProxyConnectionProviderPtr & ConnectionCache::getProxyServantProvider( const std::string & _name, const boost::asio::ip::tcp::endpoint & _endpoint )
{
TMapProxyServantProviders::const_iterator it_found = m_proxyServantProviders.find( _name );
if( it_found == m_proxyServantProviders.end() )
{
const ConnectionPtr & connection = this->getServantConnection( _name, _endpoint );
ProxyConnectionProviderPtr provider = new ProxyConnectionProvider( connection );
it_found = m_proxyServantProviders.insert( std::make_pair(_name, provider) ).first;
}
return it_found->second;
}
//////////////////////////////////////////////////////////////////////////
const ConnectionPtr & ConnectionCache::getServantConnection( const std::string & _name, const boost::asio::ip::tcp::endpoint & _endpoint )
{
TMapServantConnections::const_iterator it_found = m_servantConnections.find( _name );
if( it_found == m_servantConnections.end() )
{
ConnectionPtr connection = m_provider->createServantConnection( _name, _endpoint );
it_found = m_servantConnections.insert( std::make_pair(_name, connection) ).first;
}
return it_found->second;
}
//////////////////////////////////////////////////////////////////////////
void ConnectionCache::addRouterConnection( const boost::asio::ip::tcp::endpoint & _endpoint, const ConnectionPtr & _connection )
{
m_routerConnections.insert( std::make_pair(_endpoint, _connection) );
}
//////////////////////////////////////////////////////////////////////////
const ConnectionPtr & ConnectionCache::getRouterConnection( const boost::asio::ip::tcp::endpoint & _endpoint )
{
TMapRouterConnections::const_iterator it_found = m_routerConnections.find( _endpoint );
if( it_found == m_routerConnections.end() )
{
ConnectionPtr connection = m_provider->createRouterConnection( _endpoint );
it_found = m_routerConnections.insert( std::make_pair(_endpoint, connection) ).first;
}
return it_found->second;
}
//////////////////////////////////////////////////////////////////////////
const ProxyConnectionProviderPtr & ConnectionCache::getProxyAdapterProvider( std::size_t _servantId, std::size_t _adapterId )
{
TMapProxyAdapterProviders::const_iterator it_found = m_proxyAdapterProviders.find( _servantId );
if( it_found == m_proxyAdapterProviders.end() )
{
const ConnectionPtr & connection = this->getAdapterConnection( _adapterId );
ProxyConnectionProviderPtr provider = new ProxyConnectionProvider( connection );
it_found = m_proxyAdapterProviders.insert( std::make_pair(_servantId, provider) ).first;
}
return it_found->second;
}
//////////////////////////////////////////////////////////////////////////
void ConnectionCache::relocateProxy( std::size_t _servantId, std::size_t _adapterId )
{
TMapProxyAdapterProviders::iterator it_found = m_proxyAdapterProviders.find( _servantId );
if( it_found == m_proxyAdapterProviders.end() )
{
return;
}
const ConnectionPtr & connection = this->getAdapterConnection( _adapterId );
it_found->second->setConnection( connection );
}
} | [
"yuriy_levchenko@b35ac3e7-fb55-4080-a4c2-184bb04a16e0"
] | [
[
[
1,
119
]
]
] |
4dc9ade7ffd63692688a6457340d18bcade18828 | c5ecda551cefa7aaa54b787850b55a2d8fd12387 | /src/UILayer/AddFriend.h | a4c802cf62ecbe6beb2409e3e3b01792c9d6d051 | [] | no_license | firespeed79/easymule | b2520bfc44977c4e0643064bbc7211c0ce30cf66 | 3f890fa7ed2526c782cfcfabb5aac08c1e70e033 | refs/heads/master | 2021-05-28T20:52:15.983758 | 2007-12-05T09:41:56 | 2007-12-05T09:41:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,372 | h | //this file is part of eMule
//Copyright (C)2002-2006 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net )
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 2 of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#pragma once
#include "Friend.h"
#if _DISABLE_NONUSE
// CAddFriend dialog
class CAddFriend : public CDialog
{
DECLARE_DYNAMIC(CAddFriend)
public:
CAddFriend(); // standard constructor
virtual ~CAddFriend();
enum { IDD = IDD_ADDFRIEND };
CFriend* m_pShowFriend;
void Localize();
protected:
HICON m_icnWnd;
virtual BOOL OnInitDialog();
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
DECLARE_MESSAGE_MAP()
afx_msg void OnAddBtn();
};
#endif
| [
"LanceFong@4a627187-453b-0410-a94d-992500ef832d"
] | [
[
[
1,
46
]
]
] |
24f18cc517082e668e56d08a907e7860e9fb411d | 4d838ba98a21fc4593652e66eb7df0fac6282ef6 | /CaveProj/ShaderBuilder.cpp | c5c78837579e07fa44caa6bf7cd285978387d9d8 | [] | no_license | davidhart/ProceduralCaveEditor | 39ed0cf4ab4acb420fa2ad4af10f9546c138a83a | 31264591f2dcd250299049c826aeca18fc52880e | refs/heads/master | 2021-01-17T15:10:09.100572 | 2011-05-03T19:24:06 | 2011-05-03T19:24:06 | 69,302,913 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,760 | cpp | #include "ShaderBuilder.h"
#include <iostream>
#include <D3DX10.h>
//#define USE_PRECOMPILED_SHADERS
const std::string ShaderBuilder::compiledEffectExtension = ".fxo";
const std::string ShaderBuilder::effectSourceExtension = ".fx";
ID3D10Effect* ShaderBuilder::RequestEffect(const std::string& effectname, const std::string& profile, ID3D10Device* d3dDevice)
{
std::string objectFileName = (effectname + compiledEffectExtension).c_str();
std::string sourceFileName = (effectname + effectSourceExtension).c_str();
HANDLE objectFile = CreateFile(objectFileName.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
HANDLE sourceFile = CreateFile(sourceFileName.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
FILETIME objectFileTime;
FILETIME sourceFileTime;
if (objectFile != INVALID_HANDLE_VALUE)
{
GetFileTime(objectFile, NULL, NULL, &objectFileTime);
CloseHandle(objectFile);
}
if (sourceFile != INVALID_HANDLE_VALUE)
{
GetFileTime(sourceFile, NULL, NULL, &sourceFileTime);
CloseHandle(sourceFile);
}
#ifndef USE_PRECOMPILED_SHADERS
if (sourceFile == INVALID_HANDLE_VALUE)
{
std::cout << "Effect \"" << effectname << "\" not found" << std::endl;
return NULL;
}
if (objectFile != INVALID_HANDLE_VALUE && sourceFile != INVALID_HANDLE_VALUE && CompareFileTime(&sourceFileTime, &objectFileTime) <= 0)
{
#endif
objectFile = CreateFile(objectFileName.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (objectFile == INVALID_HANDLE_VALUE)
{
std::cout << "Could not read precompiled effect" << std::endl;
}
else
{
DWORD fileSize = GetFileSize(objectFile, NULL);
DWORD bytesRead;
unsigned char* buffer = new unsigned char[fileSize];
ReadFile(objectFile, buffer, fileSize, &bytesRead, NULL);
CloseHandle(objectFile);
objectFile = INVALID_HANDLE_VALUE;
ID3D10Effect* effect;
ID3D10Blob* error;
if (SUCCEEDED(D3DX10CreateEffectFromMemory(buffer,
fileSize,
sourceFileName.c_str(),
NULL,
NULL,
profile.c_str(),
0,
0,
d3dDevice,
NULL,
NULL,
&effect,
&error,
NULL)))
{
delete [] buffer;
std::cout << "Successfully created effect \"" << effectname << "\"" << std::endl;
return effect;
}
if (error != NULL)
error->Release();
delete [] buffer;
}
#ifndef USE_PRECOMPILED_SHADERS
}
if ((sourceFile != INVALID_HANDLE_VALUE))
{
if (objectFile != INVALID_HANDLE_VALUE && CompareFileTime(&sourceFileTime, &objectFileTime) > 0)
{
std::cout << "Precompiled effect \"" << effectname << "\" is out of date, building from source" << std::endl;
}
else
{
std::cout << "Couldn't load precompiled effect \"" << effectname << "\", building from source" << std::endl;
}
ID3D10Effect* effect;
ID3D10Blob* error;
ID3D10Blob* compiledshader;
if (FAILED(D3DX10CompileFromFile(sourceFileName.c_str(),
0,
0,
NULL,
profile.c_str(),
0,
0,
NULL,
&compiledshader,
&error,
0)))
{
std::cout << "Error compiling shader : " << std::endl;
std::cout << (char*)error->GetBufferPointer() << std::endl;
error->Release();
return NULL;
}
objectFile = CreateFile(objectFileName.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
BOOL saved = FALSE;
if (objectFile != INVALID_HANDLE_VALUE)
{
DWORD numBytesWritten;
saved = WriteFile(objectFile, compiledshader->GetBufferPointer(), compiledshader->GetBufferSize(), &numBytesWritten, NULL);
CloseHandle(objectFile);
}
if (FAILED(D3DX10CreateEffectFromMemory(compiledshader->GetBufferPointer(),
compiledshader->GetBufferSize(),
sourceFileName.c_str(),
NULL,
NULL,
profile.c_str(),
0,
0,
d3dDevice,
NULL,
NULL,
&effect,
&error,
NULL)))
{
std::cout << "Error creating effect : " << std::endl;
std::cout << (char*)error->GetBufferPointer() << std::endl;
error->Release();
compiledshader->Release();
return NULL;
}
compiledshader->Release();
if (!saved)
{
std::cout << "Successfully created effect \"" << effectname << "\", but could not save object file" << std::endl;
}
else
{
std::cout << "Successfully created effect \"" << effectname << "\"" << std::endl;
}
return effect;
}
#endif
return NULL;
}
| [
"[email protected]"
] | [
[
[
1,
177
]
]
] |
dd3bbccaa23d44b21037424a8b0917e5a4a7b0bb | e01dc698db930a300bd6e27412cd027635151f6a | /simulador-memoria/simulador-memoria/memoria/estado.h | 84d2d3d16d8087422496791eb32377f41b9e38c6 | [] | no_license | lucasjcastro/rodador-de-mepa | becda6a9cdb6bbbec6e339f7bb52ec1dda48a89f | 933fe3f522f55c55e8056c182016f9f06280b3e0 | refs/heads/master | 2021-01-10T07:37:40.226661 | 2008-09-25T02:27:58 | 2008-09-25T02:27:58 | 46,521,554 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 141 | h | #ifndef ESTADO_H_
#define ESTADO_H_
class estado{
public:
string processo;
int endereco;
};
#endif
| [
"solenoide.spm@33f839a4-89d3-11dd-bc3c-d57f4316d18f"
] | [
[
[
1,
9
]
]
] |
f140f0dceb85c01741f4cbc6b184f972a83e4613 | 5fa8f06181e88d96a9166cb238d05b185ebe7a92 | /sliq/engine.cc | 988a34d5c750ad3bcad143be708084c54f85b081 | [] | no_license | mohitkg/sliqimp | 6834092760a8a078428876baaa7cdab91b37e355 | 54f05bc55ad9c6b7e73abc51fcc0bd8e995d6b69 | refs/heads/master | 2016-09-07T07:13:04.793483 | 2007-06-20T10:49:44 | 2007-06-20T10:49:44 | 33,323,734 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 5,351 | cc | #include <fstream>
#include <sstream>
#include <iostream>
#include "engine.hh"
// fonction qui enlève les espaces de début et de fin
void trim(std::string& str)
{
std::string::size_type pos = str.find_last_not_of(' ');
if(pos != std::string::npos)
{
str.erase(pos + 1);
pos = str.find_first_not_of(' ');
if(pos != std::string::npos)
str.erase(0, pos);
}
else
str.erase(str.begin(), str.end());
}
namespace Sliq
{
Engine::Engine (std::string config_filename, std::vector<std::vector<int> > *examples)
{
*examples = load_examples(config_filename);
}
Node *Engine::init_node(int id, int nb_classes)
{
return new Node(id, nb_classes);
}
std::vector<std::vector<int> > &Engine::load_examples(std::string &config_filename)
{
std::vector<int> temp;
std::vector<std::vector<int> > *result = new std::vector<std::vector<int> > ();
std::ifstream file(config_filename.c_str ());
bool parse_colors = true;
bool parse_attributes = true;
int index = 0;
int int_value;
if (file)
{
std::string line;
std::cout << "Parsing classes..." << std::endl;
classes_names_.push_back("");
while (parse_colors && std::getline(file, line))
{
if (!line.compare("-"))
parse_colors = false;
else
{
std::string cl = line.substr(0, line.find_first_of("//") - 1);
trim(cl);
classes_names_.push_back(cl);
std::cout << cl << std::endl;
}
}
tree_ = init_node(1, classes_names_.size ());
std::cout << "Parsing attributes..." << std::endl;
while (parse_attributes && std::getline(file, line))
{
if (!line.compare("-"))
parse_attributes = false;
else
{
std::string att = line.substr(0, line.find_first_of("//") - 1);
trim(att);
attribute_names_.push_back(att);
std::cout << att << std::endl;
}
}
std::cout << "Parsing examples..." << std::endl;
while (std::getline(file, line))
{
if (!line.compare(""))
continue;
int nb_attributes = attribute_names_.size ();
temp.clear ();
for (int i = 0; i < nb_attributes; ++i)
{
std::string value = line.substr(0, line.find_first_of(","));
line = line.substr(line.find_first_of(",") + 1);
trim(value);
std::istringstream iss(value);
iss >> int_value;
attribute_lists_.push_back(Attribute::List (i));
attribute_lists_[i].insert(int_value, index);
temp.push_back(int_value);
}
std::istringstream iss(line);
iss >> int_value;
class_list_.push_back(std::pair<int, Node*>(int_value, tree_));
temp.push_back(int_value);
result->push_back(temp);
index += 1;
}
for (std::vector<std::pair<int, Node*> >::iterator it = class_list_.begin ();
it != class_list_.end ();
++it)
{
tree_->add_example((*it).first);
}
}
return *result;
}
bool Engine::compute_sliq ()
{
bool only_real_leafs = false;
Test *test;
int i = 0;
while (!only_real_leafs)
{
for (int i = 0; i < attribute_names_.size (); ++i)
attribute_lists_[i].check_best_test(i, class_list_);
for (int i = 0; i < attribute_names_.size (); ++i)
attribute_lists_[i].execute_cut(i, class_list_);
only_real_leafs = true;
for (std::vector<std::pair<int, Node*> >::iterator it = class_list_.begin ();
it != class_list_.end (); ++it)
{
only_real_leafs = only_real_leafs && (*it).second->is_leaf ();
}
}
}
int Engine::classify(std::vector<int> ex)
{
Node *node = tree_;
while (!node->is_leaf())
{
int attribute = node->test_get().attribute_get ();
int lim = node->test_get().lim_get ();
if (ex[attribute] <= lim)
node = node->fg_get ();
else
node = node->fd_get ();
}
return node->class_get();
}
}
std::ostream &operator<<(std::ostream &os, Sliq::Engine &engine)
{
os << "digraph G {\n"
<< "edge [color=\"#8855FF\", arrowsize=1]\n"
<< "node [fontsize=7, fontname=Verdana]\n";
os << *engine.tree_get ();
os << "}" << std::endl;
return os;
}
| [
"davidlandais@af1a0f03-5433-0410-83de-a7259e581374"
] | [
[
[
1,
161
]
]
] |
2014f6c2b831816a5538c8f06f777d9d66d819d8 | 565d432f8223100873944cfa22b9d9b2f14575f1 | /图片验证码/1/StdAfx.cpp | b510fb902eff56e051bdf79cd6e2aacbde121330 | [] | no_license | glencui2015/tlautologin | ce029c688e0414497e91115a2ee19e7abcac56d2 | 6e825807e2523bf4e020d91f92d86ce194747d0d | refs/heads/master | 2021-01-10T10:50:34.139524 | 2010-12-17T17:43:33 | 2010-12-17T17:43:33 | 50,753,256 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 208 | cpp | // stdafx.cpp : source file that includes just the standard includes
// ShowTL.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
| [
"woaini4t@84d92313-99f8-b76f-20ef-0d116c1dc3bd"
] | [
[
[
1,
8
]
]
] |
d12d664fe0829578c274e054be81e2587b370041 | baa53679794b11a5e99bc430149494e48e7c0d1e | /user.h | a7eb848fed44e2d37342cc321110ec3679cc5d9c | [] | no_license | BadPractice/twmailer2 | 34cf62cfc2249a8b30cf9f7e729d4713aaefaea1 | 76abd320acf4265cda7d5de19a46df7e805e51f0 | refs/heads/master | 2020-12-24T15:40:05.391935 | 2011-11-07T00:05:34 | 2011-11-07T00:05:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 654 | h | #ifndef USER_H
#define USER_H
#include <string>
#include <fstream>
#include <iostream>
#include <list>
#include <stdlib.h>
using namespace std;
class user
{
public:
user(string aaa);
void send(string to, string message);
void send(list <string> to, string message);
string do_list();
void do_del(int);
string do_read(int msg);
~user();
protected:
private:
string name;
void writefile(string);
int getfilenames(list<string > *);
string getfile(string filename);
bool sortnumb (string first, string second);
};
#endif // USER_H
| [
"[email protected]"
] | [
[
[
1,
29
]
]
] |
263eb8839235763f2151163309b4dd4be62a8c27 | 23e1deafd7805287ca582e6f5d1a9ba408e058a6 | /MN1-SistemasLineares/src/SistemaLinear.cpp | 4bec278b3433be357b2d4e12586d1a18e1f6ebaa | [] | no_license | lucaseduardo101/NumericalMethods | 8ddc7e907dc5f47a0a848ddfd515d715482616e2 | ce2e38401bb36bf702c53142d398dd56c632de0f | refs/heads/master | 2021-01-21T21:38:38.976852 | 2010-09-11T00:24:18 | 2010-09-11T00:24:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 836 | cpp | /*
* SistemaLinear.cpp
*
* Created on: 09/12/2009
* Author: Rafael Sales
*/
#include "SistemaLinear.h"
SistemaLinear::SistemaLinear(double** coeficientes, double* termosIndependentes, int numEquacoes) :
coeficientes(coeficientes), termosIndependentes(termosIndependentes), numEquacoes(numEquacoes) {
}
SistemaLinear::~SistemaLinear() {
for (int i = 0; i < numEquacoes; i++) {
delete[] coeficientes[i];
}
delete[] coeficientes;
delete[] termosIndependentes;
}
void SistemaLinear::trocarLinhas(int l1, int l2) {
double* coeficientesL1 = coeficientes[l1];
double termoIndependenteL1 = termosIndependentes[l1];
coeficientes[l1] = coeficientes[l2];
termosIndependentes[l1] = termosIndependentes[l2];
coeficientes[l2] = coeficientesL1;
termosIndependentes[l2] = termoIndependenteL1;
}
| [
"[email protected]"
] | [
[
[
1,
29
]
]
] |
519a90ef5ca6dab26973cc3d1acc2c02dd5e5ed2 | 20cf43a2e1854d71696a6264dea4ea8cbfdb16f2 | /Unix/unix_client/communicator/chat.h | b3e52bedd4185988d1829c77f8188f2a4f0f6080 | [] | no_license | thebruno/comm-nt | fb0ece0a8d36715a8f0199ba3ce9f37859170ee3 | 6ba36941b123c272efe8d81b55555d561d8842f4 | refs/heads/master | 2016-09-07T19:00:59.817929 | 2010-01-14T20:38:58 | 2010-01-14T20:38:58 | 32,205,785 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 889 | h | #ifndef CHAT_H
#define CHAT_H
#include <QtGui/QMainWindow>
#include "commonClasses.h"
namespace Ui {
class Chat;
}
class MainWindow;
class Chat : public QMainWindow {
Q_OBJECT
public:
Chat(Group & receivers, QWidget *parent = 0);
~Chat();
// reference to parent window
MainWindow * Main;
// fill message history chat with message from other user
void FillMessage(Message& m);
// fill message history chat with current user message
void FillMessage(std::string sender, std::string created, std::string text);
// get this window chat recivers
Group GetReceivers();
void showAndPosition(QWidget * parent);
protected:
void changeEvent(QEvent *e);
private:
Ui::Chat *m_ui;
Group Receivers;
private slots:
void on_btnClose_clicked();
void on_btnSend_clicked();
};
#endif // CHAT_H
| [
"konrad.balys@08f01046-b83b-11de-9b33-83dc4fd2bb11"
] | [
[
[
1,
37
]
]
] |
e71925de2936df77a981aaa4a7462eb416d2c162 | 74c8da5b29163992a08a376c7819785998afb588 | /NetAnimal/Game/Hunter/NewGameDiamond/UnitTest/include/GameNeedleComponentUT.h | 81ed125fea2b8a7186e4b79748b6cc651c2cf4a9 | [] | no_license | dbabox/aomi | dbfb46c1c9417a8078ec9a516cc9c90fe3773b78 | 4cffc8e59368e82aed997fe0f4dcbd7df626d1d0 | refs/heads/master | 2021-01-13T14:05:10.813348 | 2011-06-07T09:36:41 | 2011-06-07T09:36:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,435 | h | #ifndef __Orz_UnitTest_GameNeedleComponentUT__
#define __Orz_UnitTest_GameNeedleComponentUT__
#include "UnitTestConfig.h"
#include "CNewGameSceneInterface.h"
#include "CGameNeedleInterface.h"
BOOST_AUTO_TEST_CASE(GameNeedleComponentUT)
{
using namespace Orz;
//
ComponentPtr sceneComp = ComponentFactories::getInstance().create("NewGameScene");
//
CNewGameSceneInterface * scene = sceneComp->queryInterface<CNewGameSceneInterface>();
ComponentPtr needleComp = ComponentFactories::getInstance().create("GameNeedle");
CGameNeedleInterface * needle = needleComp->queryInterface<CGameNeedleInterface>();
scene->load();
//BOOST_CHECK(needle != NULL);
//std::cout<<scene->getHelper(24);
needle->load(scene->getHelper(CNewGameSceneInterface::Helper24));
for(int i = 0; i< 25; ++i)
{
std::cout<<scene->getHelper(CNewGameSceneInterface::HELPERS(i));
}
//boost::array<CNewGameSceneInterface::LIGHT_COLOR, 24> lights;
//for(int i = 0; i<24; ++i)
//{
// lights[i] = CNewGameSceneInterface::Red;
//}
//scene->setLights(lights);
TimeType time = 0.f;
while(time<3.f)
{
time+= 0.015f;
UnitTestEnvironmen::system->run();
}
time = 0.f;
while(time<3.f)
{
time+= 0.015f;
UnitTestEnvironmen::system->run();
}
time = 0.f;
while(time<3.f)
{
time+= 0.015f;
UnitTestEnvironmen::system->run();
}
scene->unload();
}
#endif | [
"[email protected]"
] | [
[
[
1,
68
]
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.