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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f142c0f3314dd7c163d114e2a595240befbc8235 | 38af8ef5939efeb9f98d77756fd54ff8a94985d1 | /rzpctrl/src/ctlitems.cpp | 7495cfce89af09a7253c5bff6167a7b499e35d52 | []
| no_license | suda-ee/miscprojectsrepo | 16658894d1a3ae5c5900395ce84f519cafc7fd8a | e29d56498910045d97ecc3fd3205b1add4080683 | refs/heads/master | 2021-01-18T15:29:33.618773 | 2011-01-12T06:26:06 | 2011-01-12T06:26:06 | 86,655,718 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 243 | cpp | #include "ctlitems.h"
ctlitems::ctlitems(QTreeWidget *parent, int type)
: QTreeWidgetItem(parent, type)
{
}
ctlitems::ctlitems(ctlitems *parent, int type)
: QTreeWidgetItem(parent, type)
{
}
ctlitems::~ctlitems()
{
}
| [
"cai@localhost"
]
| [
[
[
1,
15
]
]
]
|
cc7d735e9eb4643abe9f5da7ffbf277c54b056d5 | 6a925ad6f969afc636a340b1820feb8983fc049b | /librtsp/librtsp/inc/MediaSource.h | 5f4d0e763825eedb962f0462ebc108ea196d2641 | []
| no_license | dulton/librtsp | c1ac298daecd8f8008f7ab1c2ffa915bdbb710ad | 8ab300dc678dc05085f6926f016b32746c28aec3 | refs/heads/master | 2021-05-29T14:59:37.037583 | 2010-05-30T04:07:28 | 2010-05-30T04:07:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 776 | h | /*!@file MediaSource.h
@brief
Copyright (c) 2009 HUST ITEC VoIP Lab.
All rights reserved.
@author Wentao Tang
@date 2009.3.25
@version 1.0
*/
#pragma once
#include <string>
using std::string;
#define MILLION 1000000
class MediaSource
{
public:
MediaSource(void);
virtual ~MediaSource(void);
public:
virtual const string GetConfig() = 0;
virtual bool Open() = 0; //!< Open the source
virtual bool Close() = 0; //!< Close the source
virtual int GetMediaData(char *buf,
unsigned int bufsize,
unsigned long &duration,
unsigned long &ts) = 0;
protected:
bool isOpened_;
};
| [
"TangWentaoHust@95ff1050-1aa1-11de-b6aa-3535bc3264a2"
]
| [
[
[
1,
32
]
]
]
|
f3e81573a16ff418b2cd2e62d91301e62ddb21fb | b5ab57edece8c14a67cc98e745c7d51449defcff | /Captain's Log/MainGame/Source/GameObjects/CBMPFont.h | 918aac1b19451cb376ccdade78df672f6064165e | []
| no_license | tabu34/tht-captainslog | c648c6515424a6fcdb628320bc28fc7e5f23baba | 72d72a45e7ea44bdb8c1ffc5c960a0a3845557a2 | refs/heads/master | 2020-05-30T15:09:24.514919 | 2010-07-30T17:05:11 | 2010-07-30T17:05:11 | 32,187,254 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 651 | h | #ifndef CBMPFont_h__
#define CBMPFont_h__
#include <vector>
#include <Windows.h>
using namespace std;
class CBMPFont
{
RECT m_rLetterRects[256];
int m_nStartChar;
int m_nImageID;
float m_fScaleX;
float m_fScaleY;
int m_nKerning;
DWORD m_dwFontColor;
public:
void Initialize(const char* szFileName, float fScaleX, float fScaleY, int nKerning, DWORD dwKeyColor = 0, DWORD dwFontColor = -1);
void SetUp(float fScaleX, float fScaleY, int nKerning, DWORD dwFontColor = -1);
void RenderText(char* szString, int nPosX, int nPosY);
void LoadLetterRects(const char* szFileName);
};
#endif // CBMPFont_h__ | [
"notserp007@34577012-8437-c882-6fb8-056151eb068d"
]
| [
[
[
1,
25
]
]
]
|
44ac250def003f5c912602b95660722f3336a756 | be7eef50e21e11340134d150f78db8d6f5423e66 | /B11/B11g01.cpp | 363cc2fbab08d896a216c002cf4c829a6e360d48 | []
| 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 | 567 | cpp | #include <iostream>
#include <fstream>
using namespace std;
uint32_t z=1;
uint32_t n=10000;
uint32_t m=n*10;
uint32_t l=10000;
uint32_t p;
int main(int argc,char **argv)
{
ios_base::sync_with_stdio(0);
ofstream wyj(argv[1]);
ifstream wej("/dev/urandom");
wyj<<z<<endl;
while(z--)
{
wyj<<n<<' '<<1<<' '<<n<<endl;
for(uint32_t i=1;i<=n;++i)
{
p=wej.get();
wyj<<p<<' '<<n/n;
for(uint32_t j=i;j<i+1;++j)
{
wyj<<' '<<j%n+1<<' '<<l;
}
wyj<<endl;
}
}
wyj.close();
wej.close();
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
36
]
]
]
|
00d96afcd6c29b7a148cf90db1d1c14da4035065 | b9c9a4c5e7952e080a53c81a0781180a9bf80257 | /src/document/SciWrapper.h | 4efbf92c63220d6fea8ea994bdde0eabd07beed4 | []
| no_license | kaelspencer/confero | 296aa9cd87c0254a662be136a571ffb9675d9fe9 | a41c71fe082017c316bc2f79e00c2b9e3a8ef7eb | refs/heads/master | 2021-01-19T17:47:44.444616 | 2011-06-12T00:25:25 | 2011-06-12T00:25:25 | 1,777,702 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,319 | h | #ifndef SCIWRAPPER_H
#define SCIWRAPPER_H
#include <Qsci/qsciscintilla.h>
#include "../net/ConferoNet.h"
#include "Edit.h"
#include "Document.h"
#include <Qsci/qscilexer.h>
#include <Qsci/qscilexerbash.h>
#include <Qsci/qscilexerbatch.h>
#include <Qsci/qscilexercmake.h>
#include <Qsci/qscilexercpp.h>
#include <Qsci/qscilexercsharp.h>
#include <Qsci/qscilexercss.h>
#include <Qsci/qscilexerd.h>
#include <Qsci/qscilexerdiff.h>
#include <Qsci/qscilexerfortran.h>
#include <Qsci/qscilexerfortran77.h>
#include <Qsci/qscilexerhtml.h>
#include <Qsci/qscilexeridl.h>
#include <Qsci/qscilexerjava.h>
#include <Qsci/qscilexerjavascript.h>
#include <Qsci/qscilexerlua.h>
#include <Qsci/qscilexermakefile.h>
#include <Qsci/qscilexerpascal.h>
#include <Qsci/qscilexerperl.h>
#include <Qsci/qscilexerpostscript.h>
#include <Qsci/qscilexerpov.h>
#include <Qsci/qscilexerproperties.h>
#include <Qsci/qscilexerpython.h>
#include <Qsci/qscilexerruby.h>
#include <Qsci/qscilexerspice.h>
#include <Qsci/qscilexersql.h>
#include <Qsci/qscilexertcl.h>
#include <Qsci/qscilexertex.h>
#include <Qsci/qscilexerverilog.h>
#include <Qsci/qscilexervhdl.h>
#include <Qsci/qscilexerxml.h>
#include <Qsci/qscilexeryaml.h>
extern const int SC_MOD_INSERTTEXT;
extern const int SC_MOD_DELETETEXT;
class SciWrapper : public QObject
{
Q_OBJECT
private:
static QsciLexer ** m_lexers;
QsciScintilla * m_sci;
ConferoNet * m_cnet;
unsigned int m_key;
kDocument * m_doc;
bool m_okToInsert;
SciWrapper();
SciWrapper & operator=(const SciWrapper & rhs);
SciWrapper(const SciWrapper & rhs);
void InitLexers();
private slots:
void modified(int, int, const char *, int, int, int, int, int, int, int);
public:
enum Language {Bash, Batch, CMake, CPP, CSHARP, CSS, D, Diff, Fortran, Fortran77,
HTML, IDL, Java, JavaScript, LUA, MakeFile, Pascal, Perl, PostScript,
POV, Properties, Python, Ruby, Spice, SQL, TCL, TeX, Verilog,
VHDL, XML, YAML, None};
SciWrapper(QsciScintilla * sci, ConferoNet * cnet, unsigned int key);
~SciWrapper() {};
void integrateEdit(Edit * ed);
void SetLanguage(Language language);
signals:
void statusMessage(const QString & msg);
};
#endif
| [
"kael@euler"
]
| [
[
[
1,
81
]
]
]
|
f8eaab83ce9dc2e99bcfcc4b94c5f15215d8f746 | 7f6fe18cf018aafec8fa737dfe363d5d5a283805 | /ntk/interface/src/screen.cpp | f31646a3fcf23f30a1f40099b796ac38e6ac623a | []
| no_license | snori/ntk | 4db91d8a8fc836ca9a0dc2bc41b1ce767010d5ba | 86d1a32c4ad831e791ca29f5e7f9e055334e8fe7 | refs/heads/master | 2020-05-18T05:28:49.149912 | 2009-08-04T16:47:12 | 2009-08-04T16:47:12 | 268,861 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 776 | cpp | /******************************************************************************
The NTK Library
Copyright (C) 1998-2003 Noritaka Suzuki
$Id: screen.cpp,v 1.4 2003/11/11 12:07:08 nsuzuki Exp $
******************************************************************************/
#define NTK_BUILD
#include "ntk/interface/screen.h"
#include <ntk/windows/windows.h>
namespace ntk {
//########################################################
// public methods
Screen::Screen()
{
}
Screen::~Screen()
{
}
Rect
Screen::frame()
{
Rect screen_frame(
0,
0,
GetSystemMetrics(SM_CXSCREEN),
GetSystemMetrics(SM_CYSCREEN));
return screen_frame;
}
//########################################################
}// namespace ntk
| [
"[email protected]"
]
| [
[
[
1,
44
]
]
]
|
b371a3491631a3b20db38863ab419dab6becbb68 | 2fdbf2ba994ba3ed64f0e2dc75cd2dfce4936583 | /gpt/test2.cpp | c28f429b0d6ecee5d0e324a5fb8776f0060e5644 | []
| no_license | TERRANZ/terragraph | 36219a4e512e15a925769512a6b60637d39830bf | ea8c36070f532ad0a4af08e46b19f4ee1b85f279 | refs/heads/master | 2020-05-25T10:31:26.994233 | 2011-01-29T21:23:04 | 2011-01-29T21:23:04 | 1,047,237 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 110 | cpp | #include "test2.h"
namespace {
/*$GPBS$$!globals!*/
// put global variables and funcs here
/*$GPBS$*/
} | [
"[email protected]"
]
| [
[
[
1,
7
]
]
]
|
b1658b5e71b6d90010c35e767b2f141b5c5b0af7 | 62c9cb0899bbb36d3e742559831f84054b57d790 | /DeviceAdapters/LeicaDMI/LeicaDMI.cpp | 874b77341f0fa0f299c498e04a6155e3dbd388c4 | []
| no_license | astraw/micromanager1.3 | b1a245f676f32bbaf1cda7cecbaaf0a5c661ad6c | 6032a1916442dfd1847bef0ed1d5bd1895334c1d | refs/heads/master | 2020-06-05T02:37:31.526258 | 2009-04-28T16:58:58 | 2009-04-28T16:58:58 | 187,348 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 74,033 | cpp | ///////////////////////////////////////////////////////////////////////////////
// FILE: LeicaDMI.cpp
// PROJECT: MicroManage
// SUBSYSTEM: DeviceAdapters
//-----------------------------------------------------------------------------
// DESCRIPTION:
//
// COPYRIGHT: 100xImaging, Inc. 2008
// LICENSE:
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation.
//
// You should have received a copy of the GNU Lesser General Public
// License along with the source distribution; if not, write to
// the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
// Boston, MA 02111-1307 USA
//
// This file 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.
//
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
#ifdef WIN32
#include <windows.h>
#define snprintf _snprintf
#else
#include <netinet/in.h>
#endif
#include "LeicaDMI.h"
#include "LeicaDMIModel.h"
#include "LeicaDMIScopeInterface.h"
#include "LeicaDMICodes.h"
#include "../../MMDevice/ModuleInterface.h"
#include <string>
#include <math.h>
#include <sstream>
#include <algorithm>
// TODO: linux entry code
// Note that this only works with gcc (which we should be testing for)
#ifdef __GNUC__
void __attribute__ ((constructor)) my_init(void)
{
}
void __attribute__ ((destructor)) my_fini(void)
{
}
#endif
// windows dll entry code
#ifdef WIN32
BOOL APIENTRY DllMain( HANDLE /*hModule*/,
DWORD ul_reason_for_call,
LPVOID /*lpReserved*/
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
#endif
using namespace std;
LeicaScopeInterface g_ScopeInterface;
LeicaDMIModel g_ScopeModel;
///////////////////////////////////////////////////////////////////////////////
// Devices in this adapter.
// The device name needs to be a class name in this file
// Leica Devices
const char* g_LeicaDeviceName = "Scope";
const char* g_LeicaReflector = "IL-Turret";
const char* g_LeicaNosePiece = "ObjectiveTurret";
const char* g_LeicaFieldDiaphragmTL = "TL-FieldDiaphragm";
const char* g_LeicaApertureDiaphragmTL = "TL-ApertureDiaphragm";
const char* g_LeicaFieldDiaphragmIL = "IL-FieldDiaphragm";
const char* g_LeicaApertureDiaphragmIL = "IL-ApertureDiaphragm";
const char* g_LeicaFocusAxis = "FocusDrive";
const char* g_LeicaMagChanger = "MagnificationChanger";
const char* g_LeicaTubeLensShutter = "TubeLensShutter";
const char* g_LeicaSidePort = "SidePort";
const char* g_LeicaIncidentLightShutter = "IL-Shutter";
const char* g_LeicaTransmittedLightShutter = "TL-Shutter";
const char* g_LeicaHalogenLightSwitch = "HalogenLightSwitch";
const char* g_LeicaRLFLAttenuator = "IL-FLAttenuator";
const char* g_LeicaXYStage = "XYStage";
const char* g_LeicaBasePort = "BasePort";
const char* g_LeicaUniblitz = "Uniblitz";
const char* g_LeicaFilterWheel = "FilterWheel";
const char* g_LeicaTLPolarizer = "TLPolarizer";
const char* g_LeicaDICTurret = "DIC Turret";
const char* g_LeicaCondensorTurret = "Condensor";
const char* g_LeicaTransmittedLight = "Transmitted Light";
///////////////////////////////////////////////////////////////////////////////
MODULE_API void InitializeModuleData()
{
AddAvailableDeviceName(g_LeicaDeviceName,"Leica DMI microscope controlled through serial interface");
AddAvailableDeviceName(g_LeicaTransmittedLightShutter,"Transmitted Light Shutter");
AddAvailableDeviceName(g_LeicaIncidentLightShutter,"Incident Light Shutter");
AddAvailableDeviceName(g_LeicaReflector,"Reflector Turret (dichroics)");
AddAvailableDeviceName(g_LeicaNosePiece,"Objective Turret");
AddAvailableDeviceName(g_LeicaFocusAxis,"Z-drive");
AddAvailableDeviceName(g_LeicaXYStage,"XYStage");
AddAvailableDeviceName(g_LeicaFieldDiaphragmTL,"Field Diaphragm (Trans)");
AddAvailableDeviceName(g_LeicaApertureDiaphragmTL,"Aperture Diaphragm (Condensor)");
AddAvailableDeviceName(g_LeicaFieldDiaphragmIL,"Field Diaphragm (Fluorescence)");
AddAvailableDeviceName(g_LeicaApertureDiaphragmIL,"Aperture Diaphragm (Fluorescence)");
AddAvailableDeviceName(g_LeicaMagChanger,"Tube Lens (magnification changer)");
AddAvailableDeviceName(g_LeicaTLPolarizer, "Transmitted light Polarizer");
AddAvailableDeviceName(g_LeicaDICTurret, "DIC Turret");
AddAvailableDeviceName(g_LeicaCondensorTurret, "Condensor Turret");
AddAvailableDeviceName(g_LeicaTransmittedLight,"Transmitted Light");
}
using namespace std;
///////////////////////////////////////////////////////////////////////////////
// Exported MMDevice API
///////////////////////////////////////////////////////////////////////////////
MODULE_API MM::Device* CreateDevice(const char* deviceName)
{
if (deviceName == 0)
return 0;
if (strcmp(deviceName, g_LeicaDeviceName) == 0)
return new LeicaScope();
else if (strcmp(deviceName, g_LeicaTransmittedLightShutter) == 0)
return new TLShutter();
else if (strcmp(deviceName, g_LeicaIncidentLightShutter) == 0)
return new ILShutter();
else if (strcmp(deviceName, g_LeicaReflector) == 0)
return new ILTurret();
else if (strcmp(deviceName, g_LeicaNosePiece) == 0)
return new ObjectiveTurret();
else if (strcmp(deviceName, g_LeicaFocusAxis) == 0)
return new ZDrive();
else if (strcmp(deviceName, g_LeicaFieldDiaphragmTL) == 0)
return new Diaphragm(&g_ScopeModel.fieldDiaphragmTL_, g_Field_Diaphragm_TL, g_LeicaFieldDiaphragmTL);
else if (strcmp(deviceName, g_LeicaApertureDiaphragmTL) == 0)
return new Diaphragm(&g_ScopeModel.apertureDiaphragmTL_, g_Aperture_Diaphragm_TL, g_LeicaApertureDiaphragmTL);
else if (strcmp(deviceName, g_LeicaFieldDiaphragmIL) == 0)
return new Diaphragm(&g_ScopeModel.fieldDiaphragmIL_, g_Field_Diaphragm_IL, g_LeicaFieldDiaphragmIL);
else if (strcmp(deviceName, g_LeicaApertureDiaphragmIL) == 0)
return new Diaphragm(&g_ScopeModel.apertureDiaphragmIL_, g_Aperture_Diaphragm_IL, g_LeicaApertureDiaphragmIL);
else if (strcmp(deviceName, g_LeicaXYStage) == 0)
return new XYStage();
else if (strcmp(deviceName, g_LeicaMagChanger) == 0)
return new MagChanger();
else if (strcmp(deviceName, g_LeicaTLPolarizer) == 0)
return new TLPolarizer();
else if (strcmp(deviceName, g_LeicaDICTurret) == 0)
return new DICTurret();
else if (strcmp(deviceName, g_LeicaCondensorTurret) == 0)
return new CondensorTurret();
else if (strcmp(deviceName, g_LeicaTransmittedLight) == 0)
return new TransmittedLight();
return 0;
}
MODULE_API void DeleteDevice(MM::Device* pDevice)
{
delete pDevice;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// LeicaScope
//
LeicaScope::LeicaScope() :
initialized_(false),
port_("Undefined"),
answerTimeoutMs_(250)
{
InitializeDefaultErrorMessages();
SetErrorText(ERR_ANSWER_TIMEOUT, "The Leica microscope does not answer. Is it switched on and connected to this computer?");
// create pre-initialization properties
// ------------------------------------
// Name
CreateProperty(MM::g_Keyword_Name, g_LeicaDeviceName, MM::String, true);
// Description
CreateProperty(MM::g_Keyword_Description, "Leica microscope CAN bus adapter", MM::String, true);
// Port
CPropertyAction* pAct = new CPropertyAction (this, &LeicaScope::OnPort);
CreateProperty(MM::g_Keyword_Port, "Undefined", MM::String, false, pAct, true);
// AnswerTimeOut
pAct = new CPropertyAction (this, &LeicaScope::OnAnswerTimeOut);
CreateProperty("AnswerTimeOut", "250", MM::Float, false, pAct, true);
}
LeicaScope::~LeicaScope()
{
if (g_ScopeInterface.monitoringThread_ != 0) {
g_ScopeInterface.monitoringThread_->Stop();
g_ScopeInterface.monitoringThread_->wait();
delete g_ScopeInterface.monitoringThread_;
g_ScopeInterface.monitoringThread_ = 0;
}
g_ScopeInterface.initialized_ = false;
Shutdown();
}
int LeicaScope::Initialize()
{
int ret = DEVICE_OK;
if (!g_ScopeInterface.IsInitialized())
ret = g_ScopeInterface.Initialize(*this, *GetCoreCallback());
if (ret != DEVICE_OK)
return ret;
// Version
string model;
ret = g_ScopeModel.GetStandType(model);
if (DEVICE_OK != ret)
return ret;
ret = CreateProperty("Microscope Stand", model.c_str(), MM::String, true);
if (DEVICE_OK != ret)
return ret;
// Firmware
string version;
ret = g_ScopeModel.GetStandVersion(version);
if (DEVICE_OK != ret)
return ret;
ret = CreateProperty("Microscope Firmware", version.c_str(), MM::String, true);
if (DEVICE_OK != ret)
return ret;
// Method
CPropertyAction* pAct = new CPropertyAction(this, &LeicaScope::OnMethod);
CreateProperty("Method", "", MM::String, false, pAct);
for (int i=0; i<16; i++) {
if (g_ScopeModel.IsMethodAvailable(i)) {
AddAllowedValue("Method", g_ScopeModel.GetMethod(i).c_str());
}
}
ret = UpdateStatus();
if (DEVICE_OK != ret)
return ret;
initialized_ = true;
return 0;
}
int LeicaScope::Shutdown()
{
return 0;
}
void LeicaScope::GetName (char* Name) const
{
CDeviceUtils::CopyLimitedString(Name, g_LeicaDeviceName);
}
bool LeicaScope::Busy()
{
bool busy;
g_ScopeModel.method_.GetBusy(busy);
return busy;
}
///////////////////////////////////////////////////////////////////////////////
// Action handlers
///////////////////////////////////////////////////////////////////////////////
int LeicaScope::OnPort(MM::PropertyBase* pProp, MM::ActionType eAct)
{
if (eAct == MM::BeforeGet) {
pProp->Set(g_ScopeInterface.port_.c_str());
} else if (eAct == MM::AfterSet) {
if (initialized_) {
// revert
pProp->Set(g_ScopeInterface.port_.c_str());
return ERR_PORT_CHANGE_FORBIDDEN;
}
// take this port. TODO: should we check if this is a valid port?
pProp->Get(g_ScopeInterface.port_);
// Provide a pointer to the scope model
g_ScopeInterface.scopeModel_ = &g_ScopeModel;
// set flags indicating we have a port
g_ScopeInterface.portInitialized_ = true;
initialized_ = true;
}
return DEVICE_OK;
}
int LeicaScope::OnMethod(MM::PropertyBase* pProp, MM::ActionType eAct)
{
if (eAct == MM::BeforeGet) {
int position;
int ret = g_ScopeModel.method_.GetPosition(position);
if (ret != DEVICE_OK)
return ret;
std::string method = g_ScopeModel.GetMethod(position);
pProp->Set(method.c_str());
} else if (eAct == MM::AfterSet) {
std::string method;
pProp->Get(method);
int position = g_ScopeModel.GetMethodID(method);
if (position > 0) {
g_ScopeInterface.SetMethod(*this, *GetCoreCallback(), position);
}
}
return DEVICE_OK;
}
int LeicaScope::OnAnswerTimeOut(MM::PropertyBase* pProp, MM::ActionType eAct)
{
if (eAct == MM::BeforeGet) {
pProp->Set(g_ScopeInterface.GetTimeOutTime().getMsec());
} else if (eAct == MM::AfterSet) {
double tmp;
pProp->Get(tmp);
g_ScopeInterface.SetTimeOutTime(MM::MMTime(tmp * 1000.0));
}
return DEVICE_OK;
}
///////////////////////////////////////////////////////////////////////////////
// Leica Incident light Shutter
///////////////////////////////////////////////////////////////////////////////
ILShutter::ILShutter ():
initialized_ (false),
state_(0)
{
InitializeDefaultErrorMessages();
SetErrorText(ERR_SCOPE_NOT_ACTIVE, "Leica Scope is not initialized. It is needed for the Leica Shutter to work");
SetErrorText(ERR_MODULE_NOT_FOUND, "This shutter is not installed in this Leica microscope");
}
ILShutter::~ILShutter ()
{
Shutdown();
}
void ILShutter::GetName(char* name) const
{
assert(name_.length() < CDeviceUtils::GetMaxStringLength());
CDeviceUtils::CopyLimitedString(name, name_.c_str());
}
int ILShutter::Initialize()
{
if (!g_ScopeInterface.portInitialized_)
return ERR_SCOPE_NOT_ACTIVE;
int ret = DEVICE_OK;
if (!g_ScopeInterface.IsInitialized())
ret = g_ScopeInterface.Initialize(*this, *GetCoreCallback());
if (ret != DEVICE_OK)
return ret;
// check if this shutter exists:
if (!g_ScopeModel.IsDeviceAvailable(g_Lamp))
return ERR_MODULE_NOT_FOUND;
// Name
ret = CreateProperty(MM::g_Keyword_Name, name_.c_str(), MM::String, true);
if (DEVICE_OK != ret)
return ret;
// Description
ret = CreateProperty(MM::g_Keyword_Description, description_.c_str(), MM::String, true);
if (DEVICE_OK != ret)
return ret;
// Check current state of shutter:
ret = GetOpen(state_);
if (DEVICE_OK != ret)
return ret;
// State
CPropertyAction* pAct = new CPropertyAction (this, &ILShutter::OnState);
if (state_)
ret = CreateProperty(MM::g_Keyword_State, "1", MM::Integer, false, pAct);
else
ret = CreateProperty(MM::g_Keyword_State, "0", MM::Integer, false, pAct);
if (ret != DEVICE_OK)
return ret;
AddAllowedValue(MM::g_Keyword_State, "0"); // Closed
AddAllowedValue(MM::g_Keyword_State, "1"); // Open
//Label
ret = UpdateStatus();
if (ret != DEVICE_OK)
return ret;
initialized_ = true;
return DEVICE_OK;
}
bool ILShutter::Busy()
{
bool busy;
int ret = g_ScopeModel.ILShutter_.GetBusy(busy);
if (ret != DEVICE_OK) // This is bad and should not happen
return false;
return busy;
}
int ILShutter::Shutdown()
{
if (initialized_)
{
initialized_ = false;
}
return DEVICE_OK;
}
int ILShutter::SetOpen(bool open)
{
int position;
if (open)
position = 1;
else
position = 0;
int ret = g_ScopeInterface.SetILShutterPosition(*this, *GetCoreCallback(), position);
if (ret != DEVICE_OK)
return ret;
return DEVICE_OK;
}
int ILShutter::GetOpen(bool &open)
{
int position;
int ret = g_ScopeModel.ILShutter_.GetPosition(position);
if (ret != DEVICE_OK)
return ret;
if (position == 0)
open = false;
else if (position == 1)
open = true;
else
return ERR_UNEXPECTED_ANSWER;
return DEVICE_OK;
}
int ILShutter::Fire(double)
{
return DEVICE_UNSUPPORTED_COMMAND;
}
///////////////////////////////////////////////////////////////////////////////
// Action handlers
///////////////////////////////////////////////////////////////////////////////
int ILShutter::OnState(MM::PropertyBase* pProp, MM::ActionType eAct)
{
if (eAct == MM::BeforeGet)
{
// return pos as we know it
GetOpen(state_);
if (state_)
pProp->Set(1L);
else
pProp->Set(0L);
}
else if (eAct == MM::AfterSet)
{
long pos;
pProp->Get(pos);
if (pos==1)
{
return this->SetOpen(true);
}
else
{
return this->SetOpen(false);
}
}
return DEVICE_OK;
}
///////////////////////////////////////////////////////////////////////////////
// Leica Transmitted light Shutter
///////////////////////////////////////////////////////////////////////////////
TLShutter::TLShutter ():
initialized_ (false),
state_(0)
{
InitializeDefaultErrorMessages();
SetErrorText(ERR_SCOPE_NOT_ACTIVE, "Leica Scope is not initialized. It is needed for the Leica Shutter to work");
SetErrorText(ERR_MODULE_NOT_FOUND, "This shutter is not installed in this Leica microscope");
}
TLShutter::~TLShutter ()
{
Shutdown();
}
void TLShutter::GetName(char* name) const
{
assert(name_.length() < CDeviceUtils::GetMaxStringLength());
CDeviceUtils::CopyLimitedString(name, name_.c_str());
}
int TLShutter::Initialize()
{
if (!g_ScopeInterface.portInitialized_)
return ERR_SCOPE_NOT_ACTIVE;
int ret = DEVICE_OK;
if (!g_ScopeInterface.IsInitialized())
ret = g_ScopeInterface.Initialize(*this, *GetCoreCallback());
if (ret != DEVICE_OK)
return ret;
// check if this shutter exists:
if (!g_ScopeModel.IsDeviceAvailable(g_Lamp))
return ERR_MODULE_NOT_FOUND;
// Name
ret = CreateProperty(MM::g_Keyword_Name, name_.c_str(), MM::String, true);
if (DEVICE_OK != ret)
return ret;
// Description
ret = CreateProperty(MM::g_Keyword_Description, description_.c_str(), MM::String, true);
if (DEVICE_OK != ret)
return ret;
// Check current state of shutter:
ret = GetOpen(state_);
if (DEVICE_OK != ret)
return ret;
// State
CPropertyAction* pAct = new CPropertyAction (this, &TLShutter::OnState);
if (state_)
ret = CreateProperty(MM::g_Keyword_State, "1", MM::Integer, false, pAct);
else
ret = CreateProperty(MM::g_Keyword_State, "0", MM::Integer, false, pAct);
if (ret != DEVICE_OK)
return ret;
AddAllowedValue(MM::g_Keyword_State, "0"); // Closed
AddAllowedValue(MM::g_Keyword_State, "1"); // Open
//Label
ret = UpdateStatus();
if (ret != DEVICE_OK)
return ret;
initialized_ = true;
return DEVICE_OK;
}
bool TLShutter::Busy()
{
bool busy;
int ret = g_ScopeModel.TLShutter_.GetBusy(busy);
if (ret != DEVICE_OK) // This is bad and should not happen
return false;
return busy;
}
int TLShutter::Shutdown()
{
if (initialized_)
{
initialized_ = false;
}
return DEVICE_OK;
}
int TLShutter::SetOpen(bool open)
{
int position;
if (open)
position = 1;
else
position = 0;
int ret = g_ScopeInterface.SetTLShutterPosition(*this, *GetCoreCallback(), position);
if (ret != DEVICE_OK)
return ret;
return DEVICE_OK;
}
int TLShutter::GetOpen(bool &open)
{
int position;
int ret = g_ScopeModel.TLShutter_.GetPosition(position);
if (ret != DEVICE_OK)
return ret;
if (position == 0)
open = false;
else if (position == 1)
open = true;
else
return ERR_UNEXPECTED_ANSWER;
return DEVICE_OK;
}
int TLShutter::Fire(double)
{
return DEVICE_UNSUPPORTED_COMMAND;
}
///////////////////////////////////////////////////////////////////////////////
// Action handlers
///////////////////////////////////////////////////////////////////////////////
int TLShutter::OnState(MM::PropertyBase* pProp, MM::ActionType eAct)
{
if (eAct == MM::BeforeGet)
{
// return pos as we know it
GetOpen(state_);
if (state_)
pProp->Set(1L);
else
pProp->Set(0L);
}
else if (eAct == MM::AfterSet)
{
long pos;
pProp->Get(pos);
if (pos==1)
{
return this->SetOpen(true);
}
else
{
return this->SetOpen(false);
}
}
return DEVICE_OK;
}
///////////////////////////////////////////////////////////////////////////////
// ReFlected Light Turret
///////////////////////////////////////////////////////////////////////////////
ILTurret::ILTurret():
numPos_(5),
initialized_ (false),
name_("Dichroics turret"),
description_("Incident Light Reflector Turret"),
pos_(1)
{
InitializeDefaultErrorMessages();
// TODO provide error messages
SetErrorText(ERR_SCOPE_NOT_ACTIVE, "Leica Scope is not initialized. It is needed for this Turret to work");
SetErrorText(ERR_INVALID_TURRET_POSITION, "The requested position is not available on this turret");
SetErrorText(ERR_MODULE_NOT_FOUND, "This turret is not installed in this Leica microscope");
SetErrorText(ERR_TURRET_NOT_ENGAGED, "Incident Light Turret is not engaged");
// Create pre-initialization properties
// ------------------------------------
// Name
CreateProperty(MM::g_Keyword_Name, name_.c_str(), MM::String, true);
// Description
CreateProperty(MM::g_Keyword_Description, description_.c_str(), MM::String, true);
//UpdateStatus();
}
ILTurret::~ILTurret()
{
Shutdown();
}
void ILTurret::GetName(char* name) const
{
CDeviceUtils::CopyLimitedString(name, name_.c_str());
}
int ILTurret::Initialize()
{
if (!g_ScopeInterface.portInitialized_)
return ERR_SCOPE_NOT_ACTIVE;
int ret = DEVICE_OK;
if (!g_ScopeInterface.IsInitialized())
ret = g_ScopeInterface.Initialize(*this, *GetCoreCallback());
if (ret != DEVICE_OK)
return ret;
// check if this turret exists:
if (! g_ScopeModel.IsDeviceAvailable(g_IL_Turret))
return ERR_MODULE_NOT_FOUND;
// set property list
// ----------------
// State
// -----
CPropertyAction* pAct = new CPropertyAction(this, &ILTurret::OnState);
ret = CreateProperty(MM::g_Keyword_State, "1", MM::Integer, false, pAct);
if (ret != DEVICE_OK)
return ret;
// Label
// -----
pAct = new CPropertyAction(this, &CStateBase::OnLabel);
ret = CreateProperty(MM::g_Keyword_Label, "1-", MM::String, false, pAct);
if (ret != DEVICE_OK)
return ret;
// create default positions and labels
int maxPos;
ret = g_ScopeModel.ILTurret_.GetMaxPosition(maxPos);
if (ret != DEVICE_OK)
return ret;
numPos_ = maxPos;
for (unsigned i=0; i < numPos_; i++)
{
ostringstream os;
os << i+1 << "-" << g_ScopeModel.ILTurret_.cube_[i+1].name;
SetPositionLabel(i, os.str().c_str());
}
ret = UpdateStatus();
if (ret!= DEVICE_OK)
return ret;
initialized_ = true;
return DEVICE_OK;
}
int ILTurret::Shutdown()
{
if (initialized_)
initialized_ = false;
return DEVICE_OK;
}
bool ILTurret::Busy()
{
bool busy;
int ret = g_ScopeModel.ILTurret_.GetBusy(busy);
if (ret != DEVICE_OK) // This is bad and should not happen
return false;
return busy;
}
///////////////////////////////////////////////////////////////////////////////
// Action handlers
///////////////////////////////////////////////////////////////////////////////
int ILTurret::OnState(MM::PropertyBase* pProp, MM::ActionType eAct)
{
if (eAct == MM::BeforeGet)
{
int pos;
int ret = g_ScopeModel.ILTurret_.GetPosition(pos);
if (ret != DEVICE_OK)
return ret;
if (pos == 0)
return ERR_TURRET_NOT_ENGAGED;
pos_ = pos -1;
pProp->Set(pos_);
}
else if (eAct == MM::AfterSet)
{
pProp->Get(pos_);
int pos = pos_ + 1;
if ((pos > 0) && (pos <= (int) numPos_)) {
// check if the new position is allowed with this method
int method;
int ret = g_ScopeModel.method_.GetPosition(method);
if (!g_ScopeModel.ILTurret_.cube_[pos].IsMethodAvailable(method)) {
// the new cube does not support the current method. Look for a method:
// Look first in the FLUO methods, than in all available methods
int i = 10;
while (!g_ScopeModel.ILTurret_.cube_[pos].IsMethodAvailable(i) && (i < 13)) {
i++;
}
if (!g_ScopeModel.ILTurret_.cube_[pos].IsMethodAvailable(i)) {
i = 0;
while (!g_ScopeModel.ILTurret_.cube_[pos].IsMethodAvailable(i) && (i < 16)) {
i++;
}
}
if (g_ScopeModel.ILTurret_.cube_[pos].IsMethodAvailable(i))
g_ScopeInterface.SetMethod(*this, *GetCoreCallback(), i);
}
return g_ScopeInterface.SetILTurretPosition(*this, *GetCoreCallback(), pos);
} else
return ERR_INVALID_TURRET_POSITION;
}
return DEVICE_OK;
}
///////////////////////////////////////////////////////////////////////////////
// ObjectiveTurret.
///////////////////////////////////////////////////////////////////////////////
ObjectiveTurret::ObjectiveTurret() :
numPos_(7),
initialized_ (false),
name_("Objective turret"),
description_("Objective Turret"),
pos_(1)
{
InitializeDefaultErrorMessages();
// TODO provide error messages
SetErrorText(ERR_SCOPE_NOT_ACTIVE, "Leica Scope is not initialized. The Objective Turret cannot work without it");
SetErrorText(ERR_INVALID_TURRET_POSITION, "The requested position is not available");
SetErrorText(ERR_MODULE_NOT_FOUND, "No Objective turret installed in this Leica microscope");
SetErrorText(ERR_TURRET_NOT_ENGAGED, "Objective Light Turret is not engaged");
// Create pre-initialization properties
// ------------------------------------
// Name
CreateProperty(MM::g_Keyword_Name, name_.c_str(), MM::String, true);
// Description
CreateProperty(MM::g_Keyword_Description, description_.c_str(), MM::String, true);
}
ObjectiveTurret::~ObjectiveTurret()
{
Shutdown();
}
void ObjectiveTurret::GetName(char* name) const
{
CDeviceUtils::CopyLimitedString(name, name_.c_str());
}
int ObjectiveTurret::Initialize()
{
if (!g_ScopeInterface.portInitialized_)
return ERR_SCOPE_NOT_ACTIVE;
int ret = DEVICE_OK;
if (!g_ScopeInterface.IsInitialized())
ret = g_ScopeInterface.Initialize(*this, *GetCoreCallback());
if (ret != DEVICE_OK)
return ret;
// check if this turret exists:
if (! g_ScopeModel.IsDeviceAvailable(g_Revolver))
return ERR_MODULE_NOT_FOUND;
// State
// -----
CPropertyAction* pAct = new CPropertyAction(this, &ObjectiveTurret::OnState);
ret = CreateProperty(MM::g_Keyword_State, "1", MM::Integer, false, pAct);
if (ret != DEVICE_OK)
return ret;
// Label
// -----
pAct = new CPropertyAction(this, &CStateBase::OnLabel);
ret = CreateProperty(MM::g_Keyword_Label, "1-", MM::String, false, pAct);
if (ret != DEVICE_OK)
return ret;
// create default positions and labels
int maxPos;
ret = g_ScopeModel.ObjectiveTurret_.GetMaxPosition(maxPos);
if (ret != DEVICE_OK)
return ret;
numPos_ = maxPos;
for (unsigned i=0; i < numPos_; i++)
{
ostringstream os;
os << i+1 << "-" << g_ScopeModel.ObjectiveTurret_.objective_[i+1].magnification_ << "x ";
os << g_ScopeModel.ObjectiveTurret_.objective_[i+1].NA_ << "na";
SetPositionLabel(i, os.str().c_str());
}
// Article Number
// -----
pAct = new CPropertyAction(this, &ObjectiveTurret::OnArticleNumber);
ret = CreateProperty("Article Number", "", MM::String, true, pAct);
if (ret != DEVICE_OK)
return ret;
ret = UpdateStatus();
if (ret!= DEVICE_OK)
return ret;
initialized_ = true;
return DEVICE_OK;
if (ret != DEVICE_OK)
return ret;
return DEVICE_OK;
}
int ObjectiveTurret::Shutdown()
{
if (initialized_)
initialized_ = false;
return DEVICE_OK;
}
bool ObjectiveTurret::Busy()
{
bool busy;
int ret = g_ScopeModel.ObjectiveTurret_.GetBusy(busy);
if (ret != DEVICE_OK) // This is bad and should not happen
return false;
return busy;
}
int ObjectiveTurret::OnState(MM::PropertyBase* pProp, MM::ActionType eAct)
{
if (eAct == MM::BeforeGet)
{
int pos;
int ret = g_ScopeModel.ObjectiveTurret_.GetPosition(pos);
if (ret != DEVICE_OK)
return ret;
if (pos == 0)
return ERR_TURRET_NOT_ENGAGED;
pos_ = pos -1;
pProp->Set(pos_);
}
else if (eAct == MM::AfterSet)
{
pProp->Get(pos_);
int pos = pos_ + 1;
if ((pos > 0) && (pos <= (int) numPos_)) {
// check if the new position is allowed with this method
int method;
int ret = g_ScopeModel.method_.GetPosition(method);
if (!g_ScopeModel.ObjectiveTurret_.objective_[pos].IsMethodAvailable(method)) {
// the new cube does not support the current method. Look for a method:
// Look first in the FLUO methods, than in all available methods
int i = 10;
while (!g_ScopeModel.ObjectiveTurret_.objective_[pos].IsMethodAvailable(i) && i < 13) {
i++;
}
if (!g_ScopeModel.ObjectiveTurret_.objective_[pos].IsMethodAvailable(i)) {
int i = 0;
while (!g_ScopeModel.ObjectiveTurret_.objective_[pos].IsMethodAvailable(i) && i < 16) {
i++;
}
}
if (g_ScopeModel.ObjectiveTurret_.objective_[pos].IsMethodAvailable(i))
g_ScopeInterface.SetMethod(*this, *GetCoreCallback(), i);
}
return g_ScopeInterface.SetRevolverPosition(*this, *GetCoreCallback(), pos);
} else
return ERR_INVALID_TURRET_POSITION;
}
return DEVICE_OK;
}
int ObjectiveTurret::OnArticleNumber(MM::PropertyBase* pProp, MM::ActionType eAct)
{
if (eAct == MM::BeforeGet)
{
int pos;
int ret = g_ScopeModel.ObjectiveTurret_.GetPosition(pos);
if (ret != DEVICE_OK)
return ret;
if (pos == 0)
return ERR_TURRET_NOT_ENGAGED;
ostringstream os;
os << g_ScopeModel.ObjectiveTurret_.objective_[pos].articleNumber_;
pProp->Set(os.str().c_str());
}
return DEVICE_OK;
}
/*
* LeicaFocusStage: Micro-Manager implementation of focus drive
*/
ZDrive::ZDrive ():
initialized_(false),
name_("ZDrive"),
description_("Focus Drive")
{
InitializeDefaultErrorMessages();
SetErrorText(ERR_SCOPE_NOT_ACTIVE, "Leica Scope is not initialized. It is needed for the Leica Shutter to work");
SetErrorText(ERR_MODULE_NOT_FOUND, "No ZDrive found in this Leica microscope");
}
ZDrive::~ZDrive()
{
Shutdown();
}
bool ZDrive::Busy()
{
bool busy;
int ret = g_ScopeModel.ZDrive_.GetBusy(busy);
if (ret != DEVICE_OK) // This is bad and should not happen
return false;
return busy;
}
void ZDrive::GetName (char* Name) const
{
CDeviceUtils::CopyLimitedString(Name, g_LeicaFocusAxis);
}
int ZDrive::Initialize()
{
if (!g_ScopeInterface.portInitialized_)
return ERR_SCOPE_NOT_ACTIVE;
int ret = DEVICE_OK;
if (!g_ScopeInterface.IsInitialized())
ret = g_ScopeInterface.Initialize(*this, *GetCoreCallback());
if (ret != DEVICE_OK)
return ret;
// check if this turret exists:
if (! g_ScopeModel.IsDeviceAvailable(g_ZDrive))
return ERR_MODULE_NOT_FOUND;
// Acceleration
CPropertyAction* pAct = new CPropertyAction(this, &ZDrive::OnAcceleration);
ret = CreateProperty("Acceleration", "1", MM::Integer, false, pAct);
if (ret != DEVICE_OK)
return ret;
SetPropertyLimits("Acceleration", g_ScopeModel.ZDrive_.GetMinRamp(), g_ScopeModel.ZDrive_.GetMaxRamp());
// Speed
pAct = new CPropertyAction(this, &ZDrive::OnSpeed);
ret = CreateProperty("Speed", "1", MM::Integer, false, pAct);
if (ret != DEVICE_OK)
return ret;
SetPropertyLimits("Speed", g_ScopeModel.ZDrive_.GetMinSpeed(), g_ScopeModel.ZDrive_.GetMaxSpeed());
ret = UpdateStatus();
if (ret!= DEVICE_OK)
return ret;
initialized_ = true;
return DEVICE_OK;
}
int ZDrive::Shutdown()
{
if (initialized_)
initialized_ = false;
return DEVICE_OK;
}
int ZDrive::SetPositionUm(double pos)
{
long steps = (long)(pos / g_ScopeModel.ZDrive_.GetStepSize());
int ret = SetPositionSteps(steps);
if (ret != DEVICE_OK)
return ret;
return DEVICE_OK;
}
int ZDrive::GetPositionUm(double& pos)
{
long steps;
int ret = GetPositionSteps(steps);
if (ret != DEVICE_OK)
return ret;
pos = steps * g_ScopeModel.ZDrive_.GetStepSize();
return DEVICE_OK;
}
int ZDrive::SetPositionSteps(long steps)
{
return g_ScopeInterface.SetDrivePosition(*this, *GetCoreCallback(), g_ScopeModel.ZDrive_, g_ZDrive, (int) steps);
}
int ZDrive::GetPositionSteps(long& steps)
{
return g_ScopeModel.ZDrive_.GetPosition((int&) steps);
}
int ZDrive::SetOrigin()
{
return DEVICE_OK;
}
int ZDrive::GetLimits(double& lower, double& upper)
{
int min, max;
g_ScopeModel.ZDrive_.GetMinPosition(min);
g_ScopeModel.ZDrive_.GetMaxPosition(max);
lower = min * g_ScopeModel.ZDrive_.GetStepSize();
upper = max * g_ScopeModel.ZDrive_.GetStepSize();
return DEVICE_OK;
}
int ZDrive::Home()
{
// TODO: Implement!
return DEVICE_OK;
}
int ZDrive::Stop()
{
// TODO: Implement!
return DEVICE_OK;
}
int ZDrive::OnAcceleration(MM::PropertyBase* pProp, MM::ActionType eAct)
{
if (eAct == MM::BeforeGet) {
int acc;
int ret = g_ScopeModel.ZDrive_.GetRamp(acc);
if (ret != DEVICE_OK)
return ret;
pProp->Set((long)acc);
}
else if (eAct == MM::AfterSet)
{
long acc;
pProp->Get(acc);
int ret = g_ScopeInterface.SetDriveAcceleration(*this, *GetCoreCallback(), g_ScopeModel.ZDrive_, g_ZDrive, (int) acc);
if (ret != DEVICE_OK)
return ret;
}
return DEVICE_OK;
}
int ZDrive::OnSpeed(MM::PropertyBase* pProp, MM::ActionType eAct)
{
if (eAct == MM::BeforeGet) {
int speed;
int ret = g_ScopeModel.ZDrive_.GetSpeed(speed);
if (ret != DEVICE_OK)
return ret;
pProp->Set((long)speed);
}
else if (eAct == MM::AfterSet)
{
long speed;
pProp->Get(speed);
int ret = g_ScopeInterface.SetDriveSpeed(*this, *GetCoreCallback(), g_ScopeModel.ZDrive_, g_ZDrive, (int) speed);
if (ret != DEVICE_OK)
return ret;
}
return DEVICE_OK;
}
/*
* LeicaXYStage: Micro-Manager implementation of X and Y Stage
*/
XYStage::XYStage ():
CXYStageBase<XYStage>(),
busy_ (false),
initialized_ (false),
originXSteps_(0),
originYSteps_(0),
mirrorX_(false),
mirrorY_(false)
{
name_ = g_LeicaXYStage;
InitializeDefaultErrorMessages();
SetErrorText(ERR_SCOPE_NOT_ACTIVE, "Leica Scope is not initialized. It is needed for the Leica XYStage to work");
SetErrorText(ERR_MODULE_NOT_FOUND, "No XYStage installed on this Leica microscope");
}
XYStage::~XYStage()
{
Shutdown();
}
bool XYStage::Busy()
{
bool xBusy = false;
bool yBusy = false;
int ret = g_ScopeModel.XDrive_.GetBusy(xBusy);
if (ret != DEVICE_OK)
return false;
ret = g_ScopeModel.YDrive_.GetBusy(yBusy);
if (ret != DEVICE_OK) // This is bad and should not happen
return false;
return (xBusy || yBusy);
}
void XYStage::GetName (char* Name) const
{
CDeviceUtils::CopyLimitedString(Name, g_LeicaXYStage);
}
int XYStage::Initialize()
{
if (!g_ScopeInterface.portInitialized_)
return ERR_SCOPE_NOT_ACTIVE;
int ret = DEVICE_OK;
if (!g_ScopeInterface.IsInitialized())
ret = g_ScopeInterface.Initialize(*this, *GetCoreCallback());
if (ret != DEVICE_OK)
return ret;
// check if the XY stage exists
if (! (g_ScopeModel.IsDeviceAvailable(g_XDrive) && g_ScopeModel.IsDeviceAvailable(g_YDrive)))
return ERR_MODULE_NOT_FOUND;
// Acceleration
CPropertyAction* pAct = new CPropertyAction(this, &XYStage::OnAcceleration);
ret = CreateProperty("Acceleration", "1", MM::Integer, false, pAct);
if (ret != DEVICE_OK)
return ret;
int minRamp = g_ScopeModel.XDrive_.GetMinRamp();
if (g_ScopeModel.YDrive_.GetMinRamp() > minRamp)
minRamp = g_ScopeModel.YDrive_.GetMinRamp();
int maxRamp = g_ScopeModel.XDrive_.GetMaxRamp();
if (g_ScopeModel.YDrive_.GetMaxRamp() < maxRamp)
maxRamp = g_ScopeModel.YDrive_.GetMaxRamp();
SetPropertyLimits("Acceleration", minRamp, maxRamp);
// Speed
pAct = new CPropertyAction(this, &XYStage::OnSpeed);
ret = CreateProperty("Speed", "1", MM::Integer, false, pAct);
if (ret != DEVICE_OK)
return ret;
int minSpeed = g_ScopeModel.XDrive_.GetMinSpeed();
if (g_ScopeModel.YDrive_.GetMinSpeed() > minSpeed)
minSpeed = g_ScopeModel.YDrive_.GetMinSpeed();
int maxSpeed = g_ScopeModel.XDrive_.GetMaxSpeed();
if (g_ScopeModel.YDrive_.GetMaxSpeed() < maxSpeed)
maxSpeed = g_ScopeModel.YDrive_.GetMaxSpeed();
SetPropertyLimits("Speed", minSpeed, maxSpeed);
// Directionality
pAct = new CPropertyAction (this, &XYStage::OnMirrorX);
CreateProperty("MirrorX", "0", MM::Integer, false, pAct);
AddAllowedValue("MirrorX", "0");
AddAllowedValue("MirrorX", "1");
pAct = new CPropertyAction (this, &XYStage::OnMirrorY);
CreateProperty("MirrorY", "0", MM::Integer, false, pAct);
AddAllowedValue("MirrorY", "0");
AddAllowedValue("MirrorY", "1");
ret = UpdateStatus();
if (ret!= DEVICE_OK)
return ret;
initialized_ = true;
return DEVICE_OK;
}
int XYStage::Shutdown()
{
if (initialized_) initialized_ = false;
return DEVICE_OK;
}
int XYStage::GetLimitsUm(double& xMin, double& xMax, double& yMin, double& yMax)
{
int xMinStep, yMinStep, xMaxStep, yMaxStep;
g_ScopeModel.XDrive_.GetMinPosition(xMinStep);
xMin = xMinStep * g_ScopeModel.XDrive_.GetStepSize();
g_ScopeModel.YDrive_.GetMinPosition(yMinStep);
yMin = yMinStep * g_ScopeModel.YDrive_.GetStepSize();
g_ScopeModel.XDrive_.GetMaxPosition(xMaxStep);
xMax = xMaxStep * g_ScopeModel.XDrive_.GetStepSize();
g_ScopeModel.YDrive_.GetMaxPosition(yMaxStep);
yMax = yMaxStep * g_ScopeModel.YDrive_.GetStepSize();
return DEVICE_OK;
}
int XYStage::GetStepLimits(long& xMin, long& xMax, long& yMin, long& yMax)
{
int xMinStep, yMinStep, xMaxStep, yMaxStep;
g_ScopeModel.XDrive_.GetMinPosition(xMinStep);
g_ScopeModel.YDrive_.GetMinPosition(yMinStep);
g_ScopeModel.XDrive_.GetMaxPosition(xMaxStep);
g_ScopeModel.YDrive_.GetMaxPosition(yMaxStep);
xMin = xMinStep;
yMin = yMinStep;
xMax = xMaxStep;
yMax = yMaxStep;
return DEVICE_OK;
}
double XYStage::GetStepSizeXUm()
{
return g_ScopeModel.XDrive_.GetStepSize();
}
double XYStage::GetStepSizeYUm()
{
return g_ScopeModel.YDrive_.GetStepSize();
}
int XYStage::SetPositionUm(double x, double y)
{
long xSteps = 0;
long ySteps = 0;
/*
long xSteps = (long)(x / g_ScopeModel.XDrive_.GetStepSize());
long ySteps = (long)(y / g_ScopeModel.XDrive_.GetStepSize());
*/
if (mirrorX_)
xSteps = (long) (originXSteps_ - (x / g_ScopeModel.XDrive_.GetStepSize() + 0.5));
else
xSteps = (long) (originXSteps_ + (x / g_ScopeModel.XDrive_.GetStepSize() + 0.5));
if (mirrorY_)
ySteps = (long) (originYSteps_ - (x / g_ScopeModel.XDrive_.GetStepSize() + 0.5));
else
ySteps = (long) (originYSteps_ + (x / g_ScopeModel.XDrive_.GetStepSize() + 0.5));
return SetPositionSteps(xSteps, ySteps);
}
int XYStage::SetRelativePositionUm(double x, double y)
{
/*
long xSteps = (long)(x / g_ScopeModel.XDrive_.GetStepSize());
long ySteps = (long)(y / g_ScopeModel.XDrive_.GetStepSize());
*/
long xSteps = (long) (x / g_ScopeModel.XDrive_.GetStepSize() + 0.5);
if (mirrorX_)
xSteps = -xSteps;
long ySteps = (long) (y / g_ScopeModel.XDrive_.GetStepSize() + 0.5);
if (mirrorY_)
ySteps = -ySteps;
return SetRelativePositionSteps(xSteps, ySteps);
}
int XYStage::GetPositionUm(double& x, double& y)
{
long xSteps, ySteps;
int ret = GetPositionSteps(xSteps, ySteps);
if (ret != DEVICE_OK)
return ret;
/*
x = xSteps * g_ScopeModel.XDrive_.GetStepSize();
y = ySteps * g_ScopeModel.XDrive_.GetStepSize();
*/
if (mirrorX_)
x = (xSteps - originXSteps_) * g_ScopeModel.XDrive_.GetStepSize();
else
x = - (xSteps - originXSteps_) * g_ScopeModel.XDrive_.GetStepSize();
if (mirrorY_)
y = (ySteps - originYSteps_) * g_ScopeModel.XDrive_.GetStepSize();
else
y = - (ySteps - originYSteps_) * g_ScopeModel.XDrive_.GetStepSize();
return DEVICE_OK;
}
int XYStage::SetPositionSteps(long xSteps, long ySteps)
{
int ret = g_ScopeInterface.SetDrivePosition(*this, *GetCoreCallback(), g_ScopeModel.XDrive_, g_XDrive, xSteps);
if (ret != DEVICE_OK)
return ret;
ret = g_ScopeInterface.SetDrivePosition(*this, *GetCoreCallback(), g_ScopeModel.YDrive_, g_YDrive, ySteps);
if (ret != DEVICE_OK)
return ret;
return DEVICE_OK;
}
int XYStage::SetRelativePositionSteps(long xSteps, long ySteps)
{
int ret = g_ScopeInterface.SetDrivePositionRelative(*this, *GetCoreCallback(), g_ScopeModel.XDrive_, g_XDrive, xSteps);
if (ret != DEVICE_OK)
return ret;
ret = g_ScopeInterface.SetDrivePositionRelative(*this, *GetCoreCallback(), g_ScopeModel.YDrive_, g_YDrive, ySteps);
if (ret != DEVICE_OK)
return ret;
return DEVICE_OK;
}
int XYStage::GetPositionSteps(long& xSteps, long& ySteps)
{
int ret = g_ScopeModel.XDrive_.GetPosition((int&) xSteps);
if (ret != DEVICE_OK)
return ret;
ret = g_ScopeModel.YDrive_.GetPosition((int&) ySteps);
if (ret != DEVICE_OK)
return ret;
return DEVICE_OK;
}
/**
* Defines position x,y (relative to current position) as the origin of our coordinate system
* Get the current (stage-native) XY position
*/
int XYStage::SetAdapterOriginUm(double x, double y)
{
long xStep, yStep;
int ret = GetPositionSteps(xStep, yStep);
if (ret != DEVICE_OK)
return ret;
originXSteps_ = (long) (xStep + (x / g_ScopeModel.XDrive_.GetStepSize()));
originYSteps_ = (long) (yStep + (y / g_ScopeModel.XDrive_.GetStepSize()));
return DEVICE_OK;
}
int XYStage::Home()
{
int ret = g_ScopeInterface.HomeDrive(*this, *GetCoreCallback(), g_ScopeModel.XDrive_, g_XDrive);
if (ret != DEVICE_OK)
return ret;
ret = g_ScopeInterface.HomeDrive(*this, *GetCoreCallback(), g_ScopeModel.YDrive_, g_YDrive);
if (ret != DEVICE_OK)
return ret;
return DEVICE_OK;
}
int XYStage::Stop()
{
int ret = g_ScopeInterface.StopDrive(*this, *GetCoreCallback(), g_ScopeModel.XDrive_, g_XDrive);
if (ret != DEVICE_OK)
return ret;
ret = g_ScopeInterface.StopDrive(*this, *GetCoreCallback(), g_ScopeModel.YDrive_, g_YDrive);
if (ret != DEVICE_OK)
return ret;
return DEVICE_OK;
}
int XYStage::SetOrigin()
{
return SetAdapterOriginUm(0,0);
}
int XYStage::OnAcceleration(MM::PropertyBase* pProp, MM::ActionType eAct)
{
if (eAct == MM::BeforeGet) {
int acc;
int ret = g_ScopeModel.XDrive_.GetRamp(acc);
if (ret != DEVICE_OK)
return ret;
// assume that YDrive ramp is the same
pProp->Set((long)acc);
}
else if (eAct == MM::AfterSet)
{
long acc;
pProp->Get(acc);
int ret = g_ScopeInterface.SetDriveAcceleration(*this, *GetCoreCallback(), g_ScopeModel.XDrive_, g_XDrive, (int) acc);
if (ret != DEVICE_OK)
return ret;
ret = g_ScopeInterface.SetDriveAcceleration(*this, *GetCoreCallback(), g_ScopeModel.YDrive_, g_YDrive, (int) acc);
if (ret != DEVICE_OK)
return ret;
}
return DEVICE_OK;
}
int XYStage::OnSpeed(MM::PropertyBase* pProp, MM::ActionType eAct)
{
if (eAct == MM::BeforeGet) {
int speed;
int ret = g_ScopeModel.XDrive_.GetSpeed(speed);
if (ret != DEVICE_OK)
return ret;
// Assume Y-drive has the same setting
pProp->Set((long)speed);
}
else if (eAct == MM::AfterSet)
{
long speed;
pProp->Get(speed);
int ret = g_ScopeInterface.SetDriveSpeed(*this, *GetCoreCallback(), g_ScopeModel.XDrive_, g_XDrive, (int) speed);
if (ret != DEVICE_OK)
return ret;
ret = g_ScopeInterface.SetDriveSpeed(*this, *GetCoreCallback(), g_ScopeModel.YDrive_, g_YDrive, (int) speed);
if (ret != DEVICE_OK)
return ret;
}
return DEVICE_OK;
}
int XYStage::OnMirrorX(MM::PropertyBase* pProp, MM::ActionType eAct)
{
if (eAct == MM::BeforeGet)
{
if (mirrorX_)
pProp->Set("1");
else
pProp->Set("0");
} else if (eAct == MM::AfterSet) {
long mirrorX;
pProp->Get(mirrorX);
if (mirrorX == 1)
mirrorX_ = true;
else
mirrorX_ = false;
}
return DEVICE_OK;
}
int XYStage::OnMirrorY(MM::PropertyBase* pProp, MM::ActionType eAct)
{
if (eAct == MM::BeforeGet)
{
if (mirrorY_)
pProp->Set("1");
else
pProp->Set("0");
} else if (eAct == MM::AfterSet) {
long mirrorY;
pProp->Get(mirrorY);
if (mirrorY == 1)
mirrorY_ = true;
else
mirrorY_ = false;
}
return DEVICE_OK;
}
///////////////////////////////////////////////////////////////////////////////
// General Diaphragm Object, implements all Diaphragms.
///////////////////////////////////////////////////////////////////////////////
Diaphragm::Diaphragm(LeicaDeviceModel* diaphragm, int deviceID, std::string name):
numPos_(5),
initialized_ (false)
{
diaphragm_ = diaphragm;
deviceID_ = deviceID;
name_ = name;
InitializeDefaultErrorMessages();
// TODO provide error messages
SetErrorText(ERR_SCOPE_NOT_ACTIVE, "Leica Scope is not initialized. It is needed for this Diaphrgam to work");
SetErrorText(ERR_INVALID_TURRET_POSITION, "The requested position is not available on this Diaphragm");
SetErrorText(ERR_MODULE_NOT_FOUND, "This Diaphragm is not installed in this Leica microscope");
// Create pre-initialization properties
// ------------------------------------
// Name
CreateProperty(MM::g_Keyword_Name, name_.c_str(), MM::String, true);
}
Diaphragm::~Diaphragm()
{
Shutdown();
}
void Diaphragm::GetName(char* name) const
{
assert(name_.length() < CDeviceUtils::GetMaxStringLength());
CDeviceUtils::CopyLimitedString(name, name_.c_str());
}
int Diaphragm::Initialize()
{
if (!g_ScopeInterface.portInitialized_)
return ERR_SCOPE_NOT_ACTIVE;
int ret = DEVICE_OK;
if (!g_ScopeInterface.IsInitialized())
ret = g_ScopeInterface.Initialize(*this, *GetCoreCallback());
if (ret != DEVICE_OK)
return ret;
// check if this turret exists:
if (! g_ScopeModel.IsDeviceAvailable(deviceID_))
return ERR_MODULE_NOT_FOUND;
// Position
// -----
CPropertyAction* pAct = new CPropertyAction(this, &Diaphragm::OnPosition);
ret = CreateProperty("Position", "1", MM::Integer, false, pAct);
if (ret != DEVICE_OK)
return ret;
int max, min;
diaphragm_->GetMaxPosition(max);
diaphragm_->GetMinPosition(min);
ret = SetPropertyLimits("Position", min, max);
if (ret != DEVICE_OK)
return ret;
numPos_ = max;
ret = UpdateStatus();
if (ret!= DEVICE_OK)
return ret;
initialized_ = true;
return DEVICE_OK;
}
int Diaphragm::Shutdown()
{
if (initialized_)
initialized_ = false;
return DEVICE_OK;
}
bool Diaphragm::Busy()
{
bool busy;
int ret = diaphragm_->GetBusy(busy);
if (ret != DEVICE_OK) // This is bad and should not happen
return false;
return busy;
}
///////////////////////////////////////////////////////////////////////////////
// Action handlers
///////////////////////////////////////////////////////////////////////////////
int Diaphragm::OnPosition(MM::PropertyBase* pProp, MM::ActionType eAct)
{
if (eAct == MM::BeforeGet)
{
int pos;
int ret = diaphragm_->GetPosition(pos);
if (ret != DEVICE_OK)
return ret;
if (pos == 0)
return ERR_TURRET_NOT_ENGAGED;
pProp->Set((long) pos);
}
else if (eAct == MM::AfterSet)
{
long pos;
pProp->Get(pos);
if ((pos > 0) && (pos <= (int) numPos_)) {
return g_ScopeInterface.SetDiaphragmPosition(*this, *GetCoreCallback(), diaphragm_, deviceID_, (int) pos);
} else
return ERR_INVALID_TURRET_POSITION;
}
return DEVICE_OK;
}
///////////////////////////////////////////////////////////////////////////////
// Motorized Tube lens switcher (magnifier)
///////////////////////////////////////////////////////////////////////////////
MagChanger::MagChanger() :
numPos_(4),
initialized_ (false),
name_("Magnifier"),
description_("Motorized Magnifier"),
pos_(1)
{
InitializeDefaultErrorMessages();
// TODO provide error messages
SetErrorText(ERR_SCOPE_NOT_ACTIVE, "Leica Scope is not initialized. ");
SetErrorText(ERR_INVALID_TURRET_POSITION, "The requested position is not available on this motorized magnifier");
SetErrorText(ERR_MODULE_NOT_FOUND, "No motorized magnifier installed in this Leica microscope");
SetErrorText(ERR_MAGNIFIER_NOT_ENGAGED, "Magnifier is not engaged");
// Create pre-initialization properties
// ------------------------------------
// Name
CreateProperty(MM::g_Keyword_Name, name_.c_str(), MM::String, true);
// Description
CreateProperty(MM::g_Keyword_Description, description_.c_str(), MM::String, true);
}
MagChanger::~MagChanger()
{
Shutdown();
}
void MagChanger::GetName(char* name) const
{
CDeviceUtils::CopyLimitedString(name, name_.c_str());
}
int MagChanger::Initialize()
{
if (!g_ScopeInterface.portInitialized_)
return ERR_SCOPE_NOT_ACTIVE;
int ret = DEVICE_OK;
if (!g_ScopeInterface.IsInitialized())
ret = g_ScopeInterface.Initialize(*this, *GetCoreCallback());
if (ret != DEVICE_OK)
return ret;
// check if this turret exists:
if (! g_ScopeModel.IsDeviceAvailable(g_Mag_Changer_Mot))
return ERR_MODULE_NOT_FOUND;
// set property list
// ----------------
// Position
// -----
CPropertyAction* pAct = new CPropertyAction(this, &MagChanger::OnPosition);
ret = CreateProperty("Position", "1", MM::String, false, pAct);
if (ret != DEVICE_OK)
return ret;
int minPos, maxPos;
ret = g_ScopeModel.magChanger_.GetMaxPosition(maxPos);
if (ret != DEVICE_OK)
return ret;
numPos_ = maxPos;
ret = g_ScopeModel.magChanger_.GetMinPosition(minPos);
if (ret != DEVICE_OK)
return ret;
// create default positions and labels
for (unsigned i=minPos; i <= numPos_; i++)
{
ostringstream os;
double mag;
g_ScopeModel.magChanger_.GetMagnification(i, mag);
os << i << "-" << mag << "x";
AddAllowedValue("Position", os.str().c_str());
}
ret = UpdateStatus();
if (ret!= DEVICE_OK)
return ret;
initialized_ = true;
return DEVICE_OK;
}
int MagChanger::Shutdown()
{
if (initialized_)
initialized_ = false;
return DEVICE_OK;
}
bool MagChanger::Busy()
{
bool busy;
int ret = g_ScopeModel.magChanger_.GetBusy(busy);
if (ret != DEVICE_OK) // This is bad and should not happen
return false;
return busy;
}
double MagChanger::GetMagnification()
{
int pos;
g_ScopeModel.magChanger_.GetPosition(pos);
double mag;
g_ScopeModel.magChanger_.GetMagnification(pos, mag);
return mag;
}
///////////////////////////////////////////////////////////////////////////////
// Action handlers
///////////////////////////////////////////////////////////////////////////////
int MagChanger::OnPosition(MM::PropertyBase* pProp, MM::ActionType eAct)
{
if (eAct == MM::BeforeGet)
{
int pos;
int ret = g_ScopeModel.magChanger_.GetPosition(pos);
if (ret != DEVICE_OK)
return ret;
if (pos == 0)
return ERR_TURRET_NOT_ENGAGED;
ostringstream os;
double mag;
g_ScopeModel.magChanger_.GetMagnification(pos, mag);
os << pos << "-" << mag << "x";
pProp->Set(os.str().c_str());
}
else if (eAct == MM::AfterSet)
{
std::string label;
pProp->Get(label);
std::stringstream st(label);
int pos;
st >> pos;
if ((pos > 0) && (pos <= (int) numPos_)) {
return g_ScopeInterface.SetMagChangerPosition(*this, *GetCoreCallback(), pos);
} else
return ERR_INVALID_TURRET_POSITION;
}
return DEVICE_OK;
}
///////////////////////////////////////////////////////////////////////////////
// TL Polarizer (the one in the transmitted light path??)
///////////////////////////////////////////////////////////////////////////////
TLPolarizer::TLPolarizer():
numPos_(1),
initialized_ (false),
name_("TL Polarizer"),
description_("Transmitted light Polarizer"),
pos_(1)
{
InitializeDefaultErrorMessages();
// TODO provide error messages
SetErrorText(ERR_SCOPE_NOT_ACTIVE, "Leica Scope is not initialized. It is needed for this Turret to work");
SetErrorText(ERR_INVALID_TURRET_POSITION, "The requested position is not available on this turret");
SetErrorText(ERR_MODULE_NOT_FOUND, "This turret is not installed in this Leica microscope");
// Create pre-initialization properties
// ------------------------------------
// Name
CreateProperty(MM::g_Keyword_Name, name_.c_str(), MM::String, true);
// Description
CreateProperty(MM::g_Keyword_Description, description_.c_str(), MM::String, true);
}
TLPolarizer::~TLPolarizer()
{
Shutdown();
}
void TLPolarizer::GetName(char* name) const
{
CDeviceUtils::CopyLimitedString(name, name_.c_str());
}
int TLPolarizer::Initialize()
{
if (!g_ScopeInterface.portInitialized_)
return ERR_SCOPE_NOT_ACTIVE;
int ret = DEVICE_OK;
if (!g_ScopeInterface.IsInitialized())
ret = g_ScopeInterface.Initialize(*this, *GetCoreCallback());
if (ret != DEVICE_OK)
return ret;
// check if this turret exists:
if (! g_ScopeModel.IsDeviceAvailable(g_TL_Polarizer))
return ERR_MODULE_NOT_FOUND;
// set property list
// ----------------
// State
// -----
CPropertyAction* pAct = new CPropertyAction(this, &TLPolarizer::OnState);
ret = CreateProperty(MM::g_Keyword_State, "1", MM::Integer, false, pAct);
if (ret != DEVICE_OK)
return ret;
// Label
// -----
pAct = new CPropertyAction(this, &CStateBase::OnLabel);
ret = CreateProperty(MM::g_Keyword_Label, "1-", MM::String, false, pAct);
if (ret != DEVICE_OK)
return ret;
// create default positions and labels
int maxPos;
ret = g_ScopeModel.ILTurret_.GetMaxPosition(maxPos);
if (ret != DEVICE_OK)
return ret;
numPos_ = maxPos;
SetPositionLabel(0, "Out");
SetPositionLabel(1, "In");
ret = UpdateStatus();
if (ret!= DEVICE_OK)
return ret;
initialized_ = true;
return DEVICE_OK;
}
int TLPolarizer::Shutdown()
{
if (initialized_)
initialized_ = false;
return DEVICE_OK;
}
bool TLPolarizer::Busy()
{
bool busy;
int ret = g_ScopeModel.tlPolarizer_.GetBusy(busy);
if (ret != DEVICE_OK) // This is bad and should not happen
return false;
return busy;
}
///////////////////////////////////////////////////////////////////////////////
// Action handlers
///////////////////////////////////////////////////////////////////////////////
int TLPolarizer::OnState(MM::PropertyBase* pProp, MM::ActionType eAct)
{
if (eAct == MM::BeforeGet)
{
int pos;
int ret = g_ScopeModel.tlPolarizer_.GetPosition(pos);
if (ret != DEVICE_OK)
return ret;
pos_ = pos;
pProp->Set(pos_);
}
else if (eAct == MM::AfterSet)
{
pProp->Get(pos_);
return g_ScopeInterface.SetTLPolarizerPosition(*this, *GetCoreCallback(), pos_);
}
return DEVICE_OK;
}
///////////////////////////////////////////////////////////////////////////////
// DIC Turret
///////////////////////////////////////////////////////////////////////////////
DICTurret::DICTurret():
numPos_(4),
initialized_ (false),
name_("DIC Turret"),
description_("DIC Prism Turret"),
pos_(1)
{
InitializeDefaultErrorMessages();
// TODO provide error messages
SetErrorText(ERR_SCOPE_NOT_ACTIVE, "Leica Scope is not initialized. It is needed for this Turret to work");
SetErrorText(ERR_INVALID_TURRET_POSITION, "The requested position is not available on this turret");
SetErrorText(ERR_MODULE_NOT_FOUND, "This turret is not installed in this Leica microscope");
// Create pre-initialization properties
// ------------------------------------
// Name
CreateProperty(MM::g_Keyword_Name, name_.c_str(), MM::String, true);
// Description
CreateProperty(MM::g_Keyword_Description, description_.c_str(), MM::String, true);
}
DICTurret::~DICTurret()
{
Shutdown();
}
void DICTurret::GetName(char* name) const
{
CDeviceUtils::CopyLimitedString(name, name_.c_str());
}
int DICTurret::Initialize()
{
if (!g_ScopeInterface.portInitialized_)
return ERR_SCOPE_NOT_ACTIVE;
int ret = DEVICE_OK;
if (!g_ScopeInterface.IsInitialized())
ret = g_ScopeInterface.Initialize(*this, *GetCoreCallback());
if (ret != DEVICE_OK)
return ret;
// check if this turret exists:
if (! g_ScopeModel.IsDeviceAvailable(g_DIC_Turret))
return ERR_MODULE_NOT_FOUND;
// set property list
// ----------------
// State
// -----
CPropertyAction* pAct = new CPropertyAction(this, &DICTurret::OnState);
if (g_ScopeModel.dicTurret_.isMotorized())
ret = CreateProperty(MM::g_Keyword_State, "1", MM::Integer, false, pAct);
else
ret = CreateProperty(MM::g_Keyword_State, "1", MM::Integer, true, pAct);
if (ret != DEVICE_OK)
return ret;
// Label
// -----
pAct = new CPropertyAction(this, &CStateBase::OnLabel);
ret = CreateProperty(MM::g_Keyword_Label, "1-", MM::String, false, pAct);
if (ret != DEVICE_OK)
return ret;
// create default positions and labels
int minPos, maxPos;
ret = g_ScopeModel.dicTurret_.GetMaxPosition(maxPos);
if (ret != DEVICE_OK)
return ret;
ret = g_ScopeModel.dicTurret_.GetMinPosition(minPos);
if (ret != DEVICE_OK)
return ret;
numPos_ = maxPos;
for (unsigned i=minPos; i <= maxPos; i++)
{
ostringstream os;
os << i << "-" << g_ScopeModel.dicTurret_.prismName_[i];
SetPositionLabel(i-minPos, os.str().c_str());
}
// Fine Position
// -----
if (g_ScopeModel.dicTurret_.isMotorized()) {
pAct = new CPropertyAction(this, &DICTurret::OnPrismFinePosition);
ret = CreateProperty("Prism Fine Position", "0.5", MM::Float, false, pAct);
if (ret != DEVICE_OK)
return ret;
}
int max, min;
min = g_ScopeModel.dicTurret_.GetMinFinePosition();
max = g_ScopeModel.dicTurret_.GetMaxFinePosition();
ret = SetPropertyLimits("Prism Fine Position", min, max);
if (ret != DEVICE_OK)
return ret;
ret =
ret = UpdateStatus();
if (ret!= DEVICE_OK)
return ret;
initialized_ = true;
return DEVICE_OK;
}
int DICTurret::Shutdown()
{
if (initialized_)
initialized_ = false;
return DEVICE_OK;
}
bool DICTurret::Busy()
{
bool busy;
int ret = g_ScopeModel.dicTurret_.GetBusy(busy);
if (ret != DEVICE_OK) // This is bad and should not happen
return false;
return busy;
}
///////////////////////////////////////////////////////////////////////////////
// Action handlers
///////////////////////////////////////////////////////////////////////////////
int DICTurret::OnState(MM::PropertyBase* pProp, MM::ActionType eAct)
{
if (eAct == MM::BeforeGet)
{
int pos;
int ret = g_ScopeModel.dicTurret_.GetPosition(pos);
if (ret != DEVICE_OK)
return ret;
pos_ = pos;
pProp->Set(pos_ - 1);
}
else if (eAct == MM::AfterSet)
{
pProp->Get(pos_);
return g_ScopeInterface.SetDICPrismTurretPosition(*this, *GetCoreCallback(), pos_ + 1);
}
return DEVICE_OK;
}
int DICTurret::OnPrismFinePosition(MM::PropertyBase* pProp, MM::ActionType eAct)
{
if (eAct == MM::BeforeGet)
{
int finePos;
int ret = g_ScopeModel.dicTurret_.GetFinePosition(finePos);
if (ret != DEVICE_OK)
return ret;
finePos_ = finePos;
pProp->Set(finePos_);
}
else if (eAct == MM::AfterSet)
{
pProp->Get(finePos_);
return g_ScopeInterface.SetDICPrismFinePosition(*this, *GetCoreCallback(), finePos_);
}
return DEVICE_OK;
}
///////////////////////////////////////////////////////////////////////////////
// Condensor Turret
///////////////////////////////////////////////////////////////////////////////
CondensorTurret::CondensorTurret():
numPos_(7),
initialized_ (false),
name_("Condensor turret"),
description_("Conensor Turret"),
pos_(1)
{
InitializeDefaultErrorMessages();
// TODO provide error messages
SetErrorText(ERR_SCOPE_NOT_ACTIVE, "Leica Scope is not initialized. It is needed for this Turret to work");
SetErrorText(ERR_INVALID_TURRET_POSITION, "The requested position is not available on this turret");
SetErrorText(ERR_MODULE_NOT_FOUND, "This turret is not installed in this Leica microscope");
SetErrorText(ERR_TURRET_NOT_ENGAGED, "Conensor Turret is not engaged");
// Create pre-initialization properties
// ------------------------------------
// Name
CreateProperty(MM::g_Keyword_Name, name_.c_str(), MM::String, true);
// Description
CreateProperty(MM::g_Keyword_Description, description_.c_str(), MM::String, true);
}
CondensorTurret::~CondensorTurret()
{
Shutdown();
}
void CondensorTurret::GetName(char* name) const
{
CDeviceUtils::CopyLimitedString(name, name_.c_str());
}
int CondensorTurret::Initialize()
{
if (!g_ScopeInterface.portInitialized_)
return ERR_SCOPE_NOT_ACTIVE;
int ret = DEVICE_OK;
if (!g_ScopeInterface.IsInitialized())
ret = g_ScopeInterface.Initialize(*this, *GetCoreCallback());
if (ret != DEVICE_OK)
return ret;
// check if this turret exists:
if (! g_ScopeModel.IsDeviceAvailable(g_Condensor))
return ERR_MODULE_NOT_FOUND;
// set property list
// ----------------
// State
// -----
CPropertyAction* pAct = new CPropertyAction(this, &CondensorTurret::OnState);
ret = CreateProperty(MM::g_Keyword_State, "1", MM::Integer, false, pAct);
if (ret != DEVICE_OK)
return ret;
// Label
// -----
pAct = new CPropertyAction(this, &CStateBase::OnLabel);
ret = CreateProperty(MM::g_Keyword_Label, "1-", MM::String, false, pAct);
if (ret != DEVICE_OK)
return ret;
// create default positions and labels
int maxPos;
ret = g_ScopeModel.Condensor_.GetMaxPosition(maxPos);
if (ret != DEVICE_OK)
return ret;
numPos_ = maxPos;
for (unsigned i=0; i < numPos_; i++)
{
ostringstream os;
os << i+1 << "-" << g_ScopeModel.Condensor_.filter_[i+1];
SetPositionLabel(i, os.str().c_str());
}
ret = UpdateStatus();
if (ret!= DEVICE_OK)
return ret;
initialized_ = true;
return DEVICE_OK;
}
int CondensorTurret::Shutdown()
{
if (initialized_)
initialized_ = false;
return DEVICE_OK;
}
bool CondensorTurret::Busy()
{
bool busy;
int ret = g_ScopeModel.Condensor_.GetBusy(busy);
if (ret != DEVICE_OK) // This is bad and should not happen
return false;
return busy;
}
///////////////////////////////////////////////////////////////////////////////
// Action handlers
///////////////////////////////////////////////////////////////////////////////
int CondensorTurret::OnState(MM::PropertyBase* pProp, MM::ActionType eAct)
{
if (eAct == MM::BeforeGet)
{
int pos;
int ret = g_ScopeModel.Condensor_.GetPosition(pos);
if (ret != DEVICE_OK)
return ret;
if (pos == 0)
return ERR_TURRET_NOT_ENGAGED;
pos_ = pos -1;
pProp->Set(pos_);
}
else if (eAct == MM::AfterSet)
{
pProp->Get(pos_);
int pos;
int ret = g_ScopeModel.Condensor_.GetPosition(pos);
if (pos == pos_ + 1)
return DEVICE_OK;
pos = pos_ + 1;
if ((pos > 0) && (pos <= (int) numPos_)) {
return g_ScopeInterface.SetCondensorPosition(*this, *GetCoreCallback(), pos);
} else
return ERR_INVALID_TURRET_POSITION;
}
return DEVICE_OK;
}
///////////////////////////////////////////////////////////////////////////////
// Transmitted Light
///////////////////////////////////////////////////////////////////////////////
TransmittedLight::TransmittedLight():
initialized_ (false),
state_(0)
{
InitializeDefaultErrorMessages();
SetErrorText(ERR_SCOPE_NOT_ACTIVE, "Leica Scope is not initialized. It is needed for the Transmitted Light module to work");
SetErrorText(ERR_MODULE_NOT_FOUND, "This device is not installed in this Leica microscope");
}
TransmittedLight::~TransmittedLight ()
{
Shutdown();
}
void TransmittedLight::GetName(char* name) const
{
assert(name_.length() < CDeviceUtils::GetMaxStringLength());
CDeviceUtils::CopyLimitedString(name, name_.c_str());
}
int TransmittedLight::Initialize()
{
if (!g_ScopeInterface.portInitialized_)
return ERR_SCOPE_NOT_ACTIVE;
int ret = DEVICE_OK;
if (!g_ScopeInterface.IsInitialized())
ret = g_ScopeInterface.Initialize(*this, *GetCoreCallback());
if (ret != DEVICE_OK)
return ret;
// check if this shutter exists:
if (!g_ScopeModel.IsDeviceAvailable(g_Lamp))
return ERR_MODULE_NOT_FOUND;
// Name
ret = CreateProperty(MM::g_Keyword_Name, name_.c_str(), MM::String, true);
if (DEVICE_OK != ret)
return ret;
// Description
ret = CreateProperty(MM::g_Keyword_Description, description_.c_str(), MM::String, true);
if (DEVICE_OK != ret)
return ret;
// Check current state of shutter:
ret = GetOpen(state_);
if (DEVICE_OK != ret)
return ret;
// State
CPropertyAction* pAct = new CPropertyAction (this, &TransmittedLight::OnState);
if (state_)
ret = CreateProperty(MM::g_Keyword_State, "1", MM::Integer, false, pAct);
else
ret = CreateProperty(MM::g_Keyword_State, "0", MM::Integer, false, pAct);
if (ret != DEVICE_OK)
return ret;
AddAllowedValue(MM::g_Keyword_State, "0"); // Closed
AddAllowedValue(MM::g_Keyword_State, "1"); // Open
//Label
ret = UpdateStatus();
if (ret != DEVICE_OK)
return ret;
initialized_ = true;
return DEVICE_OK;
}
int TransmittedLight::Shutdown()
{
if (initialized_)
{
initialized_ = false;
}
return DEVICE_OK;
}
bool TransmittedLight::Busy()
{
bool busy;
int ret = g_ScopeModel.TransmittedLight_.GetBusy(busy);
if (ret != DEVICE_OK) // This is bad and should not happen
return false;
return busy;
}
int TransmittedLight::OnState(MM::PropertyBase *pProp, MM::ActionType eAct)
{
if (eAct == MM::BeforeGet)
{
// return pos as we know it
GetOpen(state_);
if (state_)
pProp->Set(1L);
else
pProp->Set(0L);
}
else if (eAct == MM::AfterSet)
{
long pos;
pProp->Get(pos);
if (pos==1)
{
state_ = true;
return this->SetOpen(true);
}
else
{
state_ = false;
return this->SetOpen(false);
}
}
return DEVICE_OK;
}
int TransmittedLight::SetOpen(bool open)
{
int position;
if (open)
position = 1;
else
position = 0;
int ret = g_ScopeInterface.SetTransmittedLightShutterPosition(*this, *GetCoreCallback(), position);
if (ret != DEVICE_OK)
return ret;
state_ = open;
return DEVICE_OK;
}
int TransmittedLight::GetOpen(bool &open)
{
int position;
int ret = g_ScopeModel.TransmittedLight_.GetPosition(position);
if (ret != DEVICE_OK)
return ret;
if (position == 0)
open = false;
else if (position == 1)
open = true;
else
return ERR_UNEXPECTED_ANSWER;
return DEVICE_OK;
}
int TransmittedLight::Fire(double)
{ return DEVICE_UNSUPPORTED_COMMAND;
}
| [
"OD@d0ab736e-dc22-4aeb-8dc9-08def0aa14fd",
"prashanth@d0ab736e-dc22-4aeb-8dc9-08def0aa14fd",
"nico@d0ab736e-dc22-4aeb-8dc9-08def0aa14fd"
]
| [
[
[
1,
110
],
[
112,
132
],
[
134,
175
],
[
178,
2319
]
],
[
[
111,
111
],
[
133,
133
],
[
176,
177
],
[
2320,
2484
]
],
[
[
2485,
2485
]
]
]
|
0f44113eaeee49920654b7c27ead9a94280f085b | 4323418f83efdc8b9f8b8bb1cc15680ba66e1fa8 | /Trunk/Battle Cars/Battle Cars/Source/CGameModeSelectionState.h | ec18d63e2e6af436479ad57d1f9582a0c3b4dd8a | []
| no_license | FiveFourFive/battle-cars | 5f2046e7afe5ac50eeeb9129b87fcb4b2893386c | 1809cce27a975376b0b087a96835347069fe2d4c | refs/heads/master | 2021-05-29T19:52:25.782568 | 2011-07-28T17:48:39 | 2011-07-28T17:48:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 968 | h | #ifndef _CGAMEMODESELECTIONSTATE_H
#define _CGAMEMODESELECTIONSTATE_H
#include "IGameState.h"
#include <vector>
using namespace std;
class CSGD_TextureManager;
class CPrintFont;
class CSGD_FModManager;
class CSGD_DirectInput;
class CXboxInput;
class CPlayer;
class CGameModeSelectionState : public IGameState
{
private:
CSGD_TextureManager* m_pTM;
CPrintFont* m_pPF;
CSGD_FModManager* m_pFM;
CSGD_DirectInput* m_pDI;
int m_nBGImageID;
int m_nFontID;
int m_nSelection;
int m_nMenuSelect;
int m_nMenuMove;
CGameModeSelectionState();
~CGameModeSelectionState();
CGameModeSelectionState& operator=(const CGameModeSelectionState&);
CGameModeSelectionState(const CGameModeSelectionState&);
public:
static CGameModeSelectionState* GetInstance(void);
void Enter(void);
void Exit(void);
bool Input(void);
void Update(float fElapsedTime);
void Render(void);
bool HandleEnter(void);
};
#endif | [
"[email protected]@598269ab-7e8a-4bc4-b06e-4a1e7ae79330",
"[email protected]@598269ab-7e8a-4bc4-b06e-4a1e7ae79330"
]
| [
[
[
1,
24
],
[
26,
50
]
],
[
[
25,
25
]
]
]
|
46e2421ab7216f110aa21c8a5b856f90c3250c28 | fc4946d917dc2ea50798a03981b0274e403eb9b7 | /gentleman/gentleman/WindowsAPICodePack/WindowsAPICodePack/DirectX/DirectX/Direct3D10/D3D10Blob.cpp | 37ad4f2a433f426ce1fb72598ee70b87bd5ec286 | []
| no_license | midnite8177/phever | f9a55a545322c9aff0c7d0c45be3d3ddd6088c97 | 45529e80ebf707e7299887165821ca360aa1907d | refs/heads/master | 2020-05-16T21:59:24.201346 | 2010-07-12T23:51:53 | 2010-07-12T23:51:53 | 34,965,829 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 408 | cpp | // Copyright (c) Microsoft Corporation. All rights reserved.
#include "stdafx.h"
#include "D3D10Blob.h"
using namespace Microsoft::WindowsAPICodePack::DirectX::Direct3D10;
IntPtr Blob::GetBufferPointer()
{
return IntPtr(GetInterface<ID3D10Blob>()->GetBufferPointer());
}
UInt32 Blob::GetBufferSize()
{
return static_cast<UInt32>(GetInterface<ID3D10Blob>()->GetBufferSize());
}
| [
"lucemia@9e708c16-f4dd-11de-aa3c-59de0406b4f5"
]
| [
[
[
1,
17
]
]
]
|
5bcdc6965b824636ed916d055ed6fe45330e4a25 | 205069c97095da8f15e45cede1525f384ba6efd2 | /Casino/Code/Server/ShareModule/GridCtrl/InPlaceEdit.h | 60114df9afeabf628b2cd2e9037ff22190e5c2f9 | []
| no_license | m0o0m/01technology | 1a3a5a48a88bec57f6a2d2b5a54a3ce2508de5ea | 5e04cbfa79b7e3cf6d07121273b3272f441c2a99 | refs/heads/master | 2021-01-17T22:12:26.467196 | 2010-01-05T06:39:11 | 2010-01-05T06:39:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,549 | h | //////////////////////////////////////////////////////////////////////
// InPlaceEdit.h : header file
//
// MFC Grid Control - inplace editing class
//
// Written by Chris Maunder <[email protected]>
// Copyright (c) 1998-2002. All Rights Reserved.
//
// 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 and all copyright
// notices remains intact.
//
// An email letting me know how you are using it would be nice as well.
//
// This file is provided "as is" with no expressed or implied warranty.
// The author accepts no liability for any damage/loss of business that
// this product may cause.
//
// For use with CGridCtrl v2.10+
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_INPLACEEDIT_H__ECD42821_16DF_11D1_992F_895E185F9C72__INCLUDED_)
#define AFX_INPLACEEDIT_H__ECD42821_16DF_11D1_992F_895E185F9C72__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
class CInPlaceEdit : public CEdit
{
// Construction
public:
CInPlaceEdit(CWnd* pParent, CRect& rect, DWORD dwStyle, UINT nID,
int nRow, int nColumn, CString sInitText, UINT nFirstChar);
// Attributes
public:
// Operations
public:
void EndEdit();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CInPlaceEdit)
public:
virtual BOOL PreTranslateMessage(MSG* pMsg);
protected:
virtual void PostNcDestroy();
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CInPlaceEdit();
// Generated message map functions
protected:
//{{AFX_MSG(CInPlaceEdit)
afx_msg void OnKillFocus(CWnd* pNewWnd);
afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags);
afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
afx_msg UINT OnGetDlgCode();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
public:
int m_nRow;
int m_nColumn;
CString m_sInitText;
UINT m_nLastChar;
BOOL m_bExitOnArrows;
CRect m_Rect;
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_INPLACEEDIT_H__ECD42821_16DF_11D1_992F_895E185F9C72__INCLUDED_)
| [
"[email protected]"
]
| [
[
[
1,
83
]
]
]
|
1ca6a5a8aad9431f622ca2824b7b526f0738ab0d | 508bfb3220be28811600a2cbf0aabae382f78775 | /AcademicCrawler-sdk/Qt/Qt-4.6.2/include/Qt/qwebframe.h | bfb61876f4fa220baa787b1a5b0163e3ea874576 | []
| no_license | darkbtf/academic-crawler | 295f3bd74b18e700402bc2be59f15694d6195471 | 5dfcb0f1b88b93aa7545ef233344a41570011532 | refs/heads/master | 2021-01-01T19:21:00.162442 | 2011-03-10T16:29:25 | 2011-03-10T16:29:25 | 42,468,175 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,201 | h | /*
Copyright (C) 2008,2009 Nokia Corporation and/or its subsidiary(-ies)
Copyright (C) 2007 Staikos Computing Services Inc.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef QWEBFRAME_H
#define QWEBFRAME_H
#include <QtCore/qobject.h>
#include <QtCore/qurl.h>
#include <QtCore/qvariant.h>
#include <QtGui/qicon.h>
#include <QtScript/qscriptengine.h>
#if QT_VERSION >= 0x040400
#include <QtNetwork/qnetworkaccessmanager.h>
#endif
#include "qwebkitglobal.h"
QT_BEGIN_NAMESPACE
class QRect;
class QPoint;
class QPainter;
class QPixmap;
class QMouseEvent;
class QWheelEvent;
class QNetworkRequest;
class QRegion;
class QPrinter;
QT_END_NAMESPACE
class QWebNetworkRequest;
class QWebFramePrivate;
class QWebPage;
class QWebHitTestResult;
class QWebHistoryItem;
class QWebSecurityOrigin;
class QWebElement;
class QWebElementCollection;
namespace WebCore {
class WidgetPrivate;
class FrameLoaderClientQt;
class ChromeClientQt;
}
class QWebFrameData;
class QWebHitTestResultPrivate;
class QWebFrame;
class QWEBKIT_EXPORT QWebHitTestResult {
public:
QWebHitTestResult();
QWebHitTestResult(const QWebHitTestResult &other);
QWebHitTestResult &operator=(const QWebHitTestResult &other);
~QWebHitTestResult();
bool isNull() const;
QPoint pos() const;
QRect boundingRect() const;
QWebElement enclosingBlockElement() const;
QString title() const;
QString linkText() const;
QUrl linkUrl() const;
QUrl linkTitle() const;
QWebFrame *linkTargetFrame() const;
QWebElement linkElement() const;
QString alternateText() const; // for img, area, input and applet
QUrl imageUrl() const;
QPixmap pixmap() const;
bool isContentEditable() const;
bool isContentSelected() const;
QWebElement element() const;
QWebFrame *frame() const;
private:
QWebHitTestResult(QWebHitTestResultPrivate *priv);
QWebHitTestResultPrivate *d;
friend class QWebFrame;
friend class QWebPagePrivate;
friend class QWebPage;
};
class QWEBKIT_EXPORT QWebFrame : public QObject {
Q_OBJECT
Q_PROPERTY(qreal textSizeMultiplier READ textSizeMultiplier WRITE setTextSizeMultiplier DESIGNABLE false)
Q_PROPERTY(qreal zoomFactor READ zoomFactor WRITE setZoomFactor)
Q_PROPERTY(QString title READ title)
Q_PROPERTY(QUrl url READ url WRITE setUrl)
Q_PROPERTY(QUrl requestedUrl READ requestedUrl)
Q_PROPERTY(QUrl baseUrl READ baseUrl)
Q_PROPERTY(QIcon icon READ icon)
Q_PROPERTY(QSize contentsSize READ contentsSize)
Q_PROPERTY(QPoint scrollPosition READ scrollPosition WRITE setScrollPosition)
Q_PROPERTY(bool focus READ hasFocus)
private:
QWebFrame(QWebPage *parent, QWebFrameData *frameData);
QWebFrame(QWebFrame *parent, QWebFrameData *frameData);
~QWebFrame();
public:
QWebPage *page() const;
void load(const QUrl &url);
#if QT_VERSION < 0x040400
void load(const QWebNetworkRequest &request);
#else
void load(const QNetworkRequest &request,
QNetworkAccessManager::Operation operation = QNetworkAccessManager::GetOperation,
const QByteArray &body = QByteArray());
#endif
void setHtml(const QString &html, const QUrl &baseUrl = QUrl());
void setContent(const QByteArray &data, const QString &mimeType = QString(), const QUrl &baseUrl = QUrl());
void addToJavaScriptWindowObject(const QString &name, QObject *object);
void addToJavaScriptWindowObject(const QString &name, QObject *object, QScriptEngine::ValueOwnership ownership);
QString toHtml() const;
QString toPlainText() const;
QString renderTreeDump() const;
QString title() const;
void setUrl(const QUrl &url);
QUrl url() const;
QUrl requestedUrl() const;
QUrl baseUrl() const;
QIcon icon() const;
QMultiMap<QString, QString> metaData() const;
QString frameName() const;
QWebFrame *parentFrame() const;
QList<QWebFrame*> childFrames() const;
Qt::ScrollBarPolicy scrollBarPolicy(Qt::Orientation orientation) const;
void setScrollBarPolicy(Qt::Orientation orientation, Qt::ScrollBarPolicy policy);
void setScrollBarValue(Qt::Orientation orientation, int value);
int scrollBarValue(Qt::Orientation orientation) const;
int scrollBarMinimum(Qt::Orientation orientation) const;
int scrollBarMaximum(Qt::Orientation orientation) const;
QRect scrollBarGeometry(Qt::Orientation orientation) const;
void scroll(int, int);
QPoint scrollPosition() const;
void setScrollPosition(const QPoint &pos);
enum RenderLayer {
ContentsLayer = 0x10,
ScrollBarLayer = 0x20,
PanIconLayer = 0x40,
AllLayers = 0xff
};
void render(QPainter*);
void render(QPainter*, const QRegion& clip);
void render(QPainter*, RenderLayer layer, const QRegion& clip = QRegion());
void setTextSizeMultiplier(qreal factor);
qreal textSizeMultiplier() const;
qreal zoomFactor() const;
void setZoomFactor(qreal factor);
bool hasFocus() const;
void setFocus();
QPoint pos() const;
QRect geometry() const;
QSize contentsSize() const;
QWebElement documentElement() const;
QWebElementCollection findAllElements(const QString &selectorQuery) const;
QWebElement findFirstElement(const QString &selectorQuery) const;
QWebHitTestResult hitTestContent(const QPoint &pos) const;
virtual bool event(QEvent *);
QWebSecurityOrigin securityOrigin() const;
public Q_SLOTS:
QVariant evaluateJavaScript(const QString& scriptSource);
#ifndef QT_NO_PRINTER
void print(QPrinter *printer) const;
#endif
Q_SIGNALS:
void javaScriptWindowObjectCleared();
void provisionalLoad();
void titleChanged(const QString &title);
void urlChanged(const QUrl &url);
void initialLayoutCompleted();
void iconChanged();
void contentsSizeChanged(const QSize &size);
void loadStarted();
void loadFinished(bool ok);
private:
friend class QWebPage;
friend class QWebPagePrivate;
friend class QWebFramePrivate;
friend class WebCore::WidgetPrivate;
friend class WebCore::FrameLoaderClientQt;
friend class WebCore::ChromeClientQt;
QWebFramePrivate *d;
};
#endif
| [
"ulmonkey1987@7c5ce3f8-edad-37de-be84-b98c484540b5"
]
| [
[
[
1,
235
]
]
]
|
096ec69020c418cd7c8ca1ac82c459a195e821dd | b4ec0cb07a6e388ba33dde1ee3494a970aba8a0d | /browser/client_handler.h | 247f28b596e92ef1cb519dd1cc4afc9e033d3290 | []
| no_license | ashenone0917/pea-search | 2eed03fc2314909f69a8c3c7cbca511eba192bd3 | 3837dbcc2767d6358b726587b9a77d3c0f015a9d | refs/heads/master | 2023-03-18T08:28:11.348474 | 2011-12-30T12:36:00 | 2011-12-30T12:36:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,932 | h | #ifndef _CLIENT_HANDLER_H
#define _CLIENT_HANDLER_H
#include "../3rd/cef_binary/include/cef.h"
#include "cef_util.h"
extern void exec_js_str(WCHAR *str);
extern void exec_js(const WCHAR *function_name);
class ClientHandler : public CefClient,
public CefLifeSpanHandler,
public CefLoadHandler,
public CefKeyboardHandler
{
public:
ClientHandler();
virtual ~ClientHandler();
virtual CefRefPtr<CefLifeSpanHandler> GetLifeSpanHandler() OVERRIDE
{ return this; }
virtual CefRefPtr<CefLoadHandler> GetLoadHandler() OVERRIDE
{ return this; }
virtual CefRefPtr<CefKeyboardHandler> GetKeyboardHandler() OVERRIDE
{ return this; }
virtual void OnAfterCreated(CefRefPtr<CefBrowser> browser) OVERRIDE;
virtual void OnLoadEnd(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
int httpStatusCode) OVERRIDE;
virtual bool OnLoadError(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
ErrorCode errorCode,
const CefString& failedUrl,
CefString& errorText) OVERRIDE;
virtual bool OnKeyEvent(CefRefPtr<CefBrowser> browser,
KeyEventType type,
int code,
int modifiers,
bool isSystemKey) OVERRIDE;
CefRefPtr<CefBrowser> GetBrowser() { return m_Browser; }
CefWindowHandle GetBrowserHwnd() { return m_BrowserHwnd; }
protected:
CefRefPtr<CefBrowser> m_Browser;
CefWindowHandle m_BrowserHwnd;
// Include the default reference counting implementation.
IMPLEMENT_REFCOUNTING(ClientHandler);
// Include the default locking implementation.
IMPLEMENT_LOCKING(ClientHandler);
};
#endif // _CLIENT_HANDLER_H
| [
"[email protected]"
]
| [
[
[
1,
59
]
]
]
|
b8764f6c2b7d7de86f1cd1260297485bec76ba6c | 6c5cd70473dceee91751a9ae9f1fecda20fa60d0 | /src/Replay.h | ebabed43d9f2affea0a4b746a6d98b30b2beb7fc | []
| no_license | jncraton/rep2ai | 27da3316f365ae2518b361a8186fd6fc8a53804f | c0ce7de68bb110e6f11cf1c3a29d32fec2d0694a | refs/heads/master | 2020-04-29T02:57:57.288273 | 2010-07-20T18:41:44 | 2010-07-20T18:41:44 | 441,084 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 454 | h | #ifndef REPLAY_H
#define REPLAY_H
#include <stdio.h>
#include <memory.h>
#include "ActionList.h"
#include "unpack.h"
using namespace std;
class Replay
{
public:
Replay(char * filename);
~Replay();
ActionList actionList;
char header[0x279];
char gameName[29];
char playerName[8][26];
int playerRace[8];
int playerID[8];
int numPlayers;
private:
char playerList[1024];
};
#endif
| [
"jncraton@.(none)",
"[email protected]"
]
| [
[
[
1,
21
],
[
25,
26
],
[
28,
30
]
],
[
[
22,
24
],
[
27,
27
]
]
]
|
831dfb68d56e8b3066158be02b0acba75a6b7404 | e31046aee3ad2d4600c7f35aaeeba76ee2b99039 | /trunk/libs/raknet/includes/RakNetTypes.h | 201eb7a9bc986479a4a23acc1227bcdab282ca15 | [
"BSD-3-Clause"
]
| permissive | BackupTheBerlios/trinitas-svn | ddea265cf47aff3e8853bf6d46861e0ed3031ea1 | 7d3ff64a7d0e5ba37febda38e6ce0b2d0a4b6cca | refs/heads/master | 2021-01-23T08:14:44.215249 | 2009-02-18T19:37:51 | 2009-02-18T19:37:51 | 40,749,519 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,089 | h | /// \file
/// \brief Types used by RakNet, most of which involve user code.
///
/// This file is part of RakNet Copyright 2003 Kevin Jenkins.
///
/// Usage of RakNet is subject to the appropriate license agreement.
/// Creative Commons Licensees are subject to the
/// license found at
/// http://creativecommons.org/licenses/by-nc/2.5/
/// Single application licensees are subject to the license found at
/// http://www.jenkinssoftware.com/SingleApplicationLicense.html
/// Custom license users are subject to the terms therein.
/// GPL license users are subject to 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.
#ifndef __NETWORK_TYPES_H
#define __NETWORK_TYPES_H
#include "RakNetDefines.h"
#include "NativeTypes.h"
#include "RakNetTime.h"
#include "Export.h"
#if !defined(_WIN32) && ((defined(__GNUC__) || defined(__GCCXML__)))
#include "stdint.h"
#endif
/// Forward declaration
namespace RakNet
{
class BitStream;
};
/// Given a number of bits, return how many bytes are needed to represent that.
#define BITS_TO_BYTES(x) (((x)+7)>>3)
#define BYTES_TO_BITS(x) ((x)<<3)
/// \sa NetworkIDObject.h
typedef unsigned char UniqueIDType;
typedef unsigned short SystemIndex;
typedef unsigned char RPCIndex;
const int MAX_RPC_MAP_SIZE=((RPCIndex)-1)-1;
const int UNDEFINED_RPC_INDEX=((RPCIndex)-1);
/// First byte of a network message
typedef unsigned char MessageID;
typedef unsigned int BitSize_t;
#if defined(_MSC_VER) && _MSC_VER > 0
#define PRINTF_TIME_MODIFIER "I64"
#else
#define PRINTF_TIME_MODIFIER "ll"
#endif
/// Describes the local socket to use for RakPeer::Startup
struct RAK_DLL_EXPORT SocketDescriptor
{
SocketDescriptor();
SocketDescriptor(unsigned short _port, const char *_hostAddress);
/// The local port to bind to. Pass 0 to have the OS autoassign a port.
unsigned short port;
/// The local network card address to bind to, such as "127.0.0.1". Pass an empty string to use INADDR_ANY.
char hostAddress[32];
};
/// \brief Network address for a system
/// Corresponds to a network address
/// This is not necessarily a unique identifier. For example, if a system has both LAN and internet connections, the system may be identified by either one, depending on who is communicating
/// Use RakNetGUID for a unique per-instance of RakPeer to identify systems
struct RAK_DLL_EXPORT SystemAddress
{
///The peer address from inet_addr.
unsigned int binaryAddress;
///The port number
unsigned short port;
// Return the systemAddress as a string in the format <IP>:<Port>
// Returns a static string
// NOT THREADSAFE
const char *ToString(bool writePort=true) const;
// Return the systemAddress as a string in the format <IP>:<Port>
// dest must be large enough to hold the output
// THREADSAFE
void ToString(bool writePort, char *dest) const;
// Sets the binary address part from a string. Doesn't set the port
void SetBinaryAddress(const char *str);
SystemAddress& operator = ( const SystemAddress& input )
{
binaryAddress = input.binaryAddress;
port = input.port;
return *this;
}
bool operator==( const SystemAddress& right ) const;
bool operator!=( const SystemAddress& right ) const;
bool operator > ( const SystemAddress& right ) const;
bool operator < ( const SystemAddress& right ) const;
};
/// Size of SystemAddress data
#define SystemAddress_Size 6
class RakPeerInterface;
/// All RPC functions have the same parameter list - this structure.
/// \depreciated Use the AutoRPC or RPC3 plugin instead
struct RPCParameters
{
/// The data from the remote system
unsigned char *input;
/// How many bits long \a input is
BitSize_t numberOfBitsOfData;
/// Which system called this RPC
SystemAddress sender;
/// Which instance of RakPeer (or a derived RakPeer or RakPeer) got this call
RakPeerInterface *recipient;
RakNetTime remoteTimestamp;
/// The name of the function that was called.
char *functionName;
/// You can return values from RPC calls by writing them to this BitStream.
/// This is only sent back if the RPC call originally passed a BitStream to receive the reply.
/// If you do so and your send is reliable, it will block until you get a reply or you get disconnected from the system you are sending to, whichever is first.
/// If your send is not reliable, it will block for triple the ping time, or until you are disconnected, or you get a reply, whichever is first.
RakNet::BitStream *replyToSender;
};
/// Uniquely identifies an instance of RakPeer. Use RakPeer::GetGuidFromSystemAddress() and RakPeer::GetSystemAddressFromGuid() to go between SystemAddress and RakNetGUID
/// Use RakPeer::GetGuidFromSystemAddress(UNASSIGNED_SYSTSEM_ADDRESS) to get your own GUID
struct RAK_DLL_EXPORT RakNetGUID
{
unsigned int g[4];
// Return the GUID as a string
// Returns a static string
// NOT THREADSAFE
const char *ToString(void) const;
// Return the GUID as a string
// dest must be large enough to hold the output
// THREADSAFE
void ToString(char *dest) const;
RakNetGUID& operator = ( const RakNetGUID& input )
{
g[0]=input.g[0];
g[1]=input.g[1];
g[2]=input.g[2];
g[3]=input.g[3];
return *this;
}
bool operator==( const RakNetGUID& right ) const;
bool operator!=( const RakNetGUID& right ) const;
bool operator > ( const RakNetGUID& right ) const;
bool operator < ( const RakNetGUID& right ) const;
};
/// Index of an invalid SystemAddress
const SystemAddress UNASSIGNED_SYSTEM_ADDRESS =
{
0xFFFFFFFF, 0xFFFF
};
const RakNetGUID UNASSIGNED_RAKNET_GUID =
{
0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF
};
struct RAK_DLL_EXPORT NetworkID
{
NetworkID()
{
#if defined NETWORK_ID_SUPPORTS_PEER_TO_PEER
guid = UNASSIGNED_RAKNET_GUID;
systemAddress=UNASSIGNED_SYSTEM_ADDRESS;
#endif
localSystemAddress=65535;
}
~NetworkID() {}
/// \depreciated. Use NETWORK_ID_SUPPORTS_PEER_TO_PEER in RakNetDefines.h
// Set this to true to use peer to peer mode for NetworkIDs.
// Obviously the value of this must match on all systems.
// True, and this will write the systemAddress portion with network sends. Takes more bandwidth, but NetworkIDs can be locally generated
// False, and only localSystemAddress is used.
// static bool peerToPeerMode;
#if defined NETWORK_ID_SUPPORTS_PEER_TO_PEER
// Depreciated: Use guid instead
// In peer to peer, we use both systemAddress and localSystemAddress
// In client / server, we only use localSystemAddress
SystemAddress systemAddress;
RakNetGUID guid;
#endif
unsigned short localSystemAddress;
NetworkID& operator = ( const NetworkID& input );
static bool IsPeerToPeerMode(void);
static void SetPeerToPeerMode(bool isPeerToPeer);
bool operator==( const NetworkID& right ) const;
bool operator!=( const NetworkID& right ) const;
bool operator > ( const NetworkID& right ) const;
bool operator < ( const NetworkID& right ) const;
};
/// This represents a user message from another system.
struct Packet
{
/// Server only - this is the index into the player array that this systemAddress maps to
SystemIndex systemIndex;
/// The system that send this packet.
SystemAddress systemAddress;
/// A unique identifier for the system that sent this packet, regardless of IP address (internal / external / remote system)
/// Only valid once a connection has been established (ID_CONNECTION_REQUEST_ACCEPTED, or ID_NEW_INCOMING_CONNECTION)
/// Until that time, will be UNASSIGNED_RAKNET_GUID
RakNetGUID guid;
/// The length of the data in bytes
/// \deprecated You should use bitSize.
unsigned int length;
/// The length of the data in bits
BitSize_t bitSize;
/// The data from the sender
unsigned char* data;
/// @internal
/// Indicates whether to delete the data, or to simply delete the packet.
bool deleteData;
};
/// Index of an unassigned player
const SystemIndex UNASSIGNED_PLAYER_INDEX = 65535;
/// Unassigned object ID
const NetworkID UNASSIGNED_NETWORK_ID;
const int PING_TIMES_ARRAY_SIZE = 5;
/// \brief RPC Function Implementation
///
/// The Remote Procedure Call Subsystem provide the RPC paradigm to
/// RakNet user. It consists in providing remote function call over the
/// network. A call to a remote function require you to prepare the
/// data for each parameter (using BitStream) for example.
///
/// Use the following C function prototype for your callbacks
/// @code
/// void functionName(RPCParameters *rpcParms);
/// @endcode
/// If you pass input data, you can parse the input data in two ways.
/// 1.
/// Cast input to a struct (such as if you sent a struct)
/// i.e. MyStruct *s = (MyStruct*) input;
/// Make sure that the sizeof(MyStruct) is equal to the number of bytes passed!
/// 2.
/// Create a BitStream instance with input as data and the number of bytes
/// i.e. BitStream myBitStream(input, (numberOfBitsOfData-1)/8+1)
/// (numberOfBitsOfData-1)/8+1 is how convert from bits to bytes
/// Full example:
/// @code
/// void MyFunc(RPCParameters *rpcParms) {}
/// RakPeer *rakClient;
/// REGISTER_AS_REMOTE_PROCEDURE_CALL(rakClient, MyFunc);
/// This would allow MyFunc to be called from the server using (for example)
/// rakServer->RPC("MyFunc", 0, clientID, false);
/// @endcode
/// \def REGISTER_STATIC_RPC
/// \ingroup RAKNET_RPC
/// \depreciated Use the AutoRPC plugin instead
/// Register a C function as a Remote procedure.
/// \param[in] networkObject Your instance of RakPeer, RakPeer, or RakPeer
/// \param[in] functionName The name of the C function to call
/// \attention 12/01/05 REGISTER_AS_REMOTE_PROCEDURE_CALL renamed to REGISTER_STATIC_RPC. Delete the old name sometime in the future
//#pragma deprecated(REGISTER_AS_REMOTE_PROCEDURE_CALL)
//#define REGISTER_AS_REMOTE_PROCEDURE_CALL(networkObject, functionName) REGISTER_STATIC_RPC(networkObject, functionName)
#define REGISTER_STATIC_RPC(networkObject, functionName) (networkObject)->RegisterAsRemoteProcedureCall((#functionName),(functionName))
/// \def CLASS_MEMBER_ID
/// \ingroup RAKNET_RPC
/// \depreciated Use the AutoRPC plugin instead
/// \brief Concatenate two strings
/// \def REGISTER_CLASS_MEMBER_RPC
/// \depreciated Use the AutoRPC plugin instead
/// \ingroup RAKNET_RPC
/// \brief Register a member function of an instantiated object as a Remote procedure call.
/// RPC member Functions MUST be marked __cdecl!
/// \sa ObjectMemberRPC.cpp
/// \b CLASS_MEMBER_ID is a utility macro to generate a unique signature for a class and function pair and can be used for the Raknet functions RegisterClassMemberRPC(...) and RPC(...)
/// \b REGISTER_CLASS_MEMBER_RPC is a utility macro to more easily call RegisterClassMemberRPC
/// \param[in] networkObject Your instance of RakPeer, RakPeer, or RakPeer
/// \param[in] className The class containing the function
/// \param[in] functionName The name of the function (not in quotes, just the name)
#define CLASS_MEMBER_ID(className, functionName) #className "_" #functionName
#define REGISTER_CLASS_MEMBER_RPC(networkObject, className, functionName) {union {void (__cdecl className::*cFunc)( RPCParameters *rpcParms ); void* voidFunc;}; cFunc=&className::functionName; networkObject->RegisterClassMemberRPC(CLASS_MEMBER_ID(className, functionName),voidFunc);}
/// \def UNREGISTER_AS_REMOTE_PROCEDURE_CALL
/// \brief Only calls UNREGISTER_STATIC_RPC
/// \depreciated Use the AutoRPC plugin instead
/// \def UNREGISTER_STATIC_RPC
/// \ingroup RAKNET_RPC
/// \depreciated Use the AutoRPC plugin instead
/// Unregisters a remote procedure call
/// RPC member Functions MUST be marked __cdecl! See the ObjectMemberRPC example.
/// \param[in] networkObject The object that manages the function
/// \param[in] functionName The function name
// 12/01/05 UNREGISTER_AS_REMOTE_PROCEDURE_CALL Renamed to UNREGISTER_STATIC_RPC. Delete the old name sometime in the future
//#pragma deprecated(UNREGISTER_AS_REMOTE_PROCEDURE_CALL)
//#define UNREGISTER_AS_REMOTE_PROCEDURE_CALL(networkObject,functionName) UNREGISTER_STATIC_RPC(networkObject,functionName)
#define UNREGISTER_STATIC_RPC(networkObject,functionName) (networkObject)->UnregisterAsRemoteProcedureCall((#functionName))
/// \def UNREGISTER_CLASS_INST_RPC
/// \ingroup RAKNET_RPC
/// \depreciated Use the AutoRPC plugin instead
/// \brief Unregisters a member function of an instantiated object as a Remote procedure call.
/// \param[in] networkObject The object that manages the function
/// \param[in] className The className that was originally passed to REGISTER_AS_REMOTE_PROCEDURE_CALL
/// \param[in] functionName The function name
#define UNREGISTER_CLASS_MEMBER_RPC(networkObject, className, functionName) (networkObject)->UnregisterAsRemoteProcedureCall((#className "_" #functionName))
#endif
| [
"paradoxon@ab3bda7c-5b37-0410-9911-e7f4556ba333"
]
| [
[
[
1,
344
]
]
]
|
794f3926680f77c8dfe86b4641e03e98ce4fbbb6 | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SEWarehouse/SEStaticArray.inl | c4b5535628b72783b657d2a64c20de519eb4264f | []
| no_license | pizibing/swingengine | d8d9208c00ec2944817e1aab51287a3c38103bea | e7109d7b3e28c4421c173712eaf872771550669e | refs/heads/master | 2021-01-16T18:29:10.689858 | 2011-06-23T04:27:46 | 2011-06-23T04:27:46 | 33,969,301 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,574 | inl | //----------------------------------------------------------------------------
template<class Type>
inline void StaticArray<Type>::operator=(const StaticArray<Type>& rOriginal)
{
CopyArray(rOriginal);
}
//----------------------------------------------------------------------------
template<class Type>
inline void StaticArray<Type>::Clear()
{
if( m_iCount != 0 )
Delete();
}
//----------------------------------------------------------------------------
template<class Type>
inline void StaticArray<Type>::Append(INDEX iCount)
{
ASSERT( this != 0 && iCount >= 0 );
if( iCount == 0 )
{
return;
}
ASSERT( m_iCount == 0 && m_pArray == 0 );
m_iCount = iCount;
m_pArray = new Type[iCount + 1]; //(+1 for cache-prefetch opt)
}
//----------------------------------------------------------------------------
template<class Type>
inline void StaticArray<Type>::Expand(INDEX iNewCount)
{
// 确保新尺寸大于现有尺寸才有意义
ASSERT( this != 0 && iNewCount > m_iCount );
// 如果还没有分配内存
if( m_iCount == 0 )
{
Append(iNewCount);
return;
}
else
{
ASSERT( m_iCount != 0 && m_Array != 0 );
// 分配新尺寸的内存
Type* pNewArray = new Type[iNewCount + 1]; //(+1 for cache-prefetch opt)
// 复制现有对象数据到新分配的内存中
for( INDEX iOld = 0; iOld < m_iCount; iOld++ )
{
pNewArray[iOld] = m_pArray[iOld];
}
// 释放原来的内存
delete[] m_pArray;
// 指向新内存
m_iCount = iNewCount;
m_pArray = pNewArray;
}
}
//----------------------------------------------------------------------------
template<class Type>
inline void StaticArray<Type>::Delete()
{
// 确保有对象
ASSERT( this != 0 && m_iCount != 0 && m_pArray != 0 );
delete[] m_pArray;
m_iCount = 0;
m_pArray = 0;
}
//----------------------------------------------------------------------------
template<class Type>
inline Type& StaticArray<Type>::operator[](INDEX iObject)
{
// 检查越界访问
ASSERT( this != 0 && iObject >= 0 && iObject < m_iCount);
return m_pArray[iObject];
}
//----------------------------------------------------------------------------
template<class Type>
inline const Type& StaticArray<Type>::operator[](INDEX iObject) const
{
// 检查越界访问
ASSERT( this! = 0 && iObject >= 0 && iObject < m_iCount );
return m_pArray[iObject];
}
//----------------------------------------------------------------------------
template<class Type>
inline StaticArrayIterator<Type>::StaticArrayIterator(StaticArray<Type>& rSA)
: m_rStaticArray(rSA)
{
m_iIndex = 0;
}
//----------------------------------------------------------------------------
template<class Type>
inline StaticArrayIterator<Type>::~StaticArrayIterator()
{
m_iIndex = -1;
}
//----------------------------------------------------------------------------
template<class Type>
inline void StaticArrayIterator<Type>::MoveToNext()
{
ASSERT( this != 0 );
m_iIndex++;
}
//----------------------------------------------------------------------------
template<class Type>
inline bool StaticArrayIterator<Type>::IsPastEnd()
{
ASSERT( this != 0 );
return m_iIndex >= m_rStaticArray.m_iCount;
}
//---------------------------------------------------------------------------- | [
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
]
| [
[
[
1,
119
]
]
]
|
6e05fa44b51c2c4508dbba7d595f21db381c309a | 000b887c9052e3af1cfb46e671c0f71a56576af1 | /LD18_Source/src/game.hpp | 03b328a14f8104729172e91bf7d984caa3da9bed | []
| no_license | PhilCK/LD18 | 781c999a395f64ead76bcc174908e8ec9eb21f58 | a9ca4bd0224900382fb9ffda5ea934a70057b16f | refs/heads/master | 2021-01-10T18:40:44.982764 | 2010-08-23T19:32:41 | 2010-08-23T19:32:41 | 855,157 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,951 | hpp | // game.hpp
#ifndef __game_hpp__
#define __game_hpp__
#include <algorithm>
#include "base.hpp"
#include "window.hpp"
#include "player.hpp"
#include "manager.hpp"
#include "zombie.hpp"
#include "object_manager.hpp"
using namespace Base;
class Game
{
enum GameState {
TITLESCREEN,
GAMEMODE,
GAMEOVER
};
GameState currentState;
unsigned long gameTimer;
unsigned long lastFrame;
unsigned long score;
public:
bool firstHint;
Game()
{
currentState = TITLESCREEN;
objectManagerInstance().push(new Player);
objectManagerInstance().push(new Manager);
score = 0;
gameTimer = 0;
lastFrame = Gosu::milliseconds();
firstHint = true;
}
void update()
{
if (currentState == GAMEMODE)
{
objectManagerInstance().update();
gameTimer += Gosu::milliseconds() - lastFrame;
lastFrame = Gosu::milliseconds();
if (gameTimer > 5000)
{
objectManagerInstance().push(new Zombie);
score += 1;
gameTimer = 0 + min((int)(score * 100), 4500);
}
if (objectManagerInstance().getObject("player").health < 0)
{
objectManagerInstance().clear();
currentState = GAMEOVER;
}
}
}
void draw()
{
if (currentState == TITLESCREEN)
{
static Gosu::Image intro(windowInstance().graphics(),
Directory::MediaDir + L"intro.png", false);
intro.draw(0, 0, Layer::UI_LAYER);
}
else if (currentState == GAMEMODE)
{
drawBuilding();
drawBackground();
objectManagerInstance().draw();
if (firstHint)
{
static Gosu::Image hint1(windowInstance().graphics(), Directory::MediaDir + L"hint1.png", false);
hint1.draw(150, 320, Layer::UI_LAYER);
static Gosu::Image hint2(windowInstance().graphics(), Directory::MediaDir + L"hint2.png", false);
hint2.draw(150, 360, Layer::UI_LAYER);
}
}
else if (currentState == GAMEOVER)
{
static Gosu::Image gameover(windowInstance().graphics(),
Directory::MediaDir + L"game_over.png", false);
gameover.draw(0, 0, Layer::UI_LAYER);
}
}
void buttonUp(Gosu::Button button)
{
if (currentState == GAMEMODE)
{
if (button == Gosu::msLeft)
{
if(firstHint)
firstHint = false;
}
}
if (currentState == TITLESCREEN)
currentState = GAMEMODE;
if (currentState == GAMEOVER)
{
currentState = GAMEMODE;
objectManagerInstance().push(new Player);
objectManagerInstance().push(new Manager);
score = 0;
}
}
private:
void drawBuilding()
{
static Gosu::Image buildingBody(windowInstance().graphics(),
Directory::MediaDir + L"building.png", false);
buildingBody.draw(47, 100, Layer::BUILDING_LAYER);
}
void drawBackground()
{
static Gosu::Image background(windowInstance().graphics(), Directory::MediaDir + L"bg.png", false);
background.draw(0, 0, Layer::BACKGROUND_LAYER);
}
};
#endif | [
"[email protected]"
]
| [
[
[
1,
149
]
]
]
|
413377dc86fbe8e9f24f1717b7c5db6b61062098 | 898dce1d28c7996db934d74c61d2690048b2bfb3 | /rayTracer/Camera.cpp | 8b3db88018d9e4e06b80e8c9d633a240ecfa951b | []
| no_license | claudiahwong/cs184-an-eh-sp10 | 8fa79a2aba7a917e18f393a150fc1183ba7f82a5 | d13f992bcb779411e11b1af62e9228246ed62dbd | refs/heads/master | 2016-09-05T20:06:52.877441 | 2010-10-29T04:51:15 | 2010-10-29T04:51:15 | 32,365,296 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,081 | cpp | #include "Camera.h"
Camera::Camera(void) {
}
Camera::Camera(vec3 lookFrom, vec3 lookAt, vec3 upv, float fovY, float znear, int width, int height)
{
eye = lookFrom;
center = lookAt;
up = upv;
//fovx = nv_to_deg * 2 * atan(width/(2.0 * znear));
fovx = fovY;
fovy = fovY;
screenWidth = width;
screenHeight = height;
}
Camera::~Camera(void)
{
}
void Camera::generateRay(Sample &sample, Ray *ray)
{
vec3 w = eye - center;
w.normalize();
vec3 u;
cross(u, up, w);
u.normalize();
vec3 v;
cross(v, w, u);
double z = screenHeight/2/tan(fovy/2*nv_to_rad);
double fovxTerm = 2 * atan(screenWidth/2/z);
double alpha, beta;
alpha = tan(fovxTerm/2)*((sample.x-((double) screenWidth/2.0))/((double) screenWidth/2.0));
beta = tan((fovy/2.0)*nv_to_rad)*((((double) screenHeight/2.0)-sample.y)/((double) screenHeight/2.0));
vec3 direction = alpha*u + beta*v - w;
direction.normalize();
Point eyePoint = Point(eye.x, eye.y, eye.z);
ray->pos = eyePoint;
ray->dir = direction;
ray->t_min = 0.001;
ray->t_max = 8000;
} | [
"victoria.c.chiu@9a492283-e4e1-9893-cc0f-88d6fa45db55",
"Lax100@9a492283-e4e1-9893-cc0f-88d6fa45db55"
]
| [
[
[
1,
33
],
[
37,
37
],
[
39,
48
]
],
[
[
34,
36
],
[
38,
38
]
]
]
|
4176c135cfa8dfad16c5bcbd4f49730076a2034a | b668c5a2161d35b5c3a0690a2d958a2ca1e3a5d8 | /AMC Tool/AMC Tool.cpp | 3a2adab1300574c69facf40cb50cbccbff5ce60b | [
"Apache-2.0"
]
| permissive | Bizonu/amclibrary | 5babe5ae7c7e3679a126856578c8d19979af4345 | 6dacc2386064bc1fb0ad9ef1cf0774c5fed56bed | refs/heads/master | 2021-01-10T19:31:01.970127 | 2011-12-28T18:38:03 | 2011-12-28T18:38:03 | 37,608,522 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,490 | cpp | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// File: AMCTool.cpp
/// Description: AMC Tool application starting code.
/// Author: Chiuta Adrian Marius
/// Created: 07-01-2010
///
/// 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 "platform.h"
#include "AESWizard.h"
CAppModule _Module;
HINSTANCE g_hInstance;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CString
getAppFolder(HINSTANCE hInstance)
{
TCHAR moduleFileName[MAX_PATH];
if( GetModuleFileName(hInstance, moduleFileName, MAX_PATH) == 0 )
return CString(_T(""));
CString cPath = moduleFileName;
return CString( cPath.Left(cPath.ReverseFind('\\')) );
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool
IsWindowsVistaOrLater()
{
OSVERSIONINFO osvi;
ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&osvi);
return osvi.dwMajorVersion >= 6;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int WINAPI
_tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR lpstrCmdLine, int nCmdShow)
{
g_hInstance = hInstance;
HRESULT hRes = ::CoInitialize(NULL);
ATLASSERT(SUCCEEDED(hRes));
// this resolves ATL window thunking problem when Microsoft Layer for Unicode (MSLU) is used
::DefWindowProc(NULL, 0, 0, 0L);
AtlInitCommonControls(ICC_BAR_CLASSES);
hRes = _Module.Init(NULL, hInstance);
ATLASSERT(SUCCEEDED(hRes));
AtlAxWinInit();
if( IsWindowsVistaOrLater() )
{
AESWizard dlgMain;
dlgMain.SetNoMargin();
dlgMain.DoModal(NULL);
if( dlgMain.mBenchmarkHaveResults )
{
CString resultFileName;
CString appFolder = getAppFolder(hInstance);
// Find a temporary name for the file where the results are saved
DWORD dwRetVal = 0;
TCHAR szTempFileName[MAX_PATH];
TCHAR lpTempPathBuffer[MAX_PATH];
// Gets the temp path env string (no guarantee it's a valid path).
dwRetVal = GetTempPath(MAX_PATH, lpTempPathBuffer);
if( dwRetVal > MAX_PATH || (dwRetVal == 0) )
_tcscpy_s(lpTempPathBuffer, MAX_PATH, appFolder);
// Generates a temporary file name.
if( GetTempFileName(lpTempPathBuffer, _T("AMCResults"), 0, szTempFileName) == 0 )
{
_tcscpy_s(szTempFileName, MAX_PATH, lpTempPathBuffer);
_tcscat_s(szTempFileName, MAX_PATH, _T("\\AMC_Results.tmp"));
}
resultFileName = szTempFileName;
if( dlgMain.mAESHelper->SaveBenchResults(resultFileName) )
{
CString viewerPath = appFolder + _T("\\AMC Tool Results Viewer.exe");
TCHAR szArguments[MAX_PATH];
_tcscpy_s(szArguments, MAX_PATH, _T("\""));
_tcscat_s(szArguments, MAX_PATH, szTempFileName);
_tcscat_s(szArguments, MAX_PATH, _T("\""));
if( (int)ShellExecute(GetDesktopWindow(), _T("open"), viewerPath, szArguments, NULL, SW_SHOWNORMAL) <= 32 )
_tunlink(szTempFileName);
}
}
}
else
MessageBox(NULL, _T("This application can run only on Windows Vista or newer!"),
_T("AMC Tool: Error"), MB_OK | MB_ICONERROR | MB_SYSTEMMODAL);
_Module.Term();
::CoUninitialize();
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
118
]
]
]
|
3ec2cb2b9792bc7bcc008425189e6205788add0c | bdb8fc8eb5edc84cf92ba80b8541ba2b6c2b0918 | /TPs CPOO/Gareth & Maxime/Projet/CanonNoir_Moteur_C++/fichiers/Caravelle.h | 758a12825c81d1194342d1bf1f217dd55420b6b2 | []
| 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 | 612 | h | /**
*\file Caravelle.h
*\brief File containing the attributes and function declarations of the Caravelle class
*\author Maxime HAVEZ
*\author Gareth THIVEUX
*\version 1.0
*/
#ifndef CARAVELLE_H
#define CARAVELLE_H
#include "Bateau.h"
class Caravelle : public Bateau
{
public :
/**
*\fn virtual char type()
*\brief Inherited function which gives the name of the class
*\return char the name of the class
*/
char type();
/**
*\fn Caravelle()
*\brief Default constructor
*/
Caravelle();
};
inline char Caravelle::type() { return 'C';}
#endif
| [
"havez.maxime.01@9f3b02c3-fd90-5378-97a3-836ae78947c6",
"garethiveux@9f3b02c3-fd90-5378-97a3-836ae78947c6"
]
| [
[
[
1,
2
],
[
6,
8
],
[
12,
20
],
[
22,
27
],
[
29,
35
]
],
[
[
3,
5
],
[
9,
11
],
[
21,
21
],
[
28,
28
],
[
36,
36
]
]
]
|
5e15cfe9c6959cd0479e580131ef0ba2c6256b63 | d258dd0ca5e8678c8eb81777e5fe360b8bbf7b7e | /Library/PhysXCPP/NxaControllerDescription.cpp | 5e7422180933ab61fd161a3b185a449df875b9aa | []
| no_license | ECToo/physxdotnet | 1e7d7e9078796f1dad5c8582d28441a908e11a83 | 2b85d57bc877521cdbf1a9147bd6716af68a64b0 | refs/heads/master | 2021-01-22T07:17:58.918244 | 2008-04-13T11:15:26 | 2008-04-13T11:15:26 | 32,543,781 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,404 | cpp | #include "StdAfx.h"
#include "NxaControllerDescription.h"
NxaControllerDescription::NxaControllerDescription(NxControllerDesc * ptr)
{
nxControllerDesc = ptr;
}
NxaControllerDescription::~NxaControllerDescription()
{
this->!NxaControllerDescription();
}
NxaControllerDescription::!NxaControllerDescription()
{
}
void NxaControllerDescription::SetToDefault()
{
nxControllerDesc->setToDefault();
}
bool NxaControllerDescription::IsValid()
{
return nxControllerDesc->isValid();
}
Vector3 NxaControllerDescription::Position::get()
{
return NxaMath::Vector3ExtendedPhysXToXNA(nxControllerDesc->position);
}
void NxaControllerDescription::Position::set(Vector3 value)
{
nxControllerDesc->position = NxaMath::Vector3XNAToExtendedPhysX(value);
}
float NxaControllerDescription::SlopeLimit::get()
{
return nxControllerDesc->slopeLimit;
}
void NxaControllerDescription::SlopeLimit::set(float value)
{
nxControllerDesc->slopeLimit = value;
}
float NxaControllerDescription::SkinWidth::get()
{
return nxControllerDesc->skinWidth;
}
void NxaControllerDescription::SkinWidth::set(float value)
{
nxControllerDesc->skinWidth = value;
}
float NxaControllerDescription::StepOffset::get()
{
return nxControllerDesc->stepOffset;
}
void NxaControllerDescription::StepOffset::set(float value)
{
nxControllerDesc->stepOffset = value;
}
| [
"thomasfannes@e8b6d1ee-b643-0410-9178-bfabf5f736f5"
]
| [
[
[
1,
66
]
]
]
|
3a2f260a583e04b828feb74e518be13e4b95c61b | b407e323eb85b469258b0c30892dc70b160ecdbc | /whoisalive/tiler.h | 2343e94667ab6c2c7f23eeff35e1308d88871e61 | []
| no_license | vi-k/whoisalive.fromsvn | 7f8acf1cc8f5573008327fb61b419ed0f1676f42 | c77b9619d470291389c8938e7cab87674a09f654 | refs/heads/master | 2021-01-10T02:13:41.786614 | 2010-05-30T23:18:47 | 2010-05-30T23:18:47 | 44,526,121 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,441 | h | #ifndef WHO_TILER_H
#define WHO_TILER_H
#include "ipgui.h"
#include "../common/my_thread.h"
#include "../common/my_inet.h"
#include "../common/my_mru.h"
#include <string>
#include <list>
#include <map>
#include <boost/functional/hash.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/function.hpp>
namespace who {
class server;
namespace tiler {
struct map
{
enum projection_t {wgs84, spheroid};
std::wstring id;
std::wstring name;
bool is_layer;
std::wstring tile_type;
std::wstring ext;
projection_t projection;
};
struct tile_id
{
int map_id;
int z;
int x;
int y;
tile_id()
: map_id(0), z(0), x(0), y(0) {}
tile_id(int map_id, int z, int x, int y)
: map_id(map_id), z(z), x(x), y(y) {}
tile_id(const tile_id &other)
: map_id(other.map_id)
, z(other.z)
, x(other.x)
, y(other.y) {}
inline bool operator !() const
{
return map_id == 0
&& z == 0
&& x == 0
&& y == 0;
}
inline bool operator ==(const tile_id &other) const
{
return map_id == other.map_id
&& z == other.z
&& x == other.x
&& y == other.y;
}
friend std::size_t hash_value(const tile_id &t)
{
std::size_t seed = 0;
boost::hash_combine(seed, t.map_id);
boost::hash_combine(seed, t.z);
boost::hash_combine(seed, t.x);
boost::hash_combine(seed, t.y);
return seed;
}
};
struct tile
{
typedef boost::shared_ptr<tile> ptr;
bool loaded;
Gdiplus::Image image;
tile(const std::wstring &filename)
: loaded(false)
, image(filename.c_str())
{
if (image.GetWidth() && image.GetHeight())
loaded = true;
}
};
/* Tiler-сервер */
class server
{
private:
typedef std::map<int, map> maps_list;
typedef my::mru::list<tile_id, tile::ptr> tiles_list;
bool terminate_;
boost::thread thread_;
who::server &server_;
maps_list maps_;
tiles_list tiles_;
s_mutex tiles_mutex_; /* shared_mutex */
mutex maps_mutex_;
condition_variable cond_;
boost::function<void ()> on_update_;
static int get_new_map_id_()
{
static int id = 0;
return ++id;
}
void thread_proc();
public:
server(who::server &server, size_t max_tiles, boost::function<void ()> on_update_proc);
~server();
inline void wake_up()
{ cond_.notify_all(); }
int add_map(const tiler::map &map);
tile::ptr get_tile(int map_id, int z, int x, int y);
};
} }
#endif
| [
"victor.dunaev@localhost"
]
| [
[
[
1,
137
]
]
]
|
c46f91bfa4ceed22ce697c22dad64ffafeea2562 | 90aa2eebb1ab60a2ac2be93215a988e3c51321d7 | /castor/branches/boost/libs/castor/test/test_prefix_unary_ops.cpp | 9a01bdbb09a04dcc82a235ee0fbf7cc094b395c6 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | roshannaik/castor | b9f4ea138a041fe8bccf2d8fc0dceeb13bcca5a6 | e86e2bf893719bf3164f9da9590217c107cbd913 | refs/heads/master | 2021-04-18T19:24:38.612073 | 2010-08-18T05:10:39 | 2010-08-18T05:10:39 | 126,150,539 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 731 | cpp | #include <boost/castor.h>
#include <boost/test/minimal.hpp>
#include "test_ile.h"
using namespace castor;
int test_main(int, char * [])
{
{ // Simple Prefix increment/decrement
lref<int> li = 1;
BOOST_CHECK((++li)() == 2);
BOOST_CHECK(*li == 2);
BOOST_CHECK((--li)() == 1);
BOOST_CHECK(*li == 1);
}
{ // Compound Prefix increment expression
lref<int> li = 2;
BOOST_CHECK((++(++(++li)) * 2 + 5)() == 15);
BOOST_CHECK(*li == 5);
}
{ // Compound Prefix decrement expression
lref<int> li = 5;
BOOST_CHECK((--(--(--li)) * 2)() == 4);
BOOST_CHECK(*li == 2);
}
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
37
]
]
]
|
127d38cd3e31d136e2d6733c836e9e02ab3a97e8 | 7a310d01d1a4361fd06b40a74a2afc8ddc23b4d3 | /src_plugin/PluginMaking/TabMoveBar/MoveTab.h | d98b67ae72c6f62497adeda2081ef6e19f5d4aae | []
| no_license | plus7/DonutG | b6fec6111d25b60f9a9ae5798e0ab21bb2fa28f6 | 2d204c36f366d6162eaf02f4b2e1b8bc7b403f6b | refs/heads/master | 2020-06-01T15:30:31.747022 | 2010-08-21T18:51:01 | 2010-08-21T18:51:01 | 767,753 | 1 | 2 | null | null | null | null | SHIFT_JIS | C++ | false | false | 681 | h | // MoveTab.h: CMoveTab クラスのインターフェイス
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_MOVETAB_H__EE715D23_BE8D_4F82_97D5_ADA875E1F162__INCLUDED_)
#define AFX_MOVETAB_H__EE715D23_BE8D_4F82_97D5_ADA875E1F162__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CMoveTab {
public:
CMoveTab();
virtual ~CMoveTab();
BOOL MoveTabLeft();
BOOL MoveTabRight();
BOOL MoveTabLeftEnd();
BOOL MoveTabRightEnd();
protected:
BOOL InitCom();
void UnInitCom();
IAPI* GetIAPI();
};
#endif // !defined(AFX_MOVETAB_H__EE715D23_BE8D_4F82_97D5_ADA875E1F162__INCLUDED_)
| [
"[email protected]"
]
| [
[
[
1,
28
]
]
]
|
16ab6f6b2f31a0415ca707306fded78c3619b2d3 | f9774f8f3c727a0e03c170089096d0118198145e | /传奇mod/Mir2ExCode/Mir2/GameProcess/Interface.cpp | a176e4f964187bb27afb3b0aa2764fe7ef14643d | []
| 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 | 55,228 | cpp | /******************************************************************************************************************
모듈명:
작성자:
작성일:
[일자][수정자] : 수정 내용
*******************************************************************************************************************/
#include "StdAfx.h"
/******************************************************************************************************************
함수명 : CInterface::CInterface()
작성자 :
작성일 :
목적 :
출력 :
[일자][수정자] : 수정내용
*******************************************************************************************************************/
CInterface::CInterface()
{
Init();
}
/******************************************************************************************************************
함수명 : CInterface::~CInterface()
작성자 :
작성일 :
목적 :
출력 :
[일자][수정자] : 수정내용
*******************************************************************************************************************/
CInterface::~CInterface()
{
Destroy();
}
/******************************************************************************************************************
함수명 : CInterface::Init()
작성자 :
작성일 :
목적 : 인터페이스관련 변수및, 객체초기화.
출력 : VOID
[일자][수정자] : 수정내용
*******************************************************************************************************************/
VOID CInterface::Init()
{
m_nIdxMsgBox = 0;
m_nFstLine = 0;
m_shBeltHeight = 0;
m_bShowKey = FALSE;
m_bMoveFocusedWnd = FALSE;
m_bBeltState = _BELT_STATE_STAY;
SetRect(&m_rcMain, 0, 0, 0, 0);
SetRect(&m_rcChat, 0, 0, 0, 0);
ZeroMemory(&m_stCommonItem, sizeof(ITEMSET));
m_xClientSysMsg.Init();
m_pxInterImg = NULL;
m_xInterImgEx.Init();
m_xStatusWnd.Init();
m_xStoreWnd.Init();
m_xGuildWnd.Init();
m_xGroupWnd.Init();
m_xChatPopWnd.Init();
m_xExchangeWnd.Init();
m_xGroupPopWnd.Init();
m_xInventoryWnd.Init();
m_xGuildMasterWnd.Init();
for ( INT nCnt = 0; nCnt < _MAX_INTER_BTN; nCnt++ )
{
m_xInterBtn[nCnt].Init();
}
m_xScrlBar.Init();
m_xChat.ClearAllNodes();
m_xWndOrderList.ClearAllNodes();
}
/******************************************************************************************************************
함수명 : CInterface::Destroy()
작성자 :
작성일 :
목적 : 인터페이스관련 변수, 객체의 소멸및, 초기화.
출력 : VOID
[일자][수정자] : 수정내용
*******************************************************************************************************************/
VOID CInterface::Destroy()
{
m_xClientSysMsg.Destroy();
m_xInterImgEx.Destroy();
m_pxInterImg = NULL;
m_xInventoryWnd.Destroy();
m_xStoreWnd.Destroy();
m_xStatusWnd.Destroy();
m_xGuildWnd.Destroy();
m_xGroupWnd.Destroy();
m_xExchangeWnd.Destroy();
m_xGuildMasterWnd.Destroy();
m_xGroupPopWnd.Destroy();
m_xChatPopWnd.Destroy();
for ( INT nCnt = 0; nCnt < _MAX_INTER_BTN; nCnt++ )
{
m_xInterBtn[nCnt].Destroy();
}
m_xChat.ClearAllNodes();
m_xWndOrderList.ClearAllNodes();
Init();
}
VOID CInterface::CreateInterface(CImageHandler* pxImgHandler)
{
m_pxInterImg = &(pxImgHandler->m_xImageList[_IMAGE_INTER]);
//------------------------------------------------------------------------------------------------------------
// 채팅에디트 윈도우 위치지정.
MoveWindow(g_xChatEditBox.GetSafehWnd(),
g_xMainWnd.m_rcWindow.left+_INPUT_EDITWND_XPOS, g_xMainWnd.m_rcWindow.top+_INPUT_EDITWND_YPOS,
_INPUT_EDITWND_WIDTH, _INPUT_EDITWND_HEIGHT, TRUE);
//------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------
// 인터페이스 이미지 로드.
m_pxInterImg->NewLoad(".\\Data\\gameinter.wil");
m_xInterImgEx.NewLoad(".\\Data\\interfacec2.wil");
//------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------
// 메인인터페이스 영역설정.
if ( m_pxInterImg->NewSetIndex(_WNDIMGIDX_MAIN) )
{
SetRect(&m_rcMain,
0, (600-m_pxInterImg->m_lpstNewCurrWilImageInfo->shHeight),
m_pxInterImg->m_lpstNewCurrWilImageInfo->shWidth, 600);
}
//------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------
// 채팅 영역설정.
SetRect(&m_rcChat, 224, 471, 578, 545);
//------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------
// 윈도우들 생성.
m_xInventoryWnd.CreateInventoryWnd(_WND_ID_INVENTORY, m_pxInterImg, _WNDIMGIDX_INVENTORY, 0, 0, 0, 0, TRUE);
m_xStatusWnd.CreateStatusWnd(_WND_ID_STATUS, m_pxInterImg, _WNDIMGIDX_ITEMSET, 510, 0, 0, 0, TRUE);
m_xStoreWnd.CreateStoreWnd(_WND_ID_STORE, m_pxInterImg, _WNDIMGIDX_STORE, 0, 0, 0, 0, TRUE);
m_xExchangeWnd.CreateExchangeWnd(_WND_ID_EXCHANGE, m_pxInterImg, _WNDIMGIDX_EXCHANGE, 0, 0, 0, 0, TRUE);
m_xGuildMasterWnd.CreateGuildMasterWnd(_WND_ID_GUILDMASTER, m_pxInterImg, _WNDIMGIDX_GUILDMASTER, 0, 0, 0, 0, TRUE);
m_xGuildWnd.CreateGuildWnd(_WND_ID_GUILD, &m_xInterImgEx, _WNDIMGIDX_GUILD, 0, 0, 540, 442, TRUE);
m_xGroupWnd.CreateGroupWnd(_WND_ID_GROUP, m_pxInterImg, _WNDIMGIDX_GROUP, 0, 0, 0, 0, TRUE);
m_xGroupPopWnd.CreateGroupPopWnd(_WND_ID_GROUPPOP, &m_xInterImgEx, _WNDIMGIDX_GROUPPOP, 0, 0, 260, 114, TRUE);
m_xChatPopWnd.CreateChatPopWnd(_WND_ID_CHATPOP, m_pxInterImg, _WNDIMGIDX_CHATPOP, 0, 0, 0, 0, TRUE);
m_xOptionWnd.CreateOptionWnd(_WND_ID_OPTION, m_pxInterImg, _WNDIMGIDX_OPTION, 0, 0, 0, 0, TRUE);
m_xQuestWnd.CreateQuestWnd(_WND_ID_QUEST, m_pxInterImg, _WNDIMGIDX_QUEST, 0, 0, 0, 0, TRUE);
m_xHorseWnd.CreateHorseWnd(_WND_ID_HORSE, m_pxInterImg, _WNDIMGIDX_HORSE, 0, 0, 0, 0, TRUE);
m_xNPCWnd.CreateNPCChatWnd(_WND_ID_NPCCHAT, m_pxInterImg, _WNDIMGIDX_NPCCHAT, 0, 0, 0, 0, TRUE); // 용기
//------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------
// 버튼 초기화.
m_xInterBtn[ 0].CreateGameBtn(m_pxInterImg, 80, 81, m_rcMain.left+204, m_rcMain.top+0); // 교환창.
m_xInterBtn[ 1].CreateGameBtn(m_pxInterImg, 82, 83, m_rcMain.left+228, m_rcMain.top+0); // 미니맵.
m_xInterBtn[ 2].CreateGameBtn(m_pxInterImg, 84, 85, m_rcMain.left+252, m_rcMain.top+0); // 무공창.
m_xInterBtn[ 3].CreateGameBtn(m_pxInterImg, 90, 91, m_rcMain.left+161, m_rcMain.top+65); // 게임종료.
m_xInterBtn[ 4].CreateGameBtn(m_pxInterImg, 92, 93, m_rcMain.left+161, m_rcMain.top+101); // 로그아웃.
m_xInterBtn[ 5].CreateGameBtn(m_pxInterImg, 94, 95, m_rcMain.left+616, m_rcMain.top+66); // 그룹.
m_xInterBtn[ 6].CreateGameBtn(m_pxInterImg, 96, 97, m_rcMain.left+616, m_rcMain.top+102); // 문파.
m_xInterBtn[ 7].CreateGameBtn(m_pxInterImg, 52, 53, m_rcMain.left+397, m_rcMain.top+13); // 벨트 UP, DOWN.
m_xInterBtn[ 8].CreateGameBtn(m_pxInterImg,100, 101, m_rcMain.left+703, m_rcMain.top+34); // 스킬창.
m_xInterBtn[ 9].CreateGameBtn(m_pxInterImg,102, 103, m_rcMain.left+718, m_rcMain.top+50); // 채팅팝업.
m_xInterBtn[10].CreateGameBtn(m_pxInterImg,104, 105, m_rcMain.left+718, m_rcMain.top+88); // 퀘스트.
m_xInterBtn[11].CreateGameBtn(m_pxInterImg,106, 107, m_rcMain.left+703, m_rcMain.top+103); // 옵션.
m_xInterBtn[12].CreateGameBtn(m_pxInterImg,108, 109, m_rcMain.left+664, m_rcMain.top+104); // 도움말.
m_xInterBtn[13].CreateGameBtn(m_pxInterImg,110, 111, m_rcMain.left+648, m_rcMain.top+88); // 말창.
m_xInterBtn[14].CreateGameBtn(m_pxInterImg,112, 113, m_rcMain.left+648, m_rcMain.top+50); // 가방창.
m_xInterBtn[15].CreateGameBtn(m_pxInterImg,114, 115, m_rcMain.left+665, m_rcMain.top+34); // 상태창.
//------------------------------------------------------------------------------------------------------------
m_xScrlBar.CreateScrlBar(m_pxInterImg, 68, _MAX_CHATLINE, 12, 84, 12);
m_xMsgBox.Load(&m_xInterImgEx); // 용기
}
/******************************************************************************************************************
함수명 : CInterface::MsgAdd()
작성자 :
작성일 :
목적 :
입력 : DWORD dwFontColor
DWORD dwFontBackColor
CHAR* pszMsg
출력 : VOID
[일자][수정자] : 수정내용
*******************************************************************************************************************/
VOID CInterface::MsgAdd(DWORD dwFontColor, DWORD dwFontBackColor, CHAR* pszMsg)
{
if ( pszMsg )
{
if ( pszMsg[0] != NULL )
{
INT nCnt;
CHAT stChat;
INT nLineCnt;
CHAR pszDivied[MAX_PATH*2];
CHAR pszArg[5][MAX_PATH];
m_xChatPopWnd.MsgAdd(dwFontColor, dwFontBackColor, pszMsg);
ZeroMemory(pszDivied, MAX_PATH*2);
ZeroMemory(pszArg, MAX_PATH*5);
g_xMainWnd.StringDivide(m_rcChat.right-m_rcChat.left, nLineCnt, pszMsg, pszDivied);
sscanf(pszDivied, "%[^`]%*c %[^`]%*c %[^`]%*c %[^`]%*c %[^`]%*c", pszArg[0], pszArg[1], pszArg[2], pszArg[3], pszArg[4]);
if ( nLineCnt > 5 )
{
nLineCnt = 5;
}
// 문자열 삽입.
for ( nCnt = 0; nCnt < nLineCnt; nCnt++ )
{
// 칸이 다음으로 갈조건.
if ( m_xChat.GetCounter() - m_nFstLine == _MAX_CHATLINE )
{
m_nFstLine++;
}
stChat.dwFontColor = dwFontColor;
stChat.dwBackColor = dwFontBackColor;
strcpy(stChat.pszChat, pszArg[nCnt]);
m_xChat.AddNode(stChat);
}
// 최대저장라인 검사해서 그이상이면 삭제한다.
while ( m_xChat.GetCounter() >= 50 )
{
m_xChat.MoveCurrentToTop();
m_xChat.DeleteCurrentNode();
if ( m_nFstLine > 0 )
m_nFstLine--;
}
}
}
}
/******************************************************************************************************************
함수명 : CInterface::ShowWndList()
작성자 :
작성일 :
목적 : Active되어있는 윈도우의 리스트를 보여준다.
출력 : VOID
[일자][수정자] : 수정내용
*******************************************************************************************************************/
VOID CInterface::ShowWndList()
{
if ( m_xWndOrderList.GetCounter() != 0 )
{
m_xWndOrderList.MoveCurrentToTop();
INT* pnCurrID;
for ( INT nCnt = 0; nCnt < m_xWndOrderList.GetCounter(); nCnt++ )
{
pnCurrID = m_xWndOrderList.GetCurrentData();
switch ( *pnCurrID )
{
case _WND_ID_INVENTORY:
m_xInventoryWnd.ShowInventoryWnd();
break;
case _WND_ID_STATUS:
m_xStatusWnd.ShowStatusWnd();
break;
case _WND_ID_STORE:
m_xStoreWnd.ShowStoreWnd();
break;
case _WND_ID_EXCHANGE:
m_xExchangeWnd.ShowExchangeWnd();
break;
case _WND_ID_GUILDMASTER:
m_xGuildMasterWnd.ShowGuildMasterWnd();
break;
case _WND_ID_GUILD:
m_xGuildWnd.ShowGuildWnd();
break;
case _WND_ID_GROUP:
m_xGroupWnd.ShowGroupWnd();
break;
case _WND_ID_GROUPPOP:
m_xGroupPopWnd.ShowGroupPopWnd();
break;
case _WND_ID_CHATPOP:
m_xChatPopWnd.ShowChatPopWnd();
break;
case _WND_ID_NPCCHAT: // 용기
m_xNPCWnd.ShowNPCChatWnd();
break;
case _WND_ID_QUEST:
m_xQuestWnd.ShowQuestWnd();
break;
case _WND_ID_OPTION:
m_xOptionWnd.ShowOptionWnd();
break;
case _WND_ID_HORSE:
m_xHorseWnd.ShowHorseWnd();
break;
}
m_xWndOrderList.MoveNextNode();
}
}
}
/******************************************************************************************************************
함수명 : CInterface::ShowChatList()
작성자 :
작성일 :
목적 : 채팅 리스트를 보여준다.
출력 : VOID
[일자][수정자] : 수정내용
*******************************************************************************************************************/
VOID CInterface::ShowChatList()
{
if ( !m_xChat.CheckEmpty() )
{
INT nCnt, nShowLine;
LPCHAT pstChat;
m_xChat.MoveCurrentToTop();
m_xChat.MoveNode(m_nFstLine);
nShowLine = ((m_xChat.GetCounter() - m_nFstLine ) >= _MAX_CHATLINE) ? _MAX_CHATLINE : m_xChat.GetCounter() - m_nFstLine;
for ( nCnt = 0; nCnt < nShowLine; nCnt++ )
{
pstChat = m_xChat.GetCurrentData();
g_xMainWnd.PutsHan(g_xMainWnd.GetBackBuffer(),
m_rcChat.left, m_rcChat.top+nCnt*15,
pstChat->dwBackColor, pstChat->dwFontColor, pstChat->pszChat);
m_xChat.MoveNextNode();
}
}
}
/******************************************************************************************************************
함수명 : CInterface::RenderInterface()
작성자 :
작성일 :
목적 :
입력 : INT nLoopTime
POINT ptMousePos
출력 : VOID
[일자][수정자] : 수정내용
*******************************************************************************************************************/
VOID CInterface::RenderInterface(INT nLoopTime, POINT ptMousePos)
{
INT nX, nY, nCnt;
// 윈도우.
ShowWndList();
// 마우스 아이템.
if ( m_stCommonItem.bSetted && !m_stCommonItem.bIsHideItem )
{
nX = ptMousePos.x - _INVENTORY_CELL_WIDTH /2;
nY = ptMousePos.y - _INVENTORY_CELL_HEIGHT/2;
m_stCommonItem.xItem.DrawItem(nX, nY);
}
// 벨트아이템.
ShowBeltItem();
// 메인인터페이스.
if ( m_pxInterImg->NewSetIndex(_WNDIMGIDX_MAIN) )
{
g_xMainWnd.DrawWithImageForCompClipRgn(m_rcMain.left, m_rcMain.top, m_rcMain.right-m_rcMain.left, m_rcMain.bottom-m_rcMain.top,
(WORD*)m_pxInterImg->m_pbCurrImage, _CLIP_WIDTH, 600);
}
// 채팅리스트.
ShowChatList();
// 상태치.
ShowGameStatus();
// 버튼.
for ( nCnt = 0; nCnt < _MAX_INTER_BTN; nCnt++)
{
m_xInterBtn[nCnt].ShowGameBtn();
}
// 스크롤바.
m_xScrlBar.ShowScrlBar(584, 404, m_nFstLine, m_xChat.GetCounter());
// 클라이언트메시지(왼쪽상단).
m_xClientSysMsg.ShowSysMsg(nLoopTime, 30, 30);
// 용기
m_xMsgBox.RenderMessageBox(0);
ShowMagicKey();
}
/******************************************************************************************************************
함수명 : CInterface::ShowBeltItem()
작성자 :
작성일 :
목적 :
출력 : VOID
[일자][수정자] : 수정내용
*******************************************************************************************************************/
VOID CInterface::ShowBeltItem()
{
INT nX, nY;
if ( m_bBeltState == _BELT_STATE_UP )
{
m_shBeltHeight += 10;
if ( m_shBeltHeight >= 46 )
{
m_shBeltHeight = 46;
}
}
else if ( m_bBeltState == _BELT_STATE_DOWN )
{
m_shBeltHeight -= 10;
if ( m_shBeltHeight <= 0 )
{
m_shBeltHeight = 0;
m_bBeltState = _BELT_STATE_STAY;
}
}
if ( m_bBeltState != _BELT_STATE_STAY )
{
if ( m_pxInterImg->NewSetIndex(_IMGIDX_BELT) )
{
g_xMainWnd.DrawWithImageForCompClipRgn(275, 457-m_shBeltHeight,
m_pxInterImg->m_lpstNewCurrWilImageInfo->shWidth,
m_pxInterImg->m_lpstNewCurrWilImageInfo->shHeight,
(WORD*)m_pxInterImg->m_pbCurrImage, _CLIP_WIDTH, 600);
// 벨트 아이템 그리기.
for ( INT nCnt = 0; nCnt < _MAX_BELT_ITEM; nCnt++ )
{
if ( m_xInventoryWnd.m_stBeltItem[nCnt].bSetted )
{
nX = 275 + 8 + nCnt*40;
nY = 411 + 6 + 46 - m_shBeltHeight;
m_xInventoryWnd.m_stBeltItem[nCnt].xItem.DrawItem(nX, nY);
}
}
}
}
}
/******************************************************************************************************************
함수명 : CInterface::ShowGameStatus()
작성자 :
작성일 :
목적 :
출력 : BOOL
[일자][수정자] : 수정내용
*******************************************************************************************************************/
VOID CInterface::ShowGameStatus()
{
FLOAT fMyHPRate;
FLOAT fMyMPRate;
FLOAT fMyWetRate;
FLOAT fMyExpRate;
WORD wJobIcon;
WORD wImgNum;
CHAR pszBuff[MAX_PATH];
RECT rcStats;
DWORD dwFntClr;
BYTE bMyJob = g_xGameProc.m_xMyHero.m_bJob;
BYTE bMyLevel= g_xGameProc.m_xMyHero.m_stAbility.bLevel;
WORD wMyAC = g_xGameProc.m_xMyHero.m_stAbility.wAC;
WORD wMyDC = g_xGameProc.m_xMyHero.m_stAbility.wDC;
WORD wMyMC = g_xGameProc.m_xMyHero.m_stAbility.wMC;
WORD wMySC = g_xGameProc.m_xMyHero.m_stAbility.wSC;
BYTE bDay = g_xGameProc.m_bDayState;
WORD wHP = g_xGameProc.m_xMyHero.m_stAbility.wHP;
WORD wMP = g_xGameProc.m_xMyHero.m_stAbility.wMP;
WORD wWet = g_xGameProc.m_xMyHero.m_stAbility.wWeight;
DWORD dwExp = g_xGameProc.m_xMyHero.m_stAbility.dwExp;
BYTE bJob = g_xGameProc.m_xMyHero.m_bJob;
// 하루의 상태치(밤, 낮, 저녁, 새벽)
switch ( bDay )
{
case _DAYSTATE_DAY:
wImgNum = 130;
break;
case _DAYSTATE_DUSK:
wImgNum = 131;
break;
case _DAYSTATE_NIGHT:
wImgNum = 132;
break;
case _DAYSTATE_DAWN:
wImgNum = 133;
break;
}
if ( m_pxInterImg->NewSetIndex(wImgNum) )
{
g_xMainWnd.DrawWithImageForComp(m_rcMain.left+684, m_rcMain.top+70,
m_pxInterImg->m_lpstNewCurrWilImageInfo->shWidth,
m_pxInterImg->m_lpstNewCurrWilImageInfo->shHeight,
(WORD*)m_pxInterImg->m_pbCurrImage, _CLIP_WIDTH, 600);
}
// HP, MP찍기.
// 비율검사.
if ( wHP )
{
fMyHPRate = (FLOAT)((FLOAT)wHP/(FLOAT)g_xGameProc.m_xMyHero.m_stAbility.wMaxHP);
if ( fMyHPRate > 1.0f )
{
fMyHPRate = 1.0f;
}
}
else
{
fMyHPRate = 0;
}
if ( wMP )
{
fMyMPRate = (FLOAT)((FLOAT)wMP/(FLOAT)g_xGameProc.m_xMyHero.m_stAbility.wMaxMP);
if ( fMyMPRate > 1.0f )
{
fMyMPRate = 1.0f;
}
}
else
{
fMyMPRate = 0;
}
if ( dwExp )
{
fMyExpRate = (FLOAT)((FLOAT)dwExp/(FLOAT)g_xGameProc.m_xMyHero.m_stAbility.dwMaxExp);
if ( fMyExpRate > 1.0f )
{
fMyExpRate = 1.0f;
}
}
else
{
fMyExpRate = 0;
}
if ( wWet )
{
fMyWetRate = (FLOAT)((FLOAT)wWet /(FLOAT)g_xGameProc.m_xMyHero.m_stAbility.wMaxWeight);
if ( fMyWetRate > 1.0f )
{
fMyWetRate = 1.0f;
}
}
else
{
fMyWetRate = 0;
}
if ( m_pxInterImg->NewSetIndex(60) )
{
RECT rcHP = { 0, m_pxInterImg->m_lpstNewCurrWilImageInfo->shHeight-(m_pxInterImg->m_lpstNewCurrWilImageInfo->shHeight*fMyHPRate),
m_pxInterImg->m_lpstNewCurrWilImageInfo->shWidth, m_pxInterImg->m_lpstNewCurrWilImageInfo->shHeight };
g_xMainWnd.DrawWithImageForComp(m_rcMain.left+46, m_rcMain.top+34, rcHP, (WORD*)m_pxInterImg->m_pbCurrImage);
}
if ( m_pxInterImg->NewSetIndex(61) )
{
RECT rcMP = { 0, m_pxInterImg->m_lpstNewCurrWilImageInfo->shHeight-(m_pxInterImg->m_lpstNewCurrWilImageInfo->shHeight*fMyMPRate),
m_pxInterImg->m_lpstNewCurrWilImageInfo->shWidth, m_pxInterImg->m_lpstNewCurrWilImageInfo->shHeight };
g_xMainWnd.DrawWithImageForComp(m_rcMain.left+104, m_rcMain.top+34, rcMP, (WORD*)m_pxInterImg->m_pbCurrImage);
}
// EXP, WET 찍기.
if ( m_pxInterImg->NewSetIndex(63) )
{
RECT rcEXP = { 0, m_pxInterImg->m_lpstNewCurrWilImageInfo->shHeight-(m_pxInterImg->m_lpstNewCurrWilImageInfo->shHeight*fMyExpRate),
m_pxInterImg->m_lpstNewCurrWilImageInfo->shWidth, m_pxInterImg->m_lpstNewCurrWilImageInfo->shHeight };
g_xMainWnd.DrawWithImageForComp(m_rcMain.left+76, m_rcMain.top+35, rcEXP, (WORD*)m_pxInterImg->m_pbCurrImage);
}
if ( m_pxInterImg->NewSetIndex(67) )
{
RECT rcWET = { 0, m_pxInterImg->m_lpstNewCurrWilImageInfo->shHeight-(m_pxInterImg->m_lpstNewCurrWilImageInfo->shHeight*fMyWetRate),
m_pxInterImg->m_lpstNewCurrWilImageInfo->shWidth, m_pxInterImg->m_lpstNewCurrWilImageInfo->shHeight };
g_xMainWnd.DrawWithImageForComp(m_rcMain.left+211, m_rcMain.top+35, rcWET, (WORD*)m_pxInterImg->m_pbCurrImage);
}
dwFntClr = RGB(225, 225, 0);
// 레벨찍6기.
sprintf(pszBuff, "%d", g_xGameProc.m_xMyHero.m_stAbility.bLevel);
SetRect(&rcStats, 693, 528, 709, 544);
g_xMainWnd.PutsHan(NULL, rcStats, dwFntClr, RGB(0, 0, 0), pszBuff, g_xMainWnd.CreateGameFont("궁서체", 10, 0, FW_BOLD));
dwFntClr = RGB(255, 255, 200);
// 맵이름 및 좌표찍기.
sprintf(pszBuff, "%s : [%d,%d]", g_xGameProc.m_szMapName, g_xGameProc.m_xMyHero.m_wPosX, g_xGameProc.m_xMyHero.m_wPosY);
SetRect(&rcStats, 219, 584, 379, 599);
g_xMainWnd.PutsHan(NULL, rcStats, dwFntClr, RGB(0, 0, 0), pszBuff);
dwFntClr = RGB(255, 200, 50);
// 직업별 아이콘및 특성치 찍기.
sprintf(pszBuff, "%d-%d", LOBYTE(wMyAC), HIBYTE(wMyAC));
SetRect(&rcStats, 422, 584, 483, 599);
g_xMainWnd.PutsHan(NULL, rcStats, dwFntClr, RGB(0, 0, 0), pszBuff);
SetRect(&rcStats, 520, 584, 581, 599);
switch ( bJob )
{
case _JOB_DOSA:
{
wJobIcon = 66;
wImgNum = 123;
sprintf(pszBuff, "%d-%d", LOBYTE(wMySC), HIBYTE(wMySC));
g_xMainWnd.PutsHan(NULL, rcStats, dwFntClr, RGB(0, 0, 0), pszBuff);
}
break;
case _JOB_SULSA:
{
wJobIcon = 65;
wImgNum = 124;
sprintf(pszBuff, "%d-%d", LOBYTE(wMyMC), HIBYTE(wMyMC));
g_xMainWnd.PutsHan(NULL, rcStats, dwFntClr, RGB(0, 0, 0), pszBuff);
}
break;
case _JOB_JUNSA:
{
wJobIcon = 64;
wImgNum = 122;
sprintf(pszBuff, "%d-%d", LOBYTE(wMyDC), HIBYTE(wMyDC));
g_xMainWnd.PutsHan(NULL, rcStats, dwFntClr, RGB(0, 0, 0), pszBuff);
}
break;
}
if ( m_pxInterImg->NewSetIndex(wJobIcon) )
{
g_xMainWnd.DrawWithImageForComp(m_rcMain.left+82, m_rcMain.top+71,
m_pxInterImg->m_lpstNewCurrWilImageInfo->shWidth,
m_pxInterImg->m_lpstNewCurrWilImageInfo->shHeight,
(WORD*)m_pxInterImg->m_pbCurrImage);
}
// AC찍기.
if ( m_pxInterImg->NewSetIndex(120) )
{
g_xMainWnd.DrawWithImageForComp(m_rcMain.left+391, m_rcMain.top+136,
m_pxInterImg->m_lpstNewCurrWilImageInfo->shWidth,
m_pxInterImg->m_lpstNewCurrWilImageInfo->shHeight,
(WORD*)m_pxInterImg->m_pbCurrImage);
}
// DC, MC, SC
if ( m_pxInterImg->NewSetIndex(wImgNum) )
{
g_xMainWnd.DrawWithImageForComp(m_rcMain.left+487, m_rcMain.top+136,
m_pxInterImg->m_lpstNewCurrWilImageInfo->shWidth,
m_pxInterImg->m_lpstNewCurrWilImageInfo->shHeight,
(WORD*)m_pxInterImg->m_pbCurrImage);
}
}
VOID CInterface::ShowMagicKey()
{
if ( m_bShowKey )
{
INT nCnt;
for ( nCnt = 0; nCnt < 8; nCnt++ )
{
if ( m_pxInterImg->NewSetIndex(70+nCnt) )
{
g_xMainWnd.DrawWithABlendCompDataWithBackBuffer(nCnt*m_pxInterImg->m_lpstNewCurrWilImageInfo->shWidth, 0,
m_pxInterImg->m_lpstNewCurrWilImageInfo->shWidth,
m_pxInterImg->m_lpstNewCurrWilImageInfo->shHeight,
(WORD*)m_pxInterImg->m_pbCurrImage, _CLIP_WIDTH, 600);
}
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 윈도우 관리부분/////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************************************************
함수명 : CInterface::GetWindowInMousePos()
작성자 :
작성일 :
목적 : 마우스 포인터를 영역안에 가지고 있는 윈도우리스트중 맨처음 윈도우의 ID를 리턴한다.
입력 : POINT ptMouse
출력 :
[일자][수정자] : 수정내용
*******************************************************************************************************************/
INT CInterface::GetWindowInMousePos(POINT ptMouse)
{
if ( m_xWndOrderList.GetCounter() != 0 )
{
RECT rcWnd;
INT* pnCurrID;
m_xWndOrderList.MoveCurrentToTail();
for ( INT nCnt = m_xWndOrderList.GetCounter()-1; nCnt >= 0 ; nCnt-- )
{
pnCurrID = m_xWndOrderList.GetCurrentData();
switch ( *pnCurrID )
{
case _WND_ID_INVENTORY:
rcWnd = m_xInventoryWnd.GetGameWndRect();
break;
case _WND_ID_STATUS:
rcWnd = m_xStatusWnd.GetGameWndRect();
break;
case _WND_ID_STORE:
rcWnd = m_xStoreWnd.GetGameWndRect();
break;
case _WND_ID_EXCHANGE:
rcWnd = m_xExchangeWnd.GetGameWndRect();
break;
case _WND_ID_GUILDMASTER:
rcWnd = m_xGuildMasterWnd.GetGameWndRect();
break;
case _WND_ID_GUILD:
rcWnd = m_xGuildWnd.GetGameWndRect();
break;
case _WND_ID_GROUP:
rcWnd = m_xGroupWnd.GetGameWndRect();
break;
case _WND_ID_GROUPPOP:
rcWnd = m_xGroupPopWnd.GetGameWndRect();
break;
case _WND_ID_CHATPOP:
rcWnd = m_xChatPopWnd.GetGameWndRect();
break;
case _WND_ID_NPCCHAT: // 용기
rcWnd = m_xNPCWnd.GetGameWndRect();
break;
case _WND_ID_QUEST:
rcWnd = m_xQuestWnd.GetGameWndRect();
break;
case _WND_ID_OPTION:
rcWnd = m_xOptionWnd.GetGameWndRect();
break;
case _WND_ID_HORSE:
rcWnd = m_xHorseWnd.GetGameWndRect();
break;
}
if ( PtInRect(&rcWnd, ptMouse) )
{
return *pnCurrID;
}
m_xWndOrderList.MovePreviousNode();
}
}
return -1;
}
/******************************************************************************************************************
함수명 : CInterface::AddWindowToList()
작성자 :
작성일 :
목적 : 윈도우리스트의 맨 마지막에 현재 입력받은 아이디가 nID인 윈도우를 추가한다.
입력 : INT nID
출력 : VOID
[일자][수정자] : 수정내용
*******************************************************************************************************************/
VOID CInterface::AddWindowToList(INT nID)
{
m_xWndOrderList.AddNode(nID);
}
/******************************************************************************************************************
함수명 : CInterface::DeleteWindowToList()
작성자 :
작성일 :
목적 : nID의 아이디를 가진 윈도우를 리스트상에서 삭제한다.
입력 : INT nID
출력 : VOID
[일자][수정자] : 수정내용
*******************************************************************************************************************/
VOID CInterface::DeleteWindowToList(INT nID)
{
if ( m_xWndOrderList.GetCounter() != 0 )
{
m_xWndOrderList.MoveCurrentToTop();
INT* pnCurrID;
for ( INT nCnt = 0; nCnt < m_xWndOrderList.GetCounter(); nCnt++ )
{
pnCurrID = m_xWndOrderList.GetCurrentData();
if ( *pnCurrID == nID )
{
m_xWndOrderList.DeleteCurrentNode();
break;
}
m_xWndOrderList.MoveNextNode();
}
}
}
/******************************************************************************************************************
함수명 : CInterface::WindowActivate()
작성자 :
작성일 :
목적 : nID인 윈도우를 윈도우리스트에 추가시키거나 삭제시키며, 추가의 경우, 윈도우의 상태를 최상위 상태로 세팅한다.
윈도우가 키입력을 받아서 화면에 나올때 호출하는 함수이다.
입력 : INT nID
출력 : VOID
[일자][수정자] : 수정내용
*******************************************************************************************************************/
BOOL CInterface::WindowActivate(INT nID)
{
// 새로운 윈도우에 포커스를 주기위해서 모든 윈도우의 포커스를 FALSE시켜준다.
BOOL bRet = FALSE;
AllWindowsFocusOff();
switch ( nID )
{
case _WND_ID_INVENTORY:
{
if ( m_xInventoryWnd.GetGameWndActive() )
{
DeleteWindowToList(_WND_ID_INVENTORY);
m_xInventoryWnd.SetGameWndActive(FALSE);
bRet = FALSE;
}
else
{
AddWindowToList(_WND_ID_INVENTORY);
m_xInventoryWnd.SetGameWndActive(TRUE);
bRet = TRUE;
}
}
break;
case _WND_ID_STATUS:
{
if ( m_xStatusWnd.GetGameWndActive() )
{
DeleteWindowToList(_WND_ID_STATUS);
m_xStatusWnd.SetGameWndActive(FALSE);
bRet = FALSE;
}
else
{
AddWindowToList(_WND_ID_STATUS);
m_xStatusWnd.SetGameWndActive(TRUE);
bRet = TRUE;
}
}
break;
case _WND_ID_STORE:
{
if ( m_xStoreWnd.GetGameWndActive() )
{
DeleteWindowToList(_WND_ID_STORE);
m_xStoreWnd.SetGameWndActive(FALSE);
bRet = FALSE;
}
else
{
AddWindowToList(_WND_ID_STORE);
m_xStoreWnd.SetGameWndActive(TRUE);
bRet = TRUE;
}
}
break;
case _WND_ID_EXCHANGE:
{
if ( m_xExchangeWnd.GetGameWndActive() )
{
DeleteWindowToList(_WND_ID_EXCHANGE);
m_xExchangeWnd.SetGameWndActive(FALSE);
bRet = FALSE;
}
else
{
AddWindowToList(_WND_ID_EXCHANGE);
m_xExchangeWnd.SetGameWndActive(TRUE);
bRet = TRUE;
}
}
break;
case _WND_ID_QUEST:
{
if ( m_xQuestWnd.GetGameWndActive() )
{
DeleteWindowToList(_WND_ID_QUEST);
m_xQuestWnd.SetGameWndActive(FALSE);
bRet = FALSE;
}
else
{
AddWindowToList(_WND_ID_QUEST);
m_xQuestWnd.SetGameWndActive(TRUE);
bRet = TRUE;
}
}
break;
case _WND_ID_OPTION:
{
if ( m_xOptionWnd.GetGameWndActive() )
{
DeleteWindowToList(_WND_ID_OPTION);
m_xOptionWnd.SetGameWndActive(FALSE);
bRet = FALSE;
}
else
{
AddWindowToList(_WND_ID_OPTION);
m_xOptionWnd.SetGameWndActive(TRUE);
bRet = TRUE;
}
}
break;
case _WND_ID_HORSE:
{
if ( m_xHorseWnd.GetGameWndActive() )
{
DeleteWindowToList(_WND_ID_HORSE);
m_xHorseWnd.SetGameWndActive(FALSE);
bRet = FALSE;
}
else
{
AddWindowToList(_WND_ID_HORSE);
m_xHorseWnd.SetGameWndActive(TRUE);
bRet = TRUE;
}
}
break;
case _WND_ID_GUILDMASTER:
{
if ( m_xGuildMasterWnd.GetGameWndActive() )
{
DeleteWindowToList(_WND_ID_GUILDMASTER);
m_xGuildMasterWnd.SetGameWndActive(FALSE);
bRet = FALSE;
}
else
{
AddWindowToList(_WND_ID_GUILDMASTER);
m_xGuildMasterWnd.SetGameWndActive(TRUE);
bRet = TRUE;
}
}
break;
case _WND_ID_GUILD:
{
if ( m_xGuildWnd.GetGameWndActive() )
{
DeleteWindowToList(_WND_ID_GUILD);
m_xGuildWnd.SetGameWndActive(FALSE);
bRet = FALSE;
}
else
{
AddWindowToList(_WND_ID_GUILD);
m_xGuildWnd.SetGameWndActive(TRUE);
bRet = TRUE;
}
}
break;
case _WND_ID_GROUP:
{
if ( m_xGroupWnd.GetGameWndActive() )
{
DeleteWindowToList(_WND_ID_GROUP);
m_xGroupWnd.SetGameWndActive(FALSE);
bRet = FALSE;
}
else
{
AddWindowToList(_WND_ID_GROUP);
m_xGroupWnd.SetGameWndActive(TRUE);
bRet = TRUE;
}
}
break;
case _WND_ID_GROUPPOP:
{
if ( m_xGroupPopWnd.GetGameWndActive() )
{
DeleteWindowToList(_WND_ID_GROUPPOP);
m_xGroupPopWnd.SetGameWndActive(FALSE);
bRet = FALSE;
}
else
{
AddWindowToList(_WND_ID_GROUPPOP);
m_xGroupPopWnd.SetGameWndActive(TRUE);
bRet = TRUE;
}
}
break;
case _WND_ID_CHATPOP:
{
if ( m_xChatPopWnd.GetGameWndActive() )
{
MoveWindow(g_xChatEditBox.GetSafehWnd(), g_xMainWnd.m_rcWindow.left+_INPUT_EDITWND_XPOS,
g_xMainWnd.m_rcWindow.top+_INPUT_EDITWND_YPOS, _INPUT_EDITWND_WIDTH, _INPUT_EDITWND_HEIGHT, TRUE);
DeleteWindowToList(_WND_ID_CHATPOP);
m_xChatPopWnd.SetGameWndActive(FALSE);
bRet = FALSE;
}
else
{
MoveWindow(g_xChatEditBox.GetSafehWnd(), g_xMainWnd.m_rcWindow.left + m_xChatPopWnd.m_rcWnd.left + m_xChatPopWnd.m_rcEditBoxFrame.left,
g_xMainWnd.m_rcWindow.top + m_xChatPopWnd.m_rcWnd.top + m_xChatPopWnd.m_rcEditBoxFrame.top,
m_xChatPopWnd.m_rcEditBoxFrame.right - m_xChatPopWnd.m_rcEditBoxFrame.left,
m_xChatPopWnd.m_rcEditBoxFrame.bottom - m_xChatPopWnd.m_rcEditBoxFrame.top, TRUE);
SetFocus(g_xChatEditBox.GetSafehWnd());
AddWindowToList(_WND_ID_CHATPOP);
m_xChatPopWnd.SetGameWndActive(TRUE);
bRet = TRUE;
}
}
break;
case _WND_ID_NPCCHAT: // 용기
{
if ( m_xNPCWnd.GetGameWndActive() )
{
DeleteWindowToList(_WND_ID_NPCCHAT);
// m_xNPCWnd.CloseWnd();
m_xNPCWnd.SetGameWndActive(FALSE);
bRet = FALSE;
}
else
{
// 임시
AddWindowToList(_WND_ID_NPCCHAT);
// m_xNPCWnd.SetNPCStr("하늘을 우러러 한점 부끄럼 없기를 잎세에이는 바람에도 나는 괴로워 했다 <별/@STAR>을 노래하는 마음으로 모든 죽어 가는것을 <사랑/@LOVE>해야지 그리고 또 나에게 주워 진길을 걸어 가야 겠다. 오늘 밤에도 별이 바람에 스치운다. 동해물과 백두산이 마르고 닭토록 하느님이 보우하사 우리나라 만세 무궁화 삼천리 화려강산 대한사람 대한으로 길이 보전하세. 시몬 너는 아느냐 김밥 옆구리 긁는 소리는 시몬 너는 아느냐 긁던 옆구리 터지는 소리를 너무나도 아름다운 그소리를 정넌 너는 모르는 것이냐\n <문파를 생성해볼까?/@@buildguildnow> \n <종료/@end>",0);
m_xNPCWnd.SetGameWndActive(TRUE);
bRet = TRUE;
}
}
break;
}
return bRet;
}
/******************************************************************************************************************
함수명 : CInterface::MoveTopWindow()
작성자 :
작성일 :
목적 : 맨위의 윈도우를 마우스 좌표로 이동시킨다.
입력 : POINT ptMouse
출력 : VOID
[일자][수정자] : 수정내용
*******************************************************************************************************************/
VOID CInterface::MoveTopWindow(POINT ptMouse)
{
if ( m_xWndOrderList.GetCounter() != 0 )
{
INT* pnCurrID;
m_xWndOrderList.MoveCurrentToTail();
pnCurrID = m_xWndOrderList.GetCurrentData();
if ( m_bMoveFocusedWnd )
{
switch ( *pnCurrID )
{
case _WND_ID_INVENTORY:
m_xInventoryWnd.MoveGameWnd(ptMouse);
break;
case _WND_ID_STATUS:
m_xStatusWnd.MoveGameWnd(ptMouse);
break;
case _WND_ID_STORE:
m_xStoreWnd.MoveGameWnd(ptMouse);
break;
case _WND_ID_EXCHANGE:
m_xExchangeWnd.MoveGameWnd(ptMouse);
break;
case _WND_ID_GUILDMASTER:
m_xGuildMasterWnd.MoveGameWnd(ptMouse);
break;
case _WND_ID_GUILD:
m_xGuildWnd.MoveGameWnd(ptMouse);
break;
case _WND_ID_GROUP:
m_xGroupWnd.MoveGameWnd(ptMouse);
break;
case _WND_ID_GROUPPOP:
m_xGroupPopWnd.MoveGameWnd(ptMouse);
break;
case _WND_ID_CHATPOP:
m_xChatPopWnd.MoveGameWnd(ptMouse);
ShowWindow(g_xChatEditBox.GetSafehWnd(), SW_HIDE);
break;
case _WND_ID_NPCCHAT: // 용기
m_xNPCWnd.MoveGameWnd(ptMouse);
break;
case _WND_ID_QUEST:
m_xQuestWnd.MoveGameWnd(ptMouse);
break;
case _WND_ID_OPTION:
m_xOptionWnd.MoveGameWnd(ptMouse);
break;
case _WND_ID_HORSE:
m_xHorseWnd.MoveGameWnd(ptMouse);
break;
}
}
}
}
/******************************************************************************************************************
함수명 : CInterface::WindowFocusChanged()
작성자 :
작성일 :
목적 : 윈도우 영역으로 마우스 클릭이 되면 현재 Top 윈도우를 마우스 클릭 윈도우로 바꿔주고 그윈도우로 포커스를 맞춰준다.
입력 : INT nID
출력 : VOID
[일자][수정자] : 수정내용
*******************************************************************************************************************/
VOID CInterface::WindowFocusChangedAndSetReadyMove(INT nID, POINT ptMouse)
{
if ( m_xWndOrderList.GetCounter() != 0 )
{
AllWindowsFocusOff();
DeleteWindowToList(nID);
AddWindowToList(nID);
// 마우스 클릭이 된상태이면 이동시킬 준비가 된상태이다.
m_bMoveFocusedWnd = TRUE;
switch ( nID )
{
case _WND_ID_INVENTORY:
m_xInventoryWnd.SetGameWndFocused(TRUE);
m_xInventoryWnd.SetReadyMove(ptMouse);
break;
case _WND_ID_STATUS:
m_xStatusWnd.SetGameWndFocused(TRUE);
m_xStatusWnd.SetReadyMove(ptMouse);
break;
case _WND_ID_STORE:
m_xStoreWnd.SetGameWndFocused(TRUE);
m_xStoreWnd.SetReadyMove(ptMouse);
break;
case _WND_ID_EXCHANGE:
m_xExchangeWnd.SetGameWndFocused(TRUE);
m_xExchangeWnd.SetReadyMove(ptMouse);
break;
case _WND_ID_GUILDMASTER:
m_xGuildMasterWnd.SetGameWndFocused(TRUE);
m_xGuildMasterWnd.SetReadyMove(ptMouse);
break;
case _WND_ID_GUILD:
m_xGuildWnd.SetGameWndFocused(TRUE);
m_xGuildWnd.SetReadyMove(ptMouse);
break;
case _WND_ID_GROUP:
m_xGroupWnd.SetGameWndFocused(TRUE);
m_xGroupWnd.SetReadyMove(ptMouse);
break;
case _WND_ID_GROUPPOP:
m_xGroupPopWnd.SetGameWndFocused(TRUE);
m_xGroupPopWnd.SetReadyMove(ptMouse);
break;
case _WND_ID_CHATPOP:
m_xChatPopWnd.SetGameWndFocused(TRUE);
m_xChatPopWnd.SetReadyMove(ptMouse);
break;
case _WND_ID_NPCCHAT: // 용기
m_xNPCWnd.SetGameWndFocused(TRUE);
m_xNPCWnd.SetReadyMove(ptMouse);
break;
case _WND_ID_QUEST:
m_xQuestWnd.SetGameWndFocused(TRUE);
m_xQuestWnd.SetReadyMove(ptMouse);
break;
case _WND_ID_OPTION:
m_xOptionWnd.SetGameWndFocused(TRUE);
m_xOptionWnd.SetReadyMove(ptMouse);
break;
case _WND_ID_HORSE:
m_xHorseWnd.SetGameWndFocused(TRUE);
m_xHorseWnd.SetReadyMove(ptMouse);
break;
}
}
}
VOID CInterface::AllWindowsFocusOff()
{
if ( m_xWndOrderList.GetCounter() != 0 )
{
m_xWndOrderList.MoveCurrentToTop();
INT* pnCurrID;
for ( INT nCnt = 0; nCnt < m_xWndOrderList.GetCounter(); nCnt++ )
{
pnCurrID = m_xWndOrderList.GetCurrentData();
switch ( *pnCurrID )
{
case _WND_ID_INVENTORY:
m_xInventoryWnd.SetGameWndFocused(FALSE);
break;
case _WND_ID_STATUS:
m_xStatusWnd.SetGameWndFocused(FALSE);
break;
case _WND_ID_STORE:
m_xStoreWnd.SetGameWndFocused(FALSE);
break;
case _WND_ID_EXCHANGE:
m_xExchangeWnd.SetGameWndFocused(FALSE);
break;
case _WND_ID_GUILDMASTER:
m_xGuildMasterWnd.SetGameWndFocused(FALSE);
break;
case _WND_ID_GUILD:
m_xGuildWnd.SetGameWndFocused(FALSE);
break;
case _WND_ID_GROUP:
m_xGroupWnd.SetGameWndFocused(FALSE);
break;
case _WND_ID_GROUPPOP:
m_xGroupPopWnd.SetGameWndFocused(FALSE);
break;
case _WND_ID_CHATPOP:
m_xChatPopWnd.SetGameWndFocused(FALSE);
break;
case _WND_ID_NPCCHAT: // 용기
m_xNPCWnd.SetGameWndFocused(FALSE);
break;
case _WND_ID_QUEST:
m_xQuestWnd.SetGameWndFocused(FALSE);
break;
case _WND_ID_OPTION:
m_xOptionWnd.SetGameWndFocused(FALSE);
break;
case _WND_ID_HORSE:
m_xHorseWnd.SetGameWndFocused(FALSE);
break;
}
m_xWndOrderList.MoveNextNode();
}
}
}
BOOL CInterface::IsTopWindow(INT nID)
{
if ( m_xWndOrderList.GetCounter() != 0 )
{
INT* pnCurrID;
m_xWndOrderList.MoveCurrentToTail();
pnCurrID = m_xWndOrderList.GetCurrentData();
if ( nID == *pnCurrID )
return TRUE;
}
return FALSE;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 메시지 입력관련부분/////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************************************************
함수명 : CInterface::OnLButtonDown()
작성자 :
작성일 :
목적 : Mouse LButtonDown이 일어났을때 인터페이스에서 할일을 정의한다.
입력 : POINT ptMouse
출력 : BOOL
[일자][수정자] : 수정내용
*******************************************************************************************************************/
BOOL CInterface::OnLButtonDown(POINT ptMouse)
{
if(m_xMsgBox.IsActive()) // 용기
{
m_xMsgBox.OnButtonDown(ptMouse);
return TRUE;
}
else
{
if ( m_xScrlBar.OnLButtonDown(ptMouse) )
{
FLOAT fScrlRate;
fScrlRate = m_xScrlBar.GetScrlRate();
m_nFstLine = (m_xChat.GetCounter()-1)*fScrlRate;
return TRUE;
}
for( INT nCnt = 0; nCnt < _MAX_INTER_BTN; nCnt++ )
{
if ( m_xInterBtn[nCnt].OnLButtonDown(ptMouse) )
return TRUE;
}
INT nInterfaceWndInRect;
nInterfaceWndInRect = GetWindowInMousePos(ptMouse);
if ( nInterfaceWndInRect != -1 )
{
switch ( nInterfaceWndInRect )
{
case _WND_ID_INVENTORY:
if ( !m_xInventoryWnd.OnLButtonDown(&m_stCommonItem, ptMouse) )
WindowFocusChangedAndSetReadyMove(nInterfaceWndInRect, ptMouse);
break;
case _WND_ID_STATUS:
if ( !m_xStatusWnd.OnLButtonDown(&m_stCommonItem, ptMouse) )
WindowFocusChangedAndSetReadyMove(nInterfaceWndInRect, ptMouse);
break;
case _WND_ID_STORE:
if ( !m_xStoreWnd.OnLButtonDown(ptMouse) )
WindowFocusChangedAndSetReadyMove(nInterfaceWndInRect, ptMouse);
break;
case _WND_ID_EXCHANGE:
if ( !m_xExchangeWnd.OnLButtonDown(ptMouse) )
WindowFocusChangedAndSetReadyMove(nInterfaceWndInRect, ptMouse);
break;
case _WND_ID_GUILDMASTER:
if ( !m_xGuildMasterWnd.OnLButtonDown(ptMouse) )
WindowFocusChangedAndSetReadyMove(nInterfaceWndInRect, ptMouse);
break;
case _WND_ID_GUILD:
if ( !m_xGuildWnd.OnLButtonDown(ptMouse) )
WindowFocusChangedAndSetReadyMove(nInterfaceWndInRect, ptMouse);
break;
case _WND_ID_GROUP:
if ( !m_xGroupWnd.OnLButtonDown(ptMouse) )
WindowFocusChangedAndSetReadyMove(nInterfaceWndInRect, ptMouse);
break;
case _WND_ID_GROUPPOP:
if ( !m_xGroupPopWnd.OnLButtonDown(ptMouse) )
WindowFocusChangedAndSetReadyMove(nInterfaceWndInRect, ptMouse);
break;
case _WND_ID_CHATPOP:
if ( !m_xChatPopWnd.OnLButtonDown(ptMouse) )
WindowFocusChangedAndSetReadyMove(nInterfaceWndInRect, ptMouse);
break;
case _WND_ID_NPCCHAT: // 용기
if ( !m_xNPCWnd.OnLButtonDown(ptMouse) )
WindowFocusChangedAndSetReadyMove(nInterfaceWndInRect, ptMouse);
break;
case _WND_ID_QUEST:
if ( !m_xQuestWnd.OnLButtonDown(ptMouse) )
WindowFocusChangedAndSetReadyMove(nInterfaceWndInRect, ptMouse);
break;
case _WND_ID_OPTION:
if ( !m_xOptionWnd.OnLButtonDown(ptMouse) )
WindowFocusChangedAndSetReadyMove(nInterfaceWndInRect, ptMouse);
break;
case _WND_ID_HORSE:
if ( !m_xHorseWnd.OnLButtonDown(ptMouse) )
WindowFocusChangedAndSetReadyMove(nInterfaceWndInRect, ptMouse);
break;
}
return TRUE;
}
else
AllWindowsFocusOff();
}
return FALSE;
}
/******************************************************************************************************************
함수명 : CInterface::OnLButtonUp()
작성자 :
작성일 :
목적 : Mouse LButtonUp이 일어났을때 인터페이스에서 할일을 정의한다.
입력 : POINT ptMouse
출력 : BOOL
[일자][수정자] : 수정내용
*******************************************************************************************************************/
BOOL CInterface::OnLButtonUp(POINT ptMouse)
{
m_bMoveFocusedWnd = FALSE;
if ( m_xMsgBox.IsActive() ) // 용기
{
HRESULT hResult;
hResult = m_xMsgBox.OnButtonUp(ptMouse);
if ( hResult != 0 )
{
switch ( m_nIdxMsgBox )
{
case 12:
{
switch ( hResult ) // 에디트 박스가 없음.
{
case 2:
{
DWORD dwCurrTick = timeGetTime();
if ( (dwCurrTick - g_xGameProc.m_xMyHero.m_dwLastPKStruckTime> 10000) &&
(dwCurrTick - g_xGameProc.m_xMyHero.m_dwLastMagicTime > 10000) &&
(dwCurrTick - g_xGameProc.m_xMyHero.m_dwLastHitTime > 10000) ||
(g_xGameProc.m_xMyHero.m_bCurrMtn == _MT_DIE ) )
SendMessage(g_xMainWnd.GetSafehWnd(), WM_DESTROY, NULL, NULL);
else
{
DWORD dwFont, dwBack;
dwFont = GetChatColor(3);
dwBack = GetChatColor(2);
MsgAdd(dwFont, dwBack, "전투중에는 접속을 끊을 수 없습니다.");
}
}
break;
case 4:
m_xMsgBox.HideMessageBox();
break;
}
}
break;
}
}
}
else
{
if ( m_xScrlBar.OnLButtonUp(ptMouse) )
{
return TRUE;
}
for( INT nCnt = 0; nCnt < _MAX_INTER_BTN; nCnt++ )
{
if ( m_xInterBtn[nCnt].OnLButtonUp(ptMouse) )
{
switch ( nCnt )
{
case _BTN_ID_QUEST: WindowActivate(_WND_ID_QUEST); break;
case _BTN_ID_OPTION: WindowActivate(_WND_ID_OPTION); break;
case _BTN_ID_HORSE: WindowActivate(_WND_ID_HORSE); break;
case _BTN_ID_CHANGE: WindowActivate(_WND_ID_EXCHANGE); break;
case _BTN_ID_GUILD:
g_xClientSocket.SendGuildHome();
break;
case _BTN_ID_GROUP: WindowActivate(_WND_ID_GROUP); break;
case _BTN_ID_POPUP: WindowActivate(_WND_ID_CHATPOP); break;
case _BTN_ID_BAG: WindowActivate(_WND_ID_INVENTORY); break;
case _BTN_ID_MUGONG: m_bShowKey = !m_bShowKey; break;
case _BTN_ID_BELT:
{
if ( m_shBeltHeight >= 46 )
{
m_shBeltHeight = 46;
}
else if ( m_shBeltHeight <= 0 )
{
m_shBeltHeight = 0;
}
if ( m_shBeltHeight == 46 )
{
m_bBeltState = _BELT_STATE_DOWN;
}
else if ( m_shBeltHeight == 0 )
{
m_bBeltState = _BELT_STATE_UP;
}
}
break;
case _BTN_ID_EXIT:
{
CHAR szMsg[MAX_PATH];
HINSTANCE hLib;
m_nIdxMsgBox = 12;
hLib = LoadLibrary("Ats.dll"); // Load Dll
LoadString(hLib,m_nIdxMsgBox,szMsg, MAX_PATH);
FreeLibrary(hLib);
m_xMsgBox.ShowMessageBox(szMsg, 2); // YES/No ?
}
break;
case _BTN_ID_MAGIC:
if ( m_xStatusWnd.GetStatusWndType() != _TYPE_SETMAGIC )
{
if ( !WindowActivate(_WND_ID_STATUS) ) WindowActivate(_WND_ID_STATUS);
}
else
WindowActivate(_WND_ID_STATUS);
m_xStatusWnd.SetStatusWndType(_TYPE_SETMAGIC);
break;
case _BTN_ID_CHAR:
if ( m_xStatusWnd.GetStatusWndType() != _TYPE_EQUIP )
{
if ( !WindowActivate(_WND_ID_STATUS) ) WindowActivate(_WND_ID_STATUS);
}
else
WindowActivate(_WND_ID_STATUS);
m_xStatusWnd.SetStatusWndType(_TYPE_EQUIP);
break;
}
}
}
INT nInterfaceWndInRect;
nInterfaceWndInRect = GetWindowInMousePos(ptMouse);
// 각 윈도우의 OnLButtonUp의 리턴값이 TRUE이면 윈도우즈는 Close된다.
if ( nInterfaceWndInRect != -1 )
{
switch ( nInterfaceWndInRect )
{
case _WND_ID_INVENTORY: if ( m_xInventoryWnd.OnLButtonUp(&m_stCommonItem, ptMouse) ) WindowActivate(_WND_ID_INVENTORY); break;
case _WND_ID_STATUS: if ( m_xStatusWnd.OnLButtonUp(&m_stCommonItem, ptMouse) ) WindowActivate(_WND_ID_STATUS); break;
case _WND_ID_STORE: if ( m_xStoreWnd.OnLButtonUp(ptMouse) ) WindowActivate(_WND_ID_STORE); break;
case _WND_ID_EXCHANGE: if ( m_xExchangeWnd.OnLButtonUp(ptMouse) ) WindowActivate(_WND_ID_EXCHANGE); break;
case _WND_ID_GUILDMASTER:
{
if ( m_xGuildMasterWnd.OnLButtonUp(ptMouse) )
WindowActivate(_WND_ID_EXCHANGE);
break;
}
case _WND_ID_GUILD: if ( m_xGuildWnd.OnLButtonUp(ptMouse) ) WindowActivate(_WND_ID_GUILD); break;
case _WND_ID_GROUP: if ( m_xGroupWnd.OnLButtonUp(ptMouse) ) WindowActivate(_WND_ID_GROUP); break;
case _WND_ID_GROUPPOP: if ( m_xGroupPopWnd.OnLButtonUp(ptMouse) ) WindowActivate(_WND_ID_GROUPPOP); break;
case _WND_ID_CHATPOP: if ( m_xChatPopWnd.OnLButtonUp(ptMouse) ) WindowActivate(_WND_ID_CHATPOP); break;
case _WND_ID_QUEST: if ( m_xQuestWnd.OnLButtonUp(ptMouse) ) WindowActivate(_WND_ID_QUEST); break;
case _WND_ID_OPTION: if ( m_xOptionWnd.OnLButtonUp(ptMouse) ) WindowActivate(_WND_ID_OPTION); break;
case _WND_ID_HORSE: if ( m_xHorseWnd.OnLButtonUp(ptMouse) ) WindowActivate(_WND_ID_HORSE); break;
case _WND_ID_NPCCHAT: if ( m_xNPCWnd.OnLButtonUp(ptMouse) ) WindowActivate(_WND_ID_NPCCHAT); break; // 용기
}
return TRUE;
}
}
return FALSE;
}
/******************************************************************************************************************
함수명 : CInterface::OnMouseMove()
작성자 :
작성일 :
목적 : Mouse Move가 일어났을때 인터페이스에서 할일을 정의한다.
입력 : POINT ptMouse
출력 : BOOL
[일자][수정자] : 수정내용
*******************************************************************************************************************/
BOOL CInterface::OnMouseMove(POINT ptMouse)
{
MoveTopWindow(ptMouse);
if ( m_xScrlBar.OnMouseMove(ptMouse) )
{
FLOAT fScrlRate;
fScrlRate = m_xScrlBar.GetScrlRate();
m_nFstLine = (m_xChat.GetCounter()-1)*fScrlRate;
return TRUE;
}
for( INT nCnt = 0; nCnt < _MAX_INTER_BTN; nCnt++ )
m_xInterBtn[nCnt].OnMouseMove(ptMouse);
INT nInterfaceWndInRect;
nInterfaceWndInRect = GetWindowInMousePos(ptMouse);
if ( nInterfaceWndInRect != -1 )
{
switch ( nInterfaceWndInRect )
{
case _WND_ID_INVENTORY:
m_xInventoryWnd.OnMouseMove(ptMouse);
break;
case _WND_ID_STATUS:
m_xStatusWnd.OnMouseMove(ptMouse);
break;
case _WND_ID_STORE:
m_xStoreWnd.OnMouseMove(ptMouse);
break;
case _WND_ID_EXCHANGE:
m_xExchangeWnd.OnMouseMove(ptMouse);
break;
case _WND_ID_GUILDMASTER:
m_xGuildMasterWnd.OnMouseMove(ptMouse);
break;
case _WND_ID_GUILD:
m_xGuildWnd.OnMouseMove(ptMouse);
break;
case _WND_ID_GROUP:
m_xGroupWnd.OnMouseMove(ptMouse);
break;
case _WND_ID_GROUPPOP:
m_xGroupPopWnd.OnMouseMove(ptMouse);
break;
case _WND_ID_CHATPOP:
m_xChatPopWnd.OnMouseMove(ptMouse);
break;
case _WND_ID_QUEST:
m_xQuestWnd.OnMouseMove(ptMouse);
break;
case _WND_ID_OPTION:
m_xOptionWnd.OnMouseMove(ptMouse);
break;
case _WND_ID_HORSE:
m_xHorseWnd.OnMouseMove(ptMouse);
break;
case _WND_ID_NPCCHAT: // 용기
m_xNPCWnd.OnMouseMove(ptMouse);
break;
}
return TRUE;
}
else
{
m_xStatusWnd.SetStatusBtnInit();
m_xInventoryWnd.SetInvenBtnInit();
m_xChatPopWnd.SetStatusBtnInit();
m_xGuildMasterWnd.SetStatusBtnInit();
m_xOptionWnd.SetStatusBtnInit();
m_xQuestWnd.SetStatusBtnInit();
m_xHorseWnd.SetStatusBtnInit();
m_xExchangeWnd.SetStatusBtnInit();
}
return FALSE;
}
BOOL CInterface::OnScrollDown()
{
if ( IsTopWindow(m_xInventoryWnd.m_nID) )
{
m_xInventoryWnd.OnScrollDown();
}
else if ( IsTopWindow(m_xStatusWnd.m_nID) )
{
m_xStatusWnd.OnScrollDown();
}
else if (IsTopWindow(m_xNPCWnd.m_nID)) // 용기
{
m_xNPCWnd.OnScrollDown();
}
else
{
if ( !m_xChatPopWnd.m_bActive )
{
if ( m_nFstLine > 0 )
{
m_nFstLine--;
}
}
else
{
m_xChatPopWnd.OnScrollDown();
}
}
return TRUE;
}
BOOL CInterface::OnScrollUp()
{
if ( IsTopWindow(m_xInventoryWnd.m_nID) )
{
m_xInventoryWnd.OnScrollUp();
}
else if ( IsTopWindow(m_xStatusWnd.m_nID) )
{
m_xStatusWnd.OnScrollUp();
}
else if (IsTopWindow(m_xNPCWnd.m_nID)) // 용기
{
m_xNPCWnd.OnScrollUp();
}
else
{
if ( !m_xChatPopWnd.m_bActive )
{
if ( m_nFstLine < (m_xChat.GetCounter()-1) )
{
m_nFstLine++;
}
}
else
{
m_xChatPopWnd.OnScrollUp();
}
}
return TRUE;
}
BOOL CInterface::OnLButtonDoubleClick(POINT ptMouse)
{
if ( IsTopWindow(m_xInventoryWnd.m_nID) )
m_xInventoryWnd.OnLButtonDoubleClick(&m_stCommonItem, ptMouse);
return TRUE;
}
BOOL CInterface::OnKeyUp(WPARAM wParam, LPARAM lParam)
{
if ( m_xInventoryWnd.OnKeyUp(&m_stCommonItem, wParam, lParam) )
{
return TRUE;
}
return FALSE;
}
BOOL CInterface::OnKeyDown(WPARAM wParam, LPARAM lParam)
{
switch ( wParam )
{
case VK_RETURN:
break;
case VK_F9:
WindowActivate(_WND_ID_INVENTORY);
break;
case VK_F11:
if ( m_xStatusWnd.GetStatusWndType() != _TYPE_SETMAGIC )
{
if ( !WindowActivate(_WND_ID_STATUS) )
WindowActivate(_WND_ID_STATUS);
}
else
WindowActivate(_WND_ID_STATUS);
m_xStatusWnd.SetStatusWndType(_TYPE_SETMAGIC);
break;
}
INT nInterfaceWndInRect;
nInterfaceWndInRect = GetWindowInMousePos(g_xGameProc.m_ptMousePos);
if ( nInterfaceWndInRect != -1 )
{
if ( nInterfaceWndInRect == _WND_ID_STATUS )
{
if ( m_xStatusWnd.OnKeyDown(wParam, lParam, g_xGameProc.m_ptMousePos) )
return TRUE;
}
}
return FALSE;
}
VOID CInterface::OnSysKeyDown()
{
// F10 Key 눌렸을때.
if ( m_xStatusWnd.GetStatusWndType() != _TYPE_EQUIP )
{
if ( !WindowActivate(_WND_ID_STATUS) )
WindowActivate(_WND_ID_STATUS);
}
else
WindowActivate(_WND_ID_STATUS);
m_xStatusWnd.SetStatusWndType(_TYPE_EQUIP);
}
LRESULT CInterface::OnMsgInputted(WPARAM wParam, LPARAM lParam)
{
if ( m_xNPCWnd.OnMsgInputted() )
return TRUE;
return 0L;
} | [
"fjljfat@4a88d1ba-22b1-11df-8001-4f4b503b426e"
]
| [
[
[
1,
1960
]
]
]
|
90c14299e7c6ed0b82ad1b982d37b9eb89c33b1f | 0466568120485fcabdba5aa22a4b0fea13068b8b | /opencv/modules/gpu/src/cuda/safe_call.hpp | e3e00beaaf209da13e905b80bd1733cb14bf8a66 | []
| no_license | coapp-packages/opencv | be25a9aec58d9ac890fc764932ba67914add078d | c78981e0d8f602fde523a82c3a7e2c3fef1f39bc | refs/heads/master | 2020-05-17T12:11:25.406742 | 2011-07-14T17:13:01 | 2011-07-14T17:13:01 | 2,048,483 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,030 | hpp | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#ifndef __OPENCV_CUDA_SAFE_CALL_HPP__
#define __OPENCV_CUDA_SAFE_CALL_HPP__
#include "cuda_runtime_api.h"
#include "cufft.h"
//#include <nppdefs.h>
#if defined(__GNUC__)
#define cudaSafeCall(expr) ___cudaSafeCall(expr, __FILE__, __LINE__, __func__)
#define cufftSafeCall(expr) ___cufftSafeCall(expr, __FILE__, __LINE__, __func__)
#define nppSafeCall(expr) ___nppSafeCall(expr, __FILE__, __LINE__, __func__)
#else /* defined(__CUDACC__) || defined(__MSVC__) */
#define cudaSafeCall(expr) ___cudaSafeCall(expr, __FILE__, __LINE__)
#define cufftSafeCall(expr) ___cufftSafeCall(expr, __FILE__, __LINE__)
#define nppSafeCall(expr) ___nppSafeCall(expr, __FILE__, __LINE__)
#endif
namespace cv
{
namespace gpu
{
void error(const char *error_string, const char *file, const int line, const char *func = "");
void nppError(int err, const char *file, const int line, const char *func = "");
void cufftError(int err, const char *file, const int line, const char *func = "");
static inline void ___cudaSafeCall(cudaError_t err, const char *file, const int line, const char *func = "")
{
if (cudaSuccess != err)
cv::gpu::error(cudaGetErrorString(err), file, line, func);
}
static inline void ___cufftSafeCall(cufftResult_t err, const char *file, const int line, const char *func = "")
{
if (CUFFT_SUCCESS != err)
cv::gpu::cufftError(err, file, line, func);
}
static inline void ___nppSafeCall(int err, const char *file, const int line, const char *func = "")
{
if (err < 0)
cv::gpu::nppError(err, file, line, func);
}
}
}
#endif /* __OPENCV_CUDA_SAFE_CALL_HPP__ */ | [
"anatoly@73c94f0f-984f-4a5f-82bc-2d8db8d8ee08",
"alexeys@73c94f0f-984f-4a5f-82bc-2d8db8d8ee08",
"vinogradov_vlad@73c94f0f-984f-4a5f-82bc-2d8db8d8ee08"
]
| [
[
[
1,
46
],
[
48,
50
],
[
54,
55
],
[
58,
63
],
[
67,
69
],
[
71,
72
],
[
80,
80
],
[
83,
83
],
[
85,
88
]
],
[
[
47,
47
],
[
52,
52
],
[
56,
56
],
[
64,
66
],
[
70,
70
],
[
74,
79
]
],
[
[
51,
51
],
[
53,
53
],
[
57,
57
],
[
73,
73
],
[
81,
82
],
[
84,
84
]
]
]
|
b2ddf04cdace3d0982342bf36c56b7cc3a231436 | dadae22098e24c412a8d8d4133c8f009a8a529c9 | /tp1/src/tp1/tp1_simulation_1.h | 696d15bc2985c3bb4e7ba8056681233632cfd63b | []
| no_license | maoueh/PHS4700 | 9fe2bdf96576975b0d81e816c242a8f9d9975fbc | 2c2710fcc5dbe4cd496f7329379ac28af33dc44d | refs/heads/master | 2021-01-22T22:44:17.232771 | 2009-10-06T18:49:30 | 2009-10-06T18:49:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,620 | h | #ifndef TP1_SIMULATION_1_H
#define TP1_SIMULATION_1_H
#include <vector>
#include "color.h"
#include "opengl_application.h"
class ShaderProgram;
class TextureUnit;
class Window;
class Tp1Simulation1 : public OpenGlApplication
{
public:
Tp1Simulation1(CommandLine* commandLine, const Vector& initialPosition, const Vector& initialVelocity);
virtual ~Tp1Simulation1();
protected:
virtual void initialize();
virtual STRING& getName() { return mName; }
virtual void keyPressed(KeyEvent& event);
virtual void mouseDragged(MouseEvent& event);
virtual void draw();
virtual void updateWorld();
private:
void compileCourtList(FLOAT width, FLOAT length, INT rowCount, INT columnCount, BOOL isOutsideNormal);
void compileNetList(FLOAT width, FLOAT length, INT rowCount, INT columnCount, BOOL isOutsideNormal);
void drawQuadGrid(FLOAT width, FLOAT length, INT rowCount, INT columnCount, BOOL isOutsideNormal);
void replay();
void checkEndOfSimulation();
void checkNet();
void checkFloor();
BOOL inPlayerOneZone();
BOOL inPlayerTwoZone();
void printBallOutside();
void printResult();
STRING mName;
ShaderProgram* mShaderProgram;
BOOL mIsShaderOn;
Vector mBallVelocity;
Vector mBallPosition;
FLOAT mTimeElapsed;
Vector mInitialPosition;
Vector mInitialVelocity;
UINT mCourtListId;
UINT mNetListId;
vector<Vector> mBallPositions;
FLOAT mAxisScaleFactor;
BOOL mIsAxisPresent;
BOOL mIsNetCrossed;
};
#endif | [
"[email protected]"
]
| [
[
[
1,
67
]
]
]
|
6431e9642e7f601a49ebc4ab40d712ad26958a91 | c95a83e1a741b8c0eb810dd018d91060e5872dd8 | /Game/ClientShellDLL/TO2/ScreenSave.h | 2aeaf134843e497c5f29a6639cc951f77372d68b | []
| no_license | rickyharis39/nolf2 | ba0b56e2abb076e60d97fc7a2a8ee7be4394266c | 0da0603dc961e73ac734ff365bfbfb8abb9b9b04 | refs/heads/master | 2021-01-01T17:21:00.678517 | 2011-07-23T12:11:19 | 2011-07-23T12:11:19 | 38,495,312 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 966 | h | // ----------------------------------------------------------------------- //
//
// MODULE : ScreenSave.h
//
// PURPOSE : Interface screen for saving games
//
// (c) 1999-2001 Monolith Productions, Inc. All Rights Reserved
//
// ----------------------------------------------------------------------- //
#if !defined(_SCREEN_SAVE_H_)
#define _SCREEN_SAVE_H_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "BaseScreen.h"
class CScreenSave : public CBaseScreen
{
public:
CScreenSave();
virtual ~CScreenSave();
LTBOOL Build();
void OnFocus(LTBOOL bFocus);
LTBOOL HandleKeyDown(int key, int rep);
LTBOOL SaveGame(uint32 slot);
protected:
uint32 OnCommand(uint32 dwCommand, uint32 dwParam1, uint32 dwParam2);
void BuildSavedLevelList();
void ClearSavedLevelList();
void NameSaveGame(uint32 slot, int index);
char m_szSaveName[40];
};
#endif // !defined(_SCREEN_SAVE_H_) | [
"[email protected]"
]
| [
[
[
1,
44
]
]
]
|
ca71b6eeceec00ce48438e75db55fb668fdfdbc9 | 8ce47e73afa904a145a1104fa8eaa71e3a237907 | /Robot/controller/NXTBluetooth/i2c.cpp | 683e59093a85181f9fa290ba822eeece7d88c604 | []
| no_license | nobody/magiclegoblimps | bc4f1459773773599ec397bdd1a43b1c341ff929 | d66fe634cc6727937a066118f25847fa7d71b8f6 | refs/heads/master | 2021-01-23T15:42:15.729310 | 2010-05-05T03:15:00 | 2010-05-05T03:15:00 | 39,790,220 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,484 | cpp | #include "i2c.h"
#include "error.h"
#include <iostream>
#include <stdio.h>
#include <time.h>
#include <string>
#include <stdlib.h>
#include <windows.h>
I2c::I2c(Sensor_port port, Connection* connection, Sensor_type sensor_type, unsigned char i2c_address, unsigned int wait_time):Sensor(port, connection, sensor_type, RAW_MODE){
this->wait_time = wait_time;
this->i2c_address = i2c_address;
}
I2c::~I2c(){}
void I2c::init(bool reply){
Sensor::init(reply);
//Sleep(200);
//reset(reply);
}
/*int I2C::read(){
return 0;
}*/
void I2c::i2c_write(unsigned char *tx_buf, int tx_length, int rx_length){
int i=0;
unsigned char command[24];
while(i < tx_length){
command[i+7]=tx_buf[i];
i++;
//printf("i=%d\n",i);
}
command[0]=i+5;
command[1]=0x00;
command[2]=0x80;
command[3]=0x0F;
command[4]=sensor_port;
command[5]=i;
command[6]=rx_length;
connection->send(&command[0],i+7);
}
void I2c::i2c_read(unsigned char* rx_buffer, int rx_length){
int i;
unsigned char command[5];
wait_for_bytes(rx_length);
command[0]=0x03;
command[1]=0x00;
command[2]=0x00;
command[3]=0x10;
command[4]=sensor_port;
connection->send(&command[0],5);
connection->receive(rx_buffer,22);
if(rx_buffer[4]){
throw Nxt_exception::Nxt_exception("read","I2C", 0x00ff & rx_buffer[4]);
}
i=0;
//printf("\nI2C read:\n");
while(i<16){
rx_buffer[i]=rx_buffer[i+5];
//printf("read[%d]: %d\n", i, rx_buffer[i]);
i++;
}
}
void I2c::wait_for_bytes(int num_bytes){
bytes_ready=0;
time_t start_time = clock();
do{
update_sensor_status();
Sleep(wait_time);
if(((clock()-start_time) > TIMEOUT)){
throw Nxt_exception::Nxt_exception("wait_for_bytes","I2C", NXT_I2C_TIMEOUT);
}
}while(bytes_ready < num_bytes);
}
void I2c::update_sensor_status(){
unsigned char command[5];
unsigned char answer[NXT_BUFFER_SIZE];
command[0]=0x03;
command[1]=0x00;
command[2]=0x00;
command[3]=0x0E;
command[4]=sensor_port;
connection->send(&command[0],5);
connection->receive(&answer[0],6);
if(answer[4]){
if(answer[4] != NXT_PENDING_COMMUNICATION){
throw Nxt_exception::Nxt_exception("update_sensor_status", "I2C", 0x00ff & answer[4]);
}
bytes_ready = 0;
}
else{
bytes_ready=answer[5];
}
}
unsigned char I2c::get_i2c_address(){
return this->i2c_address;
}
| [
"eXceLynX@445d4ad4-0937-11df-b996-818f58f34e26"
]
| [
[
[
1,
109
]
]
]
|
2247f47d321648df34774918ba93a169a0d50fc9 | d115cf7a1b374d857f6b094d4b4ccd8e9b1ac189 | /tags/pyplusplus_dev_1.0.0/unittests/data/duplicate_aliases_to_be_exported.cpp | da84134d91d7d65497b78debacd9456bffbe1146 | [
"BSL-1.0"
]
| permissive | gatoatigrado/pyplusplusclone | 30af9065fb6ac3dcce527c79ed5151aade6a742f | a64dc9aeeb718b2f30bd6a5ff8dcd8bfb1cd2ede | refs/heads/master | 2016-09-05T23:32:08.595261 | 2010-05-16T10:53:45 | 2010-05-16T10:53:45 | 700,369 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 313 | cpp | // Copyright 2004-2008 Roman Yakovenko.
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include "duplicate_aliases_to_be_exported.hpp"
namespace duplicate_aliases{
}//duplicate_aliases
| [
"roman_yakovenko@dc5859f9-2512-0410-ae5c-dd123cda1f76"
]
| [
[
[
1,
13
]
]
]
|
b2aa296a640e811adabd296572457a03d254f31f | b7c505dcef43c0675fd89d428e45f3c2850b124f | /Src/SimulatorQt/Util/qt/Win32/include/Qt/qnetworkaccessmanager.h | 1614c3b3ae37e2e91b565e172e6513d6bb62bbdf | [
"BSD-2-Clause"
]
| permissive | pranet/bhuman2009fork | 14e473bd6e5d30af9f1745311d689723bfc5cfdb | 82c1bd4485ae24043aa720a3aa7cb3e605b1a329 | refs/heads/master | 2021-01-15T17:55:37.058289 | 2010-02-28T13:52:56 | 2010-02-28T13:52:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,542 | h | /****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the QtNetwork module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QNETWORKACCESSMANAGER_H
#define QNETWORKACCESSMANAGER_H
#include <QtCore/QObject>
QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
QT_MODULE(Network)
class QIODevice;
class QAbstractNetworkCache;
class QAuthenticator;
class QByteArray;
template<typename T> class QList;
class QNetworkCookie;
class QNetworkCookieJar;
class QNetworkRequest;
class QNetworkReply;
class QNetworkProxy;
class QNetworkProxyFactory;
class QSslError;
class QNetworkReplyImplPrivate;
class QNetworkAccessManagerPrivate;
class Q_NETWORK_EXPORT QNetworkAccessManager: public QObject
{
Q_OBJECT
public:
enum Operation {
HeadOperation = 1,
GetOperation,
PutOperation,
PostOperation,
UnknownOperation = 0
};
explicit QNetworkAccessManager(QObject *parent = 0);
~QNetworkAccessManager();
#ifndef QT_NO_NETWORKPROXY
QNetworkProxy proxy() const;
void setProxy(const QNetworkProxy &proxy);
QNetworkProxyFactory *proxyFactory() const;
void setProxyFactory(QNetworkProxyFactory *factory);
#endif
QAbstractNetworkCache *cache() const;
void setCache(QAbstractNetworkCache *cache);
QNetworkCookieJar *cookieJar() const;
void setCookieJar(QNetworkCookieJar *cookieJar);
QNetworkReply *head(const QNetworkRequest &request);
QNetworkReply *get(const QNetworkRequest &request);
QNetworkReply *post(const QNetworkRequest &request, QIODevice *data);
QNetworkReply *post(const QNetworkRequest &request, const QByteArray &data);
QNetworkReply *put(const QNetworkRequest &request, QIODevice *data);
QNetworkReply *put(const QNetworkRequest &request, const QByteArray &data);
Q_SIGNALS:
#ifndef QT_NO_NETWORKPROXY
void proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator);
#endif
void authenticationRequired(QNetworkReply *reply, QAuthenticator *authenticator);
void finished(QNetworkReply *reply);
#ifndef QT_NO_OPENSSL
void sslErrors(QNetworkReply *reply, const QList<QSslError> &errors);
#endif
protected:
virtual QNetworkReply *createRequest(Operation op, const QNetworkRequest &request,
QIODevice *outgoingData = 0);
private:
friend class QNetworkReplyImplPrivate;
Q_DECLARE_PRIVATE(QNetworkAccessManager)
Q_PRIVATE_SLOT(d_func(), void _q_replyFinished())
Q_PRIVATE_SLOT(d_func(), void _q_replySslErrors(QList<QSslError>))
};
QT_END_NAMESPACE
QT_END_HEADER
#endif
| [
"alon@rogue.(none)"
]
| [
[
[
1,
129
]
]
]
|
7b9da9f3519a4182113b95bc0720a98f0bd32e0f | ec41b76a607f9e8dd29288997df56b6837e286c6 | /OgreMath/OgreCommon.h | cbe84b1fc800fb958532f1daab9e5e6cab3c84ec | []
| no_license | tkaleas/screen-space-fluid-rendering | 2309d5de0886ad961708d1c2203bba6976dd8c2f | 28f0968cb044a40d561747bba9574cc59d3d2fcb | refs/heads/master | 2020-06-04T07:26:25.578575 | 2011-04-26T21:29:49 | 2011-04-26T21:29:49 | 32,113,666 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 404 | h | #ifndef OGRECOMMON_H
#define OGRECOMMON_H
#define _OgreExport
#include <iostream>
#include <cassert>
#define _USE_MATH_DEFINES
#include <cmath>
#define TWO_PI (M_PI*2)
#define HALF_PI (M_PI/2)
namespace Ogre
{
class Vector2;
class Vector3;
class Vector4;
class Matrix3;
class Matrix4;
class Quaternion;
}
inline float isqrtf(float x)
{
return 1/sqrtf(x);
}
#endif | [
"[email protected]@58403bee-ede4-9baf-e632-59ccd62f6f02"
]
| [
[
[
1,
29
]
]
]
|
38a66f084512063ef2d17f6c135dc4043924c141 | ef23e388061a637f82b815d32f7af8cb60c5bb1f | /src/mame/includes/gijoe.h | 56dc3d6385d6e805a8987ec1c54d656e2cea49c8 | []
| no_license | marcellodash/psmame | 76fd877a210d50d34f23e50d338e65a17deff066 | 09f52313bd3b06311b910ed67a0e7c70c2dd2535 | refs/heads/master | 2021-05-29T23:57:23.333706 | 2011-06-23T20:11:22 | 2011-06-23T20:11:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,273 | h | /*************************************************************************
GI Joe
*************************************************************************/
class gijoe_state : public driver_device
{
public:
gijoe_state(running_machine &machine, const driver_device_config_base &config)
: driver_device(machine, config) { }
/* memory pointers */
UINT16 * m_workram;
UINT16 * m_spriteram;
// UINT16 * m_paletteram; // currently this uses generic palette handling
/* video-related */
int m_avac_bits[4];
int m_avac_occupancy[4];
int m_layer_colorbase[4];
int m_layer_pri[4];
int m_avac_vrc;
int m_sprite_colorbase;
/* misc */
UINT16 m_cur_control2;
emu_timer *m_dmadelay_timer;
/* devices */
device_t *m_maincpu;
device_t *m_audiocpu;
device_t *m_k054539;
device_t *m_k056832;
device_t *m_k053246;
device_t *m_k053251;
};
/*----------- defined in video/gijoe.c -----------*/
extern void gijoe_sprite_callback(running_machine &machine, int *code, int *color, int *priority_mask);
extern void gijoe_tile_callback(running_machine &machine, int layer, int *code, int *color, int *flags);
VIDEO_START( gijoe );
SCREEN_UPDATE( gijoe );
| [
"Mike@localhost"
]
| [
[
[
1,
45
]
]
]
|
ae4363d5d6a5143e5356704446d1268b3071b9ee | b91c59623f28031d0255684adffcaa5e54528777 | /LoginDlg.h | 1e080a6fdc13ec2438626f9f0ed00d1e19b57954 | []
| no_license | ninhoabrantes/fop3d | dbe03ba3f3b2ca5073ed6dc8f03e2c7cbdd9b1ad | 7c099f5720fca1a673fdc238bc95e6ceadb4488c | refs/heads/master | 2021-01-10T06:26:56.752957 | 2010-01-27T08:35:43 | 2010-01-27T08:35:43 | 51,085,749 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,208 | h | #if !defined(AFX_LOGINDLG_H__84AE5D0C_8DF3_4D6F_B860_5B96DB28441B__INCLUDED_)
#define AFX_LOGINDLG_H__84AE5D0C_8DF3_4D6F_B860_5B96DB28441B__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// LoginDlg.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CLoginDlg dialog
class CLoginDlg : public CDialog
{
// Construction
public:
CLoginDlg(CWnd* pParent = NULL); // standard constructor
_ConnectionPtr m_pConnection;
// Dialog Data
//{{AFX_DATA(CLoginDlg)
enum { IDD = IDD_LOGINDLG };
CString m_nInfo;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CLoginDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CLoginDlg)
virtual BOOL OnInitDialog();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_LOGINDLG_H__84AE5D0C_8DF3_4D6F_B860_5B96DB28441B__INCLUDED_)
| [
"emilyaimeihsu@6deafb92-e873-11de-91d6-89caad0352f8"
]
| [
[
[
1,
47
]
]
]
|
878033292738bc5eda80e48c28fae9186f2f57a6 | bec972e7c17702e036fed6a1126aef96db1e5d4c | /src/InputManager.cpp | d7efc8ea2b3679a1a1821cc0233a71b98c705319 | [
"MIT"
]
| permissive | andrey013/mytuner | ea72b9eb0e1339034de140b2baa9ec0cf34da466 | 266898d81be7830f9480ca4e37f886b5d4c02125 | refs/heads/master | 2021-01-01T17:57:32.828719 | 2011-06-20T15:09:41 | 2011-06-20T15:09:41 | 1,219,186 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,890 | cpp | #include "precompiled.h"
#include "InputManager.h"
InputManager::InputManager(Ogre::RenderWindow* win, bool bufferedKeys, bool bufferedMouse,
bool bufferedJoy) :
mWindow(win), mInputManager(0), mMouse(0), mKeyboard(0), mJoy(0)
{
Ogre::LogManager::getSingletonPtr()->logMessage("*** Initializing OIS ***");
OIS::ParamList pl;
size_t windowHnd = 0;
std::ostringstream windowHndStr;
win->getCustomAttribute("WINDOW", &windowHnd);
windowHndStr << windowHnd;
pl.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));
mInputManager = OIS::InputManager::createInputSystem( pl );
mKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject( OIS::OISKeyboard, bufferedKeys ));
mMouse = static_cast<OIS::Mouse*>(mInputManager->createInputObject( OIS::OISMouse, bufferedMouse ));
try
{
//mJoy = static_cast<OIS::JoyStick*>(mInputManager->createInputObject( OIS::OISJoyStick, bufferedJoy ));
}
catch(...)
{
mJoy = 0;
}
mKeyboard->setTextTranslation(OIS::Keyboard::Unicode);
windowResized(mWindow);
Ogre::WindowEventUtilities::addWindowEventListener(mWindow, this);
mMouse->setEventCallback(this);
mKeyboard->setEventCallback(this);
}
void InputManager::windowResized(Ogre::RenderWindow* rw)
{
unsigned int width, height, depth;
int left, top;
rw->getMetrics(width, height, depth, left, top);
const OIS::MouseState &ms = mMouse->getMouseState();
ms.width = width;
ms.height = height;
}
void InputManager::windowClosed(Ogre::RenderWindow* rw)
{
if( rw == mWindow )
{
if( mInputManager )
{
mInputManager->destroyInputObject( mMouse );
mInputManager->destroyInputObject( mKeyboard );
mInputManager->destroyInputObject( mJoy );
OIS::InputManager::destroyInputSystem(mInputManager);
mInputManager = 0;
}
}
}
InputManager::~InputManager()
{
Ogre::WindowEventUtilities::removeWindowEventListener(mWindow, this);
windowClosed(mWindow);
}
bool InputManager::frameRenderingQueued(const Ogre::FrameEvent& evt)
{
mEvt = evt;
if(mWindow->isClosed()) return false;
mKeyboard->capture();
mMouse->capture();
if( mJoy ) mJoy->capture();
/*
mMouse->setEventCallback()
if( !mKeyboard->buffered() )
if( processUnbufferedKeyInput(evt) == false )
return false;
if( !mMouse->buffered() )
if( processUnbufferedMouseInput(evt) == false )
return false;
*/
return true;
}
void InputManager::regKeyboardListener(IKeyboardListener *l)
{
if (l && std::find(kb_listeners.begin(), kb_listeners.end(), l) == kb_listeners.end())
kb_listeners.push_back(l);
}
void InputManager::unregKeyboardListener(IKeyboardListener *l)
{
if (l)
kb_listeners.remove(l);
}
void InputManager::regMouseListener(IMouseListener *l)
{
if (l && std::find(mouse_listeners.begin(), mouse_listeners.end(), l) == mouse_listeners.end())
mouse_listeners.push_back(l);
}
void InputManager::unregMouseListener(IMouseListener *l)
{
if (l)
mouse_listeners.remove(l);
}
bool InputManager::mouseMoved( const OIS::MouseEvent &arg )
{
bool result = true;
MouseListenersList::const_iterator m_it = mouse_listeners.begin(), m_end = mouse_listeners.end();
for (; m_it != m_end; ++m_it)
result &= (*m_it)->mouseMoved(mEvt, arg);
return result;
}
bool InputManager::mousePressed( const OIS::MouseEvent &arg, OIS::MouseButtonID id )
{
bool result = true;
MouseListenersList::const_iterator m_it = mouse_listeners.begin(), m_end = mouse_listeners.end();
for (; m_it != m_end; ++m_it)
result &= (*m_it)->mousePressed(mEvt, arg, id);
return result;
}
bool InputManager::mouseReleased( const OIS::MouseEvent &arg, OIS::MouseButtonID id )
{
bool result = true;
MouseListenersList::const_iterator m_it = mouse_listeners.begin(), m_end = mouse_listeners.end();
for (; m_it != m_end; ++m_it)
result &= (*m_it)->mouseReleased(mEvt, arg, id);
return result;
}
bool InputManager::keyPressed( const OIS::KeyEvent &arg )
{
bool result = true;
KeyboardListenersList::const_iterator m_it = kb_listeners.begin(), m_end = kb_listeners.end();
for (; m_it != m_end; ++m_it)
result &= (*m_it)->keyPressed(mEvt, arg);
return result;
}
bool InputManager::keyReleased( const OIS::KeyEvent &arg )
{
bool result = true;
KeyboardListenersList::const_iterator m_it = kb_listeners.begin(), m_end = kb_listeners.end();
for (; m_it != m_end; ++m_it)
result &= (*m_it)->keyReleased(mEvt, arg);
return result;
}
| [
"[email protected]"
]
| [
[
[
1,
154
]
]
]
|
594415a96423ff425cdc8de928f5fd6310ae4a7b | 89b01aac84d7ace68526f3619b872e52bd9e8160 | /BattleCube/src/Player.cpp | a2042f21fef2320276a95dfb0a8691465b6d2125 | []
| no_license | shekibobo/BattleCube | f9692ce628c76fc78e8887c92630625ec3756547 | 97b71aa7663d4edd9805573363875a8e58674c23 | refs/heads/master | 2021-01-10T18:34:14.214360 | 2011-04-26T17:40:43 | 2011-04-26T17:40:43 | 1,485,440 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,805 | cpp | #include "../include/Player.h"
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <algorithm>
#define PI 3.14159265
using namespace std;
Player::Player(GLfloat PosX, GLfloat PosY, GLfloat PosZ, World *world)
{
m_pWorld = world;
//ctor
SetPosX(PosX);
SetPosY(PosY);
SetPosZ(PosZ);
SetLookAngle(PI);
SetDir(1.0, 0.0, -1.0);
SetBoundary((Env().GetWallLength() / 2.0) - 2.0);
printf("Boundary: %f\n", GetBoundary());
SetFirstPerson(true);
}
Player::~Player()
{
//dtor
}
void Player::Move(bool keyStates[]) {
// move forward
if ( inBounds(true) && keyStates['w']) {
SetPosZ(GetPosZ() + GetDirZ());
SetPosX(GetPosX() + GetDirX());
}
// move backward
if ( inBounds(false) && keyStates['s']) {
SetPosZ(GetPosZ() - GetDirZ());
SetPosX(GetPosX() - GetDirX());
}
// strafe left
if (keyStates['a'] && inBounds(false) ) {
SetPosZ(GetPosZ() - GetDirX());
SetPosX(GetPosX() + GetDirZ());
}
// strafe right
if (keyStates['d'] && inBounds(false) ) {
SetPosZ(GetPosZ() + GetDirX());
SetPosX(GetPosX() - GetDirZ());
}
}
bool Player::inBounds(bool forward) {
if (forward) {
if (GetDirX() > 0 && GetPosX() >= GetBoundary() - 2) return false;
if (GetDirZ() > 0 && GetPosZ() >= GetBoundary() - 2) return false;
if (GetDirX() < 0 && GetPosX() <= -GetBoundary() + 2) return false;
if (GetDirZ() < 0 && GetPosZ() <= -GetBoundary() + 2) return false;
return true;
} else {
if (GetDirX() < 0 && GetPosX() >= GetBoundary() - 2) return false;
if (GetDirZ() < 0 && GetPosZ() >= GetBoundary() - 2) return false;
if (GetDirX() > 0 && GetPosX() <= -GetBoundary() + 2) return false;
if (GetDirZ() > 0 && GetPosZ() <= -GetBoundary() + 2) return false;
return true;
}
}
void Player::Draw() {
/*
gluLookAt(GetPosX(), GetPosY(), GetPosZ(),
GetPosX(), GetPosY(), GetPosZ() - 1.0,
0.0, 1.0, 0.0);
*/
Look();
}
void Player::Look() {
SetLookX(sin(LookAngle()) + GetPosX());
SetLookZ(cos(LookAngle()) + GetPosZ());
if (FirstPerson()) {
gluLookAt(GetPosX(), GetPosY(), GetPosZ(),
GetLookX(), GetLookY(), GetLookZ(),
0.0, 1.0, 0.0);
} else {
gluLookAt(sin(LookAngle()) - GetPosX(), GetPosY(), cos(LookAngle()) - GetPosZ(),
GetLookX(), GetLookY(), GetLookZ(),
0.0, 1.0, 0.0);
glPushMatrix();
glColor3f(1.0, 0.5, 0.1);
glTranslatef(GetPosX(), GetPosY(), GetPosZ());
glutSolidCube(8.0);
glPopMatrix();
}
}
World Player::Env() { return *m_pWorld; }
| [
"[email protected]"
]
| [
[
[
1,
108
]
]
]
|
9b18abbef8fb86cb53e06143b3799204d790b13b | 51574a600a87ecfaaec8ea0e46b3809884859680 | /include/GmapiPopups.h | dff03c29f232ad592ad514aedef748812ba871a6 | []
| no_license | suilevap/motion-plan | b5ad60a8448b118c3742c8c9c42b29fd5e41ef3e | d9f5693938287f2179ca2cb4eb75bda51b97bbb0 | refs/heads/master | 2021-01-10T03:29:50.373970 | 2011-12-20T22:39:55 | 2011-12-20T22:39:55 | 49,495,165 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,375 | h | /************************************************************************/
/* LICENSE: */
/* */
/* GMAPI is free software; you can redistribute it and/or */
/* modify it under the terms of the GNU Lesser General Public */
/* License as published by the Free Software Foundation; either */
/* version 2.1 of the License, or (at your option) any later version. */
/* */
/* GMAPI is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU */
/* Lesser General Public License for more details. */
/* */
/* You should have received a copy of the GNU Lesser General Public */
/* License along with GMAPI; if not, write to the Free Software */
/* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA */
/* 02110-1301 USA */
/************************************************************************/
/************************************************************************/
/* GmapiPopups.h */
/* - Wrapped GM functions; Parser-generated code */
/* */
/* Copyright (C) 2009-2010, Snake (http://www.sgames.ovh.org) */
/************************************************************************/
#pragma once
#include "GmapiInternal.h"
namespace gm {
void show_message( const CGMVariable& str );
double show_message_ext( const CGMVariable& str, const CGMVariable& but1,
const CGMVariable& but2, const CGMVariable& but3 );
bool show_question( const CGMVariable& str );
double get_integer( const CGMVariable& str, double def );
CGMVariable get_string( const CGMVariable& str, const CGMVariable& def );
void message_background( int back );
void message_alpha( double alpha );
void message_button( int spr );
void message_text_font( const CGMVariable& name, int size,
int color, int style );
void message_button_font( const CGMVariable& name, int size,
int color, int style );
void message_input_font( const CGMVariable& name, int size,
int color, int style );
void message_input_color( int col );
void message_mouse_color( int col );
void message_caption( bool show, const CGMVariable& str );
void message_position( int x, int y );
void message_size( int w, int h );
int show_menu( const CGMVariable& str, int def );
int show_menu_pos( int x, int y, const CGMVariable& str, int def );
int get_color( int defcol );
CGMVariable get_open_filename( const CGMVariable& filter, const CGMVariable& fname );
CGMVariable get_save_filename( const CGMVariable& filter, const CGMVariable& fname );
CGMVariable get_directory( const CGMVariable& dname );
CGMVariable get_directory_alt( const CGMVariable& capt, const CGMVariable& root );
void splash_show_video( const CGMVariable& fname, bool loop );
void splash_show_text( const CGMVariable& fname, int delay );
void splash_show_image( const CGMVariable& fname, int delay );
void splash_show_web( const CGMVariable& url, int delay );
void splash_set_main( bool main );
void splash_set_scale( double scape );
void splash_set_cursor( bool vis );
void splash_set_color( int col );
void splash_set_caption( const CGMVariable& cap );
void splash_set_fullscreen( bool full );
void splash_set_border( bool border );
void splash_set_size( int w, int h );
void splash_set_adapt( bool adapt );
void splash_set_top( bool top );
void splash_set_interrupt( bool interrupt );
void splash_set_stop_key( bool stop );
void splash_set_stop_mouse( bool stop );
void splash_set_position( int x, int y );
void splash_set_close_button( bool show );
void show_info();
void load_info( const CGMVariable& fname );
void show_error( const CGMVariable& str, bool abort );
void highscore_show( double numb );
void highscore_set_background( int back );
void highscore_set_border( bool show );
void highscore_set_font( const CGMVariable& name, int size, int style );
void highscore_set_colors( int back, int new_, int other );
void highscore_set_strings( const CGMVariable& caption, const CGMVariable& nobody,
const CGMVariable& escape );
void highscore_show_ext( double numb, int back, bool border,
int col1, int col2,
const CGMVariable& name, int size );
void highscore_clear();
void highscore_add( const CGMVariable& str, double numb );
void highscore_add_current();
double highscore_value( int place );
CGMVariable highscore_name( int place );
void draw_highscore( double x1, double y1,
double x2, double y2 );
}
| [
"suilevap@localhost"
]
| [
[
[
1,
107
]
]
]
|
a1237bd39a3d332b08c7ba8f2a4b0c3ede6223f1 | 4813a54584f8e8a8a2d541291a08b244640a7f77 | /libxl/include/ui/Bitmap.h | ef2b7259acd60ccbee62d09eefada58dae89ab70 | []
| no_license | cyberscorpio/libxl | fcc0c67390dd8eae4bb7d36f6a459ffed368183a | 8d27566f45234af214a7a1e19c455e9721073e8c | refs/heads/master | 2021-01-19T16:56:51.990977 | 2010-06-30T08:18:41 | 2010-06-30T08:18:41 | 38,444,794 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 802 | h | #ifndef XL_UI_BITMAP_H
#define XL_UI_BITMAP_H
#include <memory>
#include "../common.h"
#include "DIBSection.h"
XL_BEGIN
UI_BEGIN
class CBitmap;
typedef std::tr1::shared_ptr<CBitmap> CBitmapPtr;
class CBitmap : public CDIBSection {
COLORREF m_rgbTrans;
COLORREF *m_pTransColor;
public:
CBitmap ();
CBitmap (COLORREF colorKey);
virtual ~CBitmap ();
void setColorKey (COLORREF colorKey);
void clearColorKey ();
void gray ();
bool load (HBITMAP);
bool load (int id); // load from resource
void draw (HDC hdc, int toX, int toY, int toW, int toH, int fromX, int fromY, uint op = SRCCOPY);
void draw (HDC hdc, int toX, int toY, int toW, int toH, int fromX, int fromY, int fromW, int fromH, uint op = SRCCOPY);
};
UI_END
XL_END
#endif
| [
"doudehou@59b6eb50-eb15-11de-b362-3513cf04e977",
"[email protected]"
]
| [
[
[
1,
25
],
[
30,
35
]
],
[
[
26,
29
]
]
]
|
e037bb4f0acbf4854aa2b50c36d698824935480a | a8e78ee1cae74946b8b68aaaf0447d745d6fbaf3 | /CPPUnitBCB6/borland/TestRunner/TestRunnerUI.cpp | efd0bb34af8f040ec7b8edeb4afba50a255004c1 | []
| no_license | jmnavarro/BCB_CPPUnit | 66c155026bd8445ca016e1327b0d222e3f4a10ad | 7de1560d537db56d265fde482420bc6f66f01c32 | refs/heads/master | 2021-01-23T13:58:57.815624 | 2011-07-01T08:47:23 | 2011-07-01T08:47:23 | 1,982,570 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 475 | cpp | #include <vcl.h>
#pragma hdrstop
#include "TestRunnerUI.h"
#include "TestRunnerUnitForm.h"
#include "TreeTestUnitForm.h"
TestRunnerUI::TestRunnerUI()
: m_dlg(0)
{
// m_dlg = new TTestRunnerForm(Application);
m_dlg = new TTreeTestForm(Application);
}
TestRunnerUI::~TestRunnerUI()
{
delete m_dlg;
}
void TestRunnerUI::setTests (TestList* tests)
{
m_dlg->setTests(tests);
}
void TestRunnerUI::ShowModal()
{
m_dlg->ShowModal();
}
| [
"[email protected]"
]
| [
[
[
1,
33
]
]
]
|
15f344e9c869ba4093ef93f8bbbe67657a6b82a2 | 842997c28ef03f8deb3422d0bb123c707732a252 | /src/uslsext/USGLQuad.cpp | ada1dd749f71e9718b6841cebe47fef44a4d1da0 | []
| no_license | bjorn/moai-beta | e31f600a3456c20fba683b8e39b11804ac88d202 | 2f06a454d4d94939dc3937367208222735dd164f | refs/heads/master | 2021-01-17T11:46:46.018377 | 2011-06-10T07:33:55 | 2011-06-10T07:33:55 | 1,837,561 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,761 | cpp | // Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved.
// http://getmoai.com
#include "pch.h"
#include <uslsext/USDrawBuffer.h>
#include <uslsext/USGLQuad.h>
//================================================================//
// USGLQuad
//================================================================//
//----------------------------------------------------------------//
void USGLQuad::BindVertexFormat ( USDrawBuffer& drawBuffer ) {
drawBuffer.SetVertexPreset ( USVertexFormatMgr::VTX_FMT_XYUVC );
drawBuffer.SetPrimType ( GL_TRIANGLES );
}
//----------------------------------------------------------------//
void USGLQuad::Draw () {
this->Draw ( this->mVtx, this->mUV );
}
//----------------------------------------------------------------//
void USGLQuad::Draw ( const USMatrix2D& mtx ) {
USVec2D vtx [ 4 ];
vtx [ 0 ] = this->mVtx [ 0 ];
vtx [ 1 ] = this->mVtx [ 1 ];
vtx [ 2 ] = this->mVtx [ 2 ];
vtx [ 3 ] = this->mVtx [ 3 ];
mtx.Transform ( vtx [ 0 ]);
mtx.Transform ( vtx [ 1 ]);
mtx.Transform ( vtx [ 2 ]);
mtx.Transform ( vtx [ 3 ]);
this->Draw ( vtx, this->mUV );
}
//----------------------------------------------------------------//
void USGLQuad::Draw ( float xOff, float yOff ) {
USVec2D vtx [ 4 ];
vtx [ 0 ].mX = this->mVtx [ 0 ].mX + xOff;
vtx [ 0 ].mY = this->mVtx [ 0 ].mY + yOff;
vtx [ 1 ].mX = this->mVtx [ 1 ].mX + xOff;
vtx [ 1 ].mY = this->mVtx [ 1 ].mY + yOff;
vtx [ 2 ].mX = this->mVtx [ 2 ].mX + xOff;
vtx [ 2 ].mY = this->mVtx [ 2 ].mY + yOff;
vtx [ 3 ].mX = this->mVtx [ 3 ].mX + xOff;
vtx [ 3 ].mY = this->mVtx [ 3 ].mY + yOff;
this->Draw ( vtx, this->mUV );
}
//----------------------------------------------------------------//
void USGLQuad::Draw ( float xOff, float yOff, float xScale, float yScale ) {
USVec2D vtx [ 4 ];
vtx [ 0 ].mX = ( this->mVtx [ 0 ].mX * xScale ) + xOff;
vtx [ 0 ].mY = ( this->mVtx [ 0 ].mY * yScale ) + yOff;
vtx [ 1 ].mX = ( this->mVtx [ 1 ].mX * xScale ) + xOff;
vtx [ 1 ].mY = ( this->mVtx [ 1 ].mY * yScale ) + yOff;
vtx [ 2 ].mX = ( this->mVtx [ 2 ].mX * xScale ) + xOff;
vtx [ 2 ].mY = ( this->mVtx [ 2 ].mY * yScale ) + yOff;
vtx [ 3 ].mX = ( this->mVtx [ 3 ].mX * xScale ) + xOff;
vtx [ 3 ].mY = ( this->mVtx [ 3 ].mY * yScale ) + yOff;
this->Draw ( vtx, this->mUV );
}
//----------------------------------------------------------------//
void USGLQuad::Draw ( const USVec2D* vtx, const USVec2D* uv ) {
USDrawBuffer& drawBuffer = USDrawBuffer::Get ();
drawBuffer.BeginPrim ();
USGLQuad::WriteVertex ( drawBuffer, vtx [ 3 ], uv [ 3 ]);
USGLQuad::WriteVertex ( drawBuffer, vtx [ 1 ], uv [ 1 ]);
USGLQuad::WriteVertex ( drawBuffer, vtx [ 0 ], uv [ 0 ]);
drawBuffer.EndPrim ();
drawBuffer.BeginPrim ();
USGLQuad::WriteVertex ( drawBuffer, vtx [ 3 ], uv [ 3 ]);
USGLQuad::WriteVertex ( drawBuffer, vtx [ 2 ], uv [ 2 ]);
USGLQuad::WriteVertex ( drawBuffer, vtx [ 1 ], uv [ 1 ]);
drawBuffer.EndPrim ();
}
//----------------------------------------------------------------//
USRect USGLQuad::GetUVBounds () {
USRect rect;
rect.Init ( this->mUV [ 0 ]);
rect.Grow ( this->mUV [ 1 ]);
rect.Grow ( this->mUV [ 2 ]);
rect.Grow ( this->mUV [ 3 ]);
return rect;
}
//----------------------------------------------------------------//
USRect USGLQuad::GetVtxBounds () {
USRect rect;
rect.Init ( this->mVtx [ 0 ]);
rect.Grow ( this->mVtx [ 1 ]);
rect.Grow ( this->mVtx [ 2 ]);
rect.Grow ( this->mVtx [ 3 ]);
return rect;
}
//----------------------------------------------------------------//
void USGLQuad::ScaleUVs ( float xScale, float yScale ) {
this->mUV [ 0 ].Scale ( xScale, yScale );
this->mUV [ 1 ].Scale ( xScale, yScale );
this->mUV [ 2 ].Scale ( xScale, yScale );
this->mUV [ 3 ].Scale ( xScale, yScale );
}
//----------------------------------------------------------------//
void USGLQuad::ScaleVerts ( float xScale, float yScale ) {
this->mVtx [ 0 ].Scale ( xScale, yScale );
this->mVtx [ 1 ].Scale ( xScale, yScale );
this->mVtx [ 2 ].Scale ( xScale, yScale );
this->mVtx [ 3 ].Scale ( xScale, yScale );
}
//----------------------------------------------------------------//
void USGLQuad::SetUVs ( const USRect& rect ) {
// left top
this->mUV [ 0 ].mX = rect.mXMin;
this->mUV [ 0 ].mY = rect.mYMax;
// right top
this->mUV [ 1 ].mX = rect.mXMax;
this->mUV [ 1 ].mY = rect.mYMax;
// right bottom
this->mUV [ 2 ].mX = rect.mXMax;
this->mUV [ 2 ].mY = rect.mYMin;
// left bottom
this->mUV [ 3 ].mX = rect.mXMin;
this->mUV [ 3 ].mY = rect.mYMin;
}
//----------------------------------------------------------------//
void USGLQuad::SetUVs ( float* buffer ) {
// left top
this->mUV [ 0 ].mX = buffer [ 0 ];
this->mUV [ 0 ].mY = buffer [ 1 ];
// right top
this->mUV [ 1 ].mX = buffer [ 2 ];
this->mUV [ 1 ].mY = buffer [ 3 ];
// right bottom
this->mUV [ 2 ].mX = buffer [ 4 ];
this->mUV [ 2 ].mY = buffer [ 5 ];
// left bottom
this->mUV [ 3 ].mX = buffer [ 6 ];
this->mUV [ 3 ].mY = buffer [ 7 ];
}
//----------------------------------------------------------------//
void USGLQuad::SetUVs ( float x0, float y0, float x1, float y1 ) {
// left top
this->mUV [ 0 ].mX = x0;
this->mUV [ 0 ].mY = y1;
// right top
this->mUV [ 1 ].mX = x1;
this->mUV [ 1 ].mY = y1;
// right bottom
this->mUV [ 2 ].mX = x1;
this->mUV [ 2 ].mY = y0;
// left bottom
this->mUV [ 3 ].mX = x0;
this->mUV [ 3 ].mY = y0;
}
//----------------------------------------------------------------//
void USGLQuad::SetUVs ( const USVec2D& v0, const USVec2D& v1,const USVec2D& v2, const USVec2D& v3 ) {
// left top
this->mUV [ 0 ] = v0;
// right top
this->mUV [ 1 ] = v1;
// right bottom
this->mUV [ 2 ] = v2;
// left bottom
this->mUV [ 3 ] = v3;
}
//----------------------------------------------------------------//
void USGLQuad::SetUVs ( float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3 ) {
// left top
this->mUV [ 0 ].mX = x0;
this->mUV [ 0 ].mY = y0;
// right top
this->mUV [ 1 ].mX = x1;
this->mUV [ 1 ].mY = y1;
// right bottom
this->mUV [ 2 ].mX = x2;
this->mUV [ 2 ].mY = y2;
// left bottom
this->mUV [ 3 ].mX = x3;
this->mUV [ 3 ].mY = y3;
}
//----------------------------------------------------------------//
void USGLQuad::SetVerts ( const USRect& rect ) {
// left top
this->mVtx [ 0 ].mX = rect.mXMin;
this->mVtx [ 0 ].mY = rect.mYMax;
// right top
this->mVtx [ 1 ].mX = rect.mXMax;
this->mVtx [ 1 ].mY = rect.mYMax;
// right bottom
this->mVtx [ 2 ].mX = rect.mXMax;
this->mVtx [ 2 ].mY = rect.mYMin;
// left bottom
this->mVtx [ 3 ].mX = rect.mXMin;
this->mVtx [ 3 ].mY = rect.mYMin;
}
//----------------------------------------------------------------//
void USGLQuad::SetVerts ( float* buffer ) {
// left top
this->mVtx [ 0 ].mX = buffer [ 0 ];
this->mVtx [ 0 ].mY = buffer [ 1 ];
// right top
this->mVtx [ 1 ].mX = buffer [ 2 ];
this->mVtx [ 1 ].mY = buffer [ 3 ];
// right bottom
this->mVtx [ 2 ].mX = buffer [ 4 ];
this->mVtx [ 2 ].mY = buffer [ 5 ];
// left bottom
this->mVtx [ 3 ].mX = buffer [ 6 ];
this->mVtx [ 3 ].mY = buffer [ 7 ];
}
//----------------------------------------------------------------//
void USGLQuad::SetVerts ( float x0, float y0, float x1, float y1 ) {
// left top
this->mVtx [ 0 ].mX = x0;
this->mVtx [ 0 ].mY = y1;
// right top
this->mVtx [ 1 ].mX = x1;
this->mVtx [ 1 ].mY = y1;
// right bottom
this->mVtx [ 2 ].mX = x1;
this->mVtx [ 2 ].mY = y0;
// left bottom
this->mVtx [ 3 ].mX = x0;
this->mVtx [ 3 ].mY = y0;
}
//----------------------------------------------------------------//
void USGLQuad::SetVerts ( const USVec2D& v0, const USVec2D& v1, const USVec2D& v2, const USVec2D& v3 ) {
// left top
this->mVtx [ 0 ] = v0;
// right top
this->mVtx [ 1 ] = v1;
// right bottom
this->mVtx [ 2 ] = v2;
// left bottom
this->mVtx [ 3 ] = v3;
}
//----------------------------------------------------------------//
void USGLQuad::SetVerts ( float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3 ) {
// left top
this->mUV [ 0 ].mX = x0;
this->mUV [ 0 ].mY = y0;
// right top
this->mUV [ 1 ].mX = x1;
this->mUV [ 1 ].mY = y1;
// right bottom
this->mUV [ 2 ].mX = x2;
this->mUV [ 2 ].mY = y2;
// left bottom
this->mUV [ 3 ].mX = x3;
this->mUV [ 3 ].mY = y3;
}
//----------------------------------------------------------------//
void USGLQuad::SetVerts ( const USVec2D& v0, float radius ) {
this->SetVerts (
v0.mX - radius,
v0.mY - radius,
v0.mX + radius,
v0.mY + radius
);
}
//----------------------------------------------------------------//
void USGLQuad::TransformVerts ( const USMatrix2D& mtx ) {
mtx.Transform ( this->mVtx [ 0 ]);
mtx.Transform ( this->mVtx [ 1 ]);
mtx.Transform ( this->mVtx [ 2 ]);
mtx.Transform ( this->mVtx [ 3 ]);
}
//----------------------------------------------------------------//
void USGLQuad::TransformUVs ( const USMatrix2D& mtx ) {
mtx.Transform ( this->mUV [ 0 ]);
mtx.Transform ( this->mUV [ 1 ]);
mtx.Transform ( this->mUV [ 2 ]);
mtx.Transform ( this->mUV [ 3 ]);
}
//----------------------------------------------------------------//
USGLQuad::USGLQuad () {
}
//----------------------------------------------------------------//
USGLQuad::~USGLQuad () {
}
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
14
],
[
16,
372
]
],
[
[
15,
15
]
]
]
|
4a848a1b3c62e90d8b7cb7a043315ed572a31a20 | 3bf1d88356ad23aed59d82fa8db70149264829db | /HW2/material/guicheckers/GuiCheckSource105/database.cpp | a16d76c8b391c9aa2d45d580c07f24977364f618 | []
| no_license | NikolausDemmel/KTH-AI-Homework | c5e744352aa3e7804b2b4fa3bb2548e5d148e2da | a1cba621a9a18723b4bd64df35deed8305b8e73c | refs/heads/master | 2020-05-17T00:59:36.104454 | 2011-10-10T05:31:19 | 2011-10-10T05:31:19 | 2,303,694 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,123 | cpp | //
// Checkers Win/Loss/Draw Database Generation & Probing
// by Jonathan Kreuzer
//
// note: This is rather poor database code in most ways...
//
#include "uncompress.cpp"
const int SIZE2 = 32/4 * 32 * 2;
const int SIZE3 = SIZE2 * 32;
int SIZE4 = 0;
unsigned char ResultsTwo [ 4 * SIZE2 ];
unsigned char ResultsThree[ 6 * SIZE3 ];
unsigned char *ResultsFour;
unsigned char *pResults;
int PC2[4*4] = { WKING, BKING, EMPTY, EMPTY, WKING, BPIECE, EMPTY, EMPTY,
WPIECE, BKING, EMPTY, EMPTY, WPIECE, BPIECE, EMPTY, EMPTY};
int PC3[4*12] = {WKING, WKING, BKING, EMPTY, WKING, BKING, BKING, EMPTY,
WKING, WKING, BPIECE, EMPTY, WPIECE, BKING, BKING, EMPTY,
WKING, WPIECE, BKING, EMPTY, WKING, BKING, BPIECE, EMPTY,
WPIECE, WPIECE, BKING, EMPTY, WKING, BPIECE, BPIECE, EMPTY,
WKING, WPIECE, BPIECE, EMPTY, WPIECE, BKING, BPIECE, EMPTY,
WPIECE, WPIECE, BPIECE, EMPTY, WPIECE, BPIECE, BPIECE, EMPTY};
int PC4[4*9] = {WKING, WKING, BKING, BKING, WKING, WPIECE, BKING, BKING , WKING, WKING, BKING, BPIECE,
WKING, WPIECE, BKING, BPIECE, WPIECE, WPIECE, BKING, BKING, WKING, WKING, BPIECE, BPIECE,
WPIECE, WPIECE, BKING, BPIECE, WKING, WPIECE, BPIECE, BPIECE, WPIECE, WPIECE, BPIECE, BPIECE };
int FourIndex[9] = { 0, 1, 9, 2, 3, 11, 4, 12, 5};
int ThreeIndex[12]= { 0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13};
int FlipResult[9] = { 0, 2, 1, 3 };
int GetResult( unsigned char *pResults, int Index )
{
return( pResults[ Index/4 ] >> ((Index&3)*2) ) & 3;
}
void SetResult ( int Index, int Result )
{
pResults[ Index/4 ] ^= (GetResult(pResults, Index) << ((Index&3)*2));
pResults[ Index/4 ] |= (Result << ((Index&3)*2));
}
struct SDatabase
{
int nStart, nSizeW, nSizeB;
int Pieces[4];
int IndW[32*32], IndB[32*32];
int inline GetIndex( int nW, int nB, int stm )
{
return nStart + stm + 2*IndW[ nW ] + 2*nSizeW*IndB[ nB ];
}
};
SDatabase FourPc[12];
void Compute2PieceIndices( int pData[], int &nSize, int nP[] )
{
int nSq1, nSq2;
int bSame = (nP[0] == nP[1]) ? 1: 0;
nSize = 0;
for (nSq1 = 0; nSq1 < 32; nSq1++)
for (nSq2 = 0; nSq2 < 32; nSq2++)
{
if ((nSq2 < nSq1 && bSame) ) pData[ nSq1 + nSq2*32 ] = pData[ nSq2 + nSq1*32 ];
else if (nSq1 == nSq2) pData[ nSq1 + nSq2*32 ] = 0;
else if ((nSq1 < 4 && nP[0] == WPIECE) || (nSq2 < 4 && nP[1] == WPIECE) || (nSq1 > 27 && nP[0] == BPIECE) || (nSq2 > 27 && nP[1] == BPIECE))
{pData[ nSq1 + nSq2*32 ] = 0;}
else {pData[ nSq1 + nSq2*32 ] = nSize;
nSize++;
}
}
}
int ComputeAllIndices( )
{
int nStart = 0;
for (int i = 0; i < 9; i++)
{
int n = FourIndex[i];
if (n > 8) continue;
memcpy( &FourPc[n].Pieces[0], &PC4[4*i] , 4*sizeof(int) );
FourPc[n].nStart = nStart;
Compute2PieceIndices( FourPc[n].IndW, FourPc[n].nSizeW, &FourPc[n].Pieces[0] );
Compute2PieceIndices( FourPc[n].IndB, FourPc[n].nSizeB, &FourPc[n].Pieces[2] );
nStart += FourPc[n].nSizeW * FourPc[n].nSizeB * 2;
}
SIZE4 = nStart/4+1;
ResultsFour = (unsigned char*) malloc ( nStart/4 + 4 );
memset (ResultsFour, 0, SIZE4);
memset (ResultsThree, 0, 6*SIZE3);
memset (ResultsTwo, 0, 4*SIZE2);
return SIZE4;
}
//
//
int ComputeIndex( int WS[], int BS[], int &nPieces, int stm, int &bFlip)
{
int Index, i;
nPieces = 0;
bFlip = 0;
if (WS[0] == -1) {nPieces = 1; return 1;}
if (BS[0] == -1) {nPieces = 1; return 2;}
int Sqs[4];
Sqs[ nPieces++ ] = (WS[0]>>4);
WS[0] = (WS[0]&15);
if (WS[1] >= 0) {Sqs[ nPieces++ ]=(WS[1]>>4); WS[1] = (WS[1]&15); }
Sqs[ nPieces++ ] = (BS[0]>>4);
BS[0] = (BS[0]&15);
if (BS[1] >= 0) {Sqs[ nPieces++ ]=(BS[1]>>4); BS[1] = (BS[1]&15); }
if (nPieces == 2)
{
for (i = 0; i < 4; i++)
if (WS[0] == PC2[0 + i*4] && BS[0] == PC2[0 + i*4+1]) break;
Index = Sqs[0] + Sqs[1]*32 + stm*1024 + i*(32*32*2);
return Index;
}
if (nPieces == 3)
{
for (i = 0; i < 12; i++)
if ((WS[0] == PC3[0 + i*4] && WS[1] == PC3[1 + i*4] && BS[0] == PC3[2 + i*4]) ||
( WS[0] == PC3[0 + i*4] && BS[0] == PC3[1 + i*4] && BS[1] == PC3[2 + i*4])) break;
if ( ThreeIndex[i] < 8 ) Index = Sqs[0] + Sqs[1]*32 + Sqs[2]*32*32 + stm*32*32*32;
else {Index = (31-Sqs[1]) + (31-Sqs[2])*32 + (31-Sqs[0])*32*32 + (stm^1)*32*32*32;
bFlip = 1;
}
return Index + (ThreeIndex[i]&7) * (32*32*32*2);
}
if (nPieces == 4)
{
for (i = 0; i < 9; i++)
if (WS[0] == PC4[0 + i*4] && WS[1] == PC4[1 + i*4] && BS[0] == PC4[2 + i*4] && BS[1] == PC4[3 + i*4]) break;
if ( FourIndex[i]<8 )
Index = FourPc[ FourIndex[i] ].GetIndex( Sqs[0]+Sqs[1]*32, Sqs[2]+Sqs[3]*32, stm );
else {Index = FourPc[ FourIndex[i]&7 ].GetIndex( (31-Sqs[2]) + (31-Sqs[3])*32 , (31-Sqs[0]) + (31-Sqs[1])*32, stm^1 );
bFlip = 1;
}
return Index;
}
return 0;
}
//
// Get Index From Board
// Should be 2 of a color at most
//
int GetIndexFromBoard( CBoard &Board, int &bFlip, int &nPieces )
{
int WSqs[2], BSqs[2], Piece;
int stm = Board.SideToMove - 1;
WSqs[0] = -1; WSqs[1] = -1;
BSqs[0] = -1; BSqs[1] = -1;
UINT WPieces = Board.C.WP;
while ( WPieces ) {
UINT sq = FindLowBit( WPieces );
WPieces &= ~S[sq];
Piece = Board.Sqs[ BoardLoc32[sq] ];
if (WSqs[0]==-1) { WSqs[0] = Piece + sq*16; }
else if ( Board.C.K & S[sq] ) {WSqs[1] = WSqs[0]; WSqs[0] = Piece + sq*16; }
else WSqs[1] = Piece + sq*16;
}
UINT BPieces = Board.C.BP;
while ( BPieces ) {
UINT sq = FindLowBit( BPieces );
BPieces &= ~S[sq];
Piece = Board.Sqs[ BoardLoc32[sq] ];
if (BSqs[0]==-1) { BSqs[0] = Piece+ sq*16; }
else if ( Board.C.K & S[sq] ) {BSqs[1] = BSqs[0]; BSqs[0] = Piece + sq*16; }
else BSqs[1] = Piece + sq*16;
}
return ComputeIndex( WSqs, BSqs, nPieces, stm, bFlip);
}
//
// Return a Win/Loss/Draw value for the board
//
int QueryDatabase( CBoard &Board )
{
int bFlip, nPieces, Result = 3;
int Index = GetIndexFromBoard (Board, bFlip, nPieces);
if (nPieces == 1) return Index;
if (nPieces == 2) Result = GetResult( ResultsTwo , Index );
if (nPieces == 3) Result = GetResult( ResultsThree, Index );
if (nPieces == 4) Result = GetResult( ResultsFour , Index );
if (bFlip) return FlipResult[ Result ];
return Result;
}
//
//
//
int inline TestBoard( CBoard &Board, int nPieces, int np1, int np2, int np3, int RIndex )
{
CMoveList Moves;
CBoard OldBoard = Board;
int Result, nLosses, Win, Loss, Index, i, bFlip;
int nTotalWins = 0;
for (int stm = 0; stm < 2; stm++)
{
Board.SideToMove = stm+1;
OldBoard.SideToMove = stm+1;
Index = GetIndexFromBoard( Board, bFlip, nPieces );
if (nPieces == 2) pResults = ResultsTwo;
else if (nPieces == 3) pResults = ResultsThree;
else if (nPieces == 4) pResults = ResultsFour;
if (nPieces == 3)
{Index = np1 + np2*32 + np3*32*32 + stm*32*32*32 + (RIndex) * (32*32*32*2);}
if (GetResult( pResults, Index ) != 0) {nTotalWins++; continue;}
if (Board.SideToMove == WHITE) {Moves.FindMovesWhite( Board.Sqs, Board.C ); Win = 2; Loss = 1;}
else {Moves.FindMovesBlack( Board.Sqs, Board.C ); Win = 1; Loss = 2;}
if (Moves.nMoves == 0) {SetResult( Index, Loss ); nTotalWins++;} // Can't move, so it's a loss
else if (Moves.nMoves != 0)
{
nLosses = 0;
// Check the moves. If a move wins this is a win, if they all lose it's a loss, otherwise it's a draw
for (i = 1; i <= Moves.nMoves; i++)
{
Board.DoMove( Moves.Moves[i], SEARCHED);
Result = QueryDatabase( Board );
Board = OldBoard;
if ( Result == Win ) {SetResult(Index, Win); nTotalWins++; break;}
if ( Result == Loss ) nLosses++;
}
if ( nLosses == Moves.nMoves )
{
SetResult (Index, Loss);
nTotalWins++;
}
}
}
return nTotalWins;
}
//
// This function will generate a win/loss/draw database. It's actually not hard to generate such a database.
// Doing a good job is the tough part, but since I only want small databases for now, this is at least works.
//
void GenDatabase( int Piece1, int Piece2, int Piece3, int Piece4, int RIndex )
{
CBoard Board;
int nLastTotalWins = -1, nTotalWins = 0;
int it = 0, nPieces = -1, bFlip;
while (nTotalWins != nLastTotalWins) // Keep going until we reach a plateau
{
nLastTotalWins = nTotalWins;
nTotalWins = 0;
// Loop through every possible position
for (int np1 = 0; np1 < 32; np1++)
for (int np2 = 0; np2 < 32; np2++)
for (int np3 = 0; np3 < 32; np3++)
{
for (int np4 = 0; np4 < 32; np4++)
{
// Skip Illegal Positions
if (np1 == np2) continue;
if (Piece3 != EMPTY)
if (np1 == np3 || np2 == np3) continue;
if (Piece4 != EMPTY)
if (np4 == np3 || np4 == np2 || np4 == np1) continue;
// Setup the board
Board.Clear( );
Board.Sqs[ BoardLoc32[np4] ] = Piece4;
Board.Sqs[ BoardLoc32[np3] ] = Piece3;
Board.Sqs[ BoardLoc32[np2] ] = Piece2;
Board.Sqs[ BoardLoc32[np1] ] = Piece1;
Board.C.ConvertFromSqs( Board.Sqs );
// Skip illegal positions( checker on back row )
if (Board.C.WP & ~Board.C.K & (S[0]|S[1]|S[2]|S[3]) ) continue;
if (Board.C.BP & ~Board.C.K & (S[28]|S[29]|S[30]|S[31]) ) continue;
if (nPieces == -1)
{
GetIndexFromBoard( Board, bFlip, nPieces );
if (bFlip) return;
}
nTotalWins += TestBoard( Board, nPieces, np1, np2, np3, RIndex );
if (Piece4 == EMPTY) break;
}
if (Piece3 == EMPTY) break;
}
it++;
}
}
void SaveAllDatabases()
{
FILE *FP = fopen ("2pc.cdb", "wb");
fwrite (ResultsTwo , 4, SIZE2, FP );
fclose (FP);
FP = fopen ("3pc.cdb", "wb");
fwrite (ResultsThree, 6, SIZE3, FP );
fclose (FP);
FP = fopen ("4pc.cdb", "wb");
fwrite (ResultsFour, 1, SIZE4, FP );
fclose (FP);
}
void LoadAllDatabases( )
{
ComputeAllIndices( );
g_bDatabases = 1;
char sAFile[256];
if (bCheckerBoard) {
strcpy( sAFile, "engines\\database.jef");
FILE *FP = fopen( sAFile, "rb");
if (FP) fclose(FP);
else strcpy( sAFile, "database.jef");
}
else strcpy( sAFile, "database.jef");
if (uncompressFileFromArchive( sAFile, "2pc.cdb", ResultsTwo) != 1) g_bDatabases = 0;
if (uncompressFileFromArchive( sAFile, "3pc.cdb", ResultsThree)!= 1) g_bDatabases = 0;
if (uncompressFileFromArchive( sAFile, "4pc.cdb", ResultsFour) != 1) g_bDatabases = 0;
/*FILE *FP;
if ( (FP = fopen ("2pc.cdb", "rb")) ) {
fread (ResultsTwo , 4, SIZE2, FP );
fclose (FP);
} else g_bDatabases = 0;
if ( (FP = fopen ("3pc.cdb", "rb")) ) {
fread (ResultsThree, 6, SIZE3, FP );
fclose (FP);
} else g_bDatabases = 0;
if ((FP = fopen ("4pc.cdb", "rb"))) {
fread (ResultsFour, 1, SIZE4 , FP );
fclose (FP);
} else g_bDatabases = 0;*/
}
void GenAllDatabases( )
{
LoadAllDatabases();
/*ComputeAllIndices();
g_bDatabases = 1;
for (int i = 0; i < 4; i++) GenDatabase( PC2[ i*4 ], PC2[ i*4+1 ], PC2[ i*4+2 ], PC2[ i*4+3 ], i );
for (int i = 0; i < 12; i++) GenDatabase( PC3[ i*4 ], PC3[ i*4+1 ], PC3[ i*4+2 ], PC3[ i*4+3 ], ThreeIndex[i] );
for (int i = 0; i < 9; i++) GenDatabase( PC4[ i*4 ], PC4[ i*4+1 ], PC4[ i*4+2 ], PC4[ i*4+3 ], FourIndex[i] );
SaveAllDatabases();*/
} | [
"[email protected]"
]
| [
[
[
1,
357
]
]
]
|
d9397b673dd25ad824ac44d632fc9a0700e2b83c | 1584e139552d36bbbcc461deb81c22a06d42b713 | /shared/character.h | 7b87e196697e5ca863bf2a998350f377e8831c48 | []
| no_license | joshmg/battle | fd458da8be387ff0b4f80f0d2029759cd3fabe30 | 14ab71d903fe0bcf7c3285169026b4f96a186309 | refs/heads/master | 2020-05-18T17:20:00.768647 | 2010-09-28T04:34:34 | 2010-09-28T04:34:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,594 | h | // File: character.h
// Written by Joshua Green
#ifndef CHARACTER_H
#define CHARACTER_H
#include "../shared/shared.h"
#include "../shared/db/row.h"
#include "../shared/db/column.h"
#include <string>
#include <map>
class darkmatter;
class character {
private:
int _id;
int _hp_base, _mp_base;
mutable int _hp, _hp_max, _mp, _mp_max;
mutable bool _hp_max_valid, _mp_max_valid;
int _level, _exp;
mutable bool _dead;
std::string _name;
std::string _class; // _class is the name of the character class
bool _is_defined;
int _dmg_base;
int _speed_base;
int _speed; // _speed is the number of ticks added to _time upon time incriment (operator(++))
int _time;
int _tmax;
int _str_base, _dex_base, _int_base,
_spi_base, _fort_base;
mutable int _str, _dex, _int, _spi, _fort;
mutable bool _str_valid, _dex_valid, _int_valid,
_spi_valid, _fort_valid;
std::map<int, darkmatter*> _dmatter; // dmatter_id, dmatter_data
void _level_up();
void _void_cache() const;
public:
character();
character(const std::string&, const row&);
~character();
void clear();
void define(const row&);
row to_row() const;
std::string encode() const;
void decode(const std::string&);
int id() const;
void id(int);
std::string name() const;
std::string c_class() const;
int hp_max() const;
int mp_max() const;
int hp() const;
void hp(int) const;
int mp() const;
void mp(int) const;
bool dead() const;
void dead(bool);
int exp() const;
void exp(int);
int exp_max() const;
int level() const;
int speed() const;
int tmax() const;
int Str() const;
int Dex() const;
int Int() const;
int Spi() const;
int Fort() const;
bool is_defined() const;
void operator++(int);
int dmg() const;
void full_heal();
bool can_act(float threshold=0.0f) const;
float timebar_percent() const;
void set_timebar(float);
void load_dmatter(); // designed for server use
void add_dmatter(const row&);
void clear_dmatter();
void equip_dmatter(int, int, int); // dmatter id, weap/armor id, slot id
std::map<int, const darkmatter&> get_dmatter() const;
bool has_dmatter(int) const;
const darkmatter& get_dmatter(int) const;
point3d gui_pos;
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
115
]
]
]
|
3c5396eb13bb7c713ad99593afaafa9b70859ccc | fbe2cbeb947664ba278ba30ce713810676a2c412 | /iptv_root/iptv_media3/test_iptv_media/Kernel/Kernel.cpp | 0a662cb238ca43fd6767a5b365c62ff75e40c33d | []
| 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 | 4,248 | cpp | #include "compat.h"
//#include "CThreadSafeDeque.h"
#include "Kernel.h"
#include "Global_error.h"
#include "Media_const.h"
#include "CMedia.h"
#include "IKernelInterfaceNotify.h"
#include "media_utilities.h"
#include "log.h"
Kernel::Kernel()
{
m_bInit = FALSE;
m_pKernelInterfaceNotify = NULL;
m_pSockBuffs = new SockBuffs(MAX_TRANSMISSIONS, MAX_PKT_SIZE * MAX_PKT_COUNT);
m_pMedia = new CMedia();
if (m_pSockBuffs && m_pMedia)
{
m_bInit = TRUE;
m_pMedia->SetKernelNotify(this);
}
}
Kernel::~Kernel()
{
if (m_pSockBuffs)
delete m_pSockBuffs;
if (m_pMedia)
delete m_pMedia;
}
ULONG Kernel::InitNetwork(LPCSTR _szFilename)
{
if (!m_bInit)
return RET_INIT_ERROR;
if ( !( m_pSockBuffs->SetUrl(_szFilename) &&
m_pSockBuffs->SetINotify(this, 0) &&
m_pSockBuffs->OpenUrl() ) )
{
m_bInit = FALSE;
return RET_SOCKBUFFS_ERROR;
}
return RET_OK;
}
ULONG Kernel::InitNetwork(LPCSTR _szProtocol, LPCSTR _szHost, DWORD _dwPort, LPCSTR _szConnStr, BOOL _flListen)
{
if (!m_bInit)
return RET_INIT_ERROR;
if ( !(m_pSockBuffs->SetUrl(_szProtocol, _szHost ,_dwPort, _szConnStr, _flListen, NULL) &&
m_pSockBuffs->SetINotify(this, 0) &&
m_pSockBuffs->OpenUrl() ) )
{
m_bInit = FALSE;
return RET_SOCKBUFFS_ERROR;
}
return RET_OK;
}
BOOL Kernel::NewID(ULONG _id)
{
if (!m_bInit)
return RET_INIT_ERROR;
ULONG ret = FALSE;
if ( m_pSockBuffs->CreateWnd(_id, MAX_PKT_SIZE, 10, TRUE, SB_MEDIAPKTTYPE_EXT, _id))
{
if ( m_pMedia->AddTransmission(_id) == RET_OK )
ret = TRUE;
}
return ret;
}
BOOL Kernel::OnMediaNotify(MediaParam *_pParameters)
{
if (!m_bInit)
return RET_INIT_ERROR;
if (!_pParameters)
return RET_INVALID_ARG;
ULONG ret = RET_OK;
switch(_pParameters->code)
{
case MN_READ_PACKET:
{
ISockBuff *pSockReg = m_pSockBuffs->GetWndObj(_pParameters->id);
if (pSockReg)
{
BYTE pData[MAX_PKT_SIZE];
ULONG ulDatalen = MAX_PKT_SIZE;
if (pSockReg->Read(pData, ulDatalen, &ulDatalen) >= 0)
ret = m_pMedia->SetPacket(pData, ulDatalen);
else
ret = RET_ERROR;
}
else
ret = RET_ERROR;
}
break;
case MN_WRITE_PACKET:
break;
case MN_VIDEO_ALIVE:
ret = m_pKernelInterfaceNotify->SetMediaAlive(_pParameters->id, VIDEO);
break;
case MN_AUDIO_ALIVE:
ret = m_pKernelInterfaceNotify->SetMediaAlive(_pParameters->id, AUDIO);
break;
case MN_BUFFERING_START:
case MN_BUFFERING_STOP:
{
MediaParamExtBuf *pMediaParamExtBuf = (MediaParamExtBuf *) _pParameters;
#ifdef _DEBUG
char szBuf[200];
if (_pParameters->code == MN_BUFFERING_START)
sprintf(szBuf, "MN_BUFFERING_START - perc: %lu - ID: %lu", pMediaParamExtBuf->ulPercent, pMediaParamExtBuf->id);
else
sprintf(szBuf, "MN_BUFFERING_STOP - perc: %lu - ID: %lu", pMediaParamExtBuf->ulPercent, pMediaParamExtBuf->id);
g_FileLog.SetLog(szBuf);
#endif
}
break;
case MN_ERROR:
break;
}
return ret;
}
ULONG Kernel::TerminateConference()
{
if (!m_bInit)
return RET_INIT_ERROR;
m_pSockBuffs->Abort();
CHECK_ERROR(m_pMedia->EndAllTransmissions() , RET_OK)
return RET_OK;
}
ULONG Kernel::GetMediaDbgInfo(ULONG _id, MediaDbgInfo & _mediaDbgInfo)
{
if (!m_bInit)
return RET_INIT_ERROR;
CHECK_ERROR(m_pMedia->GetMediaDbgInfo(_id, _mediaDbgInfo), RET_OK)
return RET_OK;
}
ULONG Kernel::GetVideoReg(ULONG _id, VideoFrame_reg ** _ppVideoFrameReg)
{
if (!m_bInit)
return RET_INIT_ERROR;
CHECK_ERROR(m_pMedia->GetVideoReg(_id, _ppVideoFrameReg), RET_OK)
return RET_OK;
}
| [
"heineck@c016ff2c-3db2-11de-a81c-fde7d73ceb89"
]
| [
[
[
1,
181
]
]
]
|
8efcc3395b5f9287f45f9ceb69ac8c0c55e41260 | 216ae2fd7cba505c3690eaae33f62882102bd14a | /utils/nxogre/include/NxOgrePhysXRaycastReport.h | 09978c2c80790daab8365fcc39153d6b42e1a43b | []
| no_license | TimelineX/balyoz | c154d4de9129a8a366c1b8257169472dc02c5b19 | 5a0f2ee7402a827bbca210d7c7212a2eb698c109 | refs/heads/master | 2021-01-01T05:07:59.597755 | 2010-04-20T19:53:52 | 2010-04-20T19:53:52 | 56,454,260 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,968 | h | /** File: NxOgrePhysXRayCastReport.h
Created on: 19-Apr-09
Author: Robin Southern "betajaen"
SVN: $Id$
© Copyright, 2008-2009 by Robin Southern, http://www.nxogre.org
This file is part of NxOgre.
NxOgre is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
NxOgre is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with NxOgre. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef NXOGRE_PHYSXRAYCASTREPORT_H
#define NXOGRE_PHYSXRAYCASTREPORT_H
#include "NxOgreStable.h"
#include "NxOgreCommon.h"
#ifdef NXOGRE_SDK
# include "NxPhysics.h"
#endif
namespace NxOgre_Namespace
{
#ifdef NXOGRE_SDK
/** \brief
*/
class NxOgrePublicClass PhysXRaycastReport : public NxUserRaycastReport
{
public: // Functions
PhysXRaycastReport(Callback*);
~PhysXRaycastReport();
bool onHit(const NxRaycastHit& hits);
protected: // Variables
Callback* mCallback;
}; // class ClassName
#endif
} // namespace NxOgre_Namespace
#endif
| [
"umutert@b781d008-8b8c-11de-b664-3b115b7b7a9b"
]
| [
[
[
1,
70
]
]
]
|
ada7d6a185077e90c8c2c48d051a02d7de248214 | 9c62af23e0a1faea5aaa8dd328ba1d82688823a5 | /rl/tags/techdemo2/engine/rules/include/Inventory.h | 415940f5cecb38ced04acc11d7931ad6bfce8190 | [
"ClArtistic",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
]
| 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 | ISO-8859-1 | C++ | false | false | 6,862 | h | /* This source file is part of Rastullahs Lockenpracht.
* Copyright (C) 2003-2005 Team Pantheon. http://www.team-pantheon.de
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the Clarified Artistic License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Clarified Artistic License for more details.
*
* You should have received a copy of the Clarified Artistic License
* along with this program; if not you can get it here
* http://www.jpaulmorrison.com/fbp/artistic2.htm.
*/
#ifndef __INVENTORY_H__
#define __INVENTORY_H__
#include "Item.h"
#include "Weapon.h"
#include "Container.h"
#include "RulesPrerequisites.h"
namespace rl {
class _RlRulesExport Inventory;
class _RlRulesExport Creature;
/**
* @brief Verwaltet das Inventar des Charakters
*/
class _RlRulesExport Inventory
{
public:
///////////////////////////////////////////////////////////////////////////////
// Typedefs
/** @brief Eine Map mit Zeigern auf alle Waffen, die die Kreatur zur
* Zeit einsetzen kann.
**/
typedef map<int, Weapon*> WeaponMap;
/**
* @brief Eine Liste mit Zeigern auf Items
**/
typedef std::list<Item*> ItemList;
Inventory(Creature* owner);
virtual ~Inventory();
///////////////////////////////////////////////////////////////////////////////
// Methoden
/**
* Liefert alle Items im Inventar inm einer Liste
* Wichtig:
* NUR die erste Hierarchieebene der Items wird zurückgegeben
* Was in den Items drinnen ist, ist vernachlaessigt
*/
ItemList getAllItems();
/**
* Liefert die gesamte Last des Inventars in Unzen
*/
int getOverallWeight();
/**
* @return Die errechnete Behinderung
**/
pair<int,int> getOverallBe();
/**
* @return die gesamte Rüstung des Chars
*/
int getOverallRs();
/**
* @brief fügt das Item dem Inventar hinzu, wenn Platz ist,
* gibt sonst false zurück
* @param item Das Item, dass aufgenommen werden soll
**/
bool addItem(Item* item);
bool addItemToContainer(Item* item, Item* container);
/**
* Durchsucht alle Container und entfernt das Item daraus
*/
void removeItemFromContainers(Item* item);
/**
* Durchsucht einen Container und entfernt das Item daraus
*/
void removeItemFromContainer(Item* item, Item* container);
bool isFreeInContainer(Item* item, pair<int,int> posKaestchen, Item* container);
/**
* Liefert die Position und das Containeritem, das den Gegenstand trägt/beinhaltet
*/
pair<pair<int,int>, Item*> getItemPositionInContainer(Item* item);
void addWeapon(Weapon* weapon);
Weapon* getWeapon(int weaponId);
Weapon* removeWeapon(int weaponId);
void switchToWeapon(int weaponId);
void setItemContainerPosition(Item* item, int xPosDraggedTo, int yPosDraggedTo, Item* container);
void removeItem(Item* item);
//Ring links
Item* getRingLeft();
//Ring rechts
Item* getRingRight();
//in Hand links
Item* getHandLeft();
//in Hand rechts
Item* getHandRight();
//Handschuhe
Item* getGloves();
//Armreif links
Item* getBraceletLeft();
//Armreif rechts
Item* getBraceletRight();
//Oberkoerper Ruestung
Item* getArmor();
//Umhang
Item* getCape();
//Armschienen
Item* getBracers();
//Oberkoerper Ruecken (Rucksack, Schwertscheiden)
Item* getBackpack();
//Guertel (+Slots fuer Guerteltaschen+Scheiden)
Item* getBelt();
//Halskette
Item* getNecklace();
//Stirnband, Helm, Diadem
Item* getHelmet();
//Hose
Item* getTrousers();
//Beinschienen
Item* getShinbone();
//Stiefel
Item* getBoots();
Item* removeRingLeft();
Item* removeRingRight();
Item* removeHandLeft();
Item* removeHandRight();
Item* removeGloves();
Item* removeBraceletLeft();
Item* removeBraceletRight();
Item* removeArmor();
Item* removeCape();
Item* removeBracers();
Item* removeBackpack();
Item* removeBelt();
Item* removeNecklace();
Item* removeHelmet();
Item* removeTrousers();
Item* removeShinbone();
Item* removeBoots();
void setRingLeft(Item* item);
void setRingRight(Item* item);
void setHandLeft(Item* item);
void setHandRight(Item* item);
void setGloves(Item* item);
void setBraceletLeft(Item* item);
void setBraceletRight(Item* item);
void setBracers(Item* item);
void setArmor(Item* item);
void setCape(Item* item);
void setBackpack(Item* item);
void setBelt(Item* item);
void setNecklace(Item* item);
void setHelmet(Item* item);
void setTrousers(Item* item);
void setShinbone(Item* item);
void setBoots(Item* item);
private:
bool mValuesUpToDate;
int mCurrentWeight;
int mCurrentBeByWeight;
int mCurrentBe;
int mCurrentRs;
WeaponMap mWeapons;
Creature* mOwner;
Item* mRingLeft;
Item* mRingRight;
Item* mHandLeft;
Item* mHandRight;
Item* mGloves;
Item* mBraceletLeft;
Item* mBraceletRight;
Item* mArmor;
Item* mCape;
Item* mBracers;
Item* mBackpack;
Item* mBelt;
Item* mNecklace;
Item* mHelmet;
Item* mTrousers;
Item* mShinbone;
Item* mBoots;
/**
* Setzt Flag, dass die Werte neu berechnet werden müssen
*/
void markDirty();
/** @brief Liefert die nächste freie Position für den Gegenstand zurueck.
* @param space Die Ausmaße des Gegenstandes.
* @return Die Anfangsposition des Platzesm an den das Item gesetzt werden kann.
* @exception IllegalStateException Es gibt nicht genug Platz für das Item.
**/
pair<int,int> findPositionWithEnoughSpace(pair<int,int> space, ContainerLayout containerLayout);
/**
* Überprüft die Stelle im Inventar auf genug Platz für ein Item der Größe space
*/
bool checkSpace(int xStart, int yStart, pair<int,int> space, ContainerLayout container);
/**
* Fügt alle Items in einem Container rekursiv der Liste hinzu
*/
void addContainerItemsToList(Item &container, ItemList &itemList);
/**
* Erzeugt eine Liste aus Items, die am Körper getragen werden
*/
ItemList getWornItems();
/**
* Erzeugt eine Liste aus Containern, die der Character mit sich trägt
*/
ItemList getAllContainers();
/**
* Fügt alle Container in den Items rekursiv zur Liste hinzu
*/
void addContainersToList(Item &container, ItemList &itemList);
/**
* Update der Werte für Gewicht, Rs und Behinderung
*/
void updateStats();
/**
* Berechnet das Gewicht und aktualisiert mCurrentWeight
*/
void calculateWeight(ItemList allItems);
/**
* @pre: calculateWeight() wurde zuvor aufgerufen
* @post: berechnet die Behinderung (mCurrentRs und mCurrentBe werden aktualisiert)
*/
void calculateRsAndBe();
};
}
#endif
| [
"tanis@4c79e8ff-cfd4-0310-af45-a38c79f83013"
]
| [
[
[
1,
278
]
]
]
|
5d23e50c6bae446c86d2444eff1d20fff3e64489 | 52db451b6b354993000a4a808e9d046dff4c956f | /include/Card.h | c6bf97389e504600fd74f69a1ec5055ed38dd4e6 | []
| no_license | PuffNSting/Poker | a4b0263c27911291c6ce7148d22c1c137af457d3 | b1c606980af32b325fdf7398f30d6364c0097034 | refs/heads/master | 2021-01-15T22:29:18.718588 | 2011-12-23T03:02:07 | 2011-12-23T03:02:07 | 3,032,075 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 602 | h | #ifndef CARD_H
#define CARD_H
enum Suite {HEARTS, DIAMONDS, CLUBS, SPADES};
class Card
{
public:
Card() {};
Card(int v, int s) : value(v), suite(s) {}
int get_value() const { return value; }
int get_suite() const { return suite; }
bool operator< (const Card &rhs) const {
return (value < rhs.get_value());
}
bool operator==(const Card& c) const {
return (c.get_value() == value && c.get_suite() == suite);
}
private:
int value;
int suite;
};
#endif // CARD_H
| [
"[email protected]"
]
| [
[
[
1,
26
]
]
]
|
0038acd4dd9461a09129305d96ceff24f9f8b869 | 9448b8930b6bb3187e5d0f82c46cb37f854091de | /src/ghost/bnet.cpp | 1025af9523271f0bc4399c837c0af60e884aba32 | [
"Apache-2.0"
]
| permissive | jonasschneider/luaghost | 7c5bfd51b17409d75f49166aa622eb028d78ba70 | 5abf9884ba8df470b59a660dcee55e10f59cb018 | refs/heads/master | 2021-01-10T09:55:26.184673 | 2010-06-28T20:44:34 | 2010-06-28T20:44:34 | 730,499 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 88,300 | cpp | /*
Copyright [2008] [Trevor Hogan]
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.
CODE PORTED FROM THE ORIGINAL GHOST PROJECT: http://ghost.pwner.org/
*/
#include "ghost.h"
#include "util.h"
#include "config.h"
#include "language.h"
#include "socket.h"
#include "commandpacket.h"
#include "ghostdb.h"
#include "bncsutilinterface.h"
#include "bnlsclient.h"
#include "bnetprotocol.h"
#include "bnet.h"
#include "map.h"
#include "packed.h"
#include "savegame.h"
#include "replay.h"
#include "gameprotocol.h"
#include "game_base.h"
#include <boost/filesystem.hpp>
using namespace boost :: filesystem;
//
// CBNET
//
CBNET :: CBNET( CGHost *nGHost, string nServer, string nServerAlias, string nBNLSServer, uint16_t nBNLSPort, uint32_t nBNLSWardenCookie, string nCDKeyROC, string nCDKeyTFT, string nCountryAbbrev, string nCountry, uint32_t nLocaleID, string nUserName, string nUserPassword, string nFirstChannel, string nRootAdmin, char nCommandTrigger, bool nHoldFriends, bool nHoldClan, bool nPublicCommands, unsigned char nWar3Version, BYTEARRAY nEXEVersion, BYTEARRAY nEXEVersionHash, string nPasswordHashType, string nPVPGNRealmName, uint32_t nMaxMessageLength, uint32_t nHostCounterID )
{
// todotodo: append path seperator to Warcraft3Path if needed
m_GHost = nGHost;
m_Socket = new CTCPClient( );
m_Protocol = new CBNETProtocol( );
m_BNLSClient = NULL;
m_BNCSUtil = new CBNCSUtilInterface( nUserName, nUserPassword );
m_CallableAdminList = m_GHost->m_DB->ThreadedAdminList( nServer );
m_CallableBanList = m_GHost->m_DB->ThreadedBanList( nServer );
m_Exiting = false;
m_Server = nServer;
string LowerServer = m_Server;
transform( LowerServer.begin( ), LowerServer.end( ), LowerServer.begin( ), (int(*)(int))tolower );
if( !nServerAlias.empty( ) )
m_ServerAlias = nServerAlias;
else if( LowerServer == "useast.battle.net" )
m_ServerAlias = "USEast";
else if( LowerServer == "uswest.battle.net" )
m_ServerAlias = "USWest";
else if( LowerServer == "asia.battle.net" )
m_ServerAlias = "Asia";
else if( LowerServer == "europe.battle.net" )
m_ServerAlias = "Europe";
else
m_ServerAlias = m_Server;
if( nPasswordHashType == "pvpgn" && !nBNLSServer.empty( ) )
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] pvpgn connection found with a configured BNLS server, ignoring BNLS server" );
nBNLSServer.clear( );
nBNLSPort = 0;
nBNLSWardenCookie = 0;
}
m_BNLSServer = nBNLSServer;
m_BNLSPort = nBNLSPort;
m_BNLSWardenCookie = nBNLSWardenCookie;
m_CDKeyROC = nCDKeyROC;
m_CDKeyTFT = nCDKeyTFT;
// remove dashes and spaces from CD keys and convert to uppercase
m_CDKeyROC.erase( remove( m_CDKeyROC.begin( ), m_CDKeyROC.end( ), '-' ), m_CDKeyROC.end( ) );
m_CDKeyTFT.erase( remove( m_CDKeyTFT.begin( ), m_CDKeyTFT.end( ), '-' ), m_CDKeyTFT.end( ) );
m_CDKeyROC.erase( remove( m_CDKeyROC.begin( ), m_CDKeyROC.end( ), ' ' ), m_CDKeyROC.end( ) );
m_CDKeyTFT.erase( remove( m_CDKeyTFT.begin( ), m_CDKeyTFT.end( ), ' ' ), m_CDKeyTFT.end( ) );
transform( m_CDKeyROC.begin( ), m_CDKeyROC.end( ), m_CDKeyROC.begin( ), (int(*)(int))toupper );
transform( m_CDKeyTFT.begin( ), m_CDKeyTFT.end( ), m_CDKeyTFT.begin( ), (int(*)(int))toupper );
if( m_CDKeyROC.size( ) != 26 )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] warning - your ROC CD key is not 26 characters long and is probably invalid" );
if( m_GHost->m_TFT && m_CDKeyTFT.size( ) != 26 )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] warning - your TFT CD key is not 26 characters long and is probably invalid" );
m_CountryAbbrev = nCountryAbbrev;
m_Country = nCountry;
m_LocaleID = nLocaleID;
m_UserName = nUserName;
m_UserPassword = nUserPassword;
m_FirstChannel = nFirstChannel;
m_RootAdmin = nRootAdmin;
transform( m_RootAdmin.begin( ), m_RootAdmin.end( ), m_RootAdmin.begin( ), (int(*)(int))tolower );
m_CommandTrigger = nCommandTrigger;
m_War3Version = nWar3Version;
m_EXEVersion = nEXEVersion;
m_EXEVersionHash = nEXEVersionHash;
m_PasswordHashType = nPasswordHashType;
m_PVPGNRealmName = nPVPGNRealmName;
m_MaxMessageLength = nMaxMessageLength;
m_HostCounterID = nHostCounterID;
m_LastDisconnectedTime = 0;
m_LastConnectionAttemptTime = 0;
m_LastNullTime = 0;
m_LastOutPacketTicks = 0;
m_LastOutPacketSize = 0;
m_LastAdminRefreshTime = GetTime( );
m_LastBanRefreshTime = GetTime( );
m_FirstConnect = true;
m_WaitingToConnect = true;
m_LoggedIn = false;
m_InChat = false;
m_HoldFriends = nHoldFriends;
m_HoldClan = nHoldClan;
m_PublicCommands = nPublicCommands;
}
CBNET :: ~CBNET( )
{
delete m_Socket;
delete m_Protocol;
delete m_BNLSClient;
while( !m_Packets.empty( ) )
{
delete m_Packets.front( );
m_Packets.pop( );
}
delete m_BNCSUtil;
for( vector<CIncomingFriendList *> :: iterator i = m_Friends.begin( ); i != m_Friends.end( ); i++ )
delete *i;
for( vector<CIncomingClanList *> :: iterator i = m_Clans.begin( ); i != m_Clans.end( ); i++ )
delete *i;
for( vector<PairedAdminCount> :: iterator i = m_PairedAdminCounts.begin( ); i != m_PairedAdminCounts.end( ); i++ )
m_GHost->m_Callables.push_back( i->second );
for( vector<PairedAdminAdd> :: iterator i = m_PairedAdminAdds.begin( ); i != m_PairedAdminAdds.end( ); i++ )
m_GHost->m_Callables.push_back( i->second );
for( vector<PairedAdminRemove> :: iterator i = m_PairedAdminRemoves.begin( ); i != m_PairedAdminRemoves.end( ); i++ )
m_GHost->m_Callables.push_back( i->second );
for( vector<PairedBanCount> :: iterator i = m_PairedBanCounts.begin( ); i != m_PairedBanCounts.end( ); i++ )
m_GHost->m_Callables.push_back( i->second );
for( vector<PairedBanAdd> :: iterator i = m_PairedBanAdds.begin( ); i != m_PairedBanAdds.end( ); i++ )
m_GHost->m_Callables.push_back( i->second );
for( vector<PairedBanRemove> :: iterator i = m_PairedBanRemoves.begin( ); i != m_PairedBanRemoves.end( ); i++ )
m_GHost->m_Callables.push_back( i->second );
for( vector<PairedGPSCheck> :: iterator i = m_PairedGPSChecks.begin( ); i != m_PairedGPSChecks.end( ); i++ )
m_GHost->m_Callables.push_back( i->second );
for( vector<PairedDPSCheck> :: iterator i = m_PairedDPSChecks.begin( ); i != m_PairedDPSChecks.end( ); i++ )
m_GHost->m_Callables.push_back( i->second );
if( m_CallableAdminList )
m_GHost->m_Callables.push_back( m_CallableAdminList );
if( m_CallableBanList )
m_GHost->m_Callables.push_back( m_CallableBanList );
for( vector<CDBBan *> :: iterator i = m_Bans.begin( ); i != m_Bans.end( ); i++ )
delete *i;
}
BYTEARRAY CBNET :: GetUniqueName( )
{
return m_Protocol->GetUniqueName( );
}
unsigned int CBNET :: SetFD( void *fd, void *send_fd, int *nfds )
{
unsigned int NumFDs = 0;
if( !m_Socket->HasError( ) && m_Socket->GetConnected( ) )
{
m_Socket->SetFD( (fd_set *)fd, (fd_set *)send_fd, nfds );
NumFDs++;
if( m_BNLSClient )
NumFDs += m_BNLSClient->SetFD( fd, send_fd, nfds );
}
return NumFDs;
}
bool CBNET :: Update( void *fd, void *send_fd )
{
//
// update callables
//
for( vector<PairedAdminCount> :: iterator i = m_PairedAdminCounts.begin( ); i != m_PairedAdminCounts.end( ); )
{
if( i->second->GetReady( ) )
{
uint32_t Count = i->second->GetResult( );
if( Count == 0 )
QueueChatCommand( m_GHost->m_Language->ThereAreNoAdmins( m_Server ), i->first, !i->first.empty( ) );
else if( Count == 1 )
QueueChatCommand( m_GHost->m_Language->ThereIsAdmin( m_Server ), i->first, !i->first.empty( ) );
else
QueueChatCommand( m_GHost->m_Language->ThereAreAdmins( m_Server, UTIL_ToString( Count ) ), i->first, !i->first.empty( ) );
m_GHost->m_DB->RecoverCallable( i->second );
delete i->second;
i = m_PairedAdminCounts.erase( i );
}
else
i++;
}
for( vector<PairedAdminAdd> :: iterator i = m_PairedAdminAdds.begin( ); i != m_PairedAdminAdds.end( ); )
{
if( i->second->GetReady( ) )
{
if( i->second->GetResult( ) )
{
AddAdmin( i->second->GetUser( ) );
QueueChatCommand( m_GHost->m_Language->AddedUserToAdminDatabase( m_Server, i->second->GetUser( ) ), i->first, !i->first.empty( ) );
}
else
QueueChatCommand( m_GHost->m_Language->ErrorAddingUserToAdminDatabase( m_Server, i->second->GetUser( ) ), i->first, !i->first.empty( ) );
m_GHost->m_DB->RecoverCallable( i->second );
delete i->second;
i = m_PairedAdminAdds.erase( i );
}
else
i++;
}
for( vector<PairedAdminRemove> :: iterator i = m_PairedAdminRemoves.begin( ); i != m_PairedAdminRemoves.end( ); )
{
if( i->second->GetReady( ) )
{
if( i->second->GetResult( ) )
{
RemoveAdmin( i->second->GetUser( ) );
QueueChatCommand( m_GHost->m_Language->DeletedUserFromAdminDatabase( m_Server, i->second->GetUser( ) ), i->first, !i->first.empty( ) );
}
else
QueueChatCommand( m_GHost->m_Language->ErrorDeletingUserFromAdminDatabase( m_Server, i->second->GetUser( ) ), i->first, !i->first.empty( ) );
m_GHost->m_DB->RecoverCallable( i->second );
delete i->second;
i = m_PairedAdminRemoves.erase( i );
}
else
i++;
}
for( vector<PairedBanCount> :: iterator i = m_PairedBanCounts.begin( ); i != m_PairedBanCounts.end( ); )
{
if( i->second->GetReady( ) )
{
uint32_t Count = i->second->GetResult( );
if( Count == 0 )
QueueChatCommand( m_GHost->m_Language->ThereAreNoBannedUsers( m_Server ), i->first, !i->first.empty( ) );
else if( Count == 1 )
QueueChatCommand( m_GHost->m_Language->ThereIsBannedUser( m_Server ), i->first, !i->first.empty( ) );
else
QueueChatCommand( m_GHost->m_Language->ThereAreBannedUsers( m_Server, UTIL_ToString( Count ) ), i->first, !i->first.empty( ) );
m_GHost->m_DB->RecoverCallable( i->second );
delete i->second;
i = m_PairedBanCounts.erase( i );
}
else
i++;
}
for( vector<PairedBanAdd> :: iterator i = m_PairedBanAdds.begin( ); i != m_PairedBanAdds.end( ); )
{
if( i->second->GetReady( ) )
{
if( i->second->GetResult( ) )
{
AddBan( i->second->GetUser( ), i->second->GetIP( ), i->second->GetGameName( ), i->second->GetAdmin( ), i->second->GetReason( ) );
QueueChatCommand( m_GHost->m_Language->BannedUser( i->second->GetServer( ), i->second->GetUser( ) ), i->first, !i->first.empty( ) );
}
else
QueueChatCommand( m_GHost->m_Language->ErrorBanningUser( i->second->GetServer( ), i->second->GetUser( ) ), i->first, !i->first.empty( ) );
m_GHost->m_DB->RecoverCallable( i->second );
delete i->second;
i = m_PairedBanAdds.erase( i );
}
else
i++;
}
for( vector<PairedBanRemove> :: iterator i = m_PairedBanRemoves.begin( ); i != m_PairedBanRemoves.end( ); )
{
if( i->second->GetReady( ) )
{
if( i->second->GetResult( ) )
{
RemoveBan( i->second->GetUser( ) );
QueueChatCommand( m_GHost->m_Language->UnbannedUser( i->second->GetUser( ) ), i->first, !i->first.empty( ) );
}
else
QueueChatCommand( m_GHost->m_Language->ErrorUnbanningUser( i->second->GetUser( ) ), i->first, !i->first.empty( ) );
m_GHost->m_DB->RecoverCallable( i->second );
delete i->second;
i = m_PairedBanRemoves.erase( i );
}
else
i++;
}
for( vector<PairedGPSCheck> :: iterator i = m_PairedGPSChecks.begin( ); i != m_PairedGPSChecks.end( ); )
{
if( i->second->GetReady( ) )
{
CDBGamePlayerSummary *GamePlayerSummary = i->second->GetResult( );
if( GamePlayerSummary )
QueueChatCommand( m_GHost->m_Language->HasPlayedGamesWithThisBot( i->second->GetName( ), GamePlayerSummary->GetFirstGameDateTime( ), GamePlayerSummary->GetLastGameDateTime( ), UTIL_ToString( GamePlayerSummary->GetTotalGames( ) ), UTIL_ToString( (float)GamePlayerSummary->GetAvgLoadingTime( ) / 1000, 2 ), UTIL_ToString( GamePlayerSummary->GetAvgLeftPercent( ) ) ), i->first, !i->first.empty( ) );
else
QueueChatCommand( m_GHost->m_Language->HasntPlayedGamesWithThisBot( i->second->GetName( ) ), i->first, !i->first.empty( ) );
m_GHost->m_DB->RecoverCallable( i->second );
delete i->second;
i = m_PairedGPSChecks.erase( i );
}
else
i++;
}
for( vector<PairedDPSCheck> :: iterator i = m_PairedDPSChecks.begin( ); i != m_PairedDPSChecks.end( ); )
{
if( i->second->GetReady( ) )
{
CDBDotAPlayerSummary *DotAPlayerSummary = i->second->GetResult( );
if( DotAPlayerSummary )
{
string Summary = m_GHost->m_Language->HasPlayedDotAGamesWithThisBot( i->second->GetName( ),
UTIL_ToString( DotAPlayerSummary->GetTotalGames( ) ),
UTIL_ToString( DotAPlayerSummary->GetTotalWins( ) ),
UTIL_ToString( DotAPlayerSummary->GetTotalLosses( ) ),
UTIL_ToString( DotAPlayerSummary->GetTotalKills( ) ),
UTIL_ToString( DotAPlayerSummary->GetTotalDeaths( ) ),
UTIL_ToString( DotAPlayerSummary->GetTotalCreepKills( ) ),
UTIL_ToString( DotAPlayerSummary->GetTotalCreepDenies( ) ),
UTIL_ToString( DotAPlayerSummary->GetTotalAssists( ) ),
UTIL_ToString( DotAPlayerSummary->GetTotalNeutralKills( ) ),
UTIL_ToString( DotAPlayerSummary->GetTotalTowerKills( ) ),
UTIL_ToString( DotAPlayerSummary->GetTotalRaxKills( ) ),
UTIL_ToString( DotAPlayerSummary->GetTotalCourierKills( ) ),
UTIL_ToString( DotAPlayerSummary->GetAvgKills( ), 2 ),
UTIL_ToString( DotAPlayerSummary->GetAvgDeaths( ), 2 ),
UTIL_ToString( DotAPlayerSummary->GetAvgCreepKills( ), 2 ),
UTIL_ToString( DotAPlayerSummary->GetAvgCreepDenies( ), 2 ),
UTIL_ToString( DotAPlayerSummary->GetAvgAssists( ), 2 ),
UTIL_ToString( DotAPlayerSummary->GetAvgNeutralKills( ), 2 ),
UTIL_ToString( DotAPlayerSummary->GetAvgTowerKills( ), 2 ),
UTIL_ToString( DotAPlayerSummary->GetAvgRaxKills( ), 2 ),
UTIL_ToString( DotAPlayerSummary->GetAvgCourierKills( ), 2 ) );
QueueChatCommand( Summary, i->first, !i->first.empty( ) );
}
else
QueueChatCommand( m_GHost->m_Language->HasntPlayedDotAGamesWithThisBot( i->second->GetName( ) ), i->first, !i->first.empty( ) );
m_GHost->m_DB->RecoverCallable( i->second );
delete i->second;
i = m_PairedDPSChecks.erase( i );
}
else
i++;
}
// refresh the admin list every 5 minutes
if( !m_CallableAdminList && GetTime( ) - m_LastAdminRefreshTime >= 300 )
m_CallableAdminList = m_GHost->m_DB->ThreadedAdminList( m_Server );
if( m_CallableAdminList && m_CallableAdminList->GetReady( ) )
{
// CONSOLE_Print( "[BNET: " + m_ServerAlias + "] refreshed admin list (" + UTIL_ToString( m_Admins.size( ) ) + " -> " + UTIL_ToString( m_CallableAdminList->GetResult( ).size( ) ) + " admins)" );
m_Admins = m_CallableAdminList->GetResult( );
m_GHost->m_DB->RecoverCallable( m_CallableAdminList );
delete m_CallableAdminList;
m_CallableAdminList = NULL;
m_LastAdminRefreshTime = GetTime( );
}
// refresh the ban list every 60 minutes
if( !m_CallableBanList && GetTime( ) - m_LastBanRefreshTime >= 3600 )
m_CallableBanList = m_GHost->m_DB->ThreadedBanList( m_Server );
if( m_CallableBanList && m_CallableBanList->GetReady( ) )
{
// CONSOLE_Print( "[BNET: " + m_ServerAlias + "] refreshed ban list (" + UTIL_ToString( m_Bans.size( ) ) + " -> " + UTIL_ToString( m_CallableBanList->GetResult( ).size( ) ) + " bans)" );
for( vector<CDBBan *> :: iterator i = m_Bans.begin( ); i != m_Bans.end( ); i++ )
delete *i;
m_Bans = m_CallableBanList->GetResult( );
m_GHost->m_DB->RecoverCallable( m_CallableBanList );
delete m_CallableBanList;
m_CallableBanList = NULL;
m_LastBanRefreshTime = GetTime( );
}
// we return at the end of each if statement so we don't have to deal with errors related to the order of the if statements
// that means it might take a few ms longer to complete a task involving multiple steps (in this case, reconnecting) due to blocking or sleeping
// but it's not a big deal at all, maybe 100ms in the worst possible case (based on a 50ms blocking time)
if( m_Socket->HasError( ) )
{
// the socket has an error
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] disconnected from battle.net due to socket error" );
if( m_Socket->GetError( ) == ECONNRESET && GetTime( ) - m_LastConnectionAttemptTime <= 15 )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] warning - you are probably temporarily IP banned from battle.net" );
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] waiting 90 seconds to reconnect" );
m_GHost->EventBNETDisconnected( this );
delete m_BNLSClient;
m_BNLSClient = NULL;
m_BNCSUtil->Reset( m_UserName, m_UserPassword );
m_Socket->Reset( );
m_LastDisconnectedTime = GetTime( );
m_LoggedIn = false;
m_InChat = false;
m_WaitingToConnect = true;
return m_Exiting;
}
if( !m_Socket->GetConnecting( ) && !m_Socket->GetConnected( ) && !m_WaitingToConnect )
{
// the socket was disconnected
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] disconnected from battle.net" );
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] waiting 90 seconds to reconnect" );
m_GHost->EventBNETDisconnected( this );
delete m_BNLSClient;
m_BNLSClient = NULL;
m_BNCSUtil->Reset( m_UserName, m_UserPassword );
m_Socket->Reset( );
m_LastDisconnectedTime = GetTime( );
m_LoggedIn = false;
m_InChat = false;
m_WaitingToConnect = true;
return m_Exiting;
}
if( m_Socket->GetConnected( ) )
{
// the socket is connected and everything appears to be working properly
m_Socket->DoRecv( (fd_set *)fd );
ExtractPackets( );
ProcessPackets( );
// update the BNLS client
if( m_BNLSClient )
{
if( m_BNLSClient->Update( fd, send_fd ) )
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] deleting BNLS client" );
delete m_BNLSClient;
m_BNLSClient = NULL;
}
else
{
BYTEARRAY WardenResponse = m_BNLSClient->GetWardenResponse( );
if( !WardenResponse.empty( ) )
m_Socket->PutBytes( m_Protocol->SEND_SID_WARDEN( WardenResponse ) );
}
}
// check if at least one packet is waiting to be sent and if we've waited long enough to prevent flooding
// this formula has changed many times but currently we wait 1 second if the last packet was "small", 3.5 seconds if it was "medium", and 4 seconds if it was "big"
uint32_t WaitTicks = 0;
if( m_LastOutPacketSize < 10 )
WaitTicks = 1000;
else if( m_LastOutPacketSize < 100 )
WaitTicks = 3500;
else
WaitTicks = 4000;
if( !m_OutPackets.empty( ) && GetTicks( ) - m_LastOutPacketTicks >= WaitTicks )
{
if( m_OutPackets.size( ) > 7 )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] packet queue warning - there are " + UTIL_ToString( m_OutPackets.size( ) ) + " packets waiting to be sent" );
m_Socket->PutBytes( m_OutPackets.front( ) );
m_LastOutPacketSize = m_OutPackets.front( ).size( );
m_OutPackets.pop( );
m_LastOutPacketTicks = GetTicks( );
}
// send a null packet every 60 seconds to detect disconnects
if( GetTime( ) - m_LastNullTime >= 60 && GetTicks( ) - m_LastOutPacketTicks >= 60000 )
{
m_Socket->PutBytes( m_Protocol->SEND_SID_NULL( ) );
m_LastNullTime = GetTime( );
}
m_Socket->DoSend( (fd_set *)send_fd );
return m_Exiting;
}
if( m_Socket->GetConnecting( ) )
{
// we are currently attempting to connect to battle.net
if( m_Socket->CheckConnect( ) )
{
// the connection attempt completed
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] connected" );
m_GHost->EventBNETConnected( this );
m_Socket->PutBytes( m_Protocol->SEND_PROTOCOL_INITIALIZE_SELECTOR( ) );
m_Socket->PutBytes( m_Protocol->SEND_SID_AUTH_INFO( m_War3Version, m_GHost->m_TFT, m_LocaleID, m_CountryAbbrev, m_Country ) );
m_Socket->DoSend( (fd_set *)send_fd );
m_LastNullTime = GetTime( );
m_LastOutPacketTicks = GetTicks( );
while( !m_OutPackets.empty( ) )
m_OutPackets.pop( );
return m_Exiting;
}
else if( GetTime( ) - m_LastConnectionAttemptTime >= 15 )
{
// the connection attempt timed out (15 seconds)
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] connect timed out" );
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] waiting 90 seconds to reconnect" );
m_GHost->EventBNETConnectTimedOut( this );
m_Socket->Reset( );
m_LastDisconnectedTime = GetTime( );
m_WaitingToConnect = true;
return m_Exiting;
}
}
if( !m_Socket->GetConnecting( ) && !m_Socket->GetConnected( ) && ( m_FirstConnect || GetTime( ) - m_LastDisconnectedTime >= 90 ) )
{
// attempt to connect to battle.net
m_FirstConnect = false;
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] connecting to server [" + m_Server + "] on port 6112" );
m_GHost->EventBNETConnecting( this );
if( !m_GHost->m_BindAddress.empty( ) )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] attempting to bind to address [" + m_GHost->m_BindAddress + "]" );
if( m_ServerIP.empty( ) )
{
m_Socket->Connect( m_GHost->m_BindAddress, m_Server, 6112 );
if( !m_Socket->HasError( ) )
{
m_ServerIP = m_Socket->GetIPString( );
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] resolved and cached server IP address " + m_ServerIP );
}
}
else
{
// use cached server IP address since resolving takes time and is blocking
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] using cached server IP address " + m_ServerIP );
m_Socket->Connect( m_GHost->m_BindAddress, m_ServerIP, 6112 );
}
m_WaitingToConnect = false;
m_LastConnectionAttemptTime = GetTime( );
return m_Exiting;
}
return m_Exiting;
}
void CBNET :: ExtractPackets( )
{
// extract as many packets as possible from the socket's receive buffer and put them in the m_Packets queue
string *RecvBuffer = m_Socket->GetBytes( );
BYTEARRAY Bytes = UTIL_CreateByteArray( (unsigned char *)RecvBuffer->c_str( ), RecvBuffer->size( ) );
// a packet is at least 4 bytes so loop as long as the buffer contains 4 bytes
while( Bytes.size( ) >= 4 )
{
// byte 0 is always 255
if( Bytes[0] == BNET_HEADER_CONSTANT )
{
// bytes 2 and 3 contain the length of the packet
uint16_t Length = UTIL_ByteArrayToUInt16( Bytes, false, 2 );
if( Length >= 4 )
{
if( Bytes.size( ) >= Length )
{
m_Packets.push( new CCommandPacket( BNET_HEADER_CONSTANT, Bytes[1], BYTEARRAY( Bytes.begin( ), Bytes.begin( ) + Length ) ) );
*RecvBuffer = RecvBuffer->substr( Length );
Bytes = BYTEARRAY( Bytes.begin( ) + Length, Bytes.end( ) );
}
else
return;
}
else
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] error - received invalid packet from battle.net (bad length), disconnecting" );
m_Socket->Disconnect( );
return;
}
}
else
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] error - received invalid packet from battle.net (bad header constant), disconnecting" );
m_Socket->Disconnect( );
return;
}
}
}
void CBNET :: ProcessPackets( )
{
CIncomingGameHost *GameHost = NULL;
CIncomingChatEvent *ChatEvent = NULL;
BYTEARRAY WardenData;
vector<CIncomingFriendList *> Friends;
vector<CIncomingClanList *> Clans;
// process all the received packets in the m_Packets queue
// this normally means sending some kind of response
while( !m_Packets.empty( ) )
{
CCommandPacket *Packet = m_Packets.front( );
m_Packets.pop( );
if( Packet->GetPacketType( ) == BNET_HEADER_CONSTANT )
{
switch( Packet->GetID( ) )
{
case CBNETProtocol :: SID_NULL:
// warning: we do not respond to NULL packets with a NULL packet of our own
// this is because PVPGN servers are programmed to respond to NULL packets so it will create a vicious cycle of useless traffic
// official battle.net servers do not respond to NULL packets
m_Protocol->RECEIVE_SID_NULL( Packet->GetData( ) );
break;
case CBNETProtocol :: SID_GETADVLISTEX:
GameHost = m_Protocol->RECEIVE_SID_GETADVLISTEX( Packet->GetData( ) );
if( GameHost )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] joining game [" + GameHost->GetGameName( ) + "]" );
delete GameHost;
GameHost = NULL;
break;
case CBNETProtocol :: SID_ENTERCHAT:
if( m_Protocol->RECEIVE_SID_ENTERCHAT( Packet->GetData( ) ) )
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] joining channel [" + m_FirstChannel + "]" );
m_InChat = true;
m_Socket->PutBytes( m_Protocol->SEND_SID_JOINCHANNEL( m_FirstChannel ) );
}
break;
case CBNETProtocol :: SID_CHATEVENT:
ChatEvent = m_Protocol->RECEIVE_SID_CHATEVENT( Packet->GetData( ) );
if( ChatEvent )
ProcessChatEvent( ChatEvent );
delete ChatEvent;
ChatEvent = NULL;
break;
case CBNETProtocol :: SID_CHECKAD:
m_Protocol->RECEIVE_SID_CHECKAD( Packet->GetData( ) );
break;
case CBNETProtocol :: SID_STARTADVEX3:
if( m_Protocol->RECEIVE_SID_STARTADVEX3( Packet->GetData( ) ) )
{
m_InChat = false;
m_GHost->EventBNETGameRefreshed( this );
}
else
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] startadvex3 failed" );
m_GHost->EventBNETGameRefreshFailed( this );
}
break;
case CBNETProtocol :: SID_PING:
m_Socket->PutBytes( m_Protocol->SEND_SID_PING( m_Protocol->RECEIVE_SID_PING( Packet->GetData( ) ) ) );
break;
case CBNETProtocol :: SID_AUTH_INFO:
if( m_Protocol->RECEIVE_SID_AUTH_INFO( Packet->GetData( ) ) )
{
if( m_BNCSUtil->HELP_SID_AUTH_CHECK( m_GHost->m_TFT, m_GHost->m_Warcraft3Path, m_CDKeyROC, m_CDKeyTFT, m_Protocol->GetValueStringFormulaString( ), m_Protocol->GetIX86VerFileNameString( ), m_Protocol->GetClientToken( ), m_Protocol->GetServerToken( ) ) )
{
// override the exe information generated by bncsutil if specified in the config file
// apparently this is useful for pvpgn users
if( m_EXEVersion.size( ) == 4 )
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] using custom exe version bnet_custom_exeversion = " + UTIL_ToString( m_EXEVersion[0] ) + " " + UTIL_ToString( m_EXEVersion[1] ) + " " + UTIL_ToString( m_EXEVersion[2] ) + " " + UTIL_ToString( m_EXEVersion[3] ) );
m_BNCSUtil->SetEXEVersion( m_EXEVersion );
}
if( m_EXEVersionHash.size( ) == 4 )
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] using custom exe version hash bnet_custom_exeversionhash = " + UTIL_ToString( m_EXEVersionHash[0] ) + " " + UTIL_ToString( m_EXEVersionHash[1] ) + " " + UTIL_ToString( m_EXEVersionHash[2] ) + " " + UTIL_ToString( m_EXEVersionHash[3] ) );
m_BNCSUtil->SetEXEVersionHash( m_EXEVersionHash );
}
if( m_GHost->m_TFT )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] attempting to auth as Warcraft III: The Frozen Throne" );
else
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] attempting to auth as Warcraft III: Reign of Chaos" );
m_Socket->PutBytes( m_Protocol->SEND_SID_AUTH_CHECK( m_GHost->m_TFT, m_Protocol->GetClientToken( ), m_BNCSUtil->GetEXEVersion( ), m_BNCSUtil->GetEXEVersionHash( ), m_BNCSUtil->GetKeyInfoROC( ), m_BNCSUtil->GetKeyInfoTFT( ), m_BNCSUtil->GetEXEInfo( ), "GHost" ) );
// the Warden seed is the first 4 bytes of the ROC key hash
// initialize the Warden handler
if( !m_BNLSServer.empty( ) )
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] creating BNLS client" );
delete m_BNLSClient;
m_BNLSClient = new CBNLSClient( m_BNLSServer, m_BNLSPort, m_BNLSWardenCookie );
m_BNLSClient->QueueWardenSeed( UTIL_ByteArrayToUInt32( m_BNCSUtil->GetKeyInfoROC( ), false, 16 ) );
}
}
else
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] logon failed - bncsutil key hash failed (check your Warcraft 3 path and cd keys), disconnecting" );
m_Socket->Disconnect( );
delete Packet;
return;
}
}
break;
case CBNETProtocol :: SID_AUTH_CHECK:
if( m_Protocol->RECEIVE_SID_AUTH_CHECK( Packet->GetData( ) ) )
{
// cd keys accepted
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] cd keys accepted" );
m_BNCSUtil->HELP_SID_AUTH_ACCOUNTLOGON( );
m_Socket->PutBytes( m_Protocol->SEND_SID_AUTH_ACCOUNTLOGON( m_BNCSUtil->GetClientKey( ), m_UserName ) );
}
else
{
// cd keys not accepted
switch( UTIL_ByteArrayToUInt32( m_Protocol->GetKeyState( ), false ) )
{
case CBNETProtocol :: KR_ROC_KEY_IN_USE:
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] logon failed - ROC CD key in use by user [" + m_Protocol->GetKeyStateDescription( ) + "], disconnecting" );
break;
case CBNETProtocol :: KR_TFT_KEY_IN_USE:
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] logon failed - TFT CD key in use by user [" + m_Protocol->GetKeyStateDescription( ) + "], disconnecting" );
break;
case CBNETProtocol :: KR_OLD_GAME_VERSION:
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] logon failed - game version is too old, disconnecting" );
break;
case CBNETProtocol :: KR_INVALID_VERSION:
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] logon failed - game version is invalid, disconnecting" );
break;
default:
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] logon failed - cd keys not accepted, disconnecting" );
break;
}
m_Socket->Disconnect( );
delete Packet;
return;
}
break;
case CBNETProtocol :: SID_AUTH_ACCOUNTLOGON:
if( m_Protocol->RECEIVE_SID_AUTH_ACCOUNTLOGON( Packet->GetData( ) ) )
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] username [" + m_UserName + "] accepted" );
if( m_PasswordHashType == "pvpgn" )
{
// pvpgn logon
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] using pvpgn logon type (for pvpgn servers only)" );
m_BNCSUtil->HELP_PvPGNPasswordHash( m_UserPassword );
m_Socket->PutBytes( m_Protocol->SEND_SID_AUTH_ACCOUNTLOGONPROOF( m_BNCSUtil->GetPvPGNPasswordHash( ) ) );
}
else
{
// battle.net logon
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] using battle.net logon type (for official battle.net servers only)" );
m_BNCSUtil->HELP_SID_AUTH_ACCOUNTLOGONPROOF( m_Protocol->GetSalt( ), m_Protocol->GetServerPublicKey( ) );
m_Socket->PutBytes( m_Protocol->SEND_SID_AUTH_ACCOUNTLOGONPROOF( m_BNCSUtil->GetM1( ) ) );
}
}
else
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] logon failed - invalid username, disconnecting" );
m_Socket->Disconnect( );
delete Packet;
return;
}
break;
case CBNETProtocol :: SID_AUTH_ACCOUNTLOGONPROOF:
if( m_Protocol->RECEIVE_SID_AUTH_ACCOUNTLOGONPROOF( Packet->GetData( ) ) )
{
// logon successful
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] logon successful" );
m_LoggedIn = true;
m_GHost->EventBNETLoggedIn( this );
m_Socket->PutBytes( m_Protocol->SEND_SID_NETGAMEPORT( m_GHost->m_HostPort ) );
m_Socket->PutBytes( m_Protocol->SEND_SID_ENTERCHAT( ) );
m_Socket->PutBytes( m_Protocol->SEND_SID_FRIENDSLIST( ) );
m_Socket->PutBytes( m_Protocol->SEND_SID_CLANMEMBERLIST( ) );
}
else
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] logon failed - invalid password, disconnecting" );
// try to figure out if the user might be using the wrong logon type since too many people are confused by this
string Server = m_Server;
transform( Server.begin( ), Server.end( ), Server.begin( ), (int(*)(int))tolower );
if( m_PasswordHashType == "pvpgn" && ( Server == "useast.battle.net" || Server == "uswest.battle.net" || Server == "asia.battle.net" || Server == "europe.battle.net" ) )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] it looks like you're trying to connect to a battle.net server using a pvpgn logon type, check your config file's \"battle.net custom data\" section" );
else if( m_PasswordHashType != "pvpgn" && ( Server != "useast.battle.net" && Server != "uswest.battle.net" && Server != "asia.battle.net" && Server != "europe.battle.net" ) )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] it looks like you're trying to connect to a pvpgn server using a battle.net logon type, check your config file's \"battle.net custom data\" section" );
m_Socket->Disconnect( );
delete Packet;
return;
}
break;
case CBNETProtocol :: SID_WARDEN:
WardenData = m_Protocol->RECEIVE_SID_WARDEN( Packet->GetData( ) );
if( m_BNLSClient )
m_BNLSClient->QueueWardenRaw( WardenData );
else
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] warning - received warden packet but no BNLS server is available, you will be kicked from battle.net soon" );
break;
case CBNETProtocol :: SID_FRIENDSLIST:
Friends = m_Protocol->RECEIVE_SID_FRIENDSLIST( Packet->GetData( ) );
for( vector<CIncomingFriendList *> :: iterator i = m_Friends.begin( ); i != m_Friends.end( ); i++ )
delete *i;
m_Friends = Friends;
break;
case CBNETProtocol :: SID_CLANMEMBERLIST:
vector<CIncomingClanList *> Clans = m_Protocol->RECEIVE_SID_CLANMEMBERLIST( Packet->GetData( ) );
for( vector<CIncomingClanList *> :: iterator i = m_Clans.begin( ); i != m_Clans.end( ); i++ )
delete *i;
m_Clans = Clans;
break;
}
}
delete Packet;
}
}
void CBNET :: ProcessChatEvent( CIncomingChatEvent *chatEvent )
{
CBNETProtocol :: IncomingChatEvent Event = chatEvent->GetChatEvent( );
bool Whisper = ( Event == CBNETProtocol :: EID_WHISPER );
string User = chatEvent->GetUser( );
string Message = chatEvent->GetMessage( );
if( Event == CBNETProtocol :: EID_WHISPER || Event == CBNETProtocol :: EID_TALK )
{
if( Event == CBNETProtocol :: EID_WHISPER )
{
CONSOLE_Print( "[WHISPER: " + m_ServerAlias + "] [" + User + "] " + Message );
m_GHost->EventBNETWhisper( this, User, Message );
}
else
{
CONSOLE_Print( "[LOCAL: " + m_ServerAlias + "] [" + User + "] " + Message );
m_GHost->EventBNETChat( this, User, Message );
}
// handle spoof checking for current game
// this case covers whispers - we assume that anyone who sends a whisper to the bot with message "spoofcheck" should be considered spoof checked
// note that this means you can whisper "spoofcheck" even in a public game to manually spoofcheck if the /whois fails
if( Event == CBNETProtocol :: EID_WHISPER && m_GHost->m_CurrentGame )
{
if( Message == "s" || Message == "sc" || Message == "spoof" || Message == "check" || Message == "spoofcheck" )
m_GHost->m_CurrentGame->AddToSpoofed( m_Server, User, true );
else if( Message.find( m_GHost->m_CurrentGame->GetGameName( ) ) != string :: npos )
{
// look for messages like "entered a Warcraft III The Frozen Throne game called XYZ"
// we don't look for the English part of the text anymore because we want this to work with multiple languages
// it's a pretty safe bet that anyone whispering the bot with a message containing the game name is a valid spoofcheck
if( m_PasswordHashType == "pvpgn" && User == m_PVPGNRealmName )
{
// the equivalent pvpgn message is: [PvPGN Realm] Your friend abc has entered a Warcraft III Frozen Throne game named "xyz".
vector<string> Tokens = UTIL_Tokenize( Message, ' ' );
if( Tokens.size( ) >= 3 )
m_GHost->m_CurrentGame->AddToSpoofed( m_Server, Tokens[2], false );
}
else
m_GHost->m_CurrentGame->AddToSpoofed( m_Server, User, false );
}
}
// handle bot commands
if( Message == "?trigger" && ( IsAdmin( User ) || IsRootAdmin( User ) || ( m_PublicCommands && m_OutPackets.size( ) <= 3 ) ) )
QueueChatCommand( m_GHost->m_Language->CommandTrigger( string( 1, m_CommandTrigger ) ), User, Whisper );
else if( !Message.empty( ) && Message[0] == m_CommandTrigger )
{
// extract the command trigger, the command, and the payload
// e.g. "!say hello world" -> command: "say", payload: "hello world"
string Command;
string Payload;
string :: size_type PayloadStart = Message.find( " " );
if( PayloadStart != string :: npos )
{
Command = Message.substr( 1, PayloadStart - 1 );
Payload = Message.substr( PayloadStart + 1 );
}
else
Command = Message.substr( 1 );
transform( Command.begin( ), Command.end( ), Command.begin( ), (int(*)(int))tolower );
if( IsAdmin( User ) || IsRootAdmin( User ) )
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] admin [" + User + "] sent command [" + Message + "]" );
/*****************
* ADMIN COMMANDS *
******************/
//
// !ADDADMIN
//
if( Command == "addadmin" && !Payload.empty( ) )
{
if( IsRootAdmin( User ) )
{
if( IsAdmin( Payload ) )
QueueChatCommand( m_GHost->m_Language->UserIsAlreadyAnAdmin( m_Server, Payload ), User, Whisper );
else
m_PairedAdminAdds.push_back( PairedAdminAdd( Whisper ? User : string( ), m_GHost->m_DB->ThreadedAdminAdd( m_Server, Payload ) ) );
}
else
QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper );
}
//
// !ADDBAN
// !BAN
//
if( ( Command == "addban" || Command == "ban" ) && !Payload.empty( ) )
{
// extract the victim and the reason
// e.g. "Varlock leaver after dying" -> victim: "Varlock", reason: "leaver after dying"
string Victim;
string Reason;
stringstream SS;
SS << Payload;
SS >> Victim;
if( !SS.eof( ) )
{
getline( SS, Reason );
string :: size_type Start = Reason.find_first_not_of( " " );
if( Start != string :: npos )
Reason = Reason.substr( Start );
}
if( IsBannedName( Victim ) )
QueueChatCommand( m_GHost->m_Language->UserIsAlreadyBanned( m_Server, Victim ), User, Whisper );
else
m_PairedBanAdds.push_back( PairedBanAdd( Whisper ? User : string( ), m_GHost->m_DB->ThreadedBanAdd( m_Server, Victim, string( ), string( ), User, Reason ) ) );
}
//
// !ANNOUNCE
//
if( Command == "announce" && m_GHost->m_CurrentGame && !m_GHost->m_CurrentGame->GetCountDownStarted( ) )
{
if( Payload.empty( ) || Payload == "off" )
{
QueueChatCommand( m_GHost->m_Language->AnnounceMessageDisabled( ), User, Whisper );
m_GHost->m_CurrentGame->SetAnnounce( 0, string( ) );
}
else
{
// extract the interval and the message
// e.g. "30 hello everyone" -> interval: "30", message: "hello everyone"
uint32_t Interval;
string Message;
stringstream SS;
SS << Payload;
SS >> Interval;
if( SS.fail( ) || Interval == 0 )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input #1 to announce command" );
else
{
if( SS.eof( ) )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] missing input #2 to announce command" );
else
{
getline( SS, Message );
string :: size_type Start = Message.find_first_not_of( " " );
if( Start != string :: npos )
Message = Message.substr( Start );
QueueChatCommand( m_GHost->m_Language->AnnounceMessageEnabled( ), User, Whisper );
m_GHost->m_CurrentGame->SetAnnounce( Interval, Message );
}
}
}
}
//
// !AUTOHOST
//
if( Command == "autohost" )
{
if( IsRootAdmin( User ) )
{
if( Payload.empty( ) || Payload == "off" )
{
QueueChatCommand( m_GHost->m_Language->AutoHostDisabled( ), User, Whisper );
m_GHost->m_AutoHostGameName.clear( );
m_GHost->m_AutoHostOwner.clear( );
m_GHost->m_AutoHostServer.clear( );
m_GHost->m_AutoHostMaximumGames = 0;
m_GHost->m_AutoHostAutoStartPlayers = 0;
m_GHost->m_LastAutoHostTime = GetTime( );
m_GHost->m_AutoHostMatchMaking = false;
m_GHost->m_AutoHostMinimumScore = 0.0;
m_GHost->m_AutoHostMaximumScore = 0.0;
}
else
{
// extract the maximum games, auto start players, and the game name
// e.g. "5 10 BattleShips Pro" -> maximum games: "5", auto start players: "10", game name: "BattleShips Pro"
uint32_t MaximumGames;
uint32_t AutoStartPlayers;
string GameName;
stringstream SS;
SS << Payload;
SS >> MaximumGames;
if( SS.fail( ) || MaximumGames == 0 )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input #1 to autohost command" );
else
{
SS >> AutoStartPlayers;
if( SS.fail( ) || AutoStartPlayers == 0 )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input #2 to autohost command" );
else
{
if( SS.eof( ) )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] missing input #3 to autohost command" );
else
{
getline( SS, GameName );
string :: size_type Start = GameName.find_first_not_of( " " );
if( Start != string :: npos )
GameName = GameName.substr( Start );
QueueChatCommand( m_GHost->m_Language->AutoHostEnabled( ), User, Whisper );
delete m_GHost->m_AutoHostMap;
m_GHost->m_AutoHostMap = new CMap( *m_GHost->m_Map );
m_GHost->m_AutoHostGameName = GameName;
m_GHost->m_AutoHostOwner = User;
m_GHost->m_AutoHostServer = m_Server;
m_GHost->m_AutoHostMaximumGames = MaximumGames;
m_GHost->m_AutoHostAutoStartPlayers = AutoStartPlayers;
m_GHost->m_LastAutoHostTime = GetTime( );
m_GHost->m_AutoHostMatchMaking = false;
m_GHost->m_AutoHostMinimumScore = 0.0;
m_GHost->m_AutoHostMaximumScore = 0.0;
}
}
}
}
}
else
QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper );
}
//
// !AUTOHOSTMM
//
if( Command == "autohostmm" )
{
if( IsRootAdmin( User ) )
{
if( Payload.empty( ) || Payload == "off" )
{
QueueChatCommand( m_GHost->m_Language->AutoHostDisabled( ), User, Whisper );
m_GHost->m_AutoHostGameName.clear( );
m_GHost->m_AutoHostOwner.clear( );
m_GHost->m_AutoHostServer.clear( );
m_GHost->m_AutoHostMaximumGames = 0;
m_GHost->m_AutoHostAutoStartPlayers = 0;
m_GHost->m_LastAutoHostTime = GetTime( );
m_GHost->m_AutoHostMatchMaking = false;
m_GHost->m_AutoHostMinimumScore = 0.0;
m_GHost->m_AutoHostMaximumScore = 0.0;
}
else
{
// extract the maximum games, auto start players, minimum score, maximum score, and the game name
// e.g. "5 10 800 1200 BattleShips Pro" -> maximum games: "5", auto start players: "10", minimum score: "800", maximum score: "1200", game name: "BattleShips Pro"
uint32_t MaximumGames;
uint32_t AutoStartPlayers;
double MinimumScore;
double MaximumScore;
string GameName;
stringstream SS;
SS << Payload;
SS >> MaximumGames;
if( SS.fail( ) || MaximumGames == 0 )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input #1 to autohostmm command" );
else
{
SS >> AutoStartPlayers;
if( SS.fail( ) || AutoStartPlayers == 0 )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input #2 to autohostmm command" );
else
{
SS >> MinimumScore;
if( SS.fail( ) )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input #3 to autohostmm command" );
else
{
SS >> MaximumScore;
if( SS.fail( ) )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input #4 to autohostmm command" );
else
{
if( SS.eof( ) )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] missing input #5 to autohostmm command" );
else
{
getline( SS, GameName );
string :: size_type Start = GameName.find_first_not_of( " " );
if( Start != string :: npos )
GameName = GameName.substr( Start );
QueueChatCommand( m_GHost->m_Language->AutoHostEnabled( ), User, Whisper );
delete m_GHost->m_AutoHostMap;
m_GHost->m_AutoHostMap = new CMap( *m_GHost->m_Map );
m_GHost->m_AutoHostGameName = GameName;
m_GHost->m_AutoHostOwner = User;
m_GHost->m_AutoHostServer = m_Server;
m_GHost->m_AutoHostMaximumGames = MaximumGames;
m_GHost->m_AutoHostAutoStartPlayers = AutoStartPlayers;
m_GHost->m_LastAutoHostTime = GetTime( );
m_GHost->m_AutoHostMatchMaking = true;
m_GHost->m_AutoHostMinimumScore = MinimumScore;
m_GHost->m_AutoHostMaximumScore = MaximumScore;
}
}
}
}
}
}
}
else
QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper );
}
//
// !AUTOSTART
//
if( Command == "autostart" && m_GHost->m_CurrentGame && !m_GHost->m_CurrentGame->GetCountDownStarted( ) )
{
if( Payload.empty( ) || Payload == "off" )
{
QueueChatCommand( m_GHost->m_Language->AutoStartDisabled( ), User, Whisper );
m_GHost->m_CurrentGame->SetAutoStartPlayers( 0 );
}
else
{
uint32_t AutoStartPlayers = UTIL_ToUInt32( Payload );
if( AutoStartPlayers != 0 )
{
QueueChatCommand( m_GHost->m_Language->AutoStartEnabled( UTIL_ToString( AutoStartPlayers ) ), User, Whisper );
m_GHost->m_CurrentGame->SetAutoStartPlayers( AutoStartPlayers );
}
}
}
//
// !CHANNEL (change channel)
//
if( Command == "channel" && !Payload.empty( ) )
QueueChatCommand( "/join " + Payload );
//
// !CHECKADMIN
//
if( Command == "checkadmin" && !Payload.empty( ) )
{
if( IsRootAdmin( User ) )
{
if( IsAdmin( Payload ) )
QueueChatCommand( m_GHost->m_Language->UserIsAnAdmin( m_Server, Payload ), User, Whisper );
else
QueueChatCommand( m_GHost->m_Language->UserIsNotAnAdmin( m_Server, Payload ), User, Whisper );
}
else
QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper );
}
//
// !CHECKBAN
//
if( Command == "checkban" && !Payload.empty( ) )
{
CDBBan *Ban = IsBannedName( Payload );
if( Ban )
QueueChatCommand( m_GHost->m_Language->UserWasBannedOnByBecause( m_Server, Payload, Ban->GetDate( ), Ban->GetAdmin( ), Ban->GetReason( ) ), User, Whisper );
else
QueueChatCommand( m_GHost->m_Language->UserIsNotBanned( m_Server, Payload ), User, Whisper );
}
//
// !CLOSE (close slot)
//
if( Command == "close" && !Payload.empty( ) && m_GHost->m_CurrentGame )
{
if( !m_GHost->m_CurrentGame->GetLocked( ) )
{
// close as many slots as specified, e.g. "5 10" closes slots 5 and 10
stringstream SS;
SS << Payload;
while( !SS.eof( ) )
{
uint32_t SID;
SS >> SID;
if( SS.fail( ) )
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input to close command" );
break;
}
else
m_GHost->m_CurrentGame->CloseSlot( (unsigned char)( SID - 1 ), true );
}
}
else
QueueChatCommand( m_GHost->m_Language->TheGameIsLockedBNET( ), User, Whisper );
}
//
// !CLOSEALL
//
if( Command == "closeall" && m_GHost->m_CurrentGame )
{
if( !m_GHost->m_CurrentGame->GetLocked( ) )
m_GHost->m_CurrentGame->CloseAllSlots( );
else
QueueChatCommand( m_GHost->m_Language->TheGameIsLockedBNET( ), User, Whisper );
}
//
// !COUNTADMINS
//
if( Command == "countadmins" )
{
if( IsRootAdmin( User ) )
m_PairedAdminCounts.push_back( PairedAdminCount( Whisper ? User : string( ), m_GHost->m_DB->ThreadedAdminCount( m_Server ) ) );
else
QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper );
}
//
// !COUNTBANS
//
if( Command == "countbans" )
m_PairedBanCounts.push_back( PairedBanCount( Whisper ? User : string( ), m_GHost->m_DB->ThreadedBanCount( m_Server ) ) );
//
// !DBSTATUS
//
if( Command == "dbstatus" )
QueueChatCommand( m_GHost->m_DB->GetStatus( ), User, Whisper );
//
// !DELADMIN
//
if( Command == "deladmin" && !Payload.empty( ) )
{
if( IsRootAdmin( User ) )
{
if( !IsAdmin( Payload ) )
QueueChatCommand( m_GHost->m_Language->UserIsNotAnAdmin( m_Server, Payload ), User, Whisper );
else
m_PairedAdminRemoves.push_back( PairedAdminRemove( Whisper ? User : string( ), m_GHost->m_DB->ThreadedAdminRemove( m_Server, Payload ) ) );
}
else
QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper );
}
//
// !DELBAN
// !UNBAN
//
if( ( Command == "delban" || Command == "unban" ) && !Payload.empty( ) )
m_PairedBanRemoves.push_back( PairedBanRemove( Whisper ? User : string( ), m_GHost->m_DB->ThreadedBanRemove( Payload ) ) );
//
// !DISABLE
//
if( Command == "disable" )
{
if( IsRootAdmin( User ) )
{
QueueChatCommand( m_GHost->m_Language->BotDisabled( ), User, Whisper );
m_GHost->m_Enabled = false;
}
else
QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper );
}
//
// !DOWNLOADS
//
if( Command == "downloads" && !Payload.empty( ) )
{
uint32_t Downloads = UTIL_ToUInt32( Payload );
if( Downloads == 0 )
{
QueueChatCommand( m_GHost->m_Language->MapDownloadsDisabled( ), User, Whisper );
m_GHost->m_AllowDownloads = 0;
}
else if( Downloads == 1 )
{
QueueChatCommand( m_GHost->m_Language->MapDownloadsEnabled( ), User, Whisper );
m_GHost->m_AllowDownloads = 1;
}
else if( Downloads == 2 )
{
QueueChatCommand( m_GHost->m_Language->MapDownloadsConditional( ), User, Whisper );
m_GHost->m_AllowDownloads = 2;
}
}
//
// !ENABLE
//
if( Command == "enable" )
{
if( IsRootAdmin( User ) )
{
QueueChatCommand( m_GHost->m_Language->BotEnabled( ), User, Whisper );
m_GHost->m_Enabled = true;
}
else
QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper );
}
//
// !END
//
if( Command == "end" && !Payload.empty( ) )
{
// todotodo: what if a game ends just as you're typing this command and the numbering changes?
uint32_t GameNumber = UTIL_ToUInt32( Payload ) - 1;
if( GameNumber < m_GHost->m_Games.size( ) )
{
// if the game owner is still in the game only allow the root admin to end the game
if( m_GHost->m_Games[GameNumber]->GetPlayerFromName( m_GHost->m_Games[GameNumber]->GetOwnerName( ), false ) && !IsRootAdmin( User ) )
QueueChatCommand( m_GHost->m_Language->CantEndGameOwnerIsStillPlaying( m_GHost->m_Games[GameNumber]->GetOwnerName( ) ), User, Whisper );
else
{
QueueChatCommand( m_GHost->m_Language->EndingGame( m_GHost->m_Games[GameNumber]->GetDescription( ) ), User, Whisper );
CONSOLE_Print( "[GAME: " + m_GHost->m_Games[GameNumber]->GetGameName( ) + "] is over (admin ended game)" );
m_GHost->m_Games[GameNumber]->StopPlayers( "was disconnected (admin ended game)" );
}
}
else
QueueChatCommand( m_GHost->m_Language->GameNumberDoesntExist( Payload ), User, Whisper );
}
//
// !ENFORCESG
//
if( Command == "enforcesg" && !Payload.empty( ) )
{
// only load files in the current directory just to be safe
if( Payload.find( "/" ) != string :: npos || Payload.find( "\\" ) != string :: npos )
QueueChatCommand( m_GHost->m_Language->UnableToLoadReplaysOutside( ), User, Whisper );
else
{
string File = m_GHost->m_ReplayPath + Payload + ".w3g";
if( UTIL_FileExists( File ) )
{
QueueChatCommand( m_GHost->m_Language->LoadingReplay( File ), User, Whisper );
CReplay *Replay = new CReplay( );
Replay->Load( File, false );
Replay->ParseReplay( false );
m_GHost->m_EnforcePlayers = Replay->GetPlayers( );
delete Replay;
}
else
QueueChatCommand( m_GHost->m_Language->UnableToLoadReplayDoesntExist( File ), User, Whisper );
}
}
//
// !EXIT
// !QUIT
//
if( Command == "exit" || Command == "quit" )
{
if( IsRootAdmin( User ) )
{
if( Payload == "nice" )
m_GHost->m_ExitingNice = true;
else if( Payload == "force" )
m_Exiting = true;
else
{
if( m_GHost->m_CurrentGame || !m_GHost->m_Games.empty( ) )
QueueChatCommand( m_GHost->m_Language->AtLeastOneGameActiveUseForceToShutdown( ), User, Whisper );
else
m_Exiting = true;
}
}
else
QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper );
}
//
// !GETCLAN
//
if( Command == "getclan" )
{
SendGetClanList( );
QueueChatCommand( m_GHost->m_Language->UpdatingClanList( ), User, Whisper );
}
//
// !GETFRIENDS
//
if( Command == "getfriends" )
{
SendGetFriendsList( );
QueueChatCommand( m_GHost->m_Language->UpdatingFriendsList( ), User, Whisper );
}
//
// !GETGAME
//
if( Command == "getgame" && !Payload.empty( ) )
{
uint32_t GameNumber = UTIL_ToUInt32( Payload ) - 1;
if( GameNumber < m_GHost->m_Games.size( ) )
QueueChatCommand( m_GHost->m_Language->GameNumberIs( Payload, m_GHost->m_Games[GameNumber]->GetDescription( ) ), User, Whisper );
else
QueueChatCommand( m_GHost->m_Language->GameNumberDoesntExist( Payload ), User, Whisper );
}
//
// !GETGAMES
//
if( Command == "getgames" )
{
if( m_GHost->m_CurrentGame )
QueueChatCommand( m_GHost->m_Language->GameIsInTheLobby( m_GHost->m_CurrentGame->GetDescription( ), UTIL_ToString( m_GHost->m_Games.size( ) ), UTIL_ToString( m_GHost->m_MaxGames ) ), User, Whisper );
else
QueueChatCommand( m_GHost->m_Language->ThereIsNoGameInTheLobby( UTIL_ToString( m_GHost->m_Games.size( ) ), UTIL_ToString( m_GHost->m_MaxGames ) ), User, Whisper );
}
//
// !HOLD (hold a slot for someone)
//
if( Command == "hold" && !Payload.empty( ) && m_GHost->m_CurrentGame )
{
// hold as many players as specified, e.g. "Varlock Kilranin" holds players "Varlock" and "Kilranin"
stringstream SS;
SS << Payload;
while( !SS.eof( ) )
{
string HoldName;
SS >> HoldName;
if( SS.fail( ) )
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input to hold command" );
break;
}
else
{
QueueChatCommand( m_GHost->m_Language->AddedPlayerToTheHoldList( HoldName ), User, Whisper );
m_GHost->m_CurrentGame->AddToReserved( HoldName );
}
}
}
//
// !HOSTSG
//
if( Command == "hostsg" && !Payload.empty( ) )
m_GHost->CreateGame( m_GHost->m_Map, GAME_PRIVATE, true, Payload, User, User, m_Server, Whisper );
//
// !LOAD (load config file)
//
if( Command == "load" )
{
if( Payload.empty( ) )
QueueChatCommand( m_GHost->m_Language->CurrentlyLoadedMapCFGIs( m_GHost->m_Map->GetCFGFile( ) ), User, Whisper );
else
{
string FoundMapConfigs;
try
{
path MapCFGPath( m_GHost->m_MapCFGPath );
string Pattern = Payload;
transform( Pattern.begin( ), Pattern.end( ), Pattern.begin( ), (int(*)(int))tolower );
if( !exists( MapCFGPath ) )
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] error listing map configs - map config path doesn't exist" );
QueueChatCommand( m_GHost->m_Language->ErrorListingMapConfigs( ), User, Whisper );
}
else
{
directory_iterator EndIterator;
path LastMatch;
uint32_t Matches = 0;
for( directory_iterator i( MapCFGPath ); i != EndIterator; i++ )
{
string FileName = i->filename( );
string Stem = i->path( ).stem( );
transform( FileName.begin( ), FileName.end( ), FileName.begin( ), (int(*)(int))tolower );
transform( Stem.begin( ), Stem.end( ), Stem.begin( ), (int(*)(int))tolower );
if( !is_directory( i->status( ) ) && i->path( ).extension( ) == ".cfg" && FileName.find( Pattern ) != string :: npos )
{
LastMatch = i->path( );
Matches++;
if( FoundMapConfigs.empty( ) )
FoundMapConfigs = i->filename( );
else
FoundMapConfigs += ", " + i->filename( );
// if the pattern matches the filename exactly, with or without extension, stop any further matching
if( FileName == Pattern || Stem == Pattern )
{
Matches = 1;
break;
}
}
}
if( Matches == 0 )
QueueChatCommand( m_GHost->m_Language->NoMapConfigsFound( ), User, Whisper );
else if( Matches == 1 )
{
string File = LastMatch.filename( );
QueueChatCommand( m_GHost->m_Language->LoadingConfigFile( m_GHost->m_MapCFGPath + File ), User, Whisper );
CConfig MapCFG;
MapCFG.Read( LastMatch.string( ) );
m_GHost->m_Map->Load( &MapCFG, m_GHost->m_MapCFGPath + File );
}
else
QueueChatCommand( m_GHost->m_Language->FoundMapConfigs( FoundMapConfigs ), User, Whisper );
}
}
catch( const exception &ex )
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] error listing map configs - caught exception [" + ex.what( ) + "]" );
QueueChatCommand( m_GHost->m_Language->ErrorListingMapConfigs( ), User, Whisper );
}
}
}
//
// !LOADSG
//
if( Command == "loadsg" && !Payload.empty( ) )
{
// only load files in the current directory just to be safe
if( Payload.find( "/" ) != string :: npos || Payload.find( "\\" ) != string :: npos )
QueueChatCommand( m_GHost->m_Language->UnableToLoadSaveGamesOutside( ), User, Whisper );
else
{
string File = m_GHost->m_SaveGamePath + Payload + ".w3z";
string FileNoPath = Payload + ".w3z";
if( UTIL_FileExists( File ) )
{
if( m_GHost->m_CurrentGame )
QueueChatCommand( m_GHost->m_Language->UnableToLoadSaveGameGameInLobby( ), User, Whisper );
else
{
QueueChatCommand( m_GHost->m_Language->LoadingSaveGame( File ), User, Whisper );
m_GHost->m_SaveGame->Load( File, false );
m_GHost->m_SaveGame->ParseSaveGame( );
m_GHost->m_SaveGame->SetFileName( File );
m_GHost->m_SaveGame->SetFileNameNoPath( FileNoPath );
}
}
else
QueueChatCommand( m_GHost->m_Language->UnableToLoadSaveGameDoesntExist( File ), User, Whisper );
}
}
//
// !MAP (load map file)
//
if( Command == "map" )
{
if( Payload.empty( ) )
QueueChatCommand( m_GHost->m_Language->CurrentlyLoadedMapCFGIs( m_GHost->m_Map->GetCFGFile( ) ), User, Whisper );
else
{
string FoundMaps;
try
{
path MapPath( m_GHost->m_MapPath );
string Pattern = Payload;
transform( Pattern.begin( ), Pattern.end( ), Pattern.begin( ), (int(*)(int))tolower );
if( !exists( MapPath ) )
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] error listing maps - map path doesn't exist" );
QueueChatCommand( m_GHost->m_Language->ErrorListingMaps( ), User, Whisper );
}
else
{
directory_iterator EndIterator;
path LastMatch;
uint32_t Matches = 0;
for( directory_iterator i( MapPath ); i != EndIterator; i++ )
{
string FileName = i->filename( );
string Stem = i->path( ).stem( );
transform( FileName.begin( ), FileName.end( ), FileName.begin( ), (int(*)(int))tolower );
transform( Stem.begin( ), Stem.end( ), Stem.begin( ), (int(*)(int))tolower );
if( !is_directory( i->status( ) ) && FileName.find( Pattern ) != string :: npos )
{
LastMatch = i->path( );
Matches++;
if( FoundMaps.empty( ) )
FoundMaps = i->filename( );
else
FoundMaps += ", " + i->filename( );
// if the pattern matches the filename exactly, with or without extension, stop any further matching
if( FileName == Pattern || Stem == Pattern )
{
Matches = 1;
break;
}
}
}
if( Matches == 0 )
QueueChatCommand( m_GHost->m_Language->NoMapsFound( ), User, Whisper );
else if( Matches == 1 )
{
string File = LastMatch.filename( );
QueueChatCommand( m_GHost->m_Language->LoadingConfigFile( File ), User, Whisper );
// hackhack: create a config file in memory with the required information to load the map
CConfig MapCFG;
MapCFG.Set( "map_path", "Maps\\Download\\" + File );
MapCFG.Set( "map_localpath", File );
m_GHost->m_Map->Load( &MapCFG, File );
}
else
QueueChatCommand( m_GHost->m_Language->FoundMaps( FoundMaps ), User, Whisper );
}
}
catch( const exception &ex )
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] error listing maps - caught exception [" + ex.what( ) + "]" );
QueueChatCommand( m_GHost->m_Language->ErrorListingMaps( ), User, Whisper );
}
}
}
//
// !OPEN (open slot)
//
if( Command == "open" && !Payload.empty( ) && m_GHost->m_CurrentGame )
{
if( !m_GHost->m_CurrentGame->GetLocked( ) )
{
// open as many slots as specified, e.g. "5 10" opens slots 5 and 10
stringstream SS;
SS << Payload;
while( !SS.eof( ) )
{
uint32_t SID;
SS >> SID;
if( SS.fail( ) )
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input to open command" );
break;
}
else
m_GHost->m_CurrentGame->OpenSlot( (unsigned char)( SID - 1 ), true );
}
}
else
QueueChatCommand( m_GHost->m_Language->TheGameIsLockedBNET( ), User, Whisper );
}
//
// !OPENALL
//
if( Command == "openall" && m_GHost->m_CurrentGame )
{
if( !m_GHost->m_CurrentGame->GetLocked( ) )
m_GHost->m_CurrentGame->OpenAllSlots( );
else
QueueChatCommand( m_GHost->m_Language->TheGameIsLockedBNET( ), User, Whisper );
}
//
// !PRIV (host private game)
//
if( Command == "priv" && !Payload.empty( ) )
m_GHost->CreateGame( m_GHost->m_Map, GAME_PRIVATE, false, Payload, User, User, m_Server, Whisper );
//
// !PRIVBY (host private game by other player)
//
if( Command == "privby" && !Payload.empty( ) )
{
// extract the owner and the game name
// e.g. "Varlock dota 6.54b arem ~~~" -> owner: "Varlock", game name: "dota 6.54b arem ~~~"
string Owner;
string GameName;
string :: size_type GameNameStart = Payload.find( " " );
if( GameNameStart != string :: npos )
{
Owner = Payload.substr( 0, GameNameStart );
GameName = Payload.substr( GameNameStart + 1 );
m_GHost->CreateGame( m_GHost->m_Map, GAME_PRIVATE, false, GameName, Owner, User, m_Server, Whisper );
}
}
//
// !PUB (host public game)
//
if( Command == "pub" && !Payload.empty( ) )
m_GHost->CreateGame( m_GHost->m_Map, GAME_PUBLIC, false, Payload, User, User, m_Server, Whisper );
//
// !PUBBY (host public game by other player)
//
if( Command == "pubby" && !Payload.empty( ) )
{
// extract the owner and the game name
// e.g. "Varlock dota 6.54b arem ~~~" -> owner: "Varlock", game name: "dota 6.54b arem ~~~"
string Owner;
string GameName;
string :: size_type GameNameStart = Payload.find( " " );
if( GameNameStart != string :: npos )
{
Owner = Payload.substr( 0, GameNameStart );
GameName = Payload.substr( GameNameStart + 1 );
m_GHost->CreateGame( m_GHost->m_Map, GAME_PUBLIC, false, GameName, Owner, User, m_Server, Whisper );
}
}
//
// !RELOAD
//
if( Command == "reload" )
{
if( IsRootAdmin( User ) )
{
QueueChatCommand( m_GHost->m_Language->ReloadingConfigurationFiles( ), User, Whisper );
m_GHost->ReloadConfigs( );
}
else
QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper );
}
//
// !SAY
//
if( Command == "say" && !Payload.empty( ) )
QueueChatCommand( Payload );
//
// !SAYGAME
//
if( Command == "saygame" && !Payload.empty( ) )
{
if( IsRootAdmin( User ) )
{
// extract the game number and the message
// e.g. "3 hello everyone" -> game number: "3", message: "hello everyone"
uint32_t GameNumber;
string Message;
stringstream SS;
SS << Payload;
SS >> GameNumber;
if( SS.fail( ) )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input #1 to saygame command" );
else
{
if( SS.eof( ) )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] missing input #2 to saygame command" );
else
{
getline( SS, Message );
string :: size_type Start = Message.find_first_not_of( " " );
if( Start != string :: npos )
Message = Message.substr( Start );
if( GameNumber - 1 < m_GHost->m_Games.size( ) )
m_GHost->m_Games[GameNumber - 1]->SendAllChat( "ADMIN: " + Message );
else
QueueChatCommand( m_GHost->m_Language->GameNumberDoesntExist( UTIL_ToString( GameNumber ) ), User, Whisper );
}
}
}
else
QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper );
}
//
// !SAYGAMES
//
if( Command == "saygames" && !Payload.empty( ) )
{
if( IsRootAdmin( User ) )
{
if( m_GHost->m_CurrentGame )
m_GHost->m_CurrentGame->SendAllChat( Payload );
for( vector<CBaseGame *> :: iterator i = m_GHost->m_Games.begin( ); i != m_GHost->m_Games.end( ); i++ )
(*i)->SendAllChat( "ADMIN: " + Payload );
}
else
QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper );
}
//
// !SP
//
if( Command == "sp" && m_GHost->m_CurrentGame && !m_GHost->m_CurrentGame->GetCountDownStarted( ) )
{
if( !m_GHost->m_CurrentGame->GetLocked( ) )
{
m_GHost->m_CurrentGame->SendAllChat( m_GHost->m_Language->ShufflingPlayers( ) );
m_GHost->m_CurrentGame->ShuffleSlots( );
}
else
QueueChatCommand( m_GHost->m_Language->TheGameIsLockedBNET( ), User, Whisper );
}
//
// !START
//
if( Command == "start" && m_GHost->m_CurrentGame && !m_GHost->m_CurrentGame->GetCountDownStarted( ) && m_GHost->m_CurrentGame->GetNumHumanPlayers( ) > 0 )
{
if( !m_GHost->m_CurrentGame->GetLocked( ) )
{
// if the player sent "!start force" skip the checks and start the countdown
// otherwise check that the game is ready to start
if( Payload == "force" )
m_GHost->m_CurrentGame->StartCountDown( true );
else
m_GHost->m_CurrentGame->StartCountDown( false );
}
else
QueueChatCommand( m_GHost->m_Language->TheGameIsLockedBNET( ), User, Whisper );
}
//
// !SWAP (swap slots)
//
if( Command == "swap" && !Payload.empty( ) && m_GHost->m_CurrentGame )
{
if( !m_GHost->m_CurrentGame->GetLocked( ) )
{
uint32_t SID1;
uint32_t SID2;
stringstream SS;
SS << Payload;
SS >> SID1;
if( SS.fail( ) )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input #1 to swap command" );
else
{
if( SS.eof( ) )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] missing input #2 to swap command" );
else
{
SS >> SID2;
if( SS.fail( ) )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input #2 to swap command" );
else
m_GHost->m_CurrentGame->SwapSlots( (unsigned char)( SID1 - 1 ), (unsigned char)( SID2 - 1 ) );
}
}
}
else
QueueChatCommand( m_GHost->m_Language->TheGameIsLockedBNET( ), User, Whisper );
}
//
// !UNHOST
//
if( Command == "unhost" )
{
if( m_GHost->m_CurrentGame )
{
if( m_GHost->m_CurrentGame->GetCountDownStarted( ) )
QueueChatCommand( m_GHost->m_Language->UnableToUnhostGameCountdownStarted( m_GHost->m_CurrentGame->GetDescription( ) ), User, Whisper );
// if the game owner is still in the game only allow the root admin to unhost the game
else if( m_GHost->m_CurrentGame->GetPlayerFromName( m_GHost->m_CurrentGame->GetOwnerName( ), false ) && !IsRootAdmin( User ) )
QueueChatCommand( m_GHost->m_Language->CantUnhostGameOwnerIsPresent( m_GHost->m_CurrentGame->GetOwnerName( ) ), User, Whisper );
else
{
QueueChatCommand( m_GHost->m_Language->UnhostingGame( m_GHost->m_CurrentGame->GetDescription( ) ), User, Whisper );
m_GHost->m_CurrentGame->SetExiting( true );
}
}
else
QueueChatCommand( m_GHost->m_Language->UnableToUnhostGameNoGameInLobby( ), User, Whisper );
}
//
// !WARDENSTATUS
//
if( Command == "wardenstatus" )
{
if( m_BNLSClient )
QueueChatCommand( "WARDEN STATUS --- " + UTIL_ToString( m_BNLSClient->GetTotalWardenIn( ) ) + " requests received, " + UTIL_ToString( m_BNLSClient->GetTotalWardenOut( ) ) + " responses sent.", User, Whisper );
else
QueueChatCommand( "WARDEN STATUS --- Not connected to BNLS server.", User, Whisper );
}
}
else
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] non-admin [" + User + "] sent command [" + Message + "]" );
/*********************
* NON ADMIN COMMANDS *
*********************/
// don't respond to non admins if there are more than 3 messages already in the queue
// this prevents malicious users from filling up the bot's chat queue and crippling the bot
// in some cases the queue may be full of legitimate messages but we don't really care if the bot ignores one of these commands once in awhile
// e.g. when several users join a game at the same time and cause multiple /whois messages to be queued at once
if( IsAdmin( User ) || IsRootAdmin( User ) || ( m_PublicCommands && m_OutPackets.size( ) <= 3 ) )
{
//
// !STATS
//
if( Command == "stats" )
{
string StatsUser = User;
if( !Payload.empty( ) )
StatsUser = Payload;
// check for potential abuse
if( !StatsUser.empty( ) && StatsUser.size( ) < 16 && StatsUser[0] != '/' )
m_PairedGPSChecks.push_back( PairedGPSCheck( Whisper ? User : string( ), m_GHost->m_DB->ThreadedGamePlayerSummaryCheck( StatsUser ) ) );
}
//
// !STATSDOTA
//
if( Command == "statsdota" )
{
string StatsUser = User;
if( !Payload.empty( ) )
StatsUser = Payload;
// check for potential abuse
if( !StatsUser.empty( ) && StatsUser.size( ) < 16 && StatsUser[0] != '/' )
m_PairedDPSChecks.push_back( PairedDPSCheck( Whisper ? User : string( ), m_GHost->m_DB->ThreadedDotAPlayerSummaryCheck( StatsUser ) ) );
}
//
// !VERSION
//
if( Command == "version" )
{
if( IsAdmin( User ) || IsRootAdmin( User ) )
QueueChatCommand( m_GHost->m_Language->VersionAdmin( m_GHost->m_Version ), User, Whisper );
else
QueueChatCommand( m_GHost->m_Language->VersionNotAdmin( m_GHost->m_Version ), User, Whisper );
}
}
}
}
else if( Event == CBNETProtocol :: EID_CHANNEL )
{
// keep track of current channel so we can rejoin it after hosting a game
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] joined channel [" + Message + "]" );
m_CurrentChannel = Message;
}
else if( Event == CBNETProtocol :: EID_INFO )
{
CONSOLE_Print( "[INFO: " + m_ServerAlias + "] " + Message );
// extract the first word which we hope is the username
// this is not necessarily true though since info messages also include channel MOTD's and such
string UserName;
string :: size_type Split = Message.find( " " );
if( Split != string :: npos )
UserName = Message.substr( 0, Split );
else
UserName = Message.substr( 0 );
// handle spoof checking for current game
// this case covers whois results which are used when hosting a public game (we send out a "/whois [player]" for each player)
// at all times you can still /w the bot with "spoofcheck" to manually spoof check
if( m_GHost->m_CurrentGame && m_GHost->m_CurrentGame->GetPlayerFromName( UserName, true ) )
{
if( Message.find( "is away" ) != string :: npos )
m_GHost->m_CurrentGame->SendAllChat( m_GHost->m_Language->SpoofPossibleIsAway( UserName ) );
else if( Message.find( "is unavailable" ) != string :: npos )
m_GHost->m_CurrentGame->SendAllChat( m_GHost->m_Language->SpoofPossibleIsUnavailable( UserName ) );
else if( Message.find( "is refusing messages" ) != string :: npos )
m_GHost->m_CurrentGame->SendAllChat( m_GHost->m_Language->SpoofPossibleIsRefusingMessages( UserName ) );
else if( Message.find( "is using Warcraft III The Frozen Throne in the channel" ) != string :: npos )
m_GHost->m_CurrentGame->SendAllChat( m_GHost->m_Language->SpoofDetectedIsNotInGame( UserName ) );
else if( Message.find( "is using Warcraft III The Frozen Throne in channel" ) != string :: npos )
m_GHost->m_CurrentGame->SendAllChat( m_GHost->m_Language->SpoofDetectedIsNotInGame( UserName ) );
else if( Message.find( "is using Warcraft III The Frozen Throne in a private channel" ) != string :: npos )
m_GHost->m_CurrentGame->SendAllChat( m_GHost->m_Language->SpoofDetectedIsInPrivateChannel( UserName ) );
if( Message.find( "is using Warcraft III The Frozen Throne in game" ) != string :: npos || Message.find( "is using Warcraft III Frozen Throne and is currently in game" ) != string :: npos )
{
// check both the current game name and the last game name against the /whois response
// this is because when the game is rehosted, players who joined recently will be in the previous game according to battle.net
// note: if the game is rehosted more than once it is possible (but unlikely) for a false positive because only two game names are checked
if( Message.find( m_GHost->m_CurrentGame->GetGameName( ) ) != string :: npos || Message.find( m_GHost->m_CurrentGame->GetLastGameName( ) ) != string :: npos )
m_GHost->m_CurrentGame->AddToSpoofed( m_Server, UserName, false );
else
m_GHost->m_CurrentGame->SendAllChat( m_GHost->m_Language->SpoofDetectedIsInAnotherGame( UserName ) );
}
}
}
else if( Event == CBNETProtocol :: EID_ERROR )
CONSOLE_Print( "[ERROR: " + m_ServerAlias + "] " + Message );
else if( Event == CBNETProtocol :: EID_EMOTE )
{
CONSOLE_Print( "[EMOTE: " + m_ServerAlias + "] [" + User + "] " + Message );
m_GHost->EventBNETEmote( this, User, Message );
}
}
void CBNET :: SendJoinChannel( string channel )
{
if( m_LoggedIn && m_InChat )
m_Socket->PutBytes( m_Protocol->SEND_SID_JOINCHANNEL( channel ) );
}
void CBNET :: SendGetFriendsList( )
{
if( m_LoggedIn )
m_Socket->PutBytes( m_Protocol->SEND_SID_FRIENDSLIST( ) );
}
void CBNET :: SendGetClanList( )
{
if( m_LoggedIn )
m_Socket->PutBytes( m_Protocol->SEND_SID_CLANMEMBERLIST( ) );
}
void CBNET :: QueueEnterChat( )
{
if( m_LoggedIn )
m_OutPackets.push( m_Protocol->SEND_SID_ENTERCHAT( ) );
}
void CBNET :: QueueChatCommand( string chatCommand )
{
if( chatCommand.empty( ) )
return;
if( m_LoggedIn )
{
if( m_PasswordHashType == "pvpgn" && chatCommand.size( ) > m_MaxMessageLength )
chatCommand = chatCommand.substr( 0, m_MaxMessageLength );
if( chatCommand.size( ) > 255 )
chatCommand = chatCommand.substr( 0, 255 );
if( m_OutPackets.size( ) > 10 )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] attempted to queue chat command [" + chatCommand + "] but there are too many (" + UTIL_ToString( m_OutPackets.size( ) ) + ") packets queued, discarding" );
else
{
CONSOLE_Print( "[QUEUED: " + m_ServerAlias + "] " + chatCommand );
m_OutPackets.push( m_Protocol->SEND_SID_CHATCOMMAND( chatCommand ) );
}
}
}
void CBNET :: QueueChatCommand( string chatCommand, string user, bool whisper )
{
if( chatCommand.empty( ) )
return;
// if whisper is true send the chat command as a whisper to user, otherwise just queue the chat command
if( whisper )
QueueChatCommand( "/w " + user + " " + chatCommand );
else
QueueChatCommand( chatCommand );
}
void CBNET :: QueueGameCreate( unsigned char state, string gameName, string hostName, CMap *map, CSaveGame *savegame, uint32_t hostCounter )
{
if( m_LoggedIn && map )
{
if( !m_CurrentChannel.empty( ) )
m_FirstChannel = m_CurrentChannel;
m_InChat = false;
// a game creation message is just a game refresh message with upTime = 0
QueueGameRefresh( state, gameName, hostName, map, savegame, 0, hostCounter );
}
}
void CBNET :: QueueGameRefresh( unsigned char state, string gameName, string hostName, CMap *map, CSaveGame *saveGame, uint32_t upTime, uint32_t hostCounter )
{
if( hostName.empty( ) )
{
BYTEARRAY UniqueName = m_Protocol->GetUniqueName( );
hostName = string( UniqueName.begin( ), UniqueName.end( ) );
}
if( m_LoggedIn && map )
{
// construct a fixed host counter which will be used to identify players from this realm
// the fixed host counter's 4 most significant bits will contain a 4 bit ID (0-15)
// the rest of the fixed host counter will contain the 28 least significant bits of the actual host counter
// since we're destroying 4 bits of information here the actual host counter should not be greater than 2^28 which is a reasonable assumption
// when a player joins a game we can obtain the ID from the received host counter
// note: LAN broadcasts use an ID of 0, battle.net refreshes use an ID of 1-10, the rest are unused
uint32_t FixedHostCounter = ( hostCounter & 0x0FFFFFFF ) | ( m_HostCounterID << 28 );
if( saveGame )
{
uint32_t MapGameType = MAPGAMETYPE_SAVEDGAME;
// the state should always be private when creating a saved game
if( state == GAME_PRIVATE )
MapGameType |= MAPGAMETYPE_PRIVATEGAME;
// use an invalid map width/height to indicate reconnectable games
BYTEARRAY MapWidth;
MapWidth.push_back( 192 );
MapWidth.push_back( 7 );
BYTEARRAY MapHeight;
MapHeight.push_back( 192 );
MapHeight.push_back( 7 );
if( m_GHost->m_Reconnect )
m_OutPackets.push( m_Protocol->SEND_SID_STARTADVEX3( state, UTIL_CreateByteArray( MapGameType, false ), map->GetMapGameFlags( ), MapWidth, MapHeight, gameName, hostName, upTime, "Save\\Multiplayer\\" + saveGame->GetFileNameNoPath( ), saveGame->GetMagicNumber( ), map->GetMapSHA1( ), FixedHostCounter ) );
else
m_OutPackets.push( m_Protocol->SEND_SID_STARTADVEX3( state, UTIL_CreateByteArray( MapGameType, false ), map->GetMapGameFlags( ), UTIL_CreateByteArray( (uint16_t)0, false ), UTIL_CreateByteArray( (uint16_t)0, false ), gameName, hostName, upTime, "Save\\Multiplayer\\" + saveGame->GetFileNameNoPath( ), saveGame->GetMagicNumber( ), map->GetMapSHA1( ), FixedHostCounter ) );
}
else
{
uint32_t MapGameType = map->GetMapGameType( );
MapGameType |= MAPGAMETYPE_UNKNOWN0;
if( state == GAME_PRIVATE )
MapGameType |= MAPGAMETYPE_PRIVATEGAME;
// use an invalid map width/height to indicate reconnectable games
BYTEARRAY MapWidth;
MapWidth.push_back( 192 );
MapWidth.push_back( 7 );
BYTEARRAY MapHeight;
MapHeight.push_back( 192 );
MapHeight.push_back( 7 );
if( m_GHost->m_Reconnect )
m_OutPackets.push( m_Protocol->SEND_SID_STARTADVEX3( state, UTIL_CreateByteArray( MapGameType, false ), map->GetMapGameFlags( ), MapWidth, MapHeight, gameName, hostName, upTime, map->GetMapPath( ), map->GetMapCRC( ), map->GetMapSHA1( ), FixedHostCounter ) );
else
m_OutPackets.push( m_Protocol->SEND_SID_STARTADVEX3( state, UTIL_CreateByteArray( MapGameType, false ), map->GetMapGameFlags( ), map->GetMapWidth( ), map->GetMapHeight( ), gameName, hostName, upTime, map->GetMapPath( ), map->GetMapCRC( ), map->GetMapSHA1( ), FixedHostCounter ) );
}
}
}
void CBNET :: QueueGameUncreate( )
{
if( m_LoggedIn )
m_OutPackets.push( m_Protocol->SEND_SID_STOPADV( ) );
}
void CBNET :: UnqueuePackets( unsigned char type )
{
queue<BYTEARRAY> Packets;
uint32_t Unqueued = 0;
while( !m_OutPackets.empty( ) )
{
// todotodo: it's very inefficient to have to copy all these packets while searching the queue
BYTEARRAY Packet = m_OutPackets.front( );
m_OutPackets.pop( );
if( Packet.size( ) >= 2 && Packet[1] == type )
Unqueued++;
else
Packets.push( Packet );
}
m_OutPackets = Packets;
if( Unqueued > 0 )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] unqueued " + UTIL_ToString( Unqueued ) + " packets of type " + UTIL_ToString( type ) );
}
void CBNET :: UnqueueChatCommand( string chatCommand )
{
// hackhack: this is ugly code
// generate the packet that would be sent for this chat command
// then search the queue for that exact packet
BYTEARRAY PacketToUnqueue = m_Protocol->SEND_SID_CHATCOMMAND( chatCommand );
queue<BYTEARRAY> Packets;
uint32_t Unqueued = 0;
while( !m_OutPackets.empty( ) )
{
// todotodo: it's very inefficient to have to copy all these packets while searching the queue
BYTEARRAY Packet = m_OutPackets.front( );
m_OutPackets.pop( );
if( Packet == PacketToUnqueue )
Unqueued++;
else
Packets.push( Packet );
}
m_OutPackets = Packets;
if( Unqueued > 0 )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] unqueued " + UTIL_ToString( Unqueued ) + " chat command packets" );
}
void CBNET :: UnqueueGameRefreshes( )
{
UnqueuePackets( CBNETProtocol :: SID_STARTADVEX3 );
}
bool CBNET :: IsAdmin( string name )
{
transform( name.begin( ), name.end( ), name.begin( ), (int(*)(int))tolower );
for( vector<string> :: iterator i = m_Admins.begin( ); i != m_Admins.end( ); i++ )
{
if( *i == name )
return true;
}
return false;
}
bool CBNET :: IsRootAdmin( string name )
{
// m_RootAdmin was already transformed to lower case in the constructor
transform( name.begin( ), name.end( ), name.begin( ), (int(*)(int))tolower );
// updated to permit multiple root admins seperated by a space, e.g. "Varlock Kilranin Instinct121"
// note: this function gets called frequently so it would be better to parse the root admins just once and store them in a list somewhere
// however, it's hardly worth optimizing at this point since the code's already written
stringstream SS;
string s;
SS << m_RootAdmin;
while( !SS.eof( ) )
{
SS >> s;
if( name == s )
return true;
}
return false;
}
CDBBan *CBNET :: IsBannedName( string name )
{
transform( name.begin( ), name.end( ), name.begin( ), (int(*)(int))tolower );
// todotodo: optimize this - maybe use a map?
for( vector<CDBBan *> :: iterator i = m_Bans.begin( ); i != m_Bans.end( ); i++ )
{
if( (*i)->GetName( ) == name )
return *i;
}
return NULL;
}
CDBBan *CBNET :: IsBannedIP( string ip )
{
// todotodo: optimize this - maybe use a map?
for( vector<CDBBan *> :: iterator i = m_Bans.begin( ); i != m_Bans.end( ); i++ )
{
if( (*i)->GetIP( ) == ip )
return *i;
}
return NULL;
}
void CBNET :: AddAdmin( string name )
{
transform( name.begin( ), name.end( ), name.begin( ), (int(*)(int))tolower );
m_Admins.push_back( name );
}
void CBNET :: AddBan( string name, string ip, string gamename, string admin, string reason )
{
transform( name.begin( ), name.end( ), name.begin( ), (int(*)(int))tolower );
m_Bans.push_back( new CDBBan( m_Server, name, ip, "N/A", gamename, admin, reason ) );
}
void CBNET :: RemoveAdmin( string name )
{
transform( name.begin( ), name.end( ), name.begin( ), (int(*)(int))tolower );
for( vector<string> :: iterator i = m_Admins.begin( ); i != m_Admins.end( ); )
{
if( *i == name )
i = m_Admins.erase( i );
else
i++;
}
}
void CBNET :: RemoveBan( string name )
{
transform( name.begin( ), name.end( ), name.begin( ), (int(*)(int))tolower );
for( vector<CDBBan *> :: iterator i = m_Bans.begin( ); i != m_Bans.end( ); )
{
if( (*i)->GetName( ) == name )
i = m_Bans.erase( i );
else
i++;
}
}
void CBNET :: HoldFriends( CBaseGame *game )
{
if( game )
{
for( vector<CIncomingFriendList *> :: iterator i = m_Friends.begin( ); i != m_Friends.end( ); i++ )
game->AddToReserved( (*i)->GetAccount( ) );
}
}
void CBNET :: HoldClan( CBaseGame *game )
{
if( game )
{
for( vector<CIncomingClanList *> :: iterator i = m_Clans.begin( ); i != m_Clans.end( ); i++ )
game->AddToReserved( (*i)->GetName( ) );
}
}
| [
"jonas@titan.(none)"
]
| [
[
[
1,
2567
]
]
]
|
232307e9b3c52bf9cc7317bead1bd03171248171 | 60ef79535d316aaeb4efc4f79d700fcb1c87586f | /CUGBLinker/TextProgressCtrl.cpp | f34b2d8a55b3918856f1a50dcb30fc9150ee2a1a | []
| no_license | dinglx/cugblinker | 9b4cc5e129268cf3b2c14c99cd43a322c3f3487b | f4a2ee5bdecf41ec8ba91c63cf1923672964eae1 | refs/heads/master | 2021-01-16T00:27:54.122346 | 2009-12-16T17:00:50 | 2009-12-16T17:00:50 | 32,516,245 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 984 | cpp | // MyProgressCtrl.cpp : 实现文件
//
#include "stdafx.h"
#include "TextProgressCtrl.h"
// CTextProgressCtrl
IMPLEMENT_DYNAMIC(CTextProgressCtrl, CProgressCtrl)
CTextProgressCtrl::CTextProgressCtrl()
: m_nPos(0)
, m_nMax(0)
{
}
CTextProgressCtrl::~CTextProgressCtrl()
{
}
BEGIN_MESSAGE_MAP(CTextProgressCtrl, CProgressCtrl)
ON_WM_PAINT()
END_MESSAGE_MAP()
// CTextProgressCtrl 消息处理程序
void CTextProgressCtrl::OnPaint()
{
CProgressCtrl::OnPaint();
CDC *pDC = CProgressCtrl::GetDC();
pDC->SetBkMode(TRANSPARENT);
CString temp;
temp.Format(L"%4d/%d(%.1f%%)",m_nPos,m_nMax,(float)m_nPos/m_nMax*100);
pDC->TextOut(50,6,temp);
ReleaseDC(pDC);
}
int CTextProgressCtrl::SetPos(int nPos)
{
int res=CProgressCtrl::SetPos(nPos);;
m_nPos=nPos;
Invalidate(TRUE);
return res;
}
void CTextProgressCtrl::SetRange(short nUpper)
{
m_nMax=nUpper;
CProgressCtrl::SetRange(0,nUpper);
Invalidate(TRUE);
}
| [
"dlx1986@4ddcaae0-7081-11de-ae35-f3f989a3c448",
"dinglinxiao@4ddcaae0-7081-11de-ae35-f3f989a3c448"
]
| [
[
[
1,
55
],
[
57,
57
]
],
[
[
56,
56
]
]
]
|
16706d8bea98d746d1f7407e1a5038e22840fb00 | 115cdd77595f80aa6870893657f26f6b4e7cdd2b | /src/include/SceneGraphNodeBase.hpp | 6db1f66847ae0c93345fc5a7f6103a9655241bd1 | []
| no_license | douglyuckling/peek | 0bc036906bab49fec63944e4c23e3b0c6935d820 | 9d7c3022366290a43830be5f19a47bd406038f3c | refs/heads/master | 2021-01-23T07:21:11.076300 | 2010-07-09T04:48:33 | 2010-07-09T04:48:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 588 | hpp | /**
* @file SceneGraphNodeBase.hpp
*/
#pragma once
#include "Peek_base.hpp"
#include "Object.hpp"
#include <handle_traits.hpp>
#include <list_traits.hpp>
namespace peek {
/**
* @brief The base class for a node in a scene graph
*/
class SceneGraphNodeBase : public Object {
public:
/** Draws the node */
virtual void draw() const = 0;
/** Draws the node for picking */
virtual void pick() const = 0;
typedef handle_traits<SceneGraphNodeBase>::handle_type handle;
typedef list_traits<SceneGraphNodeBase::handle>::list_type list;
};
} | [
"douglyuckling@483a7388-aa76-4cae-9b69-882d6fd7d2f9"
]
| [
[
[
1,
31
]
]
]
|
1605f37ed19fbffa97ae2f3d4acdd7870e877b08 | 6630a81baef8700f48314901e2d39141334a10b7 | /1.4/Testing/Cxx/swFrameworkDependent/Widget/swTreeCtrl.cpp | b6a5f533639708b698bd0c01736aa8d4783c8646 | []
| no_license | jralls/wxGuiTesting | a1c0bed0b0f5f541cc600a3821def561386e461e | 6b6e59e42cfe5b1ac9bca02fbc996148053c5699 | refs/heads/master | 2021-01-10T19:50:36.388929 | 2009-03-24T20:22:11 | 2009-03-26T18:51:24 | 623,722 | 1 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 7,469 | cpp | ///////////////////////////////////////////////////////////////////////////////
// Name: swFrameworkDependent/Widget/swTreeCtrl.cpp
// Author: Yann Rouillard, Viet Bui Xuan, Reinhold Füreder
// Created: 2002
// Copyright: (c) 2002 Yann Rouillard, Viet Bui Xuan, Reinhold Füreder
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
#ifdef __GNUG__
#pragma implementation "swTreeCtrl.h"
#endif
#include "swTreeCtrl.h"
#include "wx/imaglist.h"
namespace sw {
BEGIN_EVENT_TABLE(TreeCtrl, wxTreeCtrl)
EVT_TREE_ITEM_RIGHT_CLICK (-1, TreeCtrl::OnTreeRightClick)
EVT_RIGHT_UP (TreeCtrl::OnRightClick)
EVT_RIGHT_DOWN (TreeCtrl::OnRightClick)
EVT_TREE_BEGIN_LABEL_EDIT(-1, TreeCtrl::OnBeginLabelEdit)
END_EVENT_TABLE()
IMPLEMENT_DYNAMIC_CLASS (TreeCtrl, wxTreeCtrl)
TreeCtrl::TreeCtrl(wxWindow* parent,
wxWindowID id,
const wxPoint& pos,
const wxSize& size,
long style,
const wxValidator& validator,
const wxString& name) :
wxTreeCtrl (parent, id, pos, size, style | wxTR_EDIT_LABELS | wxTR_HAS_BUTTONS | wxTR_TWIST_BUTTONS , validator, name)
{
}
TreeCtrl::TreeCtrl()
{
}
TreeCtrl::~TreeCtrl()
{
}
unsigned int TreeCtrl::GetSiblingIndex (const wxTreeItemId& siblingId, const wxTreeItemId &parentId)
{
long j;
unsigned int i = 1;
if (GetFirstChild (parentId, (void *&)j) == siblingId) {
return i;
}
i++;
while (GetNextChild (parentId, (void *&)j) != siblingId
&& i <= GetChildrenCount(parentId, FALSE)) {
i++;
}
return i <= GetChildrenCount(parentId, FALSE) ? i : 0;
}
unsigned int TreeCtrl::GetSiblingIndex (const wxTreeItemId& siblingId)
{
return GetSiblingIndex (siblingId, GetRootItem ());
}
unsigned int TreeCtrl::GetSiblingCount (const wxTreeItemId &parentId)
{
long j;
unsigned int i = 1;
if (GetFirstChild (parentId, (void *&)j) == GetLastChild (parentId)) {
return i;
}
i++;
while (GetNextChild (parentId, (void *&)j) != GetLastChild (parentId)
&& i <= GetChildrenCount(parentId, FALSE)) {
i++;
}
return i <= GetChildrenCount(parentId, FALSE) ? i : 0;
}
unsigned int TreeCtrl::GetSiblingCount ()
{
return GetSiblingCount (GetRootItem ());
}
wxTreeItemId TreeCtrl::GetNthSibling (unsigned int index, const wxTreeItemId &parentId)
{
long cookie;
wxTreeItemId sibling;
if (index == 0) {
return parentId;
}
sibling = GetFirstChild (parentId, (void *&)cookie);
for ( unsigned int i = 1; i != index && i <= GetChildrenCount(parentId, FALSE); i++) {
sibling = GetNextChild (parentId, (void *&)cookie);
}
return sibling;
}
wxTreeItemId TreeCtrl::GetNthSibling (unsigned int index)
{
return GetNthSibling (index, GetRootItem ());
}
unsigned int TreeCtrl::GetDepth (const wxTreeItemId &id)
{
wxTreeItemId parentId = GetItemParent (id);
if (parentId == wxTreeItemId ()) { // id is already the root
return 0;
} else if (parentId == GetRootItem ()) {
return 1;
} else {
return GetDepth (parentId) + 1;
}
}
void TreeCtrl::SetChildrenNumber (const wxTreeItemId &parentId, unsigned int childrenNumber)
{
wxTreeItemId childToDeleteId;
int diff = childrenNumber - GetChildrenCount (parentId, FALSE);
if (diff > 0) {
AppendItem (parentId, "");
SetChildrenNumber (parentId, childrenNumber);
} else if (diff < 0) {
childToDeleteId = GetNthSibling (GetChildrenCount (parentId, FALSE), parentId);
DeleteChildren (childToDeleteId);
Delete (childToDeleteId);
SetChildrenNumber (parentId, childrenNumber);
}
ReduceChildrenToMinimumStyle (parentId);
}
void TreeCtrl::ReduceToMinimumStyle (const wxTreeItemId &id)
{
if (id.IsOk ()) {
SetItemBackgroundColour (id, wxNullColour);
SetItemBold (id, FALSE);
SetItemTextColour (id, wxSystemSettings::GetColour (wxSYS_COLOUR_WINDOWTEXT));
SetChildrenNumber (id, 0);
SetItemImage (id, GetSiblingIndex (id), wxTreeItemIcon_Normal);
SetItemImage (id, GetSiblingIndex (id), wxTreeItemIcon_Selected);
SetItemImage (id, GetSiblingIndex (id), wxTreeItemIcon_Expanded);
SetItemImage (id, GetSiblingIndex (id), wxTreeItemIcon_SelectedExpanded );
}
}
void TreeCtrl::ReduceChildrenToMinimumStyle (const wxTreeItemId &id)
{
long cookie;
wxTreeItemId siblingId = GetFirstChild (id, (void *&)cookie);
while (siblingId.IsOk ()) {
ReduceToMinimumStyle (siblingId);
siblingId = GetNextChild (id, (void *&)cookie);
}
}
void TreeCtrl::OnRightClick (wxMouseEvent &event)
{
event.Skip ();
}
void TreeCtrl::OnTreeRightClick (wxTreeEvent &event)
{
event.Skip ();
}
void TreeCtrl::OnBeginLabelEdit (wxTreeEvent &event)
{
event.Skip ();
}
void TreeCtrl::OnEndLabelEdit (wxTreeEvent &event)
{
event.Skip ();
}
void TreeCtrl::SetBitmapColor (const wxTreeItemId &id, wxColour &colour, unsigned int i)
{
wxBitmap *colorBitmap1 = new wxBitmap (12, 12);
wxMemoryDC temp_dc;
temp_dc.SelectObject(*colorBitmap1);
temp_dc.SetBrush (wxBrush (colour, wxSOLID));
temp_dc.FloodFill (1, 1, *wxBLACK);
temp_dc.SelectObject (wxNullBitmap);
wxBitmap *colorBitmap2 = new wxBitmap (12, 12);
temp_dc.SelectObject(*colorBitmap2);
temp_dc.SetBrush (wxBrush (colour, wxSOLID));
temp_dc.FloodFill (1, 1, *wxBLACK);
temp_dc.SelectObject (wxNullBitmap);
wxBitmap *colorBitmap3 = new wxBitmap (12, 12);
temp_dc.SelectObject(*colorBitmap3);
temp_dc.SetBrush (wxBrush (colour, wxSOLID));
temp_dc.FloodFill (1, 1, *wxBLACK);
temp_dc.SelectObject (wxNullBitmap);
wxBitmap *colorBitmap4 = new wxBitmap (12, 12);
temp_dc.SelectObject(*colorBitmap4);
temp_dc.SetBrush (wxBrush (colour, wxSOLID));
temp_dc.FloodFill (1, 1, *wxBLACK);
temp_dc.SelectObject (wxNullBitmap);
wxImageList *imageList = GetImageList ();
if (imageList == NULL) {
imageList = new wxImageList (12, 12);
SetImageList (imageList);
}
if (imageList->GetImageCount () / 4 < i + 1) {
imageList->Add (*colorBitmap1);
imageList->Add (*colorBitmap2);
imageList->Add (*colorBitmap3);
imageList->Add (*colorBitmap4);
} else {
imageList->Replace (4 * i, *colorBitmap1);
imageList->Replace (4 * i + 1, *colorBitmap2);
imageList->Replace (4 * i + 2, *colorBitmap3);
imageList->Replace (4 * i + 3, *colorBitmap4);
}
SetImageList (GetImageList ());
SetStateImageList (GetImageList ());
SetItemImage (id, 4 * i, wxTreeItemIcon_Normal);
SetItemImage (id, 4 * i + 1, wxTreeItemIcon_Selected);
SetItemImage (id, 4 * i + 2, wxTreeItemIcon_Expanded);
SetItemImage (id, 4 * i + 3, wxTreeItemIcon_SelectedExpanded );
}
void TreeCtrl::DeleteBitmapList ()
{
wxImageList *imageList;
imageList = GetImageList ();
if (imageList != NULL) {
imageList->RemoveAll();
}
while (!m_bitmapList.empty ()) {
delete m_bitmapList.front ();
m_bitmapList.pop_front ();
}
}
wxTreeItemId TreeCtrl::GetNthChild (wxTreeCtrl *treeCtrl, unsigned int idx,
const wxTreeItemId &id)
{
wxASSERT (idx > 0);
wxTreeItemId cur;
wxTreeItemIdValue cookie;
cur = treeCtrl->GetFirstChild (id, cookie);
for (int i = 1; i < idx; i++) {
cur = treeCtrl->GetNextChild (id, cookie);
}
return cur;
}
} // End namespace sw
| [
"john@64288482-8357-404e-ad65-de92a562ee98"
]
| [
[
[
1,
309
]
]
]
|
346f4f15dd7fb9ffa69543d379f637073efb62d5 | b8fbe9079ce8996e739b476d226e73d4ec8e255c | /src/engine/rb_physics/colplane.cpp | bcbe628d736cbf73cc539cbf779cdddc9fb3772c | []
| no_license | dtbinh/rush | 4294f84de1b6e6cc286aaa1dd48cf12b12a467d0 | ad75072777438c564ccaa29af43e2a9fd2c51266 | refs/heads/master | 2021-01-15T17:14:48.417847 | 2011-06-16T17:41:20 | 2011-06-16T17:41:20 | 41,476,633 | 1 | 0 | null | 2015-08-27T09:03:44 | 2015-08-27T09:03:44 | null | UTF-8 | C++ | false | false | 881 | cpp | /***********************************************************************************/
// File: ColPlane.cpp
// Date: 25.08.2005
// Author: Ruslan Shestopalyuk
/***********************************************************************************/
#include "stdafx.h"
#include "ColPlane.h"
#include "PhysicsServer.h"
/***********************************************************************************/
/* ColPlane implementation
/***********************************************************************************/
decl_class(ColPlane);
ColPlane::ColPlane()
{
m_Plane = Plane::xOy;
}
dGeomID ColPlane::CreateGeom( dSpaceID spaceID )
{
float scale = PhysicsServer::s_pInstance->GetWorldScale();
Plane pl( m_Plane );
pl.Normal().normalize();
return dCreatePlane( spaceID, pl.a, pl.b, pl.c, -pl.d*scale );
} // ColPlane::CreateGeom | [
"[email protected]"
]
| [
[
[
1,
25
]
]
]
|
63c7b95dcfa2528f8db980d5e2f22b9b3dd81daa | d4f6dc3c381b82ed18117a2b81c2f83df0a02fb8 | /simulator/Instruction.cpp | 2b533d8d7d7ce2a6a96822a618f6f7889b806d94 | []
| no_license | zayac/hera-mcst | 7c20ab22f6f79dc4e25fadb8cae343facdb01b8a | ca1096557c00256bcf7361ca29602a04914f0555 | refs/heads/master | 2020-05-19T10:05:47.931830 | 2011-06-02T07:43:12 | 2011-06-02T07:43:12 | 32,114,257 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,986 | cpp | #include <iostream>
#include <stdio.h>
#include <string>
#include "Instruction.h"
#include <string.h>
#define if_cmd(cmd) if (!strcmp(instr_string.c_str(), cmd))
using namespace std;
Instruction::Instruction()
{
this->instr_word = 0;
this->cmd_counter = 1;
string branches[] = { "BR", "BL", "BGE", "BLE", "BG", "BULE", "BUG", "BZ", "BNZ", "BC", "BNC", "BS", "BNS", "BV", "BNV",
"BRR", "BLR", "BGER", "BLER", "BGR", "BULER", "BUGR", "BZR", "BNZR", "BCR", "BNCR", "BSR", "BNSR", "BVR", "BNVR" };
this->branches.insert(this->branches.begin(), branches, branches + 30);
}
string Instruction::trim(string str)
{
string::size_type pos = str.find_last_not_of(' ');
if(pos != string::npos)
{
str.erase(pos + 1);
pos = str.find_first_not_of(' ');
if(pos != string::npos) str.erase(0, pos);
}
else str.erase(str.begin(), str.end());
return str;
}
string Instruction::erase(string str, char chr)
{
string::size_type pos = str.find_first_of(chr);
while( pos != string::npos)
{
str.erase(pos, 1);
pos = str.find_first_of(chr);
}
return str;
}
int Instruction::setAddr(string str)
{
for(unsigned int i = 0; i < addr_name.size(); i++)
{
if(str == addr_name[i])
{
return addr_value[i];
}
}
return -1;
}
int Instruction::set( string source)
{
this->instr_word = 0;
this->args.clear();
size_t p0 = 0, p1 = string::npos;
source = erase(source, '\t');
p1 = source.find_first_of(":", p0);
if (p1 != string::npos)
{
addr_name.push_back(source.substr(p0, p1 - p0));
addr_value.push_back( this->cmd_counter);
return 0;
}
else
{
p0 = 0;
p1 = source.find_first_of(" ", p0);
if (p1 != p0)
{
string token = source.substr(p0, p1 - p0);
this->instr_string = trim(toUpper(token));
}
size_t p2 = source.find_first_of(";", p0);
source = trim(source.substr(p1+1, p2-p1-1));
p0 = 0;
while(p0 != string::npos)
{
p1 = source.find_first_of(",", p0);
if(p1 != p0)
{
string token = source.substr(p0, p1 - p0);
if (setAddr(token) == -1)
this->args.push_back(strToInt(trim(token)));
else
this->args.push_back(setAddr(token));
}
p0 = source.find_first_not_of(",", p1);
}
return 1;
}
}
void Instruction::process (string str, unsigned short int* instrs)
{
if (this->set(str))
{
if( this->encode(instrs))
{
instrs[this->getCmdCounter()] = this->getInstrWord();
this->incCmdCounter();
}
}
}
int Instruction::encode(unsigned short int* instrs)
{
// SETLO and SETHI
if_cmd("SETLO")
{
setValueByShift( 0xE, 12);
setValueByShift( this->args[0], 8);
setValueByShift( this->args[1], 0);
return 1;
}
else if_cmd("SETHI")
{
setValueByShift( 0xF, 12);
setValueByShift( this->args[0], 8);
setValueByShift( this->args[1], 0);
return 1;
}
// Tree-address operations
else if_cmd("AND")
{
setValueByShift( 0x1, 15);
setValueByShift( 0x0, 12);
setValueByShift( this->args[1], 8);
setValueByShift( this->args[2], 4);
setValueByShift( this->args[3], 0);
return 1;
}
else if_cmd("OR")
{
setValueByShift( 0x1, 15);
setValueByShift( 0x1, 12);
setValueByShift( this->args[0], 8);
setValueByShift( this->args[1], 4);
setValueByShift( this->args[2], 0);
return 1;
}
else if_cmd("ADD")
{
setValueByShift( 0x1, 15);
setValueByShift( 0x2, 12);
setValueByShift( this->args[0], 8);
setValueByShift( this->args[1], 4);
setValueByShift( this->args[2], 0);
return 1;
}
else if_cmd("SUB")
{
setValueByShift( 0x1, 15);
setValueByShift( 0x3, 12);
setValueByShift( this->args[0], 8);
setValueByShift( this->args[1], 4);
setValueByShift( this->args[2], 0);
return 1;
}
else if_cmd("MULT")
{
setValueByShift( 0x1, 15);
setValueByShift( 0x4, 12);
setValueByShift( this->args[0], 8);
setValueByShift( this->args[1], 4);
setValueByShift( this->args[2], 0);
return 1;
}
else if_cmd("XOR")
{
setValueByShift( 0x1, 15);
setValueByShift( 0x5, 12);
setValueByShift( this->args[0], 8);
setValueByShift( this->args[1], 4);
setValueByShift( this->args[2], 0);
return 1;
}
// Shifts
else if_cmd("LSL")
{
setValueByShift( 0x3, 12);
setValueByShift( this->args[0], 8);
setValueByShift( 0x0, 4);
setValueByShift( this->args[1], 0);
return 1;
}
else if_cmd("LSR")
{
setValueByShift( 0x3, 12);
setValueByShift( this->args[0], 8);
setValueByShift( 0x1, 4);
setValueByShift( this->args[1], 0);
return 1;
}
else if_cmd("LSL8")
{
setValueByShift( 0x3, 12);
setValueByShift( this->args[0], 8);
setValueByShift( 0x2, 4);
setValueByShift( this->args[1], 0);
return 1;
}
else if_cmd("LSR8")
{
setValueByShift( 0x3, 12);
setValueByShift( this->args[0], 8);
setValueByShift( 0x3, 4);
setValueByShift( this->args[1], 0);
return 1;
}
else if_cmd("ASL")
{
setValueByShift( 0x3, 12);
setValueByShift( this->args[0], 8);
setValueByShift( 0x4, 4);
setValueByShift( this->args[1], 0);
return 1;
}
else if_cmd("ASR")
{
setValueByShift( 0x3, 12);
setValueByShift( this->args[0], 8);
setValueByShift( 0x5, 4);
setValueByShift( this->args[1], 0);
return 1;
}
// Set/Clear flags
else if_cmd("SETF")
{
setValueByShift( 0x3, 12);
setValueByShift( 0x0, 11);
setValueByShift( (0x10 & this->args[0]) >> 4, 8);
setValueByShift( 0xF & this->args[0], 0);
setValueByShift( 0x3, 5);
return 1;
}
else if_cmd("CLRF")
{
setValueByShift( 0x3, 12);
setValueByShift( 0x1, 11);
setValueByShift( (0x10 & this->args[0]) >> 4, 8);
setValueByShift( 0xF & this->args[0], 0);
setValueByShift( 0x3, 5);
return 1;
}
// Save/restore flags
else if_cmd("SAVEF")
{
setValueByShift( 0x3, 12);
setValueByShift( 0x7, 4);
setValueByShift( 0x0, 3);
setValueByShift( this->args[0], 8);
return 1;
}
else if_cmd("RSTRF")
{
setValueByShift( 0x3, 12);
setValueByShift( 0x7, 4);
setValueByShift( 0x1, 3);
setValueByShift( this->args[0], 8);
return 1;
}
// Increments
else if_cmd("INC")
{
setValueByShift( 0x3, 12);
setValueByShift( 0x2, 6);
setValueByShift( this->args[0], 8);
setValueByShift( this->args[1], 0);
return 1;
}
else if_cmd("DEC")
{
setValueByShift( 0x3, 12);
setValueByShift( 0x3, 6);
setValueByShift( this->args[0], 8);
setValueByShift( this->args[1], 0);
return 1;
}
// Memory Instructions
else if_cmd("LOAD")
{
setValueByShift( 0x2, 13);
setValueByShift( this->args[0], 8);
setValueByShift( (0x10 & this->args[1]) >> 4, 12);
setValueByShift( 0xF & this->args[1], 4);
setValueByShift( this->args[2], 0);
return 1;
}
else if_cmd("STORE")
{
setValueByShift( 0x3, 13);
setValueByShift( this->args[0], 8);
setValueByShift( (0x10 & this->args[1]) >> 4, 12);
setValueByShift( 0xF & this->args[1], 4);
setValueByShift( this->args[2], 0);
return 1;
}
// Branches, including jumps
else if (this->instr_string[0] == 'B')
{
int brnum = findBranch( instr_string);
if (brnum != -1)
{
if( brnum < 15)
{
setValueByShift( 0x1, 12);
setValueByShift( this->args[0], 0);
}
else
{
setValueByShift( 0x0, 12);
setValueByShift( 0x00ff & (this->args[0] - this->getCmdCounter()) , 0);
}
if ((brnum % 15) == 0)
setValueByShift( 0x0, 8);
else
setValueByShift( brnum % 15 + 1, 8);
return 1;
}
}
else if_cmd("SWI")
{
setValueByShift(0x11, 8);
setValueByShift( this->args[0], 0);
return 1;
}
else if_cmd("RTI")
{
setValueByShift(0x1110, 0);
return 1;
}
else if_cmd("RETURN")
{
setValueByShift(0x1111, 0);
return 1;
}
else if_cmd("CALL")
{
setValueByShift(0x2, 12);
setValueByShift( this->args[0], 4);
setValueByShift( this->args[1], 0);
return 1;
}
// Macro commands
else if_cmd("SET")
{
char d[256];
sprintf(d, "SETLO %i %i", this->args[0], this->args[1] & 0xff);
this->process(d, instrs);
sprintf(d, "SETHI %i %i", this->args[0], this->args[1] >> 8);
this->process(d, instrs);
return 0;
}
else if_cmd("CMP")
{
char d[256];
sprintf(d, "SETC");
this->process(d, instrs);
sprintf(d, "SUB r0 %i %i", this->args[0], this->args[1]);
this->process(d, instrs);
return 0;
}
else if_cmd("NEG")
{
char d[256];
sprintf(d, "SETC");
this->process(d, instrs);
sprintf(d, "SUB %i r0 %i",this->args[0], this->args[1]);
this->process(d, instrs);
return 0;
}
else if_cmd("NEG")
{
char d[256];
sprintf(d, "SETC");
this->process(d, instrs);
sprintf(d, "SUB %i r0 %i",this->args[0], this->args[1]);
this->process(d, instrs);
return 0;
}
else if_cmd("NOT")
{
char d[256];
sprintf(d, "SET r13, 65535");
this->process(d, instrs);
sprintf(d, "XOR %i r13 %i",this->args[0], this->args[1]);
this->process(d, instrs);
return 0;
}
else if_cmd("HALT")
{
char d[256];
sprintf(d, "BRR 0");
this->process(d, instrs);
return 0;
}
else if_cmd("NOP")
{
char d[256];
sprintf(d, "BRR 1");
this->process(d, instrs);
return 0;
}
else if_cmd("SETC")
{
char d[256];
sprintf(d, "SETF 8");
this->process(d, instrs);
return 0;
}
else if_cmd("CLRC")
{
char d[256];
sprintf(d, "CLRF 8");
this->process(d, instrs);
return 0;
}
else if_cmd("SETCB")
{
char d[256];
sprintf(d, "SETF 16");
this->process(d, instrs);
return 0;
}
else if_cmd("CLCCB")
{
char d[256];
sprintf(d, "CLRF 24");
this->process(d, instrs);
return 0;
}
else if_cmd("FLAGS")
{
char d[256];
sprintf(d, "CLRC");
this->process(d, instrs);
sprintf(d, "ADD r0, %i, r0", this->args[0]);
this->process(d, instrs);
return 0;
}
return 0;
}
| [
"[email protected]@0879719b-bd20-6c4d-6a25-18cb37d9fc63"
]
| [
[
[
1,
451
]
]
]
|
df085572835376ba43ba93bf0d7747b6c92921a1 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctestsettingpage/src/bctestslidersettingpage.cpp | f8f26d08969b725a2a340036a176e377596bb80e | []
| no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,907 | cpp | /*
* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: test case
*
*/
#include "bctestslidersettingpage.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
EXPORT_C CBCTestSliderSettingPage::CBCTestSliderSettingPage( TInt aResourceId, TInt& aSliderValue ):
CAknSliderSettingPage( aResourceId, aSliderValue )
{
}
EXPORT_C CBCTestSliderSettingPage::CBCTestSliderSettingPage(
const TDesC* aSettingText,
TInt aSettingNumber,
TInt aControlType,
TInt aEditorResourceId,
TInt aSettingPageResourceId,
TInt& aSliderValue)
: CAknSliderSettingPage(
aSettingText,
aSettingNumber,
aControlType,
aEditorResourceId,
aSettingPageResourceId,
aSliderValue )
{
}
/**
* Destructor
*
*/
EXPORT_C CBCTestSliderSettingPage::~CBCTestSliderSettingPage()
{
}
EXPORT_C void CBCTestSliderSettingPage::UpdateSettingL()
{
CAknSliderSettingPage::UpdateSettingL();
}
EXPORT_C void CBCTestSliderSettingPage::AcceptSettingL()
{
CAknSliderSettingPage::AcceptSettingL();
}
EXPORT_C void CBCTestSliderSettingPage::RestoreOriginalSettingL()
{
CAknSliderSettingPage::RestoreOriginalSettingL();
}
EXPORT_C void CBCTestSliderSettingPage::SizeChanged()
{
CAknSliderSettingPage::SizeChanged();
}
EXPORT_C void CBCTestSliderSettingPage::Draw(const TRect &aRect) const
{
CAknSliderSettingPage::Draw( aRect );
}
/**
* Writes the internal state of the control and its components to aStream.
* Does nothing in release mode.
* Designed to be overidden and base called by subclasses.
*/
#ifndef _DEBUG
EXPORT_C void CBCTestSliderSettingPage::WriteInternalStateL(RWriteStream& /*aWriteStream*/) const
{}
#else
EXPORT_C void CBCTestSliderSettingPage::WriteInternalStateL(RWriteStream& aWriteStream) const
{
CAknSliderSettingPage::WriteInternalStateL(aWriteStream);
}
#endif
// End of File
| [
"none@none"
]
| [
[
[
1,
100
]
]
]
|
a0e35600c45227d69b3cb6647770d16856602fbc | 8ee26e92186ec132d621aca839c6828b53a642de | /Arduino_source-code/Bioreactor/ethernet.ino | 6962de0b94d997ccbab3a08d7062df943a46719b | []
| no_license | glocklueng/open-bioreactor | 7034b17777d6ce4a7e451d99b6474e320a35534e | 9aaacee9107c92084f6e9855ec9d8d3523490968 | refs/heads/master | 2016-09-09T22:24:06.303936 | 2011-12-16T13:01:48 | 2011-12-16T13:01:48 | 37,404,538 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,255 | ino | void ethernetSetup();
void ethernetSyncNTPTime();
unsigned long ethernetSendNTPpacket(byte *address);
void ethernetUpdateNTPTimeStamp();
unsigned long ethernetGetTimeStamp();
char * ethernetGetTimeStampChar();
void ethernetPushLog(char *logString);
void ethernetPushStatus();
void ethernetGetCommand();
/*
Web client
This sketch connects to a website (http://www.google.com)
using an Arduino Wiznet Ethernet shield.
Circuit:
* Ethernet shield attached to pins 10, 11, 12, 13
created 18 Dec 2009
by David A. Mellis
Udp NTP Client
Get the time from a Network Time Protocol (NTP) time server
Demonstrates use of UDP sendPacket and ReceivePacket
For more on NTP time servers and the messages needed to communicate with them,
see http://en.wikipedia.org/wiki/Network_Time_Protocol
created 4 Sep 2010
by Michael Margolis
modified 17 Sep 2010
by Tom Igoe
This code is in the public domain.
*/
#define MAX_HTTP_STRING_LENGTH 2048 // in bytes; max. http return string to read
// (reserve space for the http header !AND! the JSON command string)
#define MAX_COMMAND_STRING_LENGTH 400 // in bytes; max. JSON return string to read
// Enter a MAC address and IP address for the Arduino controller below.
// The IP address is reserved on the routher for this Arduino controller.
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
byte ip[] = {
10,0,0,3}; // reserved IP adress of the Arduino
// Parameters for the NTP clock
unsigned int localPort = 8888; // local port to listen for UDP packets
IPAddress server(10,0,0,2); // local NTP server
const int NTP_PACKET_SIZE= 48; // NTP time stamp is in the first 48 bytes of the message
byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets
unsigned long epoch = 0; // Unix time (starts on Jan 1 1970)
unsigned long epochTimeStampDiff = 0;
char timeStampCharBuffer[35]; // for the convertion of unsigned long into char of 'epoch'
char *pointerToTimeStampCharBuffer;
// A UDP instance to let us send and receive packets over UDP
EthernetUDP Udp;
// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;
void ethernetSetup()
{
// the ethernet pin has been initialized in the main setup() from Bioreactor
Ethernet.begin(mac,ip);
Udp.begin(localPort);
Serial.println("Ethernet successfully initialized.");
}
void ethernetSyncNTPTime()
{
epochTimeStampDiff = millis();
digitalWrite(PIN_SD_CARD,HIGH); // Disable SD card first (NEVER FORGET THIS!)
unsigned long duration = millis();
ethernetSendNTPpacket(server); // send an NTP packet to a time server
if ( Udp.parsePacket() )
{
// We've received a packet, read the data from it
Udp.read(packetBuffer,NTP_PACKET_SIZE); // read the packet into the buffer
//the timestamp starts at byte 40 of the received packet and is four bytes,
// or two words, long. First, esxtract the two words:
unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
// combine the four bytes (two words) into a long integer
// this is NTP time (seconds since Jan 1 1900):
unsigned long secsSince1900 = highWord << 16 | lowWord;
if(DEBUG)Serial.print("Seconds since Jan 1 1900 = " );
if(DEBUG)Serial.println(secsSince1900);
// now convert NTP time into everyday time:
if(DEBUG)Serial.print("Unix time = ");
// Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
const unsigned long seventyYears = 2208988800UL;
// subtract seventy years:
epoch = secsSince1900 - seventyYears;
// print Unix time:
Serial.println(epoch);
// print the hour, minute and second
if(DEBUG)
{
Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT)
Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day)
Serial.print(':');
if ( ((epoch % 3600) / 60) < 10 )
{
// In the first 10 minutes of each hour, we'll want a leading '0'
Serial.print('0');
}
Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute)
Serial.print(':');
if ( (epoch % 60) < 10 )
{
// In the first 10 seconds of each minute, we'll want a leading '0'
Serial.print('0');
}
Serial.println(epoch %60); // print the second
}
if(DEBUG)
{
duration = millis() - duration;
Serial.print("To get the NTP time stamp took: [ms]");
Serial.println(duration);
}
}
if(DEBUG)Serial.println("Time stamp updated.");
}
// send an NTP request to the time server at the given address
unsigned long ethernetSendNTPpacket(IPAddress& address)
{
// set all bytes in the buffer to 0
memset(packetBuffer, 0, NTP_PACKET_SIZE);
// Initialize values needed to form NTP request
// (see URL above for details on the packets)
packetBuffer[0] = 0b11100011; // LI, Version, Mode
packetBuffer[1] = 0; // Stratum, or type of clock
packetBuffer[2] = 6; // Polling Interval
packetBuffer[3] = 0xEC; // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
// all NTP fields have been given values, now
// you can send a packet requesting a timestamp:
if(DEBUG)Serial.print("Requesting NTP timestamp from server: ");
if(DEBUG)Serial.println(address);
Udp.beginPacket(address, 123); //NTP requests are to port 123
Udp.write(packetBuffer,NTP_PACKET_SIZE);
Udp.endPacket();
if(DEBUG)Serial.println("NTP timestamp sent to server.");
}
void ethernetUpdateNTPTimeStamp()
{
//this function is done for the case the NTP server is unreachable
//check if there is an overflow of the millis()
unsigned long now = millis();
if(now < epochTimeStampDiff)
{
epochTimeStampDiff = millis();
ethernetSyncNTPTime();
return;
// else: other solution: timer0_overflow_count = 0; // set timer0 that is used by millis to 0
}
epoch += (now-epochTimeStampDiff)/1000; // because epoch is in seconds and now in milliseconds
epochTimeStampDiff = now;
if(DEBUG)
{
Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT)
Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day)
Serial.print(':');
if ( ((epoch % 3600) / 60) < 10 )
{
// In the first 10 minutes of each hour, we'll want a leading '0'
Serial.print('0');
}
Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute)
Serial.print(':');
if ( (epoch % 60) < 10 )
{
// In the first 10 seconds of each minute, we'll want a leading '0'
Serial.print('0');
}
Serial.println(epoch %60); // print the second
}
}
unsigned long ethernetGetTimeStamp()
{
//first update the time stamp then return the new value
ethernetUpdateNTPTimeStamp();
return epoch;
}
char * ethernetGetTimeStampChar()
{
//first update the time stamp then return the new value
ethernetUpdateNTPTimeStamp();
pointerToTimeStampCharBuffer = ultoa(epoch, timeStampCharBuffer, 10);
if(DEBUG)
{
Serial.print("The converted epoch time (to char) is: ");
Serial.println(pointerToTimeStampCharBuffer);
}
return pointerToTimeStampCharBuffer;
}
void ethernetPushStatus()
{
digitalWrite(PIN_SD_CARD,HIGH); // Disable SD card first
//open a connection and try to print
if(DEBUG)Serial.println("PUSH STATUS: Connecting to server...");
ethernetOpenConnection80();
if (client.connected()) {
char pushUrl[50];
strcpy(pushUrl,"GET /bioReacTor/setStatus.php?");
char mode[3];
itoa(BIOREACTOR_MODE,mode,10);
strcat(pushUrl,mode);
strcat(pushUrl," HTTP/1.0\n\n");
if (DEBUG) Serial.print("Push URL: ");
if (DEBUG) Serial.println(pushUrl);
client.println(pushUrl);
if (DEBUG) Serial.println("The status has been pushed to the server.");
}
client.stop();
if (DEBUG) Serial.println("PUSH STATUS: Disconnected.");
}
void ethernetOpenConnection80() {
client.connect(server,80);
long start=millis();
while (! client.connected() && ((millis()-start)<500))
{
delay(1);
}
if (DEBUG) Serial.print("Connection achieved in (ms): ");
if (DEBUG) Serial.println(millis()-start);
}
void ethernetPushLog(char *logString)
{
digitalWrite(PIN_SD_CARD,HIGH); // Disable SD card first
//open a connection and try to print
if(DEBUG)Serial.println("PUSH LOG: Connecting to server...");
ethernetOpenConnection80();
if (client.connected()) {
char pushUrl[LOG_MAX_LENGTH+50];
strcpy(pushUrl,"GET /bioReacTor/add.php?");
strcat(pushUrl,logString);
strcat(pushUrl," HTTP/1.0\n\n");
if (DEBUG) Serial.print("Push URL: ");
if (DEBUG) Serial.println(pushUrl);
client.println(pushUrl);
if (DEBUG) Serial.println("The log has been pushed to the server.");
}
client.stop();
if (DEBUG) Serial.println("PUSH LOG: Disconnected.");
}
void ethernetGetCommand()
{
digitalWrite(PIN_SD_CARD,HIGH); // Disable SD card first
String jsonCommand = String(""); // reinitialize alocated string
//char jsonCommandBuffer[MAX_HTTP_STRING_LENGTH]; // reserve space
// if(DEBUG)Serial.print("String initialized has length of: ");
// if(DEBUG)Serial.println(sizeof(jsonCommand));
//open a connection and try to read the JSON command
if(DEBUG)Serial.println("Connecting to get newcommand...");
ethernetOpenConnection80();
// read the JSON object from the server and save it in a local String
// for more informations look up www.json.org
int jsonController = 0;
client.println("GET /bioReacTor/command HTTP/1.0\n"); //connect to the command page of the server
int STATUS=0; // the JSON didn't start yet
/* STATUS:
1 : the JSON started
2 : we get the field name
3 : we get the value
*/
long start=millis();
char fieldName[20];
char fieldValue[10];
while (client.connected() && ((millis()-start)<1000))
{
if (client.available()) {
char readChar = client.read();
// if(DEBUG) Serial.print(readChar);
switch(STATUS)
{
case 0:
if(readChar == '{') {
STATUS=1;
fieldName[0]='\0';
fieldValue[0]='\0';
}
break;
case 1: // we are receiving the fieldName
if(readChar == ':') {
STATUS=2;
}
else {
int len=strlen(fieldName);
fieldName[len] = readChar;
fieldName[len + 1] = '\0';
}
break;
case 2:
if(readChar == ',') {
ethernetParseCommandValue(fieldName, atof(fieldValue));
fieldName[0]='\0';
fieldValue[0]='\0';
STATUS=1;
}
else if (readChar == '}') {
ethernetParseCommandValue(fieldName, atof(fieldValue));
fieldName[0]='\0';
fieldValue[0]='\0';
STATUS=3;
}
else {
int len=strlen(fieldValue);
fieldValue[len] = readChar;
fieldValue[len + 1] = '\0';
}
break;
case 3:
break;
break;
default:
Serial.println("ERROR in fetching command");
}
}
} // end while
client.stop();
if (DEBUG) Serial.print("Received command file in (ms): ");
if (DEBUG) Serial.println(millis()-start);
}
void ethernetParseCommandValue(char *fieldName, double extractedValueFloat)
{
int extractedValueInt=(int)extractedValueFloat;
if (strcmp(fieldName,"liquidTemp")==0) {
// first check if there is a difference between the read value and the stored one
// (because floats are used, an error value of 0.05 has been set!)
if(HEATING_TEMPERATURE_LIMIT >= extractedValueFloat + 0.05 || HEATING_TEMPERATURE_LIMIT <= extractedValueFloat-0.05)
{
// check if the input value is valid, then save it
if(extractedValueFloat > HEATING_MAX_ALLOWED_LIMIT)
{
if(DEBUG)Serial.println("WARNING: The input temperature is to high! New temperature value has not been set.");
}
else if (extractedValueFloat < HEATING_MIN_ALLOWED_LIMIT)
{
if(DEBUG)Serial.println("WARNING: The input temperature is to low! New temperature value has not been set.");
}
else
{
HEATING_TEMPERATURE_LIMIT = extractedValueFloat;
if(DEBUG)Serial.print("The new temperature has been successfully set to: [C]");
if(DEBUG)Serial.println(HEATING_TEMPERATURE_LIMIT);
}
}
else if(DEBUG)Serial.println("The set temperature is the same as the saved one (deviation <0.05).");
}
else if (strcmp(fieldName,"liquidLevelMax")==0) {
if(extractedValueInt != LIQUID_LEVEL_WEB_MAX)
{
// check if the input value is valid, then save it
if(extractedValueInt > LIQUID_LEVEL_PHYSICAL_MAX_INTERVAL)
{
if(DEBUG)Serial.println("WARNING: The input liquid level is to high! New liquid value has not been set.");
}
else if (extractedValueInt < LIQUID_LEVEL_PHYSICAL_MIN_INTERVAL)
{
if(DEBUG)Serial.println("WARNING: The input liquid level negative! New liquid value has not been set.");
}
else
{
LIQUID_LEVEL_WEB_MAX = extractedValueInt;
if(DEBUG)Serial.print("The new liquid level has been successfully set to [Arduino AD interval]: ");
if(DEBUG)Serial.println(LIQUID_LEVEL_WEB_MAX);
}
}
else if(DEBUG)Serial.println("The set liquid level is the same as the saved one.");
}
else if (strcmp(fieldName,"liquidLevelMin")==0) {
if(extractedValueInt != LIQUID_LEVEL_WEB_MAX)
{
// check if the input value is valid, then save it
if(extractedValueInt > LIQUID_LEVEL_PHYSICAL_MAX_INTERVAL)
{
if(DEBUG)Serial.println("WARNING: The input liquid level is to high! New liquid value has not been set.");
}
else if (extractedValueInt < LIQUID_LEVEL_PHYSICAL_MIN_INTERVAL)
{
if(DEBUG)Serial.println("WARNING: The input liquid level negative! New liquid value has not been set.");
}
else
{
LIQUID_LEVEL_WEB_MIN = extractedValueInt;
if(DEBUG)Serial.print("The new liquid level has been successfully set to [Arduino AD interval]: ");
if(DEBUG)Serial.println(LIQUID_LEVEL_WEB_MIN);
}
}
else if(DEBUG)Serial.println("The set liquid level is the same as the saved one.");
}
else if (strcmp(fieldName,"pH")==0) {
// first check if there is a difference between the read value and the stored one
// (because floats are used, an error value of 0.05 has been set!)
if(pH_SET >= extractedValueFloat+0.05 || pH_SET <= extractedValueFloat-0.05)
{
// check if the input value is valid, then save it
if(extractedValueFloat > 14.0) // max pH level is 14
{
if(DEBUG)Serial.println("WARNING: The input pH level is to high! New pH value has not been set.");
}
else if (extractedValueFloat < 0.0) // min pH level is 0
{
if(DEBUG)Serial.println("WARNING: The input pH level negative! New pH value has not been set.");
}
else
{
pH_SET = extractedValueFloat;
if(DEBUG)Serial.print("The new pH level has been successfully set to: ");
if(DEBUG)Serial.println(pH_SET);
}
}
else if(DEBUG)Serial.println("The set temperature is the same as the saved one (deviation <0.05).");
}
else if (strcmp(fieldName,"waitTime")==0) {
// Value read from WebUI is in min; the timer uses millisec!
if(extractedValueInt != WAIT_TIME_BEFORE_PUMPING_OUT)
{
// check if the input value is valid, then save it
if(extractedValueInt * MIN_TO_SEC > WAIT_TIME_BEFORE_PUMPING_OUT_MAX) // min und max values in [sec]!
{
if(DEBUG)Serial.print("WARNING: The Wait Time is to high! Maximum allowed Wait Time is [sec]:");
if(DEBUG)Serial.println(WAIT_TIME_BEFORE_PUMPING_OUT_MAX);
}
else if (extractedValueInt * MIN_TO_SEC < WAIT_TIME_BEFORE_PUMPING_OUT_MIN)
{
if(DEBUG)Serial.print("WARNING: The Wait Time is to low! Minimum allowed Wait Time is [sec]:");
if(DEBUG)Serial.println(WAIT_TIME_BEFORE_PUMPING_OUT_MIN);
}
else
{
WAIT_TIME_BEFORE_PUMPING_OUT = extractedValueInt; //in [min]
PUMPING_OUT_TIMER = WAIT_TIME_BEFORE_PUMPING_OUT * MIN_TO_SEC * SEC_TO_MILLISEC; // in [millisec]
timerPumpingOut.setInterval(PUMPING_OUT_TIMER);
if(DEBUG)Serial.print("The new Wait Time has been successfully set to [millisec]: ");
if(DEBUG)Serial.println(PUMPING_OUT_TIMER);
}
}
else if(DEBUG)Serial.println("The Wait Time is the same as the saved one.");
}
else if (strcmp(fieldName,"methaneIn")==0)
{
// values for auto-switching mode can be changed in any mode but the error-mode
if(BIOREACTOR_MODE != BIOREACTOR_ERROR_MODE)
{
// first check if there is a difference between the read value and the stored one
if(extractedValueInt != gasValvesGetAutoSwitchInterval(CH4))
{
gasValvesSetAutoSwitchInterval(CH4, extractedValueInt);
gasValvesAutoSwitchMode(CH4);
if(DEBUG)Serial.println("CH4 value's auto-switching parameter has been changed.");
// check if the input value is valid, then save it
if(extractedValueInt > 100 && extractedValueInt < 0 )// min. value is 0% max. value is 100%
{
Serial.print("WARNING: CH4 value's auto-switching parameter is invalid!. ");
Serial.println("It has been corrected to fit the min. [0] and max. [100] allowed values.");
}
}
else if(DEBUG)Serial.println("CH4 value's auto-switching parameter is the same as the saved one.");
}
else if(DEBUG) Serial.println("WARNING: In ERROR-MODE: CH4 value has not been switched to auto-switching mode");
}
else if (strcmp(fieldName,"carbonDioxideIn")==0)
{
// values for auto-switching mode can be changed in any mode but the error-mode
if(BIOREACTOR_MODE != BIOREACTOR_ERROR_MODE)
{
// first check if there is a difference between the read value and the stored one
if(extractedValueInt != gasValvesGetAutoSwitchInterval(CO2))
{
gasValvesSetAutoSwitchInterval(CO2, extractedValueInt);
gasValvesAutoSwitchMode(CO2);
if(DEBUG)Serial.println("CO2 value's auto-switching parameter has been changed.");
// check if the input value is valid, then save it
if(extractedValueInt > 100 && extractedValueInt < 0 )// min. value is 0% max. value is 100%
{
Serial.print("WARNING: CO2 value's auto-switching parameter is invalid!. ");
Serial.println("It has been corrected to fit the min. [0] and max. [100] allowed values.");
}
}
else if(DEBUG)Serial.println("CO2 value's auto-switching parameter is the same as the saved one.");
}
else if(DEBUG) Serial.println("WARNING: In ERROR-MODE: CO2 value has not been switched to auto-switching mode");
}
else if (strcmp(fieldName,"nitrogenIn")==0)
{
// values for auto-switching mode can be changed in any mode but the error-mode
if(BIOREACTOR_MODE != BIOREACTOR_ERROR_MODE)
{
// first check if there is a difference between the read value and the stored one
if(extractedValueInt != gasValvesGetAutoSwitchInterval(N2))
{
gasValvesSetAutoSwitchInterval(N2, extractedValueInt);
gasValvesAutoSwitchMode(N2);
if(DEBUG)Serial.println("N2 value's auto-switching parameter has been changed.");
// check if the input value is valid, then save it
if(extractedValueInt > 100 && extractedValueInt < 0 )// min. value is 0% max. value is 100%
{
Serial.print("WARNING: N2 value's auto-switching parameter is invalid!. ");
Serial.println("It has been corrected to fit the min. [0] and max. [100] allowed values.");
}
}
else if(DEBUG)Serial.println("N2 value's auto-switching parameter is the same as the saved one.");
}
else if(DEBUG) Serial.println("WARNING: In ERROR-MODE: N2 value has not been switched to auto-switching mode");
}
else if (strcmp(fieldName,"liquidIn")==0)
{
}
else if (strcmp(fieldName,"liquidOut")==0)
{
}
else if (strcmp(fieldName,"mode")==0) {
// first check if there is a difference between the read value and the stored one
// then check if in pumping mode; ONLY change from pumping mode if MANUAL mode is selected
if(extractedValueInt != BIOREACTOR_MODE
&& (BIOREACTOR_MODE != BIOREACTOR_PUMPING_MODE
|| (BIOREACTOR_MODE == BIOREACTOR_PUMPING_MODE && extractedValueInt == BIOREACTOR_MANUAL_MODE)))
{
// check if the input value is valid, then save it
if(extractedValueInt == BIOREACTOR_STANDBY_MODE
|| extractedValueInt == BIOREACTOR_RUNNING_MODE
|| extractedValueInt == BIOREACTOR_MANUAL_MODE)
{
//switch Bioreactor mode
BIOREACTOR_MODE = extractedValueInt;
if(DEBUG)Serial.print("The Bioreactor has been set to a new state: ");
if(DEBUG)Serial.println(BIOREACTOR_MODE);
}
else
{
if(DEBUG)Serial.print("WARNING: The Bioreactor state is invalid!. The state is: ");
if(DEBUG)Serial.println(extractedValueInt);
}
}
else if(DEBUG)Serial.println("The Bioreactor state is the same as the saved one.");
}
else if (strcmp(fieldName,"pumpOut")==0) {
//---------Set pumpOut state ----------
// only get the pump's state if in MANUAL mode
if(BIOREACTOR_MODE == BIOREACTOR_MANUAL_MODE)
{
// first check if there is a difference between the read value and the stored one
if(extractedValueInt != relaySwitchPumpOutGetState())
{
// check if the input value is valid, then save it
if(extractedValueInt == 1 || extractedValueInt == 0 )
{
//turn ON or OFF
if(extractedValueInt == 1) relaySwitchPumpOutTurnOn();
else relaySwitchPumpOutTurnOff(); // if extractedValueInt = 0
if(DEBUG)Serial.println("PumpOut has been set to a new state.");
}
else
{
if(DEBUG)Serial.println("WARNING: PumpOut state is invalid!.");
}
}
else if(DEBUG)Serial.println("PumpOut state is the same as the saved one.");
}
else if(DEBUG) Serial.println("Not in MANUAL mode: PumpOut's value not taken");
}
else if (strcmp(fieldName,"pumpIn")==0) {
//---------Set pumpIn state ----------
// only get the pump's state if in MANUAL mode
if(BIOREACTOR_MODE == BIOREACTOR_MANUAL_MODE)
{
// first check if there is a difference between the read value and the stored one
if(extractedValueInt != relaySwitchPumpInGetState())
{
// check if the input value is valid, then save it
if(extractedValueInt == 1 || extractedValueInt == 0 )
{
//turn ON or OFF
if(extractedValueInt == 1) relaySwitchPumpInTurnOn();
else relaySwitchPumpInTurnOff(); // if extractedValueInt = 0
if(DEBUG)Serial.println("PumpIn has been set to a new state.");
}
else
{
if(DEBUG)Serial.println("WARNING: PumpIn state is invalid!.");
}
}
else if(DEBUG)Serial.println("PumpIn state is the same as the saved one.");
}
else if(DEBUG) Serial.println("Not in MANUAL mode: PumpIn's value not taken");
}
else if (strcmp(fieldName,"motor")==0) {
//---------Set motor state ----------
// only get the motor's state if in MANUAL mode
if(BIOREACTOR_MODE == BIOREACTOR_MANUAL_MODE)
{
// first check if there is a difference between the read value and the stored one
if(extractedValueInt != relaySwitchMotorGetState())
{
// check if the input value is valid, then save it
if(extractedValueInt == 1 || extractedValueInt == 0 )
{
//turn ON or OFF
if(extractedValueInt == 1) relaySwitchMotorTurnOn();
else relaySwitchMotorTurnOff(); // if extractedValueInt = 0
if(DEBUG)Serial.println("The motor has been set to a new state.");
}
else
{
if(DEBUG)Serial.println("WARNING: The motor state is invalid!.");
}
}
else if(DEBUG)Serial.println("The motor state is the same as the saved one.");
}
else if(DEBUG) Serial.println("Not in MANUAL mode: Motor's value not taken");
}
// else if (strcmp(fieldName,"methane")==0) {
// //---------Set gas valve (methane) state ----------
// // only get the pump's state if in MANUAL mode
// if(BIOREACTOR_MODE == BIOREACTOR_MANUAL_MODE)
// {
//
// // first check if there is a difference between the read value and the stored one
// if(extractedValueInt != gasValvesGetState(CH4))
// {
// // check if the input value is valid, then save it
// if(extractedValueInt == 1 || extractedValueInt == 0 )
// {
// //turn ON or OFF
// if(extractedValueInt == 1) gasValvesTurnOn(CH4);
// else gasValvesTurnOff(CH4); // if extractedValueInt = 0
// if(DEBUG)Serial.println("The gas valve (methane) has been set to a new state.");
// }
// else
// {
// if(DEBUG)Serial.println("WARNING: The gas valve (methane) state is invalid!.");
// }
// }
// else if(DEBUG)Serial.println("The gas valve (methane) state is the same as the saved one.");
// }
// else if(DEBUG) Serial.println("Not in MANUAL mode: Gas valve's value not taken");
//
// }
// else if (strcmp(fieldName,"carbonDioxide")==0) {
// //---------Set gas valve (carbonDioxide) state ----------
// // only get the pump's state if in MANUAL mode
// if(BIOREACTOR_MODE == BIOREACTOR_MANUAL_MODE)
// {
// // first check if there is a difference between the read value and the stored one
// if(extractedValueInt != gasValvesGetState(CO2))
// {
// // check if the input value is valid, then save it
// if(extractedValueInt == 1 || extractedValueInt == 0 )
// {
// //turn ON or OFF
// if(extractedValueInt == 1) gasValvesTurnOn(CO2);
// else gasValvesTurnOff(CO2); // if extractedValueInt = 0
// if(DEBUG)Serial.println("The gas valve (carbonDioxide) has been set to a new state.");
// }
// else
// {
// if(DEBUG)Serial.println("WARNING: The gas valve (carbonDioxide) state is invalid!.");
// }
// }
//
//
//
// }
// else if(DEBUG) Serial.println("Not in MANUAL mode: Gas valve's value not taken");
//
// }
// else if (strcmp(fieldName,"nitrogen")==0) {
//
// //---------Set gas valve (nitrogen) state ----------
// // only get the pump's state if in MANUAL mode
// if(BIOREACTOR_MODE == BIOREACTOR_MANUAL_MODE)
// {
//
// // first check if there is a difference between the read value and the stored one
// if(extractedValueInt != gasValvesGetState(N2))
// {
// // check if the input value is valid, then save it
// if(extractedValueInt == 1 || extractedValueInt == 0 )
// {
// //turn ON or OFF
// if(extractedValueInt == 1) gasValvesTurnOn(N2);
// else gasValvesTurnOff(N2); // if extractedValueInt = 0
// if(DEBUG)Serial.println("The gas valve (nitrogen) has been set to a new state.");
// }
// else
// {
// if(DEBUG)Serial.println("WARNING: The gas valve (nitrogen) state is invalid!.");
// }
// }
// else if(DEBUG)Serial.println("The gas valve (nitrogen) state is the same as the saved one.");
//
//
// }
//
// else if(DEBUG) Serial.println("Not in MANUAL mode: Gas valve's value not taken");
//
//
// }
}
| [
"[email protected]",
"lpatiny@a9341e05-f52e-d854-dc2e-c3bc20106509",
"[email protected]"
]
| [
[
[
1,
6
],
[
9,
48
],
[
53,
80
],
[
82,
87
],
[
89,
91
],
[
94,
94
],
[
96,
126
],
[
129,
129
],
[
138,
149
],
[
151,
178
],
[
181,
194
],
[
196,
196
],
[
198,
201
],
[
208,
209
],
[
215,
216
],
[
220,
220
],
[
222,
236
],
[
245,
245
],
[
247,
248
],
[
250,
252
],
[
278,
280
],
[
291,
291
],
[
303,
304
],
[
306,
312
],
[
315,
316
],
[
319,
323
],
[
336,
336
],
[
338,
338
],
[
343,
343
],
[
349,
349
],
[
386,
387
],
[
389,
389
],
[
392,
393
],
[
395,
396
],
[
404,
404
],
[
407,
407
],
[
419,
420
],
[
423,
425
],
[
427,
428
],
[
431,
431
],
[
437,
446
],
[
448,
463
],
[
487,
487
],
[
490,
492
],
[
494,
514
],
[
537,
538
],
[
561,
561
],
[
585,
585
],
[
607,
608
],
[
618,
619
],
[
681,
683
],
[
689,
689
],
[
694,
694
],
[
696,
696
],
[
698,
698
],
[
703,
703
],
[
794,
799
],
[
802,
807
],
[
813,
813
]
],
[
[
7,
8
],
[
49,
52
],
[
88,
88
],
[
92,
93
],
[
95,
95
],
[
127,
128
],
[
130,
137
],
[
150,
150
],
[
179,
180
],
[
195,
195
],
[
197,
197
],
[
202,
207
],
[
210,
214
],
[
217,
219
],
[
221,
221
],
[
237,
244
],
[
246,
246
],
[
249,
249
],
[
253,
277
],
[
281,
290
],
[
292,
302
],
[
305,
305
],
[
313,
314
],
[
317,
318
],
[
324,
335
],
[
337,
337
],
[
339,
342
],
[
344,
348
],
[
350,
385
],
[
388,
388
],
[
390,
391
],
[
394,
394
],
[
397,
403
],
[
406,
406
],
[
408,
418
],
[
421,
422
],
[
429,
430
],
[
432,
436
],
[
464,
469
],
[
471,
486
],
[
488,
489
],
[
539,
539
],
[
562,
562
],
[
587,
587
],
[
591,
591
],
[
595,
602
],
[
604,
606
],
[
609,
615
],
[
620,
622
],
[
676,
676
],
[
679,
680
],
[
684,
686
],
[
688,
688
],
[
690,
693
],
[
695,
695
],
[
697,
697
],
[
699,
702
],
[
704,
705
],
[
793,
793
],
[
800,
801
],
[
808,
812
]
],
[
[
81,
81
],
[
405,
405
],
[
426,
426
],
[
447,
447
],
[
470,
470
],
[
493,
493
],
[
515,
536
],
[
540,
560
],
[
563,
584
],
[
586,
586
],
[
588,
590
],
[
592,
594
],
[
603,
603
],
[
616,
617
],
[
623,
675
],
[
677,
678
],
[
687,
687
],
[
706,
792
]
]
]
|
555e2004b920cc88f18a55621f6f69a7843927cb | 2e8adfe9e0e8e6bceb7f7b20c73a66ddddc2b60e | /ThorMainComponent.h | 700255f2c2415e5eace97922959749d8792eb2a6 | []
| no_license | j3LLostyL3Z/thor-v2 | ee898f9e11023b40e0100f16150fe026dd863f24 | c4555a347a7f833780bc0b65f039397f3787a4c2 | refs/heads/master | 2021-01-10T10:25:51.677372 | 2009-02-06T12:32:34 | 2009-02-06T12:32:34 | 49,520,120 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,301 | h | /*
==============================================================================
This is an automatically generated file created by the Jucer!
Creation date: 12 May 2008 2:04:09 pm
Be careful when adding custom code to these files, as only the code within
the "//[xyz]" and "//[/xyz]" sections will be retained when the file is loaded
and re-saved.
Jucer version: 1.11
------------------------------------------------------------------------------
The Jucer is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-6 by Raw Material Software ltd.
==============================================================================
*/
#ifndef __JUCER_HEADER_THORMAINCOMPONENT_THORMAINCOMPONENT_D485A84D__
#define __JUCER_HEADER_THORMAINCOMPONENT_THORMAINCOMPONENT_D485A84D__
//[Headers] -- You can add your own extra header files here --
#include "juce.h"
#include "ThorWorkerThread.h"
#include "ThorConfig.h"
#include "ThorConfigDialog.h"
#include "ThorUpdateThread.h"
//[/Headers]
//==============================================================================
/**
//[Comments]
An auto-generated component, created by the Jucer.
Describe your class and how it works here!
//[/Comments]
*/
class ThorMainComponent : public Component,
public FileDragAndDropTarget,
public ChangeListener,
public ButtonListener
{
public:
//==============================================================================
ThorMainComponent (ThorConfig *_config);
~ThorMainComponent();
//==============================================================================
//[UserMethods] -- You can add your own custom methods in this section.
void mouseDown (const MouseEvent& e);
void mouseDrag (const MouseEvent& e);
bool isInterestedInFileDrag (const StringArray &files);
void fileDragEnter (const StringArray &files, int x, int y);
void fileDragMove (const StringArray &files, int x, int y);
void fileDragExit (const StringArray &files);
void filesDropped (const StringArray &files, int x, int y);
bool isZip (const File f);
bool isCompressedAudio (const File f);
bool isUncompressedAudio (const File f);
void changeListenerCallback(void *ptr);
//[/UserMethods]
void paint (Graphics& g);
void resized();
void buttonClicked (Button* buttonThatWasClicked);
// Binary resources:
static const char* bg_png;
static const int bg_pngSize;
static const char* help_png;
static const int help_pngSize;
static const char* burn_png;
static const int burn_pngSize;
static const char* options_png;
static const int options_pngSize;
static const char* news_item_pic_png;
static const int news_item_pic_pngSize;
static const char* processstop_png;
static const int processstop_pngSize;
//==============================================================================
juce_UseDebuggingNewOperator
private:
//[UserVariables] -- You can add your own custom variables in this section.
ComponentDragger myDragger;
Image *optionsImage;
Image *leftImage;
Image *rightImage;
Image *exitImage;
Image *helpImage;
Image *splashImage;
ProgressBar *thorProgressBar;
double progressVar;
ThorWorkerThread *worker;
int thorMode;
ThorConfig *config;
TooltipWindow tooltipWindow;
ThorConfigDialog *configDialog;
ThorUpdateThread *updateThread;
//[/UserVariables]
//==============================================================================
Label* thorDebug;
ImageButton* thorStop;
Label* thorDetails;
Image* internalCachedImage1;
//==============================================================================
// (prevent copy constructor and operator= being generated..)
ThorMainComponent (const ThorMainComponent&);
const ThorMainComponent& operator= (const ThorMainComponent&);
};
#endif // __JUCER_HEADER_THORMAINCOMPONENT_THORMAINCOMPONENT_D485A84D__
| [
"kubiak.roman@f386313e-e04c-0410-8915-733321d37a57"
]
| [
[
[
1,
123
]
]
]
|
1ec6124170e0f394b96f79c3f70ccd8a97655abd | b3b0c727bbafdb33619dedb0b61b6419692e03d3 | /Source/CppUnitTest/Test/SampleTestCalc.h | e3b131052dc4edfd46cfac5d78a2b0e3044fa48d | []
| no_license | testzzzz/hwccnet | 5b8fb8be799a42ef84d261e74ee6f91ecba96b1d | 4dbb1d1a5d8b4143e8c7e2f1537908cb9bb98113 | refs/heads/master | 2021-01-10T02:59:32.527961 | 2009-11-04T03:39:39 | 2009-11-04T03:39:39 | 45,688,112 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 1,649 | h | //////////////////////////////////////////////////////////
///
/// @file SampleTestCalc.h
///
/// @brief 利用CppUnit测试ICalculator接口
///
/// @version 1.0
///
/// @author 甘先志
///
/// @date 2009-07-22
///
//////////////////////////////////////////////////////////
#include <cppunit/extensions/HelperMacros.h>
#ifndef CPP_UNIT_SAMPLETESTCLAC_H
#define CPP_UNIT_SAMPLETESTCLAC_H
#include "LWCalculator_i.h"
#ifdef _DEBUG
# pragma comment(lib, "cppunitd.lib")
# pragma comment(lib, "testrunnerd.lib")
#else
# pragma comment(lib, "testrunner.lib")
# pragma comment(lib, "cppunit.lib")
#endif
/////////////////////////////////////////////////////////
///
/// @brief 定义测试类
///
/// 基类为cppunit的TestFixture
///
/////////////////////////////////////////////////////////
class CSampleTestCalc : public CPPUNIT_NS::TestFixture
{
/// @brief 添加一个TestCase到一个TestSuite
CPPUNIT_TEST_SUITE( CSampleTestCalc );
/// @brief 添加测试(InitiCominterface)
CPPUNIT_TEST( InitiCominterface );
/// @brief 添加测试( TestDataIn )
CPPUNIT_TEST( TestDataIn );
CPPUNIT_TEST_SUITE_END();
public:
CSampleTestCalc(void);
~CSampleTestCalc(void);
/// @brief 初始化com接口
/// @param void
/// @retval void
void InitiCominterface(void);
/// @brief 进行数据输入和结果测试
/// @param void
/// @retval void
void TestDataIn(void);
private:
/// @param 获取接口指针
ICalculator* pCalc;
/// @var 获取计算结果
long lResult;
};
#endif | [
"[email protected]"
]
| [
[
[
1,
61
]
]
]
|
31675fe4cca94496bd582eda8c7f052ba5c32a2b | b2155efef00dbb04ae7a23e749955f5ec47afb5a | /source/OEUI/OEUIRenderSystem_Impl.cpp | 85243aad8dce6bd460cc1ac01d58319e5f17d60c | []
| no_license | zjhlogo/originengine | 00c0bd3c38a634b4c96394e3f8eece86f2fe8351 | a35a83ed3f49f6aeeab5c3651ce12b5c5a43058f | refs/heads/master | 2021-01-20T13:48:48.015940 | 2011-04-21T04:10:54 | 2011-04-21T04:10:54 | 32,371,356 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,677 | cpp | /*!
* \file OEUIRenderSystem_Impl.cpp
* \date 19-2-2010 19:53:01
*
*
* \author zjhlogo ([email protected])
*/
#include "OEUIRenderSystem_Impl.h"
#include <OECore/IOEShaderMgr.h>
#include <OECore/IOEDevice.h>
#include <OEBase/IOEMsgMgr.h>
#include <libOEMsg/OEMsgList.h>
#include <assert.h>
COEUIRenderSystem_Impl::COEUIRenderSystem_Impl()
{
assert(!g_pOEUIRenderSystem);
g_pOEUIRenderSystem = this;
m_bOK = Init();
}
COEUIRenderSystem_Impl::~COEUIRenderSystem_Impl()
{
Destroy();
g_pOEUIRenderSystem = NULL;
}
bool COEUIRenderSystem_Impl::Init()
{
m_pTexture = NULL;
m_pShader = NULL;
memset(m_pSolidVertsCache, 0, sizeof(m_pSolidVertsCache));
memset(m_pTransparentVertsCache, 0, sizeof(m_pTransparentVertsCache));
m_pScreen = NULL;
m_fCurrDepth = 1.0f;
return true;
}
void COEUIRenderSystem_Impl::Destroy()
{
// TODO:
}
bool COEUIRenderSystem_Impl::Initialize()
{
m_pShader = g_pOEShaderMgr->CreateDefaultShader(DST_POLY_UI);
if (!m_pShader) return false;
for (int i = 0; i < NUM_SOLID_CACHE; ++i)
{
m_pSolidVertsCache[i] = new COEUIVertexCache(SOLID_VERTEX_CACHE, SOLID_INDEX_CACHE);
if (!m_pSolidVertsCache[i] || !m_pSolidVertsCache[i]->IsOK()) return false;
}
for (int i = 0; i < NUM_TRANSPARENT_CACHE; ++i)
{
m_pTransparentVertsCache[i] = new COEUIVertexCache(TRANSPARENT_VERTEX_CACHE, TRANSPARENT_INDEX_CACHE);
if (!m_pTransparentVertsCache[i] || !m_pTransparentVertsCache[i]->IsOK()) return false;
}
m_pScreen = new COEUIScreen();
if (!m_pScreen || !m_pScreen->IsOK()) return false;
g_pOEDevice->RegisterEvent(OMI_UI_UPDATE, this, (MSG_FUNC)&COEUIRenderSystem_Impl::OnUpdate);
g_pOEDevice->RegisterEvent(OMI_UI_RENDER, this, (MSG_FUNC)&COEUIRenderSystem_Impl::OnRender);
g_pOEDevice->RegisterEvent(OMI_UI_POST_RENDER, this, (MSG_FUNC)&COEUIRenderSystem_Impl::OnPostRender);
return true;
}
void COEUIRenderSystem_Impl::Terminate()
{
SAFE_RELEASE(m_pScreen);
SAFE_RELEASE(m_pShader);
for (int i = 0; i < NUM_TRANSPARENT_CACHE; ++i)
{
SAFE_DELETE(m_pTransparentVertsCache[i]);
}
for (int i = 0; i < NUM_SOLID_CACHE; ++i)
{
SAFE_DELETE(m_pSolidVertsCache[i]);
}
}
COEUIScreen* COEUIRenderSystem_Impl::GetScreen()
{
return m_pScreen;
}
void COEUIRenderSystem_Impl::SetTexture(IOETexture* pTexture)
{
m_pTexture = pTexture;
}
IOETexture* COEUIRenderSystem_Impl::GetTexture() const
{
return m_pTexture;
}
void COEUIRenderSystem_Impl::DrawSolidTriList(const void* pVerts, uint nVerts, const ushort* pIndis, uint nIndis)
{
COEUIVertexCache* pEmptyCache = NULL;
COEUIVertexCache* pMatchCache = NULL;
for (int i = 0; i < NUM_SOLID_CACHE; ++i)
{
if (m_pSolidVertsCache[i]->Compare(m_pTexture, m_pShader))
{
pMatchCache = m_pSolidVertsCache[i];
break;
}
if (!pEmptyCache && m_pSolidVertsCache[i]->GetVertsCount() == 0)
{
pEmptyCache = m_pSolidVertsCache[i];
}
}
if (pMatchCache)
{
if (!pMatchCache->AddVerts(pVerts, nVerts, pIndis, nIndis))
{
pMatchCache->Flush();
bool bOK = pMatchCache->AddVerts(pVerts, nVerts, pIndis, nIndis);
assert(bOK);
}
}
else if (pEmptyCache)
{
pEmptyCache->SetTexture(m_pTexture);
pEmptyCache->SetShader(m_pShader);
bool bOK = pEmptyCache->AddVerts(pVerts, nVerts, pIndis, nIndis);
assert(bOK);
}
else
{
assert(false);
}
}
void COEUIRenderSystem_Impl::DrawTransparentTriList(const void* pVerts, uint nVerts, const ushort* pIndis, uint nIndis)
{
COEUIVertexCache* pEmptyCache = NULL;
COEUIVertexCache* pMatchCache = NULL;
for (int i = 0; i < NUM_TRANSPARENT_CACHE; ++i)
{
if (m_pTransparentVertsCache[i]->Compare(m_pTexture, m_pShader))
{
pMatchCache = m_pTransparentVertsCache[i];
break;
}
if (!pEmptyCache && m_pTransparentVertsCache[i]->GetVertsCount() == 0)
{
pEmptyCache = m_pTransparentVertsCache[i];
}
}
if (pMatchCache)
{
if (!pMatchCache->AddVerts(pVerts, nVerts, pIndis, nIndis))
{
FlushSolid();
pMatchCache->Flush();
bool bOK = pMatchCache->AddVerts(pVerts, nVerts, pIndis, nIndis);
assert(bOK);
}
}
else if (pEmptyCache)
{
pEmptyCache->SetTexture(m_pTexture);
pEmptyCache->SetShader(m_pShader);
bool bOK = pEmptyCache->AddVerts(pVerts, nVerts, pIndis, nIndis);
assert(bOK);
}
else
{
assert(false);
}
}
float COEUIRenderSystem_Impl::NextDepth()
{
float fLastDepth = m_fCurrDepth;
m_fCurrDepth -= COEMath::TOL;
return fLastDepth;
}
void COEUIRenderSystem_Impl::FlushSolid()
{
for (int i = 0; i < NUM_SOLID_CACHE; ++i)
{
m_pSolidVertsCache[i]->Flush();
m_pSolidVertsCache[i]->SetTexture(NULL);
m_pSolidVertsCache[i]->SetShader(NULL);
}
}
void COEUIRenderSystem_Impl::FlushTransparent()
{
for (int i = 0; i < NUM_TRANSPARENT_CACHE; ++i)
{
m_pTransparentVertsCache[i]->Flush();
m_pTransparentVertsCache[i]->SetTexture(NULL);
m_pTransparentVertsCache[i]->SetShader(NULL);
}
}
void COEUIRenderSystem_Impl::FlushAll()
{
FlushSolid();
FlushTransparent();
}
bool COEUIRenderSystem_Impl::OnUpdate(COEMsgCommand& msg)
{
float fDetailTime = g_pOEDevice->GetDetailTime();
m_pScreen->Update(fDetailTime);
m_pScreen->UpdateChildren(fDetailTime);
return true;
}
bool COEUIRenderSystem_Impl::OnRender(COEMsgCommand& msg)
{
float fDetailTime = g_pOEDevice->GetDetailTime();
m_pScreen->Render(fDetailTime);
m_pScreen->RenderChildren(fDetailTime);
return true;
}
bool COEUIRenderSystem_Impl::OnPostRender(COEMsgCommand& msg)
{
FlushAll();
m_fCurrDepth = 1.0f;
return true;
}
| [
"zjhlogo@fdcc8808-487c-11de-a4f5-9d9bc3506571"
]
| [
[
[
1,
242
]
]
]
|
5a907adc496c18f8a66e5bc34802b2a4c62d54b3 | cd0987589d3815de1dea8529a7705caac479e7e9 | /webkit/WebKit/win/WebCoreSupport/WebChromeClient.h | 53d2985c4d238f65ebd8ff308c59024b40961ec2 | [
"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,005 | h | /*
* Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
*
* 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 <WebCore/ChromeClient.h>
#include <WebCore/COMPtr.h>
#include <WebCore/GraphicsContext.h>
#include <WebCore/FocusDirection.h>
#include <WebCore/ScrollTypes.h>
#include <wtf/Forward.h>
#include <wtf/PassRefPtr.h>
class WebView;
class WebDesktopNotificationsDelegate;
interface IWebUIDelegate;
class WebChromeClient : public WebCore::ChromeClient {
public:
WebChromeClient(WebView*);
virtual void chromeDestroyed();
virtual void setWindowRect(const WebCore::FloatRect&);
virtual WebCore::FloatRect windowRect();
virtual WebCore::FloatRect pageRect();
virtual float scaleFactor();
virtual void focus();
virtual void unfocus();
virtual bool canTakeFocus(WebCore::FocusDirection);
virtual void takeFocus(WebCore::FocusDirection);
virtual void focusedNodeChanged(WebCore::Node*);
virtual WebCore::Page* createWindow(WebCore::Frame*, const WebCore::FrameLoadRequest&, const WebCore::WindowFeatures&);
virtual void show();
virtual bool canRunModal();
virtual void runModal();
virtual void setToolbarsVisible(bool);
virtual bool toolbarsVisible();
virtual void setStatusbarVisible(bool);
virtual bool statusbarVisible();
virtual void setScrollbarsVisible(bool);
virtual bool scrollbarsVisible();
virtual void setMenubarVisible(bool);
virtual bool menubarVisible();
virtual void setResizable(bool);
virtual void addMessageToConsole(WebCore::MessageSource source, WebCore::MessageType type, WebCore::MessageLevel level, const WTF::String& message, unsigned line, const WTF::String& url);
virtual bool canRunBeforeUnloadConfirmPanel();
virtual bool runBeforeUnloadConfirmPanel(const WTF::String& message, WebCore::Frame* frame);
virtual void closeWindowSoon();
virtual void runJavaScriptAlert(WebCore::Frame*, const WTF::String&);
virtual bool runJavaScriptConfirm(WebCore::Frame*, const WTF::String&);
virtual bool runJavaScriptPrompt(WebCore::Frame*, const WTF::String& message, const WTF::String& defaultValue, WTF::String& result);
virtual void setStatusbarText(const WTF::String&);
virtual bool shouldInterruptJavaScript();
virtual bool tabsToLinks() const;
virtual WebCore::IntRect windowResizerRect() const;
virtual void invalidateWindow(const WebCore::IntRect&, bool);
virtual void invalidateContentsAndWindow(const WebCore::IntRect&, bool);
virtual void invalidateContentsForSlowScroll(const WebCore::IntRect&, bool);
virtual void scroll(const WebCore::IntSize& scrollDelta, const WebCore::IntRect& rectToScroll, const WebCore::IntRect& clipRect);
virtual WebCore::IntPoint screenToWindow(const WebCore::IntPoint& p) const;
virtual WebCore::IntRect windowToScreen(const WebCore::IntRect& r) const;
virtual PlatformPageClient platformPageClient() const;
virtual void contentsSizeChanged(WebCore::Frame*, const WebCore::IntSize&) const;
virtual void scrollbarsModeDidChange() const { }
virtual void mouseDidMoveOverElement(const WebCore::HitTestResult&, unsigned modifierFlags);
virtual bool shouldMissingPluginMessageBeButton() const;
virtual void missingPluginButtonClicked(WebCore::Element*) const;
virtual void setToolTip(const WTF::String&, WebCore::TextDirection);
virtual void print(WebCore::Frame*);
#if ENABLE(DATABASE)
virtual void exceededDatabaseQuota(WebCore::Frame*, const WTF::String&);
#endif
#if ENABLE(OFFLINE_WEB_APPLICATIONS)
virtual void reachedMaxAppCacheSize(int64_t spaceNeeded);
virtual void reachedApplicationCacheOriginQuota(WebCore::SecurityOrigin*);
#endif
virtual void populateVisitedLinks();
virtual bool paintCustomScrollbar(WebCore::GraphicsContext*, const WebCore::FloatRect&, WebCore::ScrollbarControlSize,
WebCore::ScrollbarControlState, WebCore::ScrollbarPart pressedPart, bool vertical,
float value, float proportion, WebCore::ScrollbarControlPartMask);
virtual bool paintCustomScrollCorner(WebCore::GraphicsContext*, const WebCore::FloatRect&);
virtual void runOpenPanel(WebCore::Frame*, PassRefPtr<WebCore::FileChooser>);
virtual void chooseIconForFiles(const Vector<WTF::String>&, WebCore::FileChooser*);
virtual void setCursor(const WebCore::Cursor&);
virtual void setLastSetCursorToCurrentCursor();
WebView* webView() const { return m_webView; }
virtual void formStateDidChange(const WebCore::Node*) { }
virtual PassOwnPtr<WebCore::HTMLParserQuirks> createHTMLParserQuirks() { return 0; }
#if USE(ACCELERATED_COMPOSITING)
// Pass 0 as the GraphicsLayer to detatch the root layer.
virtual void attachRootGraphicsLayer(WebCore::Frame*, WebCore::GraphicsLayer*);
// Sets a flag to specify that the next time content is drawn to the window,
// the changes appear on the screen in synchrony with updates to GraphicsLayers.
virtual void setNeedsOneShotDrawingSynchronization() { }
// Sets a flag to specify that the view needs to be updated, so we need
// to do an eager layout before the drawing.
virtual void scheduleCompositingLayerSync();
#endif
virtual void scrollRectIntoView(const WebCore::IntRect&, const WebCore::ScrollView*) const {}
virtual void requestGeolocationPermissionForFrame(WebCore::Frame*, WebCore::Geolocation*);
virtual void cancelGeolocationPermissionRequestForFrame(WebCore::Frame*, WebCore::Geolocation*) { }
#if ENABLE(VIDEO)
virtual bool supportsFullscreenForNode(const WebCore::Node*);
virtual void enterFullscreenForNode(WebCore::Node*);
virtual void exitFullscreenForNode(WebCore::Node*);
#endif
#if ENABLE(NOTIFICATIONS)
virtual WebCore::NotificationPresenter* notificationPresenter() const { return reinterpret_cast<WebCore::NotificationPresenter*>(m_notificationsDelegate.get()); }
#endif
virtual bool selectItemWritingDirectionIsNatural();
virtual PassRefPtr<WebCore::PopupMenu> createPopupMenu(WebCore::PopupMenuClient*) const;
virtual PassRefPtr<WebCore::SearchPopupMenu> createSearchPopupMenu(WebCore::PopupMenuClient*) const;
private:
COMPtr<IWebUIDelegate> uiDelegate();
WebView* m_webView;
#if ENABLE(NOTIFICATIONS)
OwnPtr<WebDesktopNotificationsDelegate> m_notificationsDelegate;
#endif
};
| [
"[email protected]"
]
| [
[
[
1,
182
]
]
]
|
b91b9b16c8697eefc4ae139e5bb4a9e7b7aebc80 | 0f8559dad8e89d112362f9770a4551149d4e738f | /Wall_Destruction/Havok/Source/Physics/Vehicle/Manager/RayCastBatchingManager/hkpVehicleRayCastBatchingManager.h | e1c25332fb1774c4a0133ae2239c7bb32e3938be | []
| no_license | TheProjecter/olafurabertaymsc | 9360ad4c988d921e55b8cef9b8dcf1959e92d814 | 456d4d87699342c5459534a7992f04669e75d2e1 | refs/heads/master | 2021-01-10T15:15:49.289873 | 2010-09-20T12:58:48 | 2010-09-20T12:58:48 | 45,933,002 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,590 | h | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HK_VEHICLE_RAY_CAST_BATCHING_MANAGER_H
#define HK_VEHICLE_RAY_CAST_BATCHING_MANAGER_H
#include <Physics/Vehicle/Manager/hkpVehicleCastBatchingManager.h>
#include <Common/Base/Thread/Semaphore/hkSemaphoreBusyWait.h>
#include <Physics/Collide/Query/Multithreaded/RayCastQuery/hkpRayCastQueryJobs.h>
struct hkpShapeRayCastCommand;
/// Manages a set of vehicles whose wheelCollide objects are instances of hkpVehicleRayCastWheelCollide.
/// Ray casts can be batched and performed multithreaded.
class hkpVehicleRayCastBatchingManager : public hkpVehicleCastBatchingManager
{
public:
HK_DECLARE_CLASS_ALLOCATOR( HK_MEMORY_CLASS_VEHICLE );
HK_DECLARE_REFLECTION();
/// Constructor.
hkpVehicleRayCastBatchingManager() { }
//
// Interface for asynchronous multithreading.
//
virtual int getBufferSize( int numJobs );
virtual int buildAndAddCastJobs( const hkpWorld* world, hkInt32 filterSize, int numJobs, hkJobQueue* jobQueue, hkSemaphoreBusyWait* semaphore, void* buffer );
virtual void stepVehiclesUsingCastResults( const hkStepInfo& stepInfo, int numJobs, void* buffer );
public:
//
// Internal
//
/// The buffer is divided as follows:
struct RaycastBatch
{
/// A pointer to enough space for one command per wheel.
/// This space is divided into chunks, with each chunk containing
/// all the commands for the wheels of a single vehicle.
/// The chunks are consecutive, so if some vehicles do not issue
/// commands, there will be unused commands at the end.
hkpShapeRayCastCommand* m_commandStorage;
/// A pointer to enough space for one raycast output per wheel.
/// The elements of this array correspond directly to the commands in
/// m_commandStorage, and are arranged in the same way.
hkpWorldRayCastOutput* m_outputStorage;
/// A pointer to an array of the number of commands issued for each vehicle.
hkUint8* m_index;
/// The headers of the raycast jobs.
hkpCollisionQueryJobHeader* m_jobHeaders;
};
/// Fills out a RaycastBatch structure with pointers into the provided buffer.
void getRaycastBatchFromBuffer( void* raycastBuffer, int numJobs, RaycastBatch& raycastBatch );
public:
hkpVehicleRayCastBatchingManager( hkFinishLoadedObjectFlag f ) : hkpVehicleCastBatchingManager(f) { }
};
#endif // HK_VEHICLE_RAY_CAST_BATCHING_MANAGER_H
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222)
*
* Confidential Information of Havok. (C) Copyright 1999-2009
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at www.havok.com/tryhavok.
*
*/
| [
"[email protected]"
]
| [
[
[
1,
84
]
]
]
|
4c0eb9efde8f5934b8276a29c8dc1d16b76e2397 | 49db059c239549a8691fda362adf0654c5749fb1 | /2010/talanov/Task7/Test/timerdialogtest.h | a539bf12bb5944cf8fd18eba1b7cfb372f2f8070 | []
| no_license | bondarevts/amse-qt | 1a063f27c45a80897bb4751ae5c10f5d9d80de1b | 2b9b76c7a5576bc1079fc037adcf039fed4dc848 | refs/heads/master | 2020-05-07T21:19:48.773724 | 2010-12-07T07:53:51 | 2010-12-07T07:53:51 | 35,804,478 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 433 | h | #ifndef TIMERDIALOGTEST_H
#define TIMERDIALOGTEST_H
#include "../Task2/timerdialog.h"
#include <QObject>
class TimerDialogTest : public QObject
{
Q_OBJECT
public:
TimerDialogTest(QObject *parent = 0);
~TimerDialogTest();
private slots:
void testLogic();
void testInterfaceAndSignals();
void testToFail();
private:
TimerDialog* myTimerDialog;
};
#endif // TIMERDIALOGTEST_H
| [
"talanov.pavel@1a14799f-55e9-4979-7f51-533a2053511e"
]
| [
[
[
1,
28
]
]
]
|
4c922feb43cb85a30575fca2ee31bf346e8a2118 | 7369bf6a69a3e9ddc0c8412846871b2f8f39abb9 | /Abstracts/ofxCacheable.h | 115632e9d9a4e51da6cccc18f2a86ebf34169b00 | []
| no_license | MiklakDIT/ofxengine | 32fffa2b8aa988ecb0726fbe93475ef9a3c2143a | ed35d885c9f6eb626ff8963f2db5b1d61d9d5fcd | refs/heads/master | 2021-03-12T22:27:45.857535 | 2009-07-23T16:39:05 | 2009-07-23T16:39:05 | 35,221,683 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,671 | h | /***************************************************************
* File: Abstracts/ofxCacheable.h
* Author: nickiannone (aka ShotgunNinja)
* Status: Complete
***************************************************************/
#pragma once
#include "ofxEngine.h"
typedef unsigned int ofxCacheID;
class ofxCacheLoader;
class ofxCacheData;
class ofxCache;
//==========================================================
// class ofxCacheable
//==========================================================
class ofxCacheable {
public:
friend class ofxCache;
ofxCacheable(ofxCache* cache);
virtual ~ofxCacheable();
virtual void precache() = 0; // Overload for each derived class to precache stuff!
// A utility to cache a file. Cached files are hooked to the Cache using this Cacheable, or withdrawn from the Cache if they are already loaded.
void precacheFile(string filename, ofxCacheLoader* customLoader = NULL);
// Unhooks the cacheable from the cached data.
void releaseCache();
// A utility to retrieve the cache data by its filename.
ofxCacheData* getCacheData(string filename);
// A utility to retrieve the cache data by its ID number.
ofxCacheData* getCacheData(ofxCacheID id);
// Gets the number of cached files that the Cacheable depends upon.
int getCachedDataCount() const;
// Checks to see if this cacheable is using any cached files.
bool isCacheReleased() const;
protected:
// Sets the used Cache (probably not important, as we're probably only gonna use 1 Cache for everything, but still...)
void setCache(ofxCache* cache);
ofxCache* m_cache;
list<ofxCacheID>* m_cacheIDs;
};
| [
"nickiannone@70296b60-74a0-11de-9207-fb4211ab666b"
]
| [
[
[
1,
51
]
]
]
|
244661d7a5a1077ba48a6a801770d5d167b589c4 | 867f5533667cce30d0743d5bea6b0c083c073386 | /jingxian-downloader/NewDownload.cpp | 2085149eae3c179604339353ea3560fa87ab016a | []
| no_license | mei-rune/jingxian-project | 32804e0fa82f3f9a38f79e9a99c4645b9256e889 | 47bc7a2cb51fa0d85279f46207f6d7bea57f9e19 | refs/heads/master | 2022-08-12T18:43:37.139637 | 2009-12-11T09:30:04 | 2009-12-11T09:30:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,777 | cpp | ///////////////////////////////////////////////////////////////////////////
// C++ code generated with wxFormBuilder (version Apr 16 2008)
// http://www.wxformbuilder.org/
//
// PLEASE DO "NOT" EDIT THIS FILE!
///////////////////////////////////////////////////////////////////////////
#include "pre_config.h"
#include "NewDownload.h"
///////////////////////////////////////////////////////////////////////////
NewDownload::NewDownload( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style )
{
this->SetSizeHints( wxDefaultSize, wxDefaultSize );
wxBoxSizer* topSizer;
topSizer = new wxBoxSizer( wxVERTICAL );
m_option_auinotebook = new wxAuiNotebook( this, wxID_ANY, wxPoint( -1,-1 ), wxDefaultSize, wxAUI_NB_TAB_EXTERNAL_MOVE );
m_general_option_panel = new wxPanel( m_option_auinotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
wxBoxSizer* bSizer37;
bSizer37 = new wxBoxSizer( wxVERTICAL );
wxFlexGridSizer* urlSizer;
urlSizer = new wxFlexGridSizer( 2, 2, 0, 0 );
urlSizer->SetFlexibleDirection( wxVERTICAL );
urlSizer->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_ALL );
m_staticText5 = new wxStaticText( m_general_option_panel, wxID_ANY, wxT("MyLabel"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText5->Wrap( -1 );
urlSizer->Add( m_staticText5, 0, wxALL, 5 );
m_textCtrl4 = new wxTextCtrl( m_general_option_panel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
m_textCtrl4->SetMaxLength( 2048 );
urlSizer->Add( m_textCtrl4, 1, wxALL|wxEXPAND, 5 );
m_staticText6 = new wxStaticText( m_general_option_panel, wxID_ANY, wxT("MyLabel"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText6->Wrap( -1 );
urlSizer->Add( m_staticText6, 0, wxALL, 5 );
m_textCtrl5 = new wxTextCtrl( m_general_option_panel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
urlSizer->Add( m_textCtrl5, 1, wxALL|wxEXPAND, 5 );
bSizer37->Add( urlSizer, 1, wxEXPAND, 5 );
m_staticline5 = new wxStaticLine( m_general_option_panel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL );
bSizer37->Add( m_staticline5, 0, wxEXPAND | wxALL, 5 );
wxFlexGridSizer* fileSizer;
fileSizer = new wxFlexGridSizer( 3, 3, 0, 0 );
fileSizer->SetFlexibleDirection( wxBOTH );
fileSizer->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
m_staticText7 = new wxStaticText( m_general_option_panel, wxID_ANY, wxT("MyLabel"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText7->Wrap( -1 );
fileSizer->Add( m_staticText7, 0, wxALL, 5 );
m_textCtrl6 = new wxTextCtrl( m_general_option_panel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
fileSizer->Add( m_textCtrl6, 0, wxALL, 5 );
m_staticText11 = new wxStaticText( m_general_option_panel, wxID_ANY, wxT("MyLabel"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText11->Wrap( -1 );
fileSizer->Add( m_staticText11, 0, wxALL, 5 );
m_staticText9 = new wxStaticText( m_general_option_panel, wxID_ANY, wxT("MyLabel"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText9->Wrap( -1 );
fileSizer->Add( m_staticText9, 0, wxALL, 5 );
m_textCtrl8 = new wxTextCtrl( m_general_option_panel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
fileSizer->Add( m_textCtrl8, 0, wxALL, 5 );
m_button7 = new wxButton( m_general_option_panel, wxID_ANY, wxT("MyButton"), wxDefaultPosition, wxDefaultSize, 0 );
fileSizer->Add( m_button7, 0, wxALL, 5 );
m_staticText10 = new wxStaticText( m_general_option_panel, wxID_ANY, wxT("MyLabel"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText10->Wrap( -1 );
fileSizer->Add( m_staticText10, 0, wxALL, 5 );
m_textCtrl9 = new wxTextCtrl( m_general_option_panel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
fileSizer->Add( m_textCtrl9, 0, wxALL, 5 );
m_button8 = new wxButton( m_general_option_panel, wxID_ANY, wxT("MyButton"), wxDefaultPosition, wxDefaultSize, 0 );
fileSizer->Add( m_button8, 0, wxALL, 5 );
bSizer37->Add( fileSizer, 1, wxEXPAND, 5 );
m_general_option_panel->SetSizer( bSizer37 );
m_general_option_panel->Layout();
bSizer37->Fit( m_general_option_panel );
m_option_auinotebook->AddPage( m_general_option_panel, wxT("General"), false, wxNullBitmap );
m_advencd_option = new wxPanel( m_option_auinotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
wxBoxSizer* bSizer14;
bSizer14 = new wxBoxSizer( wxHORIZONTAL );
wxGridBagSizer* gbSizer2;
gbSizer2 = new wxGridBagSizer( 0, 0 );
gbSizer2->SetFlexibleDirection( wxBOTH );
gbSizer2->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
m_login_checkBox = new wxCheckBox( m_advencd_option, wxID_ANY, wxT("Check Me!"), wxDefaultPosition, wxDefaultSize, 0 );
gbSizer2->Add( m_login_checkBox, wxGBPosition( 0, 0 ), wxGBSpan( 1, 2 ), wxALL|wxEXPAND, 5 );
m_user_label = new wxStaticText( m_advencd_option, wxID_ANY, wxT("Username:"), wxDefaultPosition, wxDefaultSize, 0 );
m_user_label->Wrap( -1 );
gbSizer2->Add( m_user_label, wxGBPosition( 1, 0 ), wxGBSpan( 1, 1 ), wxALL, 5 );
m_user_name_box = new wxTextCtrl( m_advencd_option, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
gbSizer2->Add( m_user_name_box, wxGBPosition( 1, 1 ), wxGBSpan( 1, 1 ), wxALL|wxEXPAND, 5 );
m_password_label = new wxStaticText( m_advencd_option, wxID_ANY, wxT("Password:"), wxDefaultPosition, wxDefaultSize, 0 );
m_password_label->Wrap( -1 );
gbSizer2->Add( m_password_label, wxGBPosition( 2, 0 ), wxGBSpan( 1, 1 ), wxALL, 5 );
m_password_box = new wxTextCtrl( m_advencd_option, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
gbSizer2->Add( m_password_box, wxGBPosition( 2, 1 ), wxGBSpan( 1, 1 ), wxALL|wxEXPAND, 5 );
m_textCtrl12 = new wxTextCtrl( m_advencd_option, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
m_textCtrl12->SetMaxLength( 256 );
gbSizer2->Add( m_textCtrl12, wxGBPosition( 4, 0 ), wxGBSpan( 5, 2 ), wxALL|wxEXPAND, 5 );
m_staticText13 = new wxStaticText( m_advencd_option, wxID_ANY, wxT("MyLabel"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText13->Wrap( -1 );
gbSizer2->Add( m_staticText13, wxGBPosition( 3, 0 ), wxGBSpan( 1, 2 ), wxALL|wxEXPAND, 5 );
bSizer14->Add( gbSizer2, 1, wxEXPAND, 5 );
wxGridBagSizer* gbSizer4;
gbSizer4 = new wxGridBagSizer( 0, 0 );
gbSizer4->SetFlexibleDirection( wxBOTH );
gbSizer4->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
bSizer14->Add( gbSizer4, 1, wxEXPAND, 5 );
m_advencd_option->SetSizer( bSizer14 );
m_advencd_option->Layout();
bSizer14->Fit( m_advencd_option );
m_option_auinotebook->AddPage( m_advencd_option, wxT("Advanced"), true, wxNullBitmap );
m_connect_option_panel = new wxPanel( m_option_auinotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
m_option_auinotebook->AddPage( m_connect_option_panel, wxT("Connect"), false, wxNullBitmap );
topSizer->Add( m_option_auinotebook, 1, wxEXPAND | wxALL, 5 );
m_staticline17 = new wxStaticLine( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL );
topSizer->Add( m_staticline17, 0, wxEXPAND | wxALL, 5 );
wxBoxSizer* buttomSizer = new wxBoxSizer( wxHORIZONTAL );
buttomSizer->Add( new wxButton( this, wxID_ANY, wxT("MyButton"), wxDefaultPosition, wxDefaultSize, 0 ), 0, wxALL, 5 );
buttomSizer->Add( new wxButton( this, wxID_ANY, wxT("MyButton"), wxDefaultPosition, wxDefaultSize, 0 ), 0, wxALL, 5 );
topSizer->Add( buttomSizer);
this->SetSizer( topSizer );
this->Layout();
}
NewDownload::~NewDownload()
{
}
| [
"runner.mei@0dd8077a-353d-11de-b438-597f59cd7555"
]
| [
[
[
1,
162
]
]
]
|
f7b0a14bc0d31d2098a5c199a232dd2ad8246158 | 8c234510906db9ae4e724c8efb0238892cb3a128 | /apps/StereoGR/GestMan.cpp | 2bf3328324e6852a08b10bb303ff63bfc0d48071 | [
"BSD-3-Clause"
]
| permissive | hcl3210/opencv | 7b8b752982afaf402a361eb8475c24e7f4c08671 | b34b1c3540716a3dadfd2b9e3bbc4253774c636d | refs/heads/master | 2020-05-19T12:45:52.864577 | 2008-08-20T01:57:54 | 2008-08-20T01:57:54 | 177,025 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,015 | cpp | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/// GestRec.cpp : implementation file
//
#include "stdafx.h"
#include "stereogr.h"
#include "GestMan.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CGestRec dialog
CGestRec::CGestRec(CWnd* pParent /*=NULL*/)
: CDialog(CGestRec::IDD, pParent)
{
//{{AFX_DATA_INIT(CGestRec)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
}
void CGestRec::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CGestRec)
// NOTE: the ClassWizard will add DDX and DDV calls here
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CGestRec, CDialog)
//{{AFX_MSG_MAP(CGestRec)
ON_BN_CLICKED(IDC_RTRAIN, OnRtrain)
ON_BN_CLICKED(IDC_RRECO, OnRreco)
ON_LBN_SELCHANGE(IDC_GESTLIST, OnSelchangeGestlist)
ON_WM_CLOSE()
ON_BN_CLICKED(IDC_RNOTHING, OnRnothing)
ON_BN_CLICKED(IDC_BCLEARGEST, OnBcleargest)
ON_BN_CLICKED(IDC_BSAVEGEST, OnBsavegest)
ON_BN_CLICKED(IDC_BLOADGEST, OnBloadgest)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CGestRec message handlers
void CGestRec::OnRtrain()
{
STEREOGRAPP(app);
app->m_findHand.SetTask(GR_TRAIN);
}
void CGestRec::OnRreco()
{
STEREOGRAPP(app);
app->m_findHand.SetTask(GR_RECOGNIZE);
}
void CGestRec::OnSelchangeGestlist()
{
STEREOGRAPP(app);
CListBox* pList = (CListBox*)GetDlgItem(IDC_GESTLIST);
int sel = pList->GetCurSel();
string buffer("", pList->GetTextLen(sel));
pList->GetText(sel, buffer.begin());
app->m_findHand.SetGestureName(buffer);
}
BOOL CGestRec::OnInitDialog()
{
CDialog::OnInitDialog();
CListBox* pList = (CListBox*)GetDlgItem(IDC_GESTLIST);
pList->AddString("Ok");
pList->AddString("Open");
pList->AddString("Three");
pList->AddString("Peace");
pList->AddString("Point");
pList->AddString("Thumb");
pList->SetCurSel(0);
CButton* pTrain = (CButton*)GetDlgItem(IDC_RTRAIN);
pTrain->SetCheck(1);
STEREOGRAPP(app);
app->m_findHand.SetTask(GR_TRAIN);
string buffer("", pList->GetTextLen(0));
pList->GetText(0, buffer.begin());
app->m_findHand.SetGestureName(buffer);
ShowWindow(SW_SHOW);
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CGestRec::OnClose()
{
STEREOGRAPP(app);
app->m_findHand.SetTask(GR_NOTHING);
CDialog::OnClose();
}
void CGestRec::UpdateStatus()
{
STEREOGRAPP(app);
int task = app->m_findHand.m_task;
CStatic* pStatus = (CStatic*)GetDlgItem(IDC_GRINFO);
CListBox* pList = (CListBox*)GetDlgItem(IDC_GESTLIST);
int current = pList->GetCurSel();
string recognized = app->m_findHand.GetRecognizedName();
CString info;
pList->GetText(current, info);
string str = LPCTSTR(info);
app->m_findHand.SetGestureName(str);
switch(task)
{
case GR_TRAIN:
if(!app->m_findHand.m_isCovMatCalculated[current])
info.Format("Collected %d samples for training...", app->m_findHand.m_features[current].size());
else
info.Format("Collected all samples.");
break;
case GR_RECOGNIZE:
if(recognized.empty())
{
info.Format("Not recognized.");
}
else
{
info.Format("Recognized as \"%s\".", recognized.c_str());
}
break;
case GR_NOTHING:
info = "Do nothing";
}
pStatus->SetWindowText(info);
pStatus->Invalidate();
pStatus->UpdateWindow();
RECT rect;
pStatus->GetWindowRect(&rect);
ScreenToClient(&rect);
InvalidateRect(&rect);
UpdateWindow();
ASSERT(iplGetErrStatus() >= 0);
}
void CGestRec::OnRnothing()
{
STEREOGRAPP(app)
app->m_findHand.SetTask(GR_NOTHING);
}
void CGestRec::OnBcleargest()
{
CListBox* pList = (CListBox*)GetDlgItem(IDC_GESTLIST);
int index = pList->GetCurSel();
CString str;
pList->GetText(index, str);
string buffer = LPCTSTR(str);
STEREOGRAPP(app)
app->m_findHand.ClearGesture(buffer);
}
void CGestRec::OnBsavegest()
{
CFileDialog dlg(FALSE, 0, 0, OFN_OVERWRITEPROMPT, "Statis training set (*.pos)|*.pos");
if(dlg.DoModal() == IDOK)
{
STEREOGRAPP(app)
app->m_findHand.SaveGestures(dlg.GetPathName());
}
}
void CGestRec::OnBloadgest()
{
CFileDialog dlg(TRUE, 0, 0, 0, "Statis training set (*.pos)|*.pos");
if(dlg.DoModal() == IDOK)
{
STEREOGRAPP(app)
app->m_findHand.LoadGestures(dlg.GetPathName());
}
}
| [
"[email protected]"
]
| [
[
[
1,
232
]
]
]
|
cd43270574c912cf59aa2bb407ad7d0d25b73103 | 6dac9369d44799e368d866638433fbd17873dcf7 | /src/branches/01032005/vfs/jpeg/VFSPlugin_JPEG.cpp | 75ffa70e98998bfa39aa9557bd500a9e7ad244e1 | []
| no_license | christhomas/fusionengine | 286b33f2c6a7df785398ffbe7eea1c367e512b8d | 95422685027bb19986ba64c612049faa5899690e | refs/heads/master | 2020-04-05T22:52:07.491706 | 2006-10-24T11:21:28 | 2006-10-24T11:21:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,626 | cpp | #include <VFSPlugin_JPEG.h>
#include <fstream>
static bool jpeg_error;
static void error_exit(j_common_ptr pcinfo)
{
// Create the message string
char sz[256];
(pcinfo->err->format_message) (pcinfo, sz);
static std::ofstream o("jerr.log");
o << sz << std::endl;
jpeg_error = true;
}
static void init_source(j_decompress_ptr cinfo){}
static boolean fill_input_buffer(j_decompress_ptr cinfo)
{
jpeg_error = true;
return TRUE;
}
static void skip_input_data(j_decompress_ptr cinfo, long count)
{
jpeg_source_mgr * src = cinfo->src;
if(count > 0) {
src->bytes_in_buffer -= count;
src->next_input_byte += count;
}
}
static void term_source(j_decompress_ptr cinfo){}
VFSPlugin_JPEG::VFSPlugin_JPEG()
{
m_type = "jpg;jpeg;";
m_offset = 0;
m_length = 0;
m_fileinfo = NULL;
m_buffer = NULL;
}
/** JPEG Plugin constructor */
VFSPlugin_JPEG::~VFSPlugin_JPEG()
{
}
std::string VFSPlugin_JPEG::Type(void)
{
return m_type;
}
FileInfo * VFSPlugin_JPEG::Read(unsigned char *buffer, unsigned int length)
{
m_offset = 0;
m_buffer = buffer;
m_length = length;
m_fileinfo = new ImageFileInfo();
m_fileinfo->filelength = m_length;
m_fileinfo->palette = NULL;
jpeg_decompress_struct cinfo;
jpeg_error_mgr jerr;
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_decompress(&cinfo);
jpeg_source_mgr jsrc;
jsrc.bytes_in_buffer = m_length;
jsrc.next_input_byte = (const unsigned char *)m_buffer;
jsrc.init_source = init_source;
jsrc.fill_input_buffer = fill_input_buffer;
jsrc.skip_input_data = skip_input_data;
jsrc.resync_to_restart = jpeg_resync_to_restart; // use default method
jsrc.term_source = term_source;
cinfo.src = &jsrc;
jpeg_read_header(&cinfo,TRUE);
jpeg_start_decompress(&cinfo);
m_fileinfo->width = cinfo.output_width;
m_fileinfo->height = cinfo.output_height;
m_fileinfo->bpp = cinfo.num_components<<3;
int bytes = m_fileinfo->width * m_fileinfo->height * (m_fileinfo->bpp>>3);
m_fileinfo->data = new unsigned char[bytes];
// read scanlines
int i;
unsigned char *p = m_fileinfo->data;
while(cinfo.output_scanline < cinfo.output_height) {
i = jpeg_read_scanlines(&cinfo, &p, 1);
p += i * (m_fileinfo->bpp>>3) * cinfo.output_width;
}
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
return m_fileinfo;
}
char * VFSPlugin_JPEG::Write(FileInfo *data, unsigned int &length)
{
return NULL;
}
void VFSPlugin_JPEG::Setup(void)
{
}
bool VFSPlugin_JPEG::Decode(void)
{
return false;
}
| [
"chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7"
]
| [
[
[
1,
128
]
]
]
|
c203efabc7fc1510c4f60ef1dba6d1ee4cc6d7da | 909e422494d7c012c2bc89c79eabdceb53c721a5 | /icpcLibrary/Computational_Geometry.cpp | 6c2033a3424c3273ba2e85fba4345c7323227fa8 | []
| no_license | aviramagen/menglin-icpc-code-library | f14cc303a3fd05992a1a40b9bcd7a0b09657f21c | c8375f39ed13312f705fb42c20ce83f5194bd297 | refs/heads/master | 2021-01-10T14:00:32.605726 | 2011-12-03T11:39:50 | 2011-12-03T11:39:50 | 54,555,734 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,918 | cpp | /*
Name: 计算几何标准程序库
Copyright: LogicalMars Library
Author: StarFish && Improved by LogicalMars
Date: 12-10-08 12:11
*/
#include <stdlib.h>
#include <math.h>
const double zero = 1e-6;
const double infinity = 1e20;
struct TPoint
{
double x, y;
};
struct TLineSeg
{
TPoint a, b;
};
double dis ( TPoint p1, TPoint p2 ) //求平面上两点之间的距离
{
return ( sqrt ( ( p1.x - p2.x ) * ( p1.x - p2.x ) + ( p1.y - p2.y ) * ( p1.y - p2.y ) ) );
}
double multiply ( TPoint p1, TPoint p2, TPoint p0 )
{
return ( ( p1.x - p0.x ) * ( p2.y - p0.y ) - ( p2.x - p0.x ) * ( p1.y - p0.y ) );
}
//确定两条线段是否相交
double max ( double m1, double m2 )
{
if ( m1 > m2 ) return m1;
return m2;
}
double min ( double m1, double m2 )
{
if ( m1 < m2 ) return m1;
return m2;
}
int intersect ( TLineSeg u, TLineSeg v ) //非严格相交,严格相交要将 >= 改成 >
{
return ( ( max ( u.a.x, u.b.x ) >= min ( v.a.x, v.b.x ) ) &&
( max ( v.a.x, v.b.x ) >= min ( u.a.x, u.b.x ) ) &&
( max ( u.a.y, u.b.y ) >= min ( v.a.y, v.b.y ) ) &&
( max ( v.a.y, v.b.y ) >= min ( u.a.y, u.b.y ) ) &&
( multiply ( v.a, u.b, u.a ) * multiply ( u.b, v.b, u.a ) >= 0 ) &&
( multiply ( u.a, v.b, v.a ) * multiply ( v.b, u.b, v.a ) >= 0 ) );
}
//判断点p是否在线段l上
int online ( TLineSeg l, TPoint p )
{
double temp = multiply ( l.b, p, l.a );
return ( temp >= -zero && temp <= zero && ( ( ( p.x - l.a.x ) * ( p.x - l.b.x ) <= -zero ) || ( ( p.y - l.a.y ) * ( p.y - l.b.y ) <= -zero ) ) );
}
//判断两个点是否相等
int Euqal_Point ( TPoint p1, TPoint p2 )
{
return ( ( abs ( p1.x - p2.x ) < zero ) && ( abs ( p1.y - p2.y ) < zero ) );
}
//一种线段相交判断函数,当且仅当u,v相交并且交点不是u,v的端点时函数为true;
int intersect_A ( TLineSeg u, TLineSeg v )
{
return ( ( intersect ( u, v ) ) &&
( !Euqal_Point ( u.a, v.a ) ) &&
( !Euqal_Point ( u.a, v.b ) ) &&
( !Euqal_Point ( u.b, v.a ) ) &&
( !Euqal_Point ( u.b, v.b ) ) );
}
/*===============================================
判断点q是否在多边形Polygon内,
其中多边形是任意的凸或凹多边形,
Polygon中存放多边形的逆时针顶点序列
================================================*/
int InsidePolygon ( int vcount, TPoint Polygon[], TPoint q )
{
int c = 0, i, n;
TLineSeg l1, l2;
l1.a = q;
l1.b = q;
l1.b.x = infinity;
n = vcount;
for ( i = 0; i < vcount; i++ )
{
l2.a = Polygon[i];
l2.b = Polygon[ ( i + 1 ) % n];
if ( ( intersect_A ( l1, l2 ) ) ||
(
( online ( l1, Polygon[ ( i + 1 ) % n] ) ) &&
(
( !online ( l1, Polygon[ ( i + 2 ) % n] ) ) &&
( multiply ( Polygon[i], Polygon[ ( i + 1 ) % n], l1.a ) *multiply ( Polygon[ ( i + 1 ) % n], Polygon[ ( i + 2 ) % n], l1.a ) > 0 )
||
( online ( l1, Polygon[ ( i + 2 ) % n] ) ) &&
( multiply ( Polygon[i], Polygon[ ( i + 2 ) % n], l1.a ) *multiply ( Polygon[ ( i + 2 ) % n], Polygon[ ( i + 3 ) % n], l1.a ) > 0 )
)
)
) c++;
}
return ( c % 2 != 0 );
}
/********************************************\
* *
* 计算多边形的面积 *
* *
* 要求按照逆时针方向输入多边形顶点 *
* 可以是凸多边形或凹多边形 *
* 如果为顺时针,则为相应负值 *
* *
\********************************************/
double area_of_polygon ( int vcount, double x[], double y[] )
{
int i;
double s;
if ( vcount < 3 ) return 0;
s = y[0] * ( x[vcount - 1] - x[1] );
for ( i = 1; i < vcount; i++ )
s += y[i] * ( x[ ( i - 1 )] - x[ ( i + 1 ) % vcount] );
return s / 2;
}
/*====================================================================================
寻找凸包 graham 扫描法
PointSet为输入的点集;
ch为输出的凸包上的点集,按照逆时针方向排列;
n为PointSet中的点的数目
len为输出的凸包上的点的个数;
设下一个扫描的点PointSet[i]=P2,当前栈顶的两个点ch[top]=P1,ch[top-1]=P0,
如果P1P2相对于P0P1在点P1向左旋转(共线也不行),则P0,P1一定是凸包上的点;
否则P1一定不是凸包上的点,应该将其出栈。
比如下面左图中点1就一定是凸包上的点,右图中点1就一定不是凸包上的点,因为
可以连接点0,2构成凸包的边
2
|
| _____2
1 1
/ /
____0/ ____0/
====================================================================================*/
//未考虑实数类型,需增加1e-8
TPoint bp;
bool PolarComp ( const TPoint &p1, const TPoint &p2 )
{
int u = multiply ( p1, p2, bp );
return ( u > 0 ) || ( u == 0 && dis ( p1, bp ) < dis ( p2, bp ) );
}
void Graham_scan ( TPoint PointSet[], TPoint ch[], int n, long &len )
{
if ( n <= 3 )
{
len = n;
int i;
for ( i = 0; i < n; i++ ) ch[i] = PointSet[i];
return;
}
int i, j, k = 0, top = 2;
TPoint tmp;
//选取PointSet中y坐标最小的点PointSet[k],如果这样的点右多个,则取最左边的一个
for ( i = 1; i < n; i++ )
if ( ( PointSet[i].y < PointSet[k].y ) || ( ( PointSet[i].y == PointSet[k].y ) && ( PointSet[i].x < PointSet[k].x ) ) )
k = i;
tmp = PointSet[0];
PointSet[0] = PointSet[k];
PointSet[k] = tmp; //现在PointSet中y坐标最小的点在PointSet[0]
bp = PointSet[0];
sort ( PointSet, PointSet + n, PolarComp );
ch[0] = PointSet[0];
ch[1] = PointSet[1];
ch[2] = PointSet[2];
top = 2;
for ( i = 3; i < n; i++ )
{
while ( multiply ( PointSet[i], ch[top], ch[top - 1] ) >= 0 && top > 0 ) top--;
if ( top < 0 ) break;
ch[++top] = PointSet[i];
}
len = top + 1;
}
== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == =
求直径 未考虑1e-8
== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == =
long Diameter ( TPoint ch[], long len )
{
if ( len == 1 ) return 0;
if ( len == 2 ) return dis ( ch[0], ch[1] );
int nu, nv, v, u, k;
long re = 0;
ch[len] = ch[0];
for ( u = 0, v = 1; u < len; u = nu )
{
nu = u + 1;
while ( 1 )
{
nv = ( v + 1 ) % len;
k = ( ( ch[nu].x - ch[u].x ) * ( ch[nv].y - ch[v].y ) -
( ch[nv].x - ch[v].x ) * ( ch[nu].y - ch[u].y ) );
if ( k <= 0 ) break;
v = nv;
}
re = max ( re, dis ( ch[u], ch[v] ) );
re = max ( re, dis ( ch[u], ch[nv] ) );
}
return re;
}
| [
"bluebird498@localhost"
]
| [
[
[
1,
440
]
]
]
|
52f0244002bed98c64321a40c56a3029bb26001b | ce105c9e4ac9b1b77a160793e0c336826b936670 | /c++/classwork911/classwork911/MyString.cpp | bdf8ca97957865105e61cafb90a5aeb0043bb929 | []
| no_license | jmcgranahan/jusall-programinghw | a32909655cec085d459c2c567c2f1bed2b947612 | d6c5b54d0300a784dee0257364cd049f741cee81 | refs/heads/master | 2020-08-27T03:27:24.013332 | 2011-04-25T06:30:27 | 2011-04-25T06:30:27 | 40,640,139 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,990 | cpp | // MyString.cpp
#include <iostream>
#include "MyString.h"
#include <cstring>
// CONSTRUCTORS
//-----------------------------------------------------
MyString::MyString() //defualt constructor ( no variables)
{
_capacity = 16;
_length = 0;
_string = new char[_capacity + 1];
_string[0] = '\0';
}
//-----------------------------------------------------
MyString::MyString(const char * aCString) // C String variable
{
int NumCharsToCopy = strlen(aCString);
if ( NumCharsToCopy < 16)
_capacity = 16;
else
_capacity = NumCharsToCopy;
_string = new char[_capacity + 1];
strcpy(_string , aCString);
_length = NumCharsToCopy;
}
//-----------------------------------------------------
MyString::MyString(int numChars) // int variable
{
_capacity = numChars;
_string = new char[_capacity + 1];
_string[0] = '\0';
_length = 0;
}
//-----------------------------------------------------
MyString::MyString(const MyString & original)// MyString variable
{
_capacity = original._capacity;
_string = new char [_capacity+1];
strcpy(_string, original._string);
_length = original._length;
}
//-----------------------------------------------------
//DECONSTRUCTOR
MyString::~MyString()//dealocate dynamic storage
{
delete [] _string; // OMG DELETE
}
// METHODS
//-----------------------------------------------------
void MyString::Append(const MyString & aMyString)
{
int MyStringLength = _length + aMyString._length;
char * _Temp = new char[_capacity + 1];
strcpy( _Temp, _string);
char * _Temp2 = new char[aMyString._capacity + 1];
strcpy( _Temp2, aMyString._string);
// Did All this Temp Strings because your s4.append(s4) test fouled up elsewise
if(MyStringLength > _capacity)
{
//need more capacity
_capacity = MyStringLength;
delete [] _string;
_string = new char[_capacity + 1];
}
strcpy( _string, _Temp);
delete [] _Temp;
strcat( _string, _Temp2);
delete [] _Temp2;
_length = MyStringLength;
}
//-----------------------------------------------------
void MyString::Append(const char * const aCString)
{
int StringLength = strlen(aCString);
int MyStringLength = _length + StringLength;
char * _Temp = new char[_capacity + 1];
strcpy( _Temp, _string);
if(MyStringLength > _capacity)
{
//need more capacity
_capacity = MyStringLength;
delete [] _string;
_string = new char[_capacity + 1];
}
strcpy( _string, _Temp);
delete [] _Temp;
strcat( _string, aCString);
_length = MyStringLength;
}
//-----------------------------------------------------
void MyString::Assign(const MyString & aMyString)
{
int numCharsToCopy = aMyString._length;
if(numCharsToCopy > _capacity)
{
//need more capacity
_capacity = numCharsToCopy;
delete [] _string;
_string = new char[_capacity + 1];
}
strcpy( _string, aMyString._string);
_length = numCharsToCopy;
}
//-----------------------------------------------------
void MyString::Assign(const char * const aCString)
{
int numCharsToCopy = strlen(aCString);
if(numCharsToCopy > _capacity)
{
//need more capacity
_capacity = numCharsToCopy;
delete [] _string;
_string = new char[_capacity + 1];
}
strcpy( _string, aCString);
_length = numCharsToCopy;
}
//-----------------------------------------------------
char MyString::At(int index) const
{
char At = '\0';
if((index <= _length) && (index != 0)){
char * Pointer = _string;
Pointer += index-1;
At = *Pointer ;
}
if(index >= _length){
std::cout << "error: index longer than MyString length" << std::endl;
}
if(index == 0){
std::cout << "error: index cannot equal 0" << std::endl;
}
return At;
}
//-----------------------------------------------------
void MyString::Clear()
{
delete [] _string;
_string = new char[_capacity + 1];
strcpy(_string , "");
_length = 0;
}
//-----------------------------------------------------
void MyString::Clear(int newCapacity)
{
_capacity = newCapacity;
delete [] _string;
_string = new char[_capacity + 1];
strcpy(_string , "");
_length = 0;
}
//-----------------------------------------------------
int MyString::Compare(const MyString & aMyString)
{
int Compare = strncmp(_string,aMyString._string,_length);
return Compare;
}
//-----------------------------------------------------
bool MyString::Equals(const MyString & aMyString) const
{
int Compare = strncmp(_string,aMyString._string,_length);
bool Equal;
if(Compare == 0){Equal = true;}
if(Compare != 0){Equal = false;}
return Equal;
}
//-----------------------------------------------------
bool MyString::Equals(const char * const aCString) const
{
int Compare = strncmp(_string,aCString,_length);
bool Equal;
if(Compare == 0){Equal = true;}
if(Compare != 0){Equal = false;}
return Equal;
}
//-----------------------------------------------------
int MyString::Find(const MyString & aMyString) const
{
int Index;
char * Pointer;
Pointer = strstr(_string, aMyString._string);
if(Pointer == 0){ Index = -1; }
else{
Index = Pointer - _string;
}
return Index;
}
//-----------------------------------------------------
void MyString::Insert(const MyString & aMyString, int index)
{
int MyStringLength = _length + aMyString._length;
char * _Temp = new char[_capacity + 1];
char * _Temp2 = new char[aMyString._capacity + 1];
strcpy( _Temp, _string);
strcpy( _Temp2, aMyString._string);
this->Clear(MyStringLength+1);
strncpy( _string, _Temp, index);
_string[index] = '\0';
this->Append(_Temp2);
strcat(_string, _Temp+index);
_length = MyStringLength;
}
//-----------------------------------------------------
int MyString::Length(void) const
{
return _length;
}
//-----------------------------------------------------
void MyString::Replace(int startIndex, int numChars, const MyString & aMyString)
{
if( startIndex >= _length )
{
std::cout << "error: Index larger than MyString length" << std::endl;
}
else if( startIndex + numChars > this->Length())
{
std::cout << "error: Replacing more charcaters than there are" << std::endl;
}
else if(aMyString.Length() < numChars)
{
std::cout << "error: Copying more characters than given" << std::endl;
}
else
{
for(int i = 0; i < numChars; i++)
{
_string[startIndex+i] = aMyString._string[i];
}
}
}
//-----------------------------------------------------
MyString MyString::SubStr(int startIndex, int numChars) const
{
MyString m(numChars);
if( startIndex + numChars > this->Length())
{
std::cout << "error: Requesting more charcaters than there are" << std::endl;
}
else
{
for(int i = 0; i < numChars; i++)
{
m._string[i] = _string[startIndex+i];
}
m._string[numChars] = '\0';
}
m._length = numChars;
return m;
}
//-----------------------------------------------------
MyString MyString::operator= (const MyString & aMyString)
{
this->Assign(aMyString);
return 0;
}
//-----------------------------------------------------
MyString MyString::operator= (const char * const aCString)
{
this->Assign(aCString);
return 0;
}
//-----------------------------------------------------
MyString MyString::operator+ (const MyString & aMyString)
{
MyString Temp;
Temp.Assign(*this);
Temp.Append(aMyString);
return Temp;
}
//-----------------------------------------------------
MyString MyString::operator+ (const char * const aCString)
{
MyString Temp;
Temp.Assign(*this);
Temp.Append(aCString);
return Temp;
}
//-----------------------------------------------------
MyString MyString::operator+= (const MyString & aMyString)
{
this->Append(aMyString);
return 0;
}
//-----------------------------------------------------
MyString MyString::operator+= (const char * const aCString)
{
this->Append(aCString);
return 0;
}
//-----------------------------------------------------
char & MyString::operator[] (int index) const
{
if((index <= _length) && (index >= 0)){
return _string[index];
}
else if(index >= _length){
std::cout << "error: index longer than MyString length" << std::endl;
return _string[0];
}
else if(index < 0){
std::cout << "error: index cannot be less than 0" << std::endl;
return _string[0];
}
}
//-----------------------------------------------------
bool MyString::operator> (const MyString & aMyString)
{
int Compare = strcmp(_string,aMyString._string);
bool Equal;
if(Compare > 0){Equal = true;}
else {Equal = false;}
return Equal;
}
//-----------------------------------------------------
bool MyString::operator< (const MyString & aMyString)
{
int Compare = strcmp(_string,aMyString._string);
bool Equal;
if(Compare < 0){Equal = true;}
else {Equal = false;}
return Equal;
}
//-----------------------------------------------------
bool MyString::operator>= (const MyString & aMyString)
{
int Compare = strcmp(_string,aMyString._string);
bool Equal;
if(Compare >= 0){Equal = true;}
else {Equal = false;}
return Equal;
}
//-----------------------------------------------------
bool MyString::operator<= (const MyString & aMyString)
{
int Compare = strcmp(_string,aMyString._string);
bool Equal;
if(Compare <= 0){Equal = true;}
else {Equal = false;}
return Equal;
}
//-----------------------------------------------------
bool MyString::operator== (const MyString & aMyString)
{
int Compare = strcmp(_string,aMyString._string);
bool Equal;
if(Compare == 0){Equal = true;}
else {Equal = false;}
return Equal;
}
//-----------------------------------------------------
bool MyString::operator!= (const MyString & aMyString)
{
int Compare = strcmp(_string,aMyString._string);
bool Equal;
if(Compare != 0){Equal = true;}
else {Equal = false;}
return Equal;
}
//-----------------------------------------------------
ostream & operator<< (ostream & os, const MyString & aMyString)
{
os << aMyString._string ;
return os;
}
//-----------------------------------------------------
istream & operator>> (istream & is, MyString & aMyString)
{
char Buffer[80];
aMyString.Clear();
if(is.peek() != '\n')
{
do
{
//79 chars at once woo
is.get(Buffer,80);
aMyString.Append(Buffer);
}while(/*(int)*/ strlen(Buffer) == 79);
}
if ( is.peek() == '\n')
{
is.get(); // remove trailing nullchar
}
return is;
// old attempt worked mostly...
//char * _Temp = new char[10000000];
//
//is.getline (_Temp,10000000);
//
//if(strlen(_Temp) > aMyString._capacity)
//{
// //need more capacity
// aMyString._capacity = strlen(_Temp);
// delete [] aMyString._string;
// aMyString._string = new char[aMyString._capacity + 1];
//}
//strcpy(aMyString._string,_Temp);
//delete [] _Temp;
//return is;
}
| [
"biga05@c0f360ae-aefd-11de-b8dd-ab4b6ce6d521"
]
| [
[
[
1,
447
]
]
]
|
9ed7dd7e7b69f9a844f153d012b349ea72718979 | 1cc5720e245ca0d8083b0f12806a5c8b13b5cf98 | /v5/540/c.cpp | 0060a41c50951d93b2f6c5ef00abcbb85fa87371 | []
| no_license | Emerson21/uva-problems | 399d82d93b563e3018921eaff12ca545415fd782 | 3079bdd1cd17087cf54b08c60e2d52dbd0118556 | refs/heads/master | 2021-01-18T09:12:23.069387 | 2010-12-15T00:38:34 | 2010-12-15T00:38:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 731 | cpp | #include <iostream>
#include <stdlib.h>
#define REP(a,b) for(int a=0;a<b;a++)
using namespace std;
int **time,n;
int tot[1001];
int tim(int v) {
REP(i,n) REP(j,tot[i]) if(v==time[i][j]) return i;
}
int main() {
int fs,fe;
int fila[1001];
int ja[200000];
int jatot = 0;
time = (int **) malloc (sizeof(int *)*1001);
char s[200];
REP(i,1001) time[i] = new int(1001);
int k,l;
while((cin >> n)) {
fs = fe = 0;
REP(i,n) tot[i] = 0;
REP(i,n) {
cin >> tot[i];
REP(j,tot[i]) cin >> time[i][j];
}
while(1) {
cin >> s;
if(s[0]=='S') break;
if(s[0]=='E') {
cin >> k;
l = tim(k);
} else if(s[0]=='D') {
}
}
}
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
49
]
]
]
|
ce3ac3093a80a63c5a05df6092bd3a06c10e74ed | bf7d05c055c5686e4ded30f9705a28a396520d48 | /Meta/MetaAspect.cpp | c4876e3f11d4cf8941e556d916a7aa74898a2877 | []
| no_license | ghemingway/mgalib | f32438d5abdbeb5739c298e401a0513f91c8d6d0 | c8cf8507a7fe73efe1da19abcdb77b52e75e2de0 | refs/heads/master | 2020-12-24T15:40:33.538434 | 2011-02-04T16:38:09 | 2011-02-04T16:38:09 | 32,185,568 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,546 | cpp | /*** Included Header Files ***/
#include "MetaAspect.h"
#include "MetaGeneric.h"
#include "MetaRole.h"
#include "MetaPart.h"
#include "MetaModel.h"
// --------------------------- Public MetaAspect Methods --------------------------- //
const Result_t MetaAspect::GetParentModel(MetaModel* &metaModel) const throw()
{
// Use the MetaBase helper function to get this pointer attribute
return MetaBase::ObjectFromAttribute(this->_coreObject, this->_metaProject, ATTRID_ASPECTS_COLL, metaModel);
}
const Result_t MetaAspect::GetParts(std::list<MetaPart*> &partList) const throw()
{
// Use the MetaBase helper function to get this collection attribute
return MetaBase::CollectionFromAttribute(this->_coreObject, this->_metaProject, ATTRID_PARTASPECT_PTR, partList);
}
const Result_t MetaAspect::AddAttribute(MetaAttribute* &metaAttribute) throw()
{
// Use the MetaBase helper function to add a link between the attribute and the aspect
return MetaBase::AddLink(this->_coreObject, this->_metaProject, METAID_METAATTRLINK, ATTRID_ATTRLINK_USEDIN_PTR, ATTRID_ATTRLINK_ATTR_PTR, metaAttribute);
}
const Result_t MetaAspect::CreatePart(MetaRole* &metaRole, MetaPart* &metaPart) throw()
{
// Get the associated coreProject
CoreProject* coreProject = NULL;
Result_t result = this->_coreObject->Project(coreProject);
ASSERT( result == S_OK );
ASSERT( coreProject != NULL );
// Start a transaction
result = coreProject->BeginTransaction(false);
ASSERT( result == S_OK );
// Create a new coreObject
CoreObject newCoreObject;
result = coreProject->CreateObject(METAID_METAPART, newCoreObject);
ASSERT( result == S_OK );
ASSERT( newCoreObject != NULL );
// Link the new Part to this aspect
Uuid uuid = Uuid::Null();
result = this->_coreObject->GetUuid(uuid);
ASSERT( result == S_OK );
ASSERT( uuid != Uuid::Null() );
result = newCoreObject->SetAttributeValue(ATTRID_PARTASPECT_PTR, uuid);
ASSERT( result == S_OK );
// Link the new Part object to the metaRole provided
result = metaRole->GetUuid(uuid);
ASSERT( result == S_OK );
ASSERT( uuid != Uuid::Null() );
result = newCoreObject->SetAttributeValue(ATTRID_PARTROLE_PTR, uuid);
ASSERT( result == S_OK );
// Commit transaction at the CoreProject level
result = coreProject->CommitTransaction();
ASSERT( result == S_OK );
// Now use the core object to create a new metaObject of type T
metaPart = new MetaPart(newCoreObject, this->_metaProject);
ASSERT( metaPart != NULL );
return S_OK;
} | [
"graham.hemingway@8932de9b-a0df-7518-fb39-9aee4a96b462"
]
| [
[
[
1,
72
]
]
]
|
3a5a0b7a8a38ee74c34a3b3766821b6ffb01a352 | c94135316a6706e7a1131e810222c12910cb8495 | /EditorDeNiveles/EditorDeNiveles.cpp | 0d2d5669d34d9f64c163c70666ddb56413e677b2 | []
| no_license | lcianelli/compgraf-marble-madness | 05d2e8f23adf034723dd3d1267e7cdf6350cf5e7 | f3e79763b43a31095ffeff49f440c24614db045b | refs/heads/master | 2016-09-06T14:20:10.951974 | 2011-05-28T21:10:48 | 2011-05-28T21:10:48 | 32,283,765 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 168 | cpp | // EditorDeNiveles.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
| [
"srodriki@1aa7beb8-f67a-c4d8-682d-4e0fe4e45017"
]
| [
[
[
1,
11
]
]
]
|
a5ed51d49ed5fbdaf53a9dc609c2da761f8e5682 | 7b379862f58f587d9327db829ae4c6493b745bb1 | /JuceLibraryCode/modules/juce_core/streams/juce_MemoryOutputStream.cpp | 4ff05f9c2f6976bded3391a88af93bbf05ea78e5 | []
| no_license | owenvallis/Nomestate | 75e844e8ab68933d481640c12019f0d734c62065 | 7fe7c06c2893421a3c77b5180e5f27ab61dd0ffd | refs/heads/master | 2021-01-19T07:35:14.301832 | 2011-12-28T07:42:50 | 2011-12-28T07:42:50 | 2,950,072 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,015 | cpp | /*
==============================================================================
This file is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-11 by Raw Material Software Ltd.
------------------------------------------------------------------------------
JUCE can be redistributed and/or modified under the terms of the GNU General
Public License (Version 2), as published by the Free Software Foundation.
A copy of the license is included in the JUCE distribution, or can be found
online at www.gnu.org/licenses.
JUCE 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.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.rawmaterialsoftware.com/juce for more information.
==============================================================================
*/
BEGIN_JUCE_NAMESPACE
//==============================================================================
MemoryOutputStream::MemoryOutputStream (const size_t initialSize)
: data (internalBlock),
position (0),
size (0)
{
internalBlock.setSize (initialSize, false);
}
MemoryOutputStream::MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
const bool appendToExistingBlockContent)
: data (memoryBlockToWriteTo),
position (0),
size (0)
{
if (appendToExistingBlockContent)
position = size = memoryBlockToWriteTo.getSize();
}
MemoryOutputStream::~MemoryOutputStream()
{
trimExternalBlockSize();
}
void MemoryOutputStream::flush()
{
trimExternalBlockSize();
}
void MemoryOutputStream::trimExternalBlockSize()
{
if (&data != &internalBlock)
data.setSize (size, false);
}
void MemoryOutputStream::preallocate (const size_t bytesToPreallocate)
{
data.ensureSize (bytesToPreallocate + 1);
}
void MemoryOutputStream::reset() noexcept
{
position = 0;
size = 0;
}
void MemoryOutputStream::prepareToWrite (int numBytes)
{
const size_t storageNeeded = position + numBytes;
if (storageNeeded >= data.getSize())
data.ensureSize ((storageNeeded + jmin ((int) (storageNeeded / 2), 1024 * 1024) + 32) & ~31);
}
bool MemoryOutputStream::write (const void* const buffer, int howMany)
{
jassert (buffer != nullptr && howMany >= 0);
if (howMany > 0)
{
prepareToWrite (howMany);
memcpy (static_cast<char*> (data.getData()) + position, buffer, (size_t) howMany);
position += howMany;
size = jmax (size, position);
}
return true;
}
void MemoryOutputStream::writeRepeatedByte (uint8 byte, int howMany)
{
if (howMany > 0)
{
prepareToWrite (howMany);
memset (static_cast<char*> (data.getData()) + position, byte, (size_t) howMany);
position += howMany;
size = jmax (size, position);
}
}
MemoryBlock MemoryOutputStream::getMemoryBlock() const
{
return MemoryBlock (getData(), getDataSize());
}
const void* MemoryOutputStream::getData() const noexcept
{
if (data.getSize() > size)
static_cast <char*> (data.getData()) [size] = 0;
return data.getData();
}
bool MemoryOutputStream::setPosition (int64 newPosition)
{
if (newPosition <= (int64) size)
{
// ok to seek backwards
position = jlimit ((size_t) 0, size, (size_t) newPosition);
return true;
}
else
{
// trying to make it bigger isn't a good thing to do..
return false;
}
}
int MemoryOutputStream::writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite)
{
// before writing from an input, see if we can preallocate to make it more efficient..
int64 availableData = source.getTotalLength() - source.getPosition();
if (availableData > 0)
{
if (maxNumBytesToWrite > 0 && maxNumBytesToWrite < availableData)
availableData = maxNumBytesToWrite;
preallocate (data.getSize() + (size_t) maxNumBytesToWrite);
}
return OutputStream::writeFromInputStream (source, maxNumBytesToWrite);
}
String MemoryOutputStream::toUTF8() const
{
const char* const d = static_cast <const char*> (getData());
return String (CharPointer_UTF8 (d), CharPointer_UTF8 (d + getDataSize()));
}
String MemoryOutputStream::toString() const
{
return String::createStringFromData (getData(), (int) getDataSize());
}
OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead)
{
stream.write (streamToRead.getData(), streamToRead.getDataSize());
return stream;
}
END_JUCE_NAMESPACE
| [
"ow3nskip"
]
| [
[
[
1,
169
]
]
]
|
018c5d427a97e2571d747a0b9c441018e4543fb2 | 881321ed22c5c024aa515e0f152b7f9cc7d1decd | /Pathman/Level.h | b48f486848996c161774818e9da87089b0622289 | []
| no_license | titarenko/Pathman | c37f756c08a1473fc0df561f303942cde97e1d90 | 1c998f57b02576574c48943734fcc0e22e9a63c3 | refs/heads/master | 2020-05-19T08:02:44.881983 | 2011-04-01T20:13:39 | 2011-04-01T20:13:39 | 3,443,429 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,708 | h | #pragma once
#include "Stage.h"
#include "LevelConfig.h"
#include "IController.h"
class Hud;
class Board;
class MainCharacter;
class Enemy;
class MovableController;
/*!
Represents game level. This is actually "game itself":
board, obstacels, coins, main character, environment etc.
*/
class Level : Stage
{
public:
/*!
Initializes level using provided info.
@param game Game instance.
@param stage Contains path to config file.
*/
Level(Game* game, const StageInfo& stage);
~Level(void);
Game* getGame() const;
Board* getBoard() const;
MainCharacter* getMainCharacter() const;
/*!
Refreshes HUD and checks win and loss conditions.
*/
void refreshStatistics();
/*!
Implementation of IEventReceiver.
*/
virtual bool OnEvent(const irr::SEvent& event);
private:
LevelConfig _config;
Hud* _hud;
Board* _board;
MainCharacter* _mainCharacter;
irr::core::array<Enemy*> _enemies;
irr::core::array<IController*> _controllers;
bool _paused;
/*!
Pauses or resumes level.
*/
void togglePaused();
/*!
Implementation of Stage.
*/
void update();
/*!
Helper for creating scene nodes for characters.
*/
irr::scene::IAnimatedMeshSceneNode* createNode(
const LevelConfig::Model& model, irr::u32 position);
/*!
Helper for creating controllers for characters.
*/
MovableController* createController(
const LevelConfig::MovableController& config);
void createCamera();
void createBoard();
void createMainCharacter();
void createEnemies();
void removeControllers();
void removeCamera();
void removeBoard();
void removeMainCharacter();
void removeEnemies();
}; | [
"[email protected]"
]
| [
[
[
1,
88
]
]
]
|
6cadace8753b611414da8884e1693dcdd834f5f4 | 0bab4267636e3b06cb0e73fe9d31b0edd76260c2 | /freewar-alpha/AFirstChaos/src/init.cpp | 30f1631eabdefc241e06b345c6ff1e99a2da5c36 | []
| no_license | BackupTheBerlios/freewar-svn | 15fafedeed3ea1d374500d3430ff16b412b2f223 | aa1a28f19610dbce12be463d5ccd98f712631bc3 | refs/heads/master | 2021-01-10T19:54:11.599797 | 2006-12-10T21:45:11 | 2006-12-10T21:45:11 | 40,725,388 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,029 | cpp | //
// init.cpp for freewar in /u/ept2/skondr_m
//
// Made by mael skondras
// Login <[email protected]>
//
// Started on Tue May 11 18:22:22 2004 mael skondras
// Last update Tue Jun 29 18:49:59 2004 jonathan huot
//
#include "freewar.h"
// int init_sdl()
// {
// char err_msg[BUF_SIZE];
// if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0)
// {
// strcpy(err_msg, "Error: Couldn't initialize SDL: \n");
// strcat(err_msg, SDL_GetError());
// send_error_trap(err_msg, 1);
// return (1);
// }
// atexit(SDL_Quit);
// return (0);
// }
// int init_3d_menu(t_display *win)
// {
// char err_msg[BUF_SIZE];
// win->sdlVideoInfo = (SDL_VideoInfo*)SDL_GetVideoInfo();
// fprintf(fd_log, "%s: Checking mode 800x600@16bpp...", NAME);
// win->bpp=SDL_VideoModeOK(800, 600, 16, SDL_HWSURFACE);
// if(!(win->bpp))
// {
// fprintf(fd_log, "Mode not available.\n");
// return (1);
// }
// else
// {
// win->sdlMainScreen =
// SDL_SetVideoMode(800, 600,
// win->sdlVideoInfo->vfmt->BitsPerPixel,
// SDL_HWSURFACE | SDL_DOUBLEBUF
// /*| SDL_FULLSCREEN*/);
// fprintf(fd_log, "Mode OK\n");
// }
// return (0);
// }
int init_game(t_game_goodies *nfo)
{
//fprintf(fd_log, "%s: Initializing SDL...", NAME);
//if (init_sdl())
// return (1);
//fprintf(fd_log, "done.\n");
fprintf(fd_log, "%s: Initializing network engine...\n", NAME);
if (init_connection("127.0.0.1", NET_GAME_PORT))
return (1);
fprintf(fd_log, "%s: Network engine started.\n", NAME);
//fprintf(fd_log, "%s: Initializing 3D engine...\n", NAME);
//if (init_3d_menu(nfo->win))
// return (1);
//fprintf(fd_log, "%s: 3D engine started.\n", NAME);
fprintf(fd_log, "%s: Waiting for database info from engine...", NAME);
if (get_db_info(nfo))
{
fprintf(fd_log, "timed out!\n");
return(1);
}
else
fprintf(fd_log, "done.\n");
return (0);
}
| [
"doomsday@b2c3ed95-53e8-0310-b220-efb193137011"
]
| [
[
[
1,
75
]
]
]
|
e3c647a375aeb1d135e3808d616f7f4f6e8249ca | f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0 | /Depend/MyGUI/Tools/SkinEditor/SeparatorItem.cpp | 13db2034edf5bc7c76af4103218cdb43f906689a | []
| no_license | lxinhcn/starworld | 79ed06ca49d4064307ae73156574932d6185dbab | 86eb0fb8bd268994454b0cfe6419ffef3fc0fc80 | refs/heads/master | 2021-01-10T07:43:51.858394 | 2010-09-15T02:38:48 | 2010-09-15T02:38:48 | 47,859,019 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,659 | cpp | /*!
@file
@author Albert Semenov
@date 08/2010
*/
#include "precompiled.h"
#include "SeparatorItem.h"
namespace tools
{
SeparatorItem::SeparatorItem() :
mPropertySet(nullptr)
{
mPropertySet = new PropertySet();
mPropertySet->createChild("Visible", "Bool", "False");
mPropertySet->createChild("Offset", "Int", "0");
mPropertySet->createChild("Corner", "", "Center");
}
SeparatorItem::~SeparatorItem()
{
delete mPropertySet;
}
const MyGUI::UString& SeparatorItem::getName()
{
return mName;
}
void SeparatorItem::setName(const MyGUI::UString& _value)
{
mName = _value;
}
PropertySet* SeparatorItem::getPropertySet()
{
return mPropertySet;
}
MyGUI::Align SeparatorItem::getCorner()
{
return MyGUI::Align::parse(mPropertySet->getPropertyValue("Corner"));
}
void SeparatorItem::setCorner(MyGUI::Align _value)
{
mPropertySet->setPropertyValue("Corner", _value.print(), "");
}
void SeparatorItem::serialization(MyGUI::xml::Element* _node, MyGUI::Version _version)
{
_node->addAttribute("name", mName);
MyGUI::xml::Element* node = _node->createChild("PropertySet");
mPropertySet->serialization(node, _version);
}
void SeparatorItem::deserialization(MyGUI::xml::Element* _node, MyGUI::Version _version)
{
mName = _node->findAttribute("name");
MyGUI::xml::ElementEnumerator nodes = _node->getElementEnumerator();
while (nodes.next())
{
MyGUI::xml::Element* node = nodes.current();
if (node->getName() == "PropertySet")
{
mPropertySet->deserialization(node, _version);
}
}
}
} // namespace tools
| [
"albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c"
]
| [
[
[
1,
75
]
]
]
|
7bffb7b6befe3a1681cd9e3079223da5af2b9a75 | 45c0d7927220c0607531d6a0d7ce49e6399c8785 | /GlobeFactory/src/gfx/material_def/simple_color.hh | a214f3e9b86f65e637744d7f30715fb28600f73d | []
| 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 | 1,843 | hh | ////////////////////////////////////////////////////////////////////////////////
// Filename : simple_color.hh
// Authors : Creteur Clement
// Last edit : 30/01/10 - 03h46
// Comment :
////////////////////////////////////////////////////////////////////////////////
#ifndef MATERIAL_DEF_SIMPLE_COLOR_HH
#define MATERIAL_DEF_SIMPLE_COLOR_HH
#include "../../useful/all.hh"
#include "../material.hh"
#include "../material_type_descriptor.hh"
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
class SimpleColorMaterialDescriptor;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
class SimpleColorMaterial : public Material
{
friend class SimpleColorMaterialDescriptor;
public:
SimpleColorMaterial(const std::string& parFilename);
~SimpleColorMaterial();
void PreRender();
void PostRender();
private:
Color MColor;
};
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
class SimpleColorMaterialDescriptor : public MaterialTypeDescriptor
{
public:
SimpleColorMaterialDescriptor();
virtual ~SimpleColorMaterialDescriptor();
virtual SimpleColorMaterial* Load(XmlTree& parXmlFile) const;
virtual SimpleColorMaterial* Load(unsigned parCfgFileId) const;
virtual void PreRender() const;
virtual void PostRender() const;
};
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
#endif
| [
"creteur.c@8e971d8e-9cf3-0c36-aa0f-a7c54ab41ffc"
]
| [
[
[
1,
56
]
]
]
|
d4b869a07e5df83355a6fbdfdd0c9248fa547091 | c1bcff0f1321de8a6425723cdfa0b5aa65b5c81f | /TransX/tags/3.10/intercept.cpp | 3edb4759e19b8fc7f770099de4c9915cee8f6f37 | []
| no_license | net-lisias-orbiter/transx | 560266e7a4ef73ed29d9004e406fd8db28da9a43 | b9297027718a7499934a9614430aebb47422ce7f | refs/heads/master | 2023-06-27T14:16:10.697238 | 2010-09-05T01:18:54 | 2010-09-05T01:18:54 | 390,398,358 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,078 | cpp | #define STRICT
#include <windows.h>
#include <stdio.h>
#include <math.h>
#include "orbitersdk.h"
#include "mfd.h"
#include "intercept.h"
//extern double debug;
intercept::intercept()
{
iceptmethod=1;
newintercept=true;
gain=1;
lasttimecorrection=0;
fullorbits=halforbits=-1;
}
void intercept::resetintercept()
{
iceptmethod=1;
newintercept=true;
fullorbits=halforbits=-1;
}
void intercept::adjustorbitsdown()
{
if (halforbits>0)
{
halforbits=0;
}
else
{
if (fullorbits>0)
{
fullorbits--;
halforbits=1;
}
}
}
void intercept::improveinterceptstraightline(const ORBIT &craft, const ORBIT &target)
{
//int fullorbits=int(floor(craftorbitsahead));
//int halforbits=int((craftorbitsahead-fullorbits)*2);
double craftorbittime;
if (craft.geteccentricity()<1)
{
craftorbittime=craft.gettimeorbit();
}
else
{
craftorbittime=0;
fullorbits=halforbits=0;
}
double timeoffset=craft.gettimestamp()-target.gettimestamp();
newintercept=false;
double craftcosthi,craftsinthi,targetcosthi,targetsinthi;
craft.vectortothi(iceptalpha,&craftcosthi,&craftsinthi);
target.vectortothi(iceptbeta,&targetcosthi,&targetsinthi);
double crafttimeest=craft.GetTimeToThi(craftcosthi,craftsinthi,fullorbits,halforbits)+timeoffset;
if (crafttimeest-icepttimeoffset>craftorbittime/4)
{//You've just hit a border point on the orbit system
adjustorbitsdown();
crafttimeest=craft.GetTimeToThi(craftcosthi,craftsinthi,fullorbits,halforbits)+timeoffset;
}
double targettimeest=target.GetTimeToThi(targetcosthi,targetsinthi);
double orbittime;
double orbitnumber;
int temp;
target.gettimeorbit(&temp,&orbittime,targettimeest);
double diff=crafttimeest-targettimeest;
orbitnumber=floor(diff/orbittime+0.5);
diff-=orbitnumber*orbittime;
;
//
//Now correcting the costhi of the craft to account for the time error
//
double craftradius=craft.thitoradius(craftcosthi);
double craftangle=acos(craftcosthi);
if (craftsinthi<0) craftangle=-craftangle;
craftangle+=(-diff)*sqrt(craft.getangmomentum2())/(craftradius*craftradius);
//Get time corrected cos and sin of thi
craftcosthi=cos(craftangle);
craftsinthi=sin(craftangle);
// Get vectors for angles now that time error has been reduced
craft.thitovectors(craftcosthi,craftsinthi,&icraftpos,&icraftvel);
target.thitovectors(targetcosthi,targetsinthi,&itargetpos,&itargetvel);
//Find the (Now reduced) time error again
crafttimeest=craft.GetTimeToThi(craftcosthi,craftsinthi,fullorbits,halforbits)+timeoffset;
if (crafttimeest-icepttimeoffset>craftorbittime/4)
{//You've just hit a border point on the orbit system
adjustorbitsdown();//This
crafttimeest=craft.GetTimeToThi(craftcosthi,craftsinthi,fullorbits,halforbits)+timeoffset;
}
//targettimeest=target.GetTimeToThi(targetcosthi,targetsinthi);
diff=crafttimeest-targettimeest;
orbitnumber=floor(diff/orbittime+0.5);
diff-=orbitnumber*orbittime;
//Remove this error linearly from the craft position vector
icraftpos=icraftpos+icraftvel*(-diff);
//Find the time to closest approach from here
//We now have craft and target position and velocity
//Now use dotproduct to estimate remaining course correction
VECTOR3 relcraftpos=icraftpos-itargetpos;
VECTOR3 relcraftvel=icraftvel-itargetvel;
double timecorrection=-dotproduct(relcraftpos,relcraftvel)/dotproduct(relcraftvel,relcraftvel);
if (timecorrection*lasttimecorrection<0 && fabs(timecorrection/orbittime)>0.0001)
{//Oscillatory
gain=gain*0.5;
}
else
{
gain=gain*1.1;
if (gain>1) gain=1;
}
lasttimecorrection=timecorrection;
//Now calculate new vectors from the time correction
icraftpos=icraftpos+icraftvel*timecorrection*gain;
itargetpos=itargetpos+itargetvel*timecorrection*gain;
relcraftpos=icraftpos-itargetpos;
iceptalpha=icraftpos;
iceptbeta=itargetpos;
icepttimeoffset=crafttimeest+timecorrection*gain;
itimeintercept=icepttimeoffset+target.gettimestamp();
if (vectorsize(relcraftpos)*3>vectorsize(icraftpos))//Allows method to switch back if solution is no longer good
{
iceptmethod=1;
}
return;
}
void intercept::getorbitsoffset(int *ifullorbits,int *ihalforbits) const
{
*ifullorbits=fullorbits;
*ihalforbits=halforbits;
}
void intercept::updateintercept(const ORBIT &craft, const ORBIT &target,double craftorbitsahead)
// Updates the intercept structure holding closest approach between 'craft' and target. 'craft' may be hypothetical or actual
// Only one orbit may be hyperbolic
//To be broken up into submethods next time it's revised
{
if (!craft.isvalid() || !target.isvalid()) return;//Ensure no void updates!
double timeoffset=craft.gettimestamp()-target.gettimestamp();
iplanecept=crossproduct(craft.getplanevector(),target.getplanevector());
if (iceptmethod==2)
{
improveinterceptstraightline(craft,target);
return;
}
fullorbits=halforbits=-1;//This is not provided in this case
//Our task now is to come up with an initial guess for the intercept that works
//First option is to check to see whether the plane intercept vector is a good first guess.
//
const ORBIT *alpha, *beta;
//The inversion functionality no longer matters - timetovectors is now good enough to avoid the problem
alpha=&craft;
beta=⌖
double betacos=beta->getcurrcosthi();
double alphacos=alpha->getcurrcosthi();
double alphasin;
if (newintercept)
{
iceptradius=beta->getcurrradius();
newintercept=false;
}
double term1=alpha->getangmomentum2()/(alpha->getgmplanet()*alpha->geteccentricity());
double term2=1/alpha->geteccentricity();
double timea, timeb;
VECTOR3 alphaposa, alphaposb, alphavela,alphavelb, betaposa, betaposb, betavela, betavelb;
alphacos=term1/iceptradius-term2; //This gives the cos of the angle - can be (and frequently is) beyond range of cosine
double tradius=iceptradius;
if (alphacos>1) //Make angle legal !
{
alphacos=1;
tradius=fabs(alpha->getangmomentum2()/(alpha->getgmplanet()*(1-alpha->geteccentricity())));
}
if (alphacos<-1)
{
alphacos=-1;
tradius=fabs(alpha->getangmomentum2()/(alpha->getgmplanet()*(alpha->geteccentricity()+1)));
}
int full=int(floor(craftorbitsahead));
int half=int((craftorbitsahead-full)*2);
alpha->GetTimesToThi(alphacos, &timea, &timeb,full,half);//times are found so that you can tell where beta is
timea+=timeoffset;
timeb+=timeoffset;
alphasin=1-alphacos*alphacos;
if (alphasin>0)
{
alphasin=sqrt(alphasin);
}
else
{
alphasin=0;
}
alpha->thitovectors(alphacos,alphasin,&alphaposa,&alphavela);
alpha->thitovectors(alphacos,-alphasin,&alphaposb,&alphavelb);
if (tradius<alpha->getcurrradius() || alpha->geteccentricity()>1)
{
VECTOR3 temp=alphaposa;
alphaposa=alphaposb;
alphasin=-alphasin;
alphaposb=temp;
}
// Pos now guaranteed to match
//New system
beta->timetovectors(timea,&alphatime);
beta->timetovectors(timeb,&betatime);
alphatime.getposvel(&betaposa,&betavela);
betatime.getposvel(&betaposb,&betavelb);
bool abetter=(vectorsize2(betaposa-alphaposa)<vectorsize2(betaposb-alphaposb)); //Picks best on grounds of distance
if (timea<timeoffset)
{
if (craftorbitsahead<0.3)
{
abetter=false;//Invalidates first solution if in the past, if not looking ahead
}
else
{
timea+=alpha->gettimeorbit();
}
}
if (abetter)
{
//a is better
iceptradius=(vectorsize(betaposa)+iceptradius)/2;// Takes average of new and old as this converges better
itimeintercept=timea;
if (vectorsize2(betaposa-alphaposa)*9<vectorsize2(alphaposa))
{
iceptmethod=2;
icepttimeoffset=timea;
iceptalpha=alphaposa;
iceptbeta=betaposa;
fullorbits=full;
halforbits=half;
}
}
else
{
//b is better
iceptradius=(vectorsize(betaposb)+iceptradius)/2;
itimeintercept=timeb;
if (vectorsize2(betaposb-alphaposb)*9<vectorsize2(alphaposb))
{
iceptmethod=2;
icepttimeoffset=timeb;
iceptalpha=alphaposb;
iceptbeta=betaposb;
fullorbits=full;
halforbits=half;
}
}
if (abetter)
{
icraftpos=alphaposa;
icraftvel=alphavela;
itargetpos=betaposa;
itargetvel=betavela;
}
else
{
icraftpos=alphaposb;
icraftvel=alphavelb;
itargetpos=betaposb;
itargetvel=betavelb;
}
itimeintercept+=target.gettimestamp();
}
void intercept::getplanecept(VECTOR3 *planecept) const
{
*planecept=iplanecept;
}
void intercept::getpositions(VECTOR3 *craftpos, VECTOR3 *targetpos) const
{
*craftpos=icraftpos;
*targetpos=itargetpos;
}
void intercept::getrelpos(VECTOR3 *relpos) const
{
*relpos=icraftpos-itargetpos;
}
void intercept::getrelvel(VECTOR3 *relvel) const
{
*relvel=icraftvel-itargetvel;
}
void intercept::getvelocities(VECTOR3 *craftvel, VECTOR3 *targetvel) const
{
*craftvel=icraftvel;
*targetvel=itargetvel;
}
double intercept::gettimeintercept() const
{
return itimeintercept;
}
| [
"steve@5a6c10e1-6920-0410-8c7b-9669c677a970"
]
| [
[
[
1,
325
]
]
]
|
2157e58f4ff68de7c63ce450130b4f71a4b3dbdc | aefc3d630a28e054a438d13ab16d32f2d39ccb1e | /ModuleEx.cpp | 3eb352b50564bce2e928db49053f15e4a8052b41 | []
| no_license | imcooder/publicwince | e64305d86496b550116c312d2e9a67e7fb33c6f8 | 58a337768161e1a10664b4d5edc2aadfb2ab1328 | refs/heads/master | 2021-05-28T10:40:35.786601 | 2010-06-27T06:25:09 | 2010-06-27T06:25:09 | 32,301,144 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 975 | cpp |
#include "stdafx.h"
#include "ModuleEx.h"
#include "Ext_Type.h"
#include "HWDebug.h"
//////////////////////////////////////////////////////////////////////////
HWModule::HWModule() : m_hModule(NULL)
{
m_szModuleFilePath[0] = 0;
}
HWModule::~HWModule()
{
FreeLibrary();
}
BOOL HWModule::LoadLibrary( LPCTSTR pszPath)
{
BOOL blReturn = FALSE;
FreeLibrary();
if (m_hModule = ::LoadLibrary(pszPath))
{
StringCchCopy(m_szModuleFilePath, _countof(m_szModuleFilePath), pszPath);
blReturn = TRUE;
}
else
{
HWTRACE(TEXT("LoadLibrary %s failed %08X\n"), pszPath, GetLastError());
}
return blReturn;
}
void HWModule::FreeLibrary()
{
SAFE_FREE_LIBRARY(m_hModule);
m_szModuleFilePath[0] = 0;
m_blSucceed = FALSE;
}
BOOL HWModule::Succeed()
{
return m_hModule != NULL;
}
HMODULE HWModule::GetSafeHModule()
{
return m_hModule;
}
////////////////////////////////////////////////////////////////////////// | [
"[email protected]@a9ac5a9c-960a-11de-b8e1-0bcae535652c"
]
| [
[
[
1,
50
]
]
]
|
cc3faf35a5c52442ed46dabf9be0311664a8ac18 | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/nGENE Proj/DefaultFileArchive.cpp | 00fff163b1490aab5cd9f5ba3cbc4c048f21a253 | []
| 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 | 8,322 | cpp | /*
---------------------------------------------------------------------------
This source file is part of nGENE Tech.
Copyright (c) 2006- Wojciech Toman
This program is free software.
File: DefaultFileArchive.cpp
Version: 0.03
---------------------------------------------------------------------------
*/
#include "PrecompiledHeaders.h"
#include "DefaultFileArchive.h"
#include "BWTEncoder.h"
#include "FileArchiveEntry.h"
#include "FileArchiveEnumerator.h"
#include "HuffmanEncoder.h"
#include "MTFEncoder.h"
#include "RLEEncoder.h"
#if _MSC_VER < 1500
#include "omp.h"
#endif
namespace nGENE
{
// Initialize static members
const uint DefaultFileArchive::s_kArchiverVersion = 1;
DefaultFileArchive::DefaultFileArchive(const wstring& _fileName, dword _openMode):
FileArchive(_fileName, _openMode),
m_nVersion(s_kArchiverVersion),
m_nFlags(0),
m_nFilesCount(0),
m_nDataOffset(0)
{
}
//----------------------------------------------------------------------
DefaultFileArchive::~DefaultFileArchive()
{
}
//----------------------------------------------------------------------
VFS_ENTRY* DefaultFileArchive::getEntry(const string& _fileName)
{
// No file exists in the archive, so exit
if(m_FileHeaders.find(_fileName) == m_FileHeaders.end())
{
Log::log(LET_ERROR, L"nGENE", __WFILE__, __WFUNCTION__, __LINE__,
L"File does not exist in the archive");
return NULL;
}
SFileHeader& header = m_FileHeaders[_fileName];
// Read archive entry
seek(header.offset, SD_BEGIN);
char* data = new char[header.length];
read((char*)data, header.length);
VFS_ENTRY* pEntry = new VFS_ENTRY(data, header.length);
pEntry->setFileName(_fileName);
NGENE_DELETE_ARRAY(data);
// Decompress data
if((m_nFlags & DFAF_COMPRESS) && (header.flags & DFAF_COMPRESS))
{
// Perform inverse Huffman to really decompress data...
HuffmanEncoder huffman;
stringstream output1;
huffman.decode(output1, pEntry->getData(), pEntry->getSize());
// Perform inverse Run-Length Encoding
RLEEncoder rle;
stringstream output2;
rle.decode(output2, output1.str().c_str(), output1.str().length());
// Now perform inverse Move-to-Front
MTFEncoder mtf;
stringstream output3;
mtf.decode(output3, output2.str().c_str(), output2.str().length());
// Finally Run Burrows-Wheeler inverse transform
BWTEncoder bwt;
stringstream output4;
bwt.decode(output4, output3.str().c_str(), output3.str().length());
// Set entry data
pEntry->put(output4.str().c_str(), output4.str().length());
}
return pEntry;
}
//----------------------------------------------------------------------
bool DefaultFileArchive::hasEntry(const string& _fileName)
{
return (m_FileHeaders.find(_fileName) != m_FileHeaders.end());
}
//----------------------------------------------------------------------
void DefaultFileArchive::init()
{
if(m_dwOpenMode & OPEN_READ)
{
// Read archive file header
read((char*)&m_nVersion, sizeof(uint));
read((char*)&m_nFlags, sizeof(uint));
read((char*)&m_nFilesCount, sizeof(uint));
// Check if version is the same as current one
if(m_nVersion != s_kArchiverVersion)
{
Log::log(LET_WARNING, L"nGENE", __WFILE__, __WFUNCTION__, __LINE__,
L"Archive version: %d is different than currently supported by nGENE: %d",
m_nVersion, s_kArchiverVersion);
}
// Read files' headers
for(uint i = 0; i < m_nFilesCount; ++i)
{
short fileNameLength = 0;
read((char*)&fileNameLength, sizeof(short));
char* name = new char[fileNameLength + 1];
read(name, fileNameLength);
name[fileNameLength] = '\0';
SFileHeader header;
read((char*)&header.offset, sizeof(uint));
read((char*)&header.length, sizeof(uint));
read((char*)&header.flags, sizeof(uint));
m_FileHeaders[name] = header;
}
}
else
m_nDataOffset = 3 * sizeof(uint);
}
//----------------------------------------------------------------------
uint DefaultFileArchive::getEntriesCount()
{
return m_nFilesCount;
}
//----------------------------------------------------------------------
void DefaultFileArchive::insertFile(IFile* _file)
{
SFileHeader header;
header.length = _file->getSize();
header.offset = 0;
char* data = new char[header.length];
_file->read(data, header.length);
VFS_ENTRY entry(data, header.length);
m_vEntries.push_back(entry);
header.entry = m_nFilesCount;
header.flags = 0;
string stName(_file->getFileName().begin(), _file->getFileName().end());
m_FileHeaders[stName] = header;
m_nDataOffset += sizeof(short) + stName.length() * sizeof(char) + 3 * sizeof(uint);
++m_nFilesCount;
NGENE_DELETE_ARRAY(data);
}
//----------------------------------------------------------------------
void DefaultFileArchive::close()
{
if(m_dwOpenMode & OPEN_WRITE)
{
// Write archive file header
put((char*)&m_nVersion, sizeof(uint));
put((char*)&m_nFlags, sizeof(uint));
put((char*)&m_nFilesCount, sizeof(uint));
// If we have to compress, lets do it here
HashTable <string, SFileHeader>::iterator iter;
if(m_nFlags & DFAF_COMPRESS)
{
#pragma omp parallel for schedule( dynamic )
for(iter = m_FileHeaders.begin(); iter != m_FileHeaders.end(); ++iter)
{
VFS_ENTRY& entry = m_vEntries[iter->second.entry];
// First run Burrows-Wheeler transform on the data to make
// it more compression friendly
BWTEncoder bwt;
stringstream output1;
bwt.encode(output1, entry.getData(), entry.getSize());
// Now perform Move-to-Front to reduce data entropy
MTFEncoder mtf;
stringstream output2;
mtf.encode(output2, output1.str().c_str(), output1.str().length());
// Perform Run-Length Encoding to remove runs of identical characters
RLEEncoder rle;
stringstream output3;
rle.encode(output3, output2.str().c_str(), output2.str().length());
// Now perform Huffman to really compress data...
HuffmanEncoder huffman;
stringstream output4;
huffman.encode(output4, output3.str().c_str(), output3.str().length());
// Now set it as the entry data if it is smaller than originally was
if(output4.str().length() < entry.getSize())
{
iter->second.flags |= DFAF_COMPRESS;
entry.put(output4.str().c_str(), output4.str().length());
}
else
{
iter->second.flags |= 0;
}
}
}
// Write files' headers
uint nPrevSize = 0;
for(iter = m_FileHeaders.begin(); iter != m_FileHeaders.end(); ++iter)
{
short fileNameLength = (short)iter->first.length();
put((char*)&fileNameLength, sizeof(short));
put(iter->first.c_str(), fileNameLength);
SFileHeader& header = iter->second;
header.offset = m_nDataOffset + nPrevSize;
header.length = m_vEntries[iter->second.entry].getSize();
put((char*)&header.offset, sizeof(uint));
put((char*)&header.length, sizeof(uint));
// Write file compression flag
put((char*)&header.flags, sizeof(uint));
nPrevSize += header.length;
}
// Write files' entries
for(iter = m_FileHeaders.begin(); iter != m_FileHeaders.end(); ++iter)
{
VFS_ENTRY& entry = m_vEntries[iter->second.entry];
put((char*)entry.getData(), entry.getSize());
}
}
FileArchive::close();
}
//----------------------------------------------------------------------
//----------------------------------------------------------------------
//----------------------------------------------------------------------
DefaultFileArchiveFactory::DefaultFileArchiveFactory()
{
}
//----------------------------------------------------------------------
DefaultFileArchiveFactory::~DefaultFileArchiveFactory()
{
}
//----------------------------------------------------------------------
FileArchive* DefaultFileArchiveFactory::createFileArchive(const wstring& _fileName, dword _openMode)
{
return new DefaultFileArchive(_fileName, _openMode);
}
//----------------------------------------------------------------------
} | [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
]
| [
[
[
1,
276
]
]
]
|
20435da5fa763ae46e020a0a638d52f44e61e1d3 | b414a8f5b425617f897b5d97bbede96507e17d96 | /agdevku_qt_version/agdevku_GUI/utils/debug.h | 2758ae76ac2e33fa79d311f0053234601553fe56 | []
| no_license | agenthunt/agdevku | e7ce02e6f936a6980839fc538f158160c2060d05 | c6f6c8e9fbbb71f2b0288b8ab3ebd001aac6d5d7 | refs/heads/master | 2016-08-02T23:22:21.985871 | 2010-01-24T01:00:36 | 2010-01-24T01:00:36 | 32,114,047 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 885 | h | /*
* debug.h
*
* Created on: Oct 8, 2009
* Author: shailesh
*/
#ifndef DEBUG_H_
#define DEBUG_H_
//#define DEBUG_FLAG 1
#define HEX_DEBUG_FLAG 1
#include <iostream>
#include "../global/ExternDefOfGlobalVariables.h"
//#ifndef DEBUG_FLAG
//#define DEBUG(x)
//#else
#define DEBUG(x) \
if(COMMON_DEBUG == true){ \
std::cout <<"File:"<< __FILE__ <<",Line:" <<__LINE__ <<",msg:"<< x << std::endl;\
std::cout.flush();\
}
//#endif
#ifndef HEX_DEBUG_FLAG
#define DEBUG_HEX(x)
#else
#define DEBUG_HEX(x) \
std::cout <<"File:"<< __FILE__ <<",Line:" <<__LINE__ <<",msg:"<<std::hex<< x << std::endl;\
std::cout.flush();
#endif
#define DEBUG_B(x) \
if(BPLUSTREE_DEBUG == true){ \
std::cout <<x << std::endl; \
}
#define HEAP_VERBOSE_MSG(x) \
if(HEAP_VERBOSE == true){ \
std::cout <<x << std::endl; \
}
#endif /* DEBUG_H_ */
| [
"[email protected]@1dbec2b6-b029-11de-8bdf-3374eb5c7316"
]
| [
[
[
1,
42
]
]
]
|
33ccfa17a3a984fcd0b654faa8b145a0443e6104 | 5d92407e6596b28b8f6b676429d5d4a93dfab5cc | /course_version1.0.7/client/MyCondition.h | 583496483c66ddf19dd048108ceaffc715ff5df2 | []
| no_license | nearsyh/Database | a9634c458d54b7cee4d666bbe1a0ec1e62718c9d | 476214975a21d628f0467c860283735ab12a669e | refs/heads/master | 2021-01-19T17:57:16.697231 | 2011-12-29T17:59:07 | 2011-12-29T17:59:07 | 3,052,347 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 292 | h | class MyCondition{
char* condition;
char* op1;
char* op2;
char optr;
bool _isInt;
bool _isStr;
bool _isCol;
public:
MyCondition(char* cond);
bool isInt();
bool isCol();
bool isStr();
char* getOp1();
char* getOp2();
char getOptr();
bool judge(char* ctemp);
};
| [
"root@Near.(none)"
]
| [
[
[
1,
18
]
]
]
|
317ac4cd3016e3a49a76a4cf9d805d3a9077a3c3 | 04fec4cbb69789d44717aace6c8c5490f2cdfa47 | /include/wx/richtext/richtextctrl.h | decbca2496cd057c4810f25ece93e728fb1210cd | []
| 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 | 40,483 | h | /////////////////////////////////////////////////////////////////////////////
// Name: wx/richtext/richtextctrl.h
// Purpose: A rich edit control
// Author: Julian Smart
// Modified by:
// Created: 2005-09-30
// RCS-ID: $Id: richtextctrl.h 49804 2007-11-10 01:09:42Z VZ $
// Copyright: (c) Julian Smart
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifndef _WX_RICHTEXTCTRL_H_
#define _WX_RICHTEXTCTRL_H_
#include "wx/richtext/richtextbuffer.h"
#if wxUSE_RICHTEXT
#include "wx/scrolwin.h"
#include "wx/caret.h"
#include "wx/textctrl.h"
#if !defined(__WXGTK__) && !defined(__WXMAC__)
#define wxRICHTEXT_BUFFERED_PAINTING 1
#else
#define wxRICHTEXT_BUFFERED_PAINTING 0
#endif
class WXDLLIMPEXP_FWD_RICHTEXT wxRichTextStyleDefinition;
/*!
* Styles and flags
*/
/* Styles
*/
#define wxRE_READONLY 0x0010
#define wxRE_MULTILINE 0x0020
/* Flags
*/
#define wxRICHTEXT_SHIFT_DOWN 0x01
#define wxRICHTEXT_CTRL_DOWN 0x02
#define wxRICHTEXT_ALT_DOWN 0x04
/* Defaults
*/
#define wxRICHTEXT_DEFAULT_OVERALL_SIZE wxSize(-1, -1)
#define wxRICHTEXT_DEFAULT_IMAGE_SIZE wxSize(80, 80)
#define wxRICHTEXT_DEFAULT_SPACING 3
#define wxRICHTEXT_DEFAULT_MARGIN 3
#define wxRICHTEXT_DEFAULT_UNFOCUSSED_BACKGROUND wxColour(175, 175, 175)
#define wxRICHTEXT_DEFAULT_FOCUSSED_BACKGROUND wxColour(140, 140, 140)
#define wxRICHTEXT_DEFAULT_UNSELECTED_BACKGROUND wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE)
#define wxRICHTEXT_DEFAULT_TYPE_COLOUR wxColour(0, 0, 200)
#define wxRICHTEXT_DEFAULT_FOCUS_RECT_COLOUR wxColour(100, 80, 80)
#define wxRICHTEXT_DEFAULT_CARET_WIDTH 2
// Minimum buffer size before delayed layout kicks in
#define wxRICHTEXT_DEFAULT_DELAYED_LAYOUT_THRESHOLD 20000
// Milliseconds before layout occurs after resize
#define wxRICHTEXT_DEFAULT_LAYOUT_INTERVAL 50
/*!
* Forward declarations
*/
/*!
* wxRichTextItem class declaration
*/
// Drawing styles/states
#define wxRICHTEXT_SELECTED 0x01
#define wxRICHTEXT_TAGGED 0x02
// The control is focussed
#define wxRICHTEXT_FOCUSSED 0x04
// The item itself has the focus
#define wxRICHTEXT_IS_FOCUS 0x08
/*!
* wxRichTextCtrl class declaration
*/
class WXDLLIMPEXP_RICHTEXT wxRichTextCtrl : public wxTextCtrlBase,
public wxScrollHelper
{
DECLARE_CLASS( wxRichTextCtrl )
DECLARE_EVENT_TABLE()
public:
// Constructors
wxRichTextCtrl( );
wxRichTextCtrl( wxWindow* parent, wxWindowID id = -1, const wxString& value = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize,
long style = wxRE_MULTILINE, const wxValidator& validator = wxDefaultValidator, const wxString& name = wxTextCtrlNameStr);
virtual ~wxRichTextCtrl( );
// Operations
/// Creation
bool Create( wxWindow* parent, wxWindowID id = -1, const wxString& value = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize,
long style = wxRE_MULTILINE, const wxValidator& validator = wxDefaultValidator, const wxString& name = wxTextCtrlNameStr );
/// Member initialisation
void Init();
///// wxTextCtrl compatibility
// Accessors
virtual wxString GetValue() const;
virtual wxString GetRange(long from, long to) const;
virtual int GetLineLength(long lineNo) const ;
virtual wxString GetLineText(long lineNo) const ;
virtual int GetNumberOfLines() const ;
virtual bool IsModified() const ;
virtual bool IsEditable() const ;
// more readable flag testing methods
bool IsSingleLine() const { return !HasFlag(wxRE_MULTILINE); }
bool IsMultiLine() const { return !IsSingleLine(); }
// If the return values from and to are the same, there is no selection.
virtual void GetSelection(long* from, long* to) const;
virtual wxString GetStringSelection() const;
/// Get filename
wxString GetFilename() const { return m_filename; }
/// Set filename
void SetFilename(const wxString& filename) { m_filename = filename; }
/// Set the threshold in character positions for doing layout optimization during sizing
void SetDelayedLayoutThreshold(long threshold) { m_delayedLayoutThreshold = threshold; }
/// Get the threshold in character positions for doing layout optimization during sizing
long GetDelayedLayoutThreshold() const { return m_delayedLayoutThreshold; }
// Operations
// editing
virtual void Clear();
virtual void Replace(long from, long to, const wxString& value);
virtual void Remove(long from, long to);
// load/save the controls contents from/to the file
virtual bool DoLoadFile(const wxString& file, int fileType);
virtual bool DoSaveFile(const wxString& file = wxEmptyString, int fileType = wxRICHTEXT_TYPE_ANY);
/// Set the handler flags, controlling loading and saving
void SetHandlerFlags(int flags) { GetBuffer().SetHandlerFlags(flags); }
/// Get the handler flags, controlling loading and saving
int GetHandlerFlags() const { return GetBuffer().GetHandlerFlags(); }
// sets/clears the dirty flag
virtual void MarkDirty();
virtual void DiscardEdits();
// set the max number of characters which may be entered in a single line
// text control
virtual void SetMaxLength(unsigned long WXUNUSED(len)) { }
// writing text inserts it at the current position, appending always
// inserts it at the end
virtual void WriteText(const wxString& text);
virtual void AppendText(const wxString& text);
// text control under some platforms supports the text styles: these
// methods allow to apply the given text style to the given selection or to
// set/get the style which will be used for all appended text
virtual bool SetStyle(long start, long end, const wxTextAttr& style);
virtual bool SetStyle(long start, long end, const wxTextAttrEx& style);
virtual bool SetStyle(const wxRichTextRange& range, const wxRichTextAttr& style);
virtual bool GetStyle(long position, wxTextAttr& style);
virtual bool GetStyle(long position, wxTextAttrEx& style);
virtual bool GetStyle(long position, wxRichTextAttr& style);
// get the common set of styles for the range
virtual bool GetStyleForRange(const wxRichTextRange& range, wxRichTextAttr& style);
virtual bool GetStyleForRange(const wxRichTextRange& range, wxTextAttrEx& style);
// extended style setting operation with flags including:
// wxRICHTEXT_SETSTYLE_WITH_UNDO, wxRICHTEXT_SETSTYLE_OPTIMIZE, wxRICHTEXT_SETSTYLE_PARAGRAPHS_ONLY, wxRICHTEXT_SETSTYLE_CHARACTERS_ONLY
// see richtextbuffer.h for more details.
virtual bool SetStyleEx(long start, long end, const wxTextAttrEx& style, int flags = wxRICHTEXT_SETSTYLE_WITH_UNDO);
virtual bool SetStyleEx(const wxRichTextRange& range, const wxTextAttrEx& style, int flags = wxRICHTEXT_SETSTYLE_WITH_UNDO);
virtual bool SetStyleEx(const wxRichTextRange& range, const wxRichTextAttr& style, int flags = wxRICHTEXT_SETSTYLE_WITH_UNDO);
/// Get the content (uncombined) attributes for this position.
virtual bool GetUncombinedStyle(long position, wxTextAttr& style);
virtual bool GetUncombinedStyle(long position, wxTextAttrEx& style);
virtual bool GetUncombinedStyle(long position, wxRichTextAttr& style);
virtual bool SetDefaultStyle(const wxTextAttrEx& style);
virtual bool SetDefaultStyle(const wxTextAttr& style);
// TODO: change to GetDefaultStyle if we merge wxTextAttr and wxTextAttrEx
virtual const wxTextAttrEx& GetDefaultStyleEx() const;
virtual const wxTextAttr& GetDefaultStyle() const;
/// Set list style
virtual bool SetListStyle(const wxRichTextRange& range, wxRichTextListStyleDefinition* def, int flags = wxRICHTEXT_SETSTYLE_WITH_UNDO, int startFrom = 1, int specifiedLevel = -1);
virtual bool SetListStyle(const wxRichTextRange& range, const wxString& defName, int flags = wxRICHTEXT_SETSTYLE_WITH_UNDO, int startFrom = 1, int specifiedLevel = -1);
/// Clear list for given range
virtual bool ClearListStyle(const wxRichTextRange& range, int flags = wxRICHTEXT_SETSTYLE_WITH_UNDO);
/// Number/renumber any list elements in the given range
/// def/defName can be NULL/empty to indicate that the existing list style should be used.
virtual bool NumberList(const wxRichTextRange& range, wxRichTextListStyleDefinition* def = NULL, int flags = wxRICHTEXT_SETSTYLE_WITH_UNDO, int startFrom = 1, int specifiedLevel = -1);
virtual bool NumberList(const wxRichTextRange& range, const wxString& defName, int flags = wxRICHTEXT_SETSTYLE_WITH_UNDO, int startFrom = 1, int specifiedLevel = -1);
/// Promote the list items within the given range. promoteBy can be a positive or negative number, e.g. 1 or -1
/// def/defName can be NULL/empty to indicate that the existing list style should be used.
virtual bool PromoteList(int promoteBy, const wxRichTextRange& range, wxRichTextListStyleDefinition* def = NULL, int flags = wxRICHTEXT_SETSTYLE_WITH_UNDO, int specifiedLevel = -1);
virtual bool PromoteList(int promoteBy, const wxRichTextRange& range, const wxString& defName, int flags = wxRICHTEXT_SETSTYLE_WITH_UNDO, int specifiedLevel = -1);
/// Deletes the content in the given range
virtual bool Delete(const wxRichTextRange& range);
// translate between the position (which is just an index in the text ctrl
// considering all its contents as a single strings) and (x, y) coordinates
// which represent column and line.
virtual long XYToPosition(long x, long y) const;
virtual bool PositionToXY(long pos, long *x, long *y) const;
virtual void ShowPosition(long pos);
// find the character at position given in pixels
//
// NB: pt is in device coords (not adjusted for the client area origin nor
// scrolling)
virtual wxTextCtrlHitTestResult HitTest(const wxPoint& pt, long *pos) const;
virtual wxTextCtrlHitTestResult HitTest(const wxPoint& pt,
wxTextCoord *col,
wxTextCoord *row) const;
// Clipboard operations
virtual void Copy();
virtual void Cut();
virtual void Paste();
virtual void DeleteSelection();
virtual bool CanCopy() const;
virtual bool CanCut() const;
virtual bool CanPaste() const;
virtual bool CanDeleteSelection() const;
// Undo/redo
virtual void Undo();
virtual void Redo();
virtual bool CanUndo() const;
virtual bool CanRedo() const;
// Insertion point
virtual void SetInsertionPoint(long pos);
virtual void SetInsertionPointEnd();
virtual long GetInsertionPoint() const;
virtual wxTextPos GetLastPosition() const;
virtual void SetSelection(long from, long to);
virtual void SelectAll();
virtual void SetEditable(bool editable);
/// Call Freeze to prevent refresh
virtual void Freeze();
/// Call Thaw to refresh
virtual void Thaw();
/// Call Thaw to refresh
virtual bool IsFrozen() const { return m_freezeCount > 0; }
virtual bool HasSelection() const;
///// Functionality specific to wxRichTextCtrl
/// Write an image at the current insertion point. Supply optional type to use
/// for internal and file storage of the raw data.
virtual bool WriteImage(const wxImage& image, int bitmapType = wxBITMAP_TYPE_PNG);
/// Write a bitmap at the current insertion point. Supply optional type to use
/// for internal and file storage of the raw data.
virtual bool WriteImage(const wxBitmap& bitmap, int bitmapType = wxBITMAP_TYPE_PNG);
/// Load an image from file and write at the current insertion point.
virtual bool WriteImage(const wxString& filename, int bitmapType);
/// Write an image block at the current insertion point.
virtual bool WriteImage(const wxRichTextImageBlock& imageBlock);
/// Insert a newline (actually paragraph) at the current insertion point.
virtual bool Newline();
/// Insert a line break at the current insertion point.
virtual bool LineBreak();
/// Set basic (overall) style
virtual void SetBasicStyle(const wxTextAttrEx& style) { GetBuffer().SetBasicStyle(style); }
virtual void SetBasicStyle(const wxRichTextAttr& style) { GetBuffer().SetBasicStyle(style); }
/// Get basic (overall) style
virtual const wxTextAttrEx& GetBasicStyle() const { return GetBuffer().GetBasicStyle(); }
/// Begin using a style
virtual bool BeginStyle(const wxTextAttrEx& style) { return GetBuffer().BeginStyle(style); }
/// End the style
virtual bool EndStyle() { return GetBuffer().EndStyle(); }
/// End all styles
virtual bool EndAllStyles() { return GetBuffer().EndAllStyles(); }
/// Begin using bold
bool BeginBold() { return GetBuffer().BeginBold(); }
/// End using bold
bool EndBold() { return GetBuffer().EndBold(); }
/// Begin using italic
bool BeginItalic() { return GetBuffer().BeginItalic(); }
/// End using italic
bool EndItalic() { return GetBuffer().EndItalic(); }
/// Begin using underline
bool BeginUnderline() { return GetBuffer().BeginUnderline(); }
/// End using underline
bool EndUnderline() { return GetBuffer().EndUnderline(); }
/// Begin using point size
bool BeginFontSize(int pointSize) { return GetBuffer().BeginFontSize(pointSize); }
/// End using point size
bool EndFontSize() { return GetBuffer().EndFontSize(); }
/// Begin using this font
bool BeginFont(const wxFont& font) { return GetBuffer().BeginFont(font); }
/// End using a font
bool EndFont() { return GetBuffer().EndFont(); }
/// Begin using this colour
bool BeginTextColour(const wxColour& colour) { return GetBuffer().BeginTextColour(colour); }
/// End using a colour
bool EndTextColour() { return GetBuffer().EndTextColour(); }
/// Begin using alignment
bool BeginAlignment(wxTextAttrAlignment alignment) { return GetBuffer().BeginAlignment(alignment); }
/// End alignment
bool EndAlignment() { return GetBuffer().EndAlignment(); }
/// Begin left indent
bool BeginLeftIndent(int leftIndent, int leftSubIndent = 0) { return GetBuffer().BeginLeftIndent(leftIndent, leftSubIndent); }
/// End left indent
bool EndLeftIndent() { return GetBuffer().EndLeftIndent(); }
/// Begin right indent
bool BeginRightIndent(int rightIndent) { return GetBuffer().BeginRightIndent(rightIndent); }
/// End right indent
bool EndRightIndent() { return GetBuffer().EndRightIndent(); }
/// Begin paragraph spacing
bool BeginParagraphSpacing(int before, int after) { return GetBuffer().BeginParagraphSpacing(before, after); }
/// End paragraph spacing
bool EndParagraphSpacing() { return GetBuffer().EndParagraphSpacing(); }
/// Begin line spacing
bool BeginLineSpacing(int lineSpacing) { return GetBuffer().BeginLineSpacing(lineSpacing); }
/// End line spacing
bool EndLineSpacing() { return GetBuffer().EndLineSpacing(); }
/// Begin numbered bullet
bool BeginNumberedBullet(int bulletNumber, int leftIndent, int leftSubIndent, int bulletStyle = wxTEXT_ATTR_BULLET_STYLE_ARABIC|wxTEXT_ATTR_BULLET_STYLE_PERIOD)
{ return GetBuffer().BeginNumberedBullet(bulletNumber, leftIndent, leftSubIndent, bulletStyle); }
/// End numbered bullet
bool EndNumberedBullet() { return GetBuffer().EndNumberedBullet(); }
/// Begin symbol bullet
bool BeginSymbolBullet(const wxString& symbol, int leftIndent, int leftSubIndent, int bulletStyle = wxTEXT_ATTR_BULLET_STYLE_SYMBOL)
{ return GetBuffer().BeginSymbolBullet(symbol, leftIndent, leftSubIndent, bulletStyle); }
/// End symbol bullet
bool EndSymbolBullet() { return GetBuffer().EndSymbolBullet(); }
/// Begin standard bullet
bool BeginStandardBullet(const wxString& bulletName, int leftIndent, int leftSubIndent, int bulletStyle = wxTEXT_ATTR_BULLET_STYLE_STANDARD)
{ return GetBuffer().BeginStandardBullet(bulletName, leftIndent, leftSubIndent, bulletStyle); }
/// End standard bullet
bool EndStandardBullet() { return GetBuffer().EndStandardBullet(); }
/// Begin named character style
bool BeginCharacterStyle(const wxString& characterStyle) { return GetBuffer().BeginCharacterStyle(characterStyle); }
/// End named character style
bool EndCharacterStyle() { return GetBuffer().EndCharacterStyle(); }
/// Begin named paragraph style
bool BeginParagraphStyle(const wxString& paragraphStyle) { return GetBuffer().BeginParagraphStyle(paragraphStyle); }
/// End named character style
bool EndParagraphStyle() { return GetBuffer().EndParagraphStyle(); }
/// Begin named list style
bool BeginListStyle(const wxString& listStyle, int level = 1, int number = 1) { return GetBuffer().BeginListStyle(listStyle, level, number); }
/// End named character style
bool EndListStyle() { return GetBuffer().EndListStyle(); }
/// Begin URL
bool BeginURL(const wxString& url, const wxString& characterStyle = wxEmptyString) { return GetBuffer().BeginURL(url, characterStyle); }
/// End URL
bool EndURL() { return GetBuffer().EndURL(); }
/// Sets the default style to the style under the cursor
bool SetDefaultStyleToCursorStyle();
/// Clear the selection
virtual void SelectNone();
/// Select the word at the given character position
virtual bool SelectWord(long position);
/// Get/set the selection range in character positions. -1, -1 means no selection.
/// The range is in API convention, i.e. a single character selection is denoted
/// by (n, n+1)
wxRichTextRange GetSelectionRange() const;
void SetSelectionRange(const wxRichTextRange& range);
/// Get/set the selection range in character positions. -1, -1 means no selection.
/// The range is in internal format, i.e. a single character selection is denoted
/// by (n, n)
const wxRichTextRange& GetInternalSelectionRange() const { return m_selectionRange; }
void SetInternalSelectionRange(const wxRichTextRange& range) { m_selectionRange = range; }
/// Add a new paragraph of text to the end of the buffer
virtual wxRichTextRange AddParagraph(const wxString& text);
/// Add an image
virtual wxRichTextRange AddImage(const wxImage& image);
/// Layout the buffer: which we must do before certain operations, such as
/// setting the caret position.
virtual bool LayoutContent(bool onlyVisibleRect = false);
/// Move the caret to the given character position
virtual bool MoveCaret(long pos, bool showAtLineStart = false);
/// Move right
virtual bool MoveRight(int noPositions = 1, int flags = 0);
/// Move left
virtual bool MoveLeft(int noPositions = 1, int flags = 0);
/// Move up
virtual bool MoveUp(int noLines = 1, int flags = 0);
/// Move up
virtual bool MoveDown(int noLines = 1, int flags = 0);
/// Move to the end of the line
virtual bool MoveToLineEnd(int flags = 0);
/// Move to the start of the line
virtual bool MoveToLineStart(int flags = 0);
/// Move to the end of the paragraph
virtual bool MoveToParagraphEnd(int flags = 0);
/// Move to the start of the paragraph
virtual bool MoveToParagraphStart(int flags = 0);
/// Move to the start of the buffer
virtual bool MoveHome(int flags = 0);
/// Move to the end of the buffer
virtual bool MoveEnd(int flags = 0);
/// Move n pages up
virtual bool PageUp(int noPages = 1, int flags = 0);
/// Move n pages down
virtual bool PageDown(int noPages = 1, int flags = 0);
/// Move n words left
virtual bool WordLeft(int noPages = 1, int flags = 0);
/// Move n words right
virtual bool WordRight(int noPages = 1, int flags = 0);
/// Returns the buffer associated with the control.
wxRichTextBuffer& GetBuffer() { return m_buffer; }
const wxRichTextBuffer& GetBuffer() const { return m_buffer; }
/// Start batching undo history for commands.
virtual bool BeginBatchUndo(const wxString& cmdName) { return m_buffer.BeginBatchUndo(cmdName); }
/// End batching undo history for commands.
virtual bool EndBatchUndo() { return m_buffer.EndBatchUndo(); }
/// Are we batching undo history for commands?
virtual bool BatchingUndo() const { return m_buffer.BatchingUndo(); }
/// Start suppressing undo history for commands.
virtual bool BeginSuppressUndo() { return m_buffer.BeginSuppressUndo(); }
/// End suppressing undo history for commands.
virtual bool EndSuppressUndo() { return m_buffer.EndSuppressUndo(); }
/// Are we suppressing undo history for commands?
virtual bool SuppressingUndo() const { return m_buffer.SuppressingUndo(); }
/// Test if this whole range has character attributes of the specified kind. If any
/// of the attributes are different within the range, the test fails. You
/// can use this to implement, for example, bold button updating. style must have
/// flags indicating which attributes are of interest.
virtual bool HasCharacterAttributes(const wxRichTextRange& range, const wxTextAttrEx& style) const
{
return GetBuffer().HasCharacterAttributes(range.ToInternal(), style);
}
virtual bool HasCharacterAttributes(const wxRichTextRange& range, const wxRichTextAttr& style) const
{
return GetBuffer().HasCharacterAttributes(range.ToInternal(), style);
}
/// Test if this whole range has paragraph attributes of the specified kind. If any
/// of the attributes are different within the range, the test fails. You
/// can use this to implement, for example, centering button updating. style must have
/// flags indicating which attributes are of interest.
virtual bool HasParagraphAttributes(const wxRichTextRange& range, const wxTextAttrEx& style) const
{
return GetBuffer().HasParagraphAttributes(range.ToInternal(), style);
}
virtual bool HasParagraphAttributes(const wxRichTextRange& range, const wxRichTextAttr& style) const
{
return GetBuffer().HasParagraphAttributes(range.ToInternal(), style);
}
/// Is all of the selection bold?
virtual bool IsSelectionBold();
/// Is all of the selection italics?
virtual bool IsSelectionItalics();
/// Is all of the selection underlined?
virtual bool IsSelectionUnderlined();
/// Is all of the selection aligned according to the specified flag?
virtual bool IsSelectionAligned(wxTextAttrAlignment alignment);
/// Apply bold to the selection
virtual bool ApplyBoldToSelection();
/// Apply italic to the selection
virtual bool ApplyItalicToSelection();
/// Apply underline to the selection
virtual bool ApplyUnderlineToSelection();
/// Apply alignment to the selection
virtual bool ApplyAlignmentToSelection(wxTextAttrAlignment alignment);
/// Apply a named style to the selection
virtual bool ApplyStyle(wxRichTextStyleDefinition* def);
/// Set style sheet, if any
void SetStyleSheet(wxRichTextStyleSheet* styleSheet) { GetBuffer().SetStyleSheet(styleSheet); }
wxRichTextStyleSheet* GetStyleSheet() const { return GetBuffer().GetStyleSheet(); }
/// Push style sheet to top of stack
bool PushStyleSheet(wxRichTextStyleSheet* styleSheet) { return GetBuffer().PushStyleSheet(styleSheet); }
/// Pop style sheet from top of stack
wxRichTextStyleSheet* PopStyleSheet() { return GetBuffer().PopStyleSheet(); }
/// Apply the style sheet to the buffer, for example if the styles have changed.
bool ApplyStyleSheet(wxRichTextStyleSheet* styleSheet = NULL);
// Command handlers
void Command(wxCommandEvent& event);
void OnDropFiles(wxDropFilesEvent& event);
void OnCaptureLost(wxMouseCaptureLostEvent& event);
void OnCut(wxCommandEvent& event);
void OnCopy(wxCommandEvent& event);
void OnPaste(wxCommandEvent& event);
void OnUndo(wxCommandEvent& event);
void OnRedo(wxCommandEvent& event);
void OnSelectAll(wxCommandEvent& event);
void OnClear(wxCommandEvent& event);
void OnUpdateCut(wxUpdateUIEvent& event);
void OnUpdateCopy(wxUpdateUIEvent& event);
void OnUpdatePaste(wxUpdateUIEvent& event);
void OnUpdateUndo(wxUpdateUIEvent& event);
void OnUpdateRedo(wxUpdateUIEvent& event);
void OnUpdateSelectAll(wxUpdateUIEvent& event);
void OnUpdateClear(wxUpdateUIEvent& event);
// Show a context menu for Rich Edit controls (the standard
// EDIT control has one already)
void OnContextMenu(wxContextMenuEvent& event);
// Event handlers
/// Painting
void OnPaint(wxPaintEvent& event);
void OnEraseBackground(wxEraseEvent& event);
/// Left-click
void OnLeftClick(wxMouseEvent& event);
/// Left-up
void OnLeftUp(wxMouseEvent& event);
/// Motion
void OnMoveMouse(wxMouseEvent& event);
/// Left-double-click
void OnLeftDClick(wxMouseEvent& event);
/// Middle-click
void OnMiddleClick(wxMouseEvent& event);
/// Right-click
void OnRightClick(wxMouseEvent& event);
/// Key press
void OnChar(wxKeyEvent& event);
/// Sizing
void OnSize(wxSizeEvent& event);
/// Setting/losing focus
void OnSetFocus(wxFocusEvent& event);
void OnKillFocus(wxFocusEvent& event);
/// Idle-time processing
void OnIdle(wxIdleEvent& event);
/// Scrolling
void OnScroll(wxScrollWinEvent& event);
/// Set font, and also default attributes
virtual bool SetFont(const wxFont& font);
/// Set up scrollbars, e.g. after a resize
virtual void SetupScrollbars(bool atTop = false);
/// Keyboard navigation
virtual bool KeyboardNavigate(int keyCode, int flags);
/// Paint the background
virtual void PaintBackground(wxDC& dc);
#if wxRICHTEXT_BUFFERED_PAINTING
/// Recreate buffer bitmap if necessary
virtual bool RecreateBuffer(const wxSize& size = wxDefaultSize);
#endif
/// Set the selection
virtual void DoSetSelection(long from, long to, bool scrollCaret = true);
/// Write text
virtual void DoWriteText(const wxString& value, int flags = 0);
/// Should we inherit colours?
virtual bool ShouldInheritColours() const { return false; }
/// Position the caret
virtual void PositionCaret();
/// Extend the selection, returning true if the selection was
/// changed. Selections are in caret positions.
virtual bool ExtendSelection(long oldPosition, long newPosition, int flags);
/// Scroll into view. This takes a _caret_ position.
virtual bool ScrollIntoView(long position, int keyCode);
/// The caret position is the character position just before the caret.
/// A value of -1 means the caret is at the start of the buffer.
void SetCaretPosition(long position, bool showAtLineStart = false) ;
long GetCaretPosition() const { return m_caretPosition; }
/// The adjusted caret position is the character position adjusted to take
/// into account whether we're at the start of a paragraph, in which case
/// style information should be taken from the next position, not current one.
long GetAdjustedCaretPosition(long caretPos) const;
/// Move caret one visual step forward: this may mean setting a flag
/// and keeping the same position if we're going from the end of one line
/// to the start of the next, which may be the exact same caret position.
void MoveCaretForward(long oldPosition) ;
/// Move caret one visual step forward: this may mean setting a flag
/// and keeping the same position if we're going from the end of one line
/// to the start of the next, which may be the exact same caret position.
void MoveCaretBack(long oldPosition) ;
/// Get the caret height and position for the given character position
bool GetCaretPositionForIndex(long position, wxRect& rect);
/// Gets the line for the visible caret position. If the caret is
/// shown at the very end of the line, it means the next character is actually
/// on the following line. So let's get the line we're expecting to find
/// if this is the case.
wxRichTextLine* GetVisibleLineForCaretPosition(long caretPosition) const;
/// Gets the command processor
wxCommandProcessor* GetCommandProcessor() const { return GetBuffer().GetCommandProcessor(); }
/// Delete content if there is a selection, e.g. when pressing a key.
/// Returns the new caret position in newPos, or leaves it if there
/// was no action.
bool DeleteSelectedContent(long* newPos= NULL);
/// Transform logical to physical
wxPoint GetPhysicalPoint(const wxPoint& ptLogical) const;
/// Transform physical to logical
wxPoint GetLogicalPoint(const wxPoint& ptPhysical) const;
/// Finds the caret position for the next word. Direction
/// is 1 (forward) or -1 (backwards).
virtual long FindNextWordPosition(int direction = 1) const;
/// Is the given position visible on the screen?
bool IsPositionVisible(long pos) const;
/// Returns the first visible position in the current view
long GetFirstVisiblePosition() const;
/// Returns the caret position since the default formatting was changed. As
/// soon as this position changes, we no longer reflect the default style
/// in the UI. A value of -2 means that we should only reflect the style of the
/// content under the caret.
long GetCaretPositionForDefaultStyle() const { return m_caretPositionForDefaultStyle; }
/// Set the caret position for the default style that the user is selecting.
void SetCaretPositionForDefaultStyle(long pos) { m_caretPositionForDefaultStyle = pos; }
/// Should the UI reflect the default style chosen by the user, rather than the style under
/// the caret?
bool IsDefaultStyleShowing() const { return m_caretPositionForDefaultStyle != -2; }
/// Convenience function that tells the control to start reflecting the default
/// style, since the user is changing it.
void SetAndShowDefaultStyle(const wxRichTextAttr& attr)
{
SetDefaultStyle(attr);
SetCaretPositionForDefaultStyle(GetCaretPosition());
}
/// Get the first visible point in the window
wxPoint GetFirstVisiblePoint() const;
// Implementation
/// Font names take a long time to retrieve, so cache them (on demand)
static const wxArrayString& GetAvailableFontNames();
static void ClearAvailableFontNames();
WX_FORWARD_TO_SCROLL_HELPER()
// Overrides
protected:
virtual wxSize DoGetBestSize() const ;
virtual void DoSetValue(const wxString& value, int flags = 0);
// Data members
private:
/// Allows nested Freeze/Thaw
int m_freezeCount;
#if wxRICHTEXT_BUFFERED_PAINTING
/// Buffer bitmap
wxBitmap m_bufferBitmap;
#endif
/// Text buffer
wxRichTextBuffer m_buffer;
wxMenu* m_contextMenu;
/// Caret position (1 less than the character position, so -1 is the
/// first caret position).
long m_caretPosition;
/// Caret position when the default formatting has been changed. As
/// soon as this position changes, we no longer reflect the default style
/// in the UI.
long m_caretPositionForDefaultStyle;
/// Selection range in character positions. -2, -2 means no selection.
wxRichTextRange m_selectionRange;
/// Anchor so we know how to extend the selection
/// It's a caret position since it's between two characters.
long m_selectionAnchor;
/// Are we editable?
bool m_editable;
/// Are we showing the caret position at the start of a line
/// instead of at the end of the previous one?
bool m_caretAtLineStart;
/// Are we dragging a selection?
bool m_dragging;
/// Start position for drag
wxPoint m_dragStart;
/// Do we need full layout in idle?
bool m_fullLayoutRequired;
wxLongLong m_fullLayoutTime;
long m_fullLayoutSavedPosition;
/// Threshold for doing delayed layout
long m_delayedLayoutThreshold;
/// Cursors
wxCursor m_textCursor;
wxCursor m_urlCursor;
static wxArrayString sm_availableFontNames;
};
/*!
* wxRichTextEvent - the event class for wxRichTextCtrl notifications
*/
class WXDLLIMPEXP_RICHTEXT wxRichTextEvent : public wxNotifyEvent
{
public:
wxRichTextEvent(wxEventType commandType = wxEVT_NULL, int winid = 0)
: wxNotifyEvent(commandType, winid),
m_flags(0), m_position(-1), m_oldStyleSheet(NULL), m_newStyleSheet(NULL),
m_char((wxChar) 0)
{ }
wxRichTextEvent(const wxRichTextEvent& event)
: wxNotifyEvent(event),
m_flags(event.m_flags), m_position(-1),
m_oldStyleSheet(event.m_oldStyleSheet), m_newStyleSheet(event.m_newStyleSheet),
m_char((wxChar) 0)
{ }
long GetPosition() const { return m_position; }
void SetPosition(long pos) { m_position = pos; }
int GetFlags() const { return m_flags; }
void SetFlags(int flags) { m_flags = flags; }
wxRichTextStyleSheet* GetOldStyleSheet() const { return m_oldStyleSheet; }
void SetOldStyleSheet(wxRichTextStyleSheet* sheet) { m_oldStyleSheet = sheet; }
wxRichTextStyleSheet* GetNewStyleSheet() const { return m_newStyleSheet; }
void SetNewStyleSheet(wxRichTextStyleSheet* sheet) { m_newStyleSheet = sheet; }
const wxRichTextRange& GetRange() const { return m_range; }
void SetRange(const wxRichTextRange& range) { m_range = range; }
wxChar GetCharacter() const { return m_char; }
void SetCharacter(wxChar ch) { m_char = ch; }
virtual wxEvent *Clone() const { return new wxRichTextEvent(*this); }
protected:
int m_flags;
long m_position;
wxRichTextStyleSheet* m_oldStyleSheet;
wxRichTextStyleSheet* m_newStyleSheet;
wxRichTextRange m_range;
wxChar m_char;
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxRichTextEvent)
};
/*!
* wxRichTextCtrl event macros
*/
BEGIN_DECLARE_EVENT_TYPES()
DECLARE_EXPORTED_EVENT_TYPE(WXDLLIMPEXP_RICHTEXT, wxEVT_COMMAND_RICHTEXT_LEFT_CLICK, 2602)
DECLARE_EXPORTED_EVENT_TYPE(WXDLLIMPEXP_RICHTEXT, wxEVT_COMMAND_RICHTEXT_RIGHT_CLICK, 2603)
DECLARE_EXPORTED_EVENT_TYPE(WXDLLIMPEXP_RICHTEXT, wxEVT_COMMAND_RICHTEXT_MIDDLE_CLICK, 2604)
DECLARE_EXPORTED_EVENT_TYPE(WXDLLIMPEXP_RICHTEXT, wxEVT_COMMAND_RICHTEXT_LEFT_DCLICK, 2605)
DECLARE_EXPORTED_EVENT_TYPE(WXDLLIMPEXP_RICHTEXT, wxEVT_COMMAND_RICHTEXT_RETURN, 2606)
DECLARE_EXPORTED_EVENT_TYPE(WXDLLIMPEXP_RICHTEXT, wxEVT_COMMAND_RICHTEXT_CHARACTER, 2607)
DECLARE_EXPORTED_EVENT_TYPE(WXDLLIMPEXP_RICHTEXT, wxEVT_COMMAND_RICHTEXT_DELETE, 2608)
DECLARE_EXPORTED_EVENT_TYPE(WXDLLIMPEXP_RICHTEXT, wxEVT_COMMAND_RICHTEXT_STYLESHEET_CHANGING, 2609)
DECLARE_EXPORTED_EVENT_TYPE(WXDLLIMPEXP_RICHTEXT, wxEVT_COMMAND_RICHTEXT_STYLESHEET_CHANGED, 2610)
DECLARE_EXPORTED_EVENT_TYPE(WXDLLIMPEXP_RICHTEXT, wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACING, 2611)
DECLARE_EXPORTED_EVENT_TYPE(WXDLLIMPEXP_RICHTEXT, wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACED, 2612)
DECLARE_EXPORTED_EVENT_TYPE(WXDLLIMPEXP_RICHTEXT, wxEVT_COMMAND_RICHTEXT_CONTENT_INSERTED, 2613)
DECLARE_EXPORTED_EVENT_TYPE(WXDLLIMPEXP_RICHTEXT, wxEVT_COMMAND_RICHTEXT_CONTENT_DELETED, 2614)
DECLARE_EXPORTED_EVENT_TYPE(WXDLLIMPEXP_RICHTEXT, wxEVT_COMMAND_RICHTEXT_STYLE_CHANGED, 2615)
DECLARE_EXPORTED_EVENT_TYPE(WXDLLIMPEXP_RICHTEXT, wxEVT_COMMAND_RICHTEXT_SELECTION_CHANGED, 2616)
END_DECLARE_EVENT_TYPES()
typedef void (wxEvtHandler::*wxRichTextEventFunction)(wxRichTextEvent&);
#define EVT_RICHTEXT_LEFT_CLICK(id, fn) DECLARE_EVENT_TABLE_ENTRY( wxEVT_COMMAND_RICHTEXT_LEFT_CLICK, id, -1, (wxObjectEventFunction) (wxEventFunction) wxStaticCastEvent( wxRichTextEventFunction, & fn ), NULL ),
#define EVT_RICHTEXT_RIGHT_CLICK(id, fn) DECLARE_EVENT_TABLE_ENTRY( wxEVT_COMMAND_RICHTEXT_RIGHT_CLICK, id, -1, (wxObjectEventFunction) (wxEventFunction) wxStaticCastEvent( wxRichTextEventFunction, & fn ), NULL ),
#define EVT_RICHTEXT_MIDDLE_CLICK(id, fn) DECLARE_EVENT_TABLE_ENTRY( wxEVT_COMMAND_RICHTEXT_MIDDLE_CLICK, id, -1, (wxObjectEventFunction) (wxEventFunction) wxStaticCastEvent( wxRichTextEventFunction, & fn ), NULL ),
#define EVT_RICHTEXT_LEFT_DCLICK(id, fn) DECLARE_EVENT_TABLE_ENTRY( wxEVT_COMMAND_RICHTEXT_LEFT_DCLICK, id, -1, (wxObjectEventFunction) (wxEventFunction) wxStaticCastEvent( wxRichTextEventFunction, & fn ), NULL ),
#define EVT_RICHTEXT_RETURN(id, fn) DECLARE_EVENT_TABLE_ENTRY( wxEVT_COMMAND_RICHTEXT_RETURN, id, -1, (wxObjectEventFunction) (wxEventFunction) wxStaticCastEvent( wxRichTextEventFunction, & fn ), NULL ),
#define EVT_RICHTEXT_CHARACTER(id, fn) DECLARE_EVENT_TABLE_ENTRY( wxEVT_COMMAND_RICHTEXT_CHARACTER, id, -1, (wxObjectEventFunction) (wxEventFunction) wxStaticCastEvent( wxRichTextEventFunction, & fn ), NULL ),
#define EVT_RICHTEXT_DELETE(id, fn) DECLARE_EVENT_TABLE_ENTRY( wxEVT_COMMAND_RICHTEXT_DELETE, id, -1, (wxObjectEventFunction) (wxEventFunction) wxStaticCastEvent( wxRichTextEventFunction, & fn ), NULL ),
#define EVT_RICHTEXT_STYLESHEET_CHANGING(id, fn) DECLARE_EVENT_TABLE_ENTRY( wxEVT_COMMAND_RICHTEXT_STYLESHEET_CHANGING, id, -1, (wxObjectEventFunction) (wxEventFunction) wxStaticCastEvent( wxRichTextEventFunction, & fn ), NULL ),
#define EVT_RICHTEXT_STYLESHEET_CHANGED(id, fn) DECLARE_EVENT_TABLE_ENTRY( wxEVT_COMMAND_RICHTEXT_STYLESHEET_CHANGED, id, -1, (wxObjectEventFunction) (wxEventFunction) wxStaticCastEvent( wxRichTextEventFunction, & fn ), NULL ),
#define EVT_RICHTEXT_STYLESHEET_REPLACING(id, fn) DECLARE_EVENT_TABLE_ENTRY( wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACING, id, -1, (wxObjectEventFunction) (wxEventFunction) wxStaticCastEvent( wxRichTextEventFunction, & fn ), NULL ),
#define EVT_RICHTEXT_STYLESHEET_REPLACED(id, fn) DECLARE_EVENT_TABLE_ENTRY( wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACED, id, -1, (wxObjectEventFunction) (wxEventFunction) wxStaticCastEvent( wxRichTextEventFunction, & fn ), NULL ),
#define EVT_RICHTEXT_CONTENT_INSERTED(id, fn) DECLARE_EVENT_TABLE_ENTRY( wxEVT_COMMAND_RICHTEXT_CONTENT_INSERTED, id, -1, (wxObjectEventFunction) (wxEventFunction) wxStaticCastEvent( wxRichTextEventFunction, & fn ), NULL ),
#define EVT_RICHTEXT_CONTENT_DELETED(id, fn) DECLARE_EVENT_TABLE_ENTRY( wxEVT_COMMAND_RICHTEXT_CONTENT_DELETED, id, -1, (wxObjectEventFunction) (wxEventFunction) wxStaticCastEvent( wxRichTextEventFunction, & fn ), NULL ),
#define EVT_RICHTEXT_STYLE_CHANGED(id, fn) DECLARE_EVENT_TABLE_ENTRY( wxEVT_COMMAND_RICHTEXT_STYLE_CHANGED, id, -1, (wxObjectEventFunction) (wxEventFunction) wxStaticCastEvent( wxRichTextEventFunction, & fn ), NULL ),
#define EVT_RICHTEXT_SELECTION_CHANGED(id, fn) DECLARE_EVENT_TABLE_ENTRY( wxEVT_COMMAND_RICHTEXT_SELECTION_CHANGED, id, -1, (wxObjectEventFunction) (wxEventFunction) wxStaticCastEvent( wxRichTextEventFunction, & fn ), NULL ),
#endif
// wxUSE_RICHTEXT
#endif
// _WX_RICHTEXTCTRL_H_
| [
"[email protected]"
]
| [
[
[
1,
954
]
]
]
|
062613b39ad4ae47c784f4c497507885d4d081db | 22d9640edca14b31280fae414f188739a82733e4 | /Code/VTK/include/vtk-5.2/vtkParallelopipedRepresentation.h | ba45edbde8dc9303bc9a90909188a111f2bc0550 | []
| 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 | 10,463 | h | /*=========================================================================
Program: Visualization Toolkit
Module: $RCSfile: vtkParallelopipedRepresentation.h,v $
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .NAME vtkParallelopipedRepresentation - Default representation for vtkParallelopipedWidget
// .SECTION Description
// This class provides the default geometrical representation for
// vtkParallelopipedWidget. As a result of interactions of the widget, this
// representation can take on of the following shapes:
// <p>1) A parallelopiped. (8 handles, 6 faces)
// <p>2) Paralleopiped with a chair depression on any one handle. (A chair
// is a depression on one of the handles that carves inwards so as to allow
// the user to visualize cuts in the volume). (14 handles, 9 faces).
//
// .SECTION See Also
// vtkParallelopipedWidget
#ifndef __vtkParallelopipedRepresentation_h
#define __vtkParallelopipedRepresentation_h
#include "vtkWidgetRepresentation.h"
class vtkActor;
class vtkPlane;
class vtkPoints;
class vtkPolyData;
class vtkPolyDataMapper;
class vtkProperty;
class vtkCellArray;
class vtkTransform;
class vtkHandleRepresentation;
class vtkClosedSurfacePointPlacer;
class vtkPlaneCollection;
class vtkParallelopipedTopology;
class VTK_WIDGETS_EXPORT vtkParallelopipedRepresentation
: public vtkWidgetRepresentation
{
public:
// Description:
// Instantiate the class.
static vtkParallelopipedRepresentation *New();
// Description:
// Standard methods for instances of this class.
vtkTypeRevisionMacro(vtkParallelopipedRepresentation,vtkWidgetRepresentation);
void PrintSelf(ostream& os, vtkIndent indent);
// Description:
// Methods to satisfy the superclass.
virtual void GetActors(vtkPropCollection *pc);
// Description:
// Place the widget in the scene. You can use either of the two APIs :
// 1) PlaceWidget( double bounds[6] )
// Creates a cuboid conforming to the said bounds.
// 2) PlaceWidget( double corners[8][3] )
// Creates a parallelopiped with corners specified. The order in
// which corners are specified must obey the following rule:
// Corner 0 - 1 - 2 - 3 - 0 forms a face
// Corner 4 - 5 - 6 - 7 - 4 forms a face
// Corner 0 - 4 - 5 - 1 - 0 forms a face
// Corner 1 - 5 - 6 - 2 - 1 forms a face
// Corner 2 - 6 - 7 - 3 - 2 forms a face
// Corner 3 - 7 - 4 - 0 - 3 forms a face
virtual void PlaceWidget(double corners[8][3]);
virtual void PlaceWidget(double bounds[6]);
// Description:
// The interaction state may be set from a widget (e.g., PointWidget)
// or other object. This controls how the interaction with the
// widget proceeds.
vtkSetMacro(InteractionState,int);
// Description:
// Get the bounding planes of the object. The first 6 planes will
// be bounding planes of the parallelopiped. If in chair mode, three
// additional planes will be present. The last three planes will be those
// of the chair. The normals of all the planes will point into the object.
void GetBoundingPlanes( vtkPlaneCollection *pc );
// Description:
// The parallelopiped polydata.
void GetPolyData(vtkPolyData *pd);
// Description:
// The parallelopiped polydata.
virtual double *GetBounds();
// Description:
// Set/Get the handle properties.
virtual void SetHandleProperty (vtkProperty *);
virtual void SetHoveredHandleProperty (vtkProperty *);
virtual void SetSelectedHandleProperty (vtkProperty *);
vtkGetObjectMacro(HandleProperty, vtkProperty );
vtkGetObjectMacro(HoveredHandleProperty, vtkProperty );
vtkGetObjectMacro(SelectedHandleProperty, vtkProperty );
void SetHandleRepresentation(vtkHandleRepresentation *handle);
vtkHandleRepresentation* GetHandleRepresentation(int index);
// Description:
// Turns the visibility of the handles on/off. Sometimes they may get in
// the way of visualization.
void HandlesOn();
void HandlesOff();
// Description:
// Get the face properties. When a face is being translated, the face gets
// highlighted with the SelectedFaceProperty.
vtkGetObjectMacro(FaceProperty,vtkProperty);
vtkGetObjectMacro(SelectedFaceProperty,vtkProperty);
// Description:
// Get the outline properties. These are the properties with which the
// parallelopiped wireframe is rendered.
vtkGetObjectMacro(OutlineProperty,vtkProperty);
vtkGetObjectMacro(SelectedOutlineProperty,vtkProperty);
// Description:
// This actually constructs the geometry of the widget from the various
// data parameters.
virtual void BuildRepresentation();
// Description:
// Methods required by vtkProp superclass.
virtual void ReleaseGraphicsResources(vtkWindow *w);
virtual int RenderOverlay(vtkViewport *viewport);
virtual int RenderOpaqueGeometry(vtkViewport *viewport);
// Description:
// Given and x-y display coordinate, compute the interaction state of
// the widget.
virtual int ComputeInteractionState(int X, int Y, int modify=0);
//BTX - manage the state of the widget
enum _InteractionState
{
Outside = 0,
Inside,
RequestResizeParallelopiped,
RequestResizeParallelopipedAlongAnAxis,
RequestChairMode,
RequestTranslateParallelopiped,
RequestScaleParallelopiped,
RequestRotateParallelopiped,
ResizingParallelopiped,
ResizingParallelopipedAlongAnAxis,
ChairMode,
TranslatingParallelopiped,
ScalingParallelopiped,
RotatingParallelopiped,
};
//ETX
// Methods to manipulate the piped.
virtual void Translate( double translation[3] );
virtual void Translate( int X, int Y );
virtual void Scale( int X, int Y );
// Description:
// Synchronize the parallelopiped handle positions with the
// Polygonal datastructure.
virtual void PositionHandles();
// Description:
// Minimum thickness for the parallelopiped. User interactions cannot make
// any individual axis of the parallopiped thinner than this value.
// Default is 0.05 expressed as a fraction of the diagonal of the bounding
// box used in the PlaceWidget() invocation.
vtkSetMacro( MinimumThickness, double );
vtkGetMacro( MinimumThickness, double );
protected:
vtkParallelopipedRepresentation();
~vtkParallelopipedRepresentation();
// Description:
// Translate the nth PtId (0 <= n <= 15) by the specified amount.
void TranslatePoint( int n, const double motionVector[3] );
// Description:
// Set the highlight state of a handle.
// If handleIdx is -1, the property is applied to all handles.
void SetHandleHighlight( int handleIdx, vtkProperty *property );
// Description:
// Highlight face defined by the supplied ptids with the specified property.
void SetFaceHighlight( vtkCellArray * face, vtkProperty * );
void HighlightAllFaces();
void UnHighlightAllFaces();
// Node can be a value within [0,7]. This will create a chair one one of
// the handle corners. '0 < InitialChairDepth < 1' value dicates the starting
// depth of the cavity.
void UpdateChairAtNode( int node );
// Removes any existing chairs.
void RemoveExistingChairs();
// Convenience method to get just the planes that define the parallelopiped.
// If we aren't in chair mode, this will be the same as GetBoundingPlanes().
// If we are in chair mode, this will be the first 6 planes from amongst
// those returned by "GetBoundingPlanes".
// All planes have their normals pointing inwards.
void GetParallelopipedBoundingPlanes( vtkPlaneCollection * pc );
// Convenience method to edefine a plane passing through 3 points.
void DefinePlane( vtkPlane *, double p[3][3]);
// Convenience method to edefine a plane passing through 3 pointIds of the
// parallelopiped. The point Ids must like in the range [0,15], ie the
// 15 points comprising the parallelopiped and the chair (also modelled
// as a parallelopiped)
void DefinePlane( vtkPlane *, vtkIdType, vtkIdType, vtkIdType);
vtkActor * HexActor;
vtkPolyDataMapper * HexMapper;
vtkPolyData * HexPolyData;
vtkPoints * Points;
vtkActor * HexFaceActor;
vtkPolyDataMapper * HexFaceMapper;
vtkPolyData * HexFacePolyData;
double LastEventPosition[2];
// Cache the axis index used for face aligned resize.
int LastResizeAxisIdx;
vtkHandleRepresentation * HandleRepresentation;
vtkHandleRepresentation ** HandleRepresentations;
int CurrentHandleIdx;
int ChairHandleIdx;
// When a chair is carved out for the first time, this is the initial
// depth of the chair
double InitialChairDepth;
vtkProperty * HandleProperty;
vtkProperty * HoveredHandleProperty;
vtkProperty * FaceProperty;
vtkProperty * OutlineProperty;
vtkProperty * SelectedHandleProperty;
vtkProperty * SelectedFaceProperty;
vtkProperty * SelectedOutlineProperty;
vtkClosedSurfacePointPlacer * ChairPointPlacer;
vtkParallelopipedTopology * Topology;
double MinimumThickness;
double AbsoluteMinimumThickness;
private:
vtkParallelopipedRepresentation(const vtkParallelopipedRepresentation&); //Not implemented
void operator=(const vtkParallelopipedRepresentation&); //Not implemented
};
#endif
| [
"nnsmit@9b22acdf-97ab-464f-81e2-08fcc4a6931f"
]
| [
[
[
1,
267
]
]
]
|
686232c72573c391149fa78474c00c0806774a41 | 21da454a8f032d6ad63ca9460656c1e04440310e | /src/wcpp/util/wsiEnumeration.h | b3604603d6ce33f9b0b34cf7a872f298d11a3c6a | []
| no_license | merezhang/wcpp | d9879ffb103513a6b58560102ec565b9dc5855dd | e22eb48ea2dd9eda5cd437960dd95074774b70b0 | refs/heads/master | 2021-01-10T06:29:42.908096 | 2009-08-31T09:20:31 | 2009-08-31T09:20:31 | 46,339,619 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 296 | h | #pragma once
#include <wcpp/lang/wsiObject.h>
template <typename E>
class wsiEnumeration : public wsiObject
{
public:
static const ws_iid sIID;
public:
WS_METHOD( ws_boolean , HasMoreElements )(void) = 0;
WS_METHOD( ws_result , NextElement )(E ** ret) = 0;
};
| [
"xukun0217@98f29a9a-77f1-11de-91f8-ab615253d9e8"
]
| [
[
[
1,
15
]
]
]
|
f27c2beed7d3e7860e08fa0a5cdd40dd93dcd13d | 1102f77e8dbf563a024cec0b885c0d9f9da2ef39 | /lib/database.h | 9b826e372befe0ed791339b9168fa98e05b45209 | []
| no_license | pgoodman/uwo-cooper | 7c38c1bc0b3fc04cabb128cd5a3c984c67efc2f3 | ea881e9794cb2c0ae64c0d73117facfd92c3f96b | refs/heads/master | 2016-09-11T03:29:39.537161 | 2010-04-05T21:28:26 | 2010-04-05T21:28:26 | 32,091,588 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,477 | h | #ifndef COOPERDB_H
#define COOPERDB_H
#include <sstream>
#include <utility>
#include <cassert>
#include <ctime>
#include <QDateTime>
#include <QSqlDatabase>
#include <QString>
#include <QStringList>
#include <QSqlQuery>
#include <QSqlError>
#include <QVariant>
#include <QSqlRecord>
#include "lib/imodeliterator.h"
/**
* Handle creating, connecting, and querying the cooper database.
*/
class Database
{
typedef bool (install_func_t)(QSqlQuery &);
public:
~Database();
static bool connect(const char *, const char *, install_func_t *);
static bool hasAny(const char *);
static QSqlQuery select(const char *query);
static QSqlQuery select(const char *table, const char *cond);
static QSqlQuery select(const char *table, const int id);
static bool remove(const char *table, const int id);
static bool remove(const char *table, const char *cond);
template <typename T>
static pair<IModelIterator<T>, IModelIterator<T> >
selectAll(const char *table, const char *cond="1=1");
static void disconnect(void);
private:
Database();
static void makeDatabase();
static QSqlDatabase db;
static bool is_connected;
};
/* helper functions for dealing with db stuff */
//QVariant qcol(QSqlQuery &q, const char *index);
template <typename T> T qcol(const QSqlQuery &q, const char *index);
template <> QVariant qcol(const QSqlQuery &q, const char *index);
template <> int qcol(const QSqlQuery &q, const char *index);
template <> unsigned int qcol(const QSqlQuery &q, const char *index);
template <> double qcol(const QSqlQuery &q, const char *index);
template <> bool qcol(const QSqlQuery &q, const char *index);
template <> string qcol(const QSqlQuery &q, const char *index);
template <> QString qcol(const QSqlQuery &q, const char *index);
template <> long qcol(const QSqlQuery &q, const char *index);
template <> long qcol(const QSqlQuery &q, const char *index);
const QVariant &operator>>(const QVariant &v, int &x);
const QVariant &operator>>(const QVariant &v, bool &x);
const QVariant &operator>>(const QVariant &v, double &x);
const QVariant &operator>>(const QVariant &v, string &x);
const QVariant &operator>>(const QVariant &v, QString &x);
template <typename T> QSqlQuery &operator<<(QSqlQuery &q, T val);
template <> QSqlQuery &operator<< <string &>(QSqlQuery &q, string &val);
template <> QSqlQuery &operator<< <string>(QSqlQuery &q, string val);
template <> QSqlQuery &operator<< <time_t>(QSqlQuery &q, time_t val);
template <> QSqlQuery &operator<< <void *>(QSqlQuery &q, void *val);
template <> QSqlQuery &operator<< <QDateTime>(QSqlQuery &q, QDateTime val);
template <> QSqlQuery &operator<< <const QDateTime>(QSqlQuery &q, const QDateTime val);
template <> QSqlQuery &operator<< <bool>(QSqlQuery &q, bool val);
/**
* Linkage stuff.
*/
template <typename T>
std::pair<IModelIterator<T>, IModelIterator<T> >
Database::selectAll(const char *table, const char *conditions) {
stringstream ss;
ss << "SELECT COUNT(id) as c FROM " << table << " WHERE " << conditions;
QSqlQuery count(ss.str().c_str());
int size((count.next() && count.isValid()) ? qcol<int>(count, "c") : 0);
count.finish();
ss.str(string(""));
ss << "SELECT id FROM " << table << " WHERE " << conditions;
return IModelIterator<T>::make(QSqlQuery(ss.str().c_str()), size);
}
#endif // COOPERDB_H
| [
"jlu.newera@c307de66-1bdf-11df-a447-cf726199f266",
"peter.goodman@c307de66-1bdf-11df-a447-cf726199f266",
"nick.perreault@c307de66-1bdf-11df-a447-cf726199f266"
]
| [
[
[
1,
3
],
[
21,
21
],
[
24,
24
],
[
27,
27
],
[
51,
52
],
[
64,
64
],
[
99,
99
]
],
[
[
4,
20
],
[
22,
23
],
[
25,
26
],
[
28,
50
],
[
53,
63
],
[
65,
82
],
[
84,
98
]
],
[
[
83,
83
]
]
]
|
f06ac8bb4c0fc53e95989c50eadee4f15d9d144c | 9c62af23e0a1faea5aaa8dd328ba1d82688823a5 | /rl/tags/techdemo2/engine/dialog/src/predicates/QuestPartsPredicates.cpp | 75ebcd566f41aa16f0a30454fec1c904b702bf68 | [
"ClArtistic",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | jacmoe/dsa-hl-svn | 55b05b6f28b0b8b216eac7b0f9eedf650d116f85 | 97798e1f54df9d5785fb206c7165cd011c611560 | refs/heads/master | 2021-04-22T12:07:43.389214 | 2009-11-27T22:01:03 | 2009-11-27T22:01:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,481 | cpp | /* This source file is part of Rastullahs Lockenpracht.
* Copyright (C) 2003-2006 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 Perl 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
* Perl Artistic License for more details.
*
* You should have received a copy of the Perl Artistic License
* along with this program; if not you can get it here
* http://www.perldoc.com/perl5.6/Artistic.html.
*/
#include "QuestPartsPredicates.h"
#include <CEGUIPropertyHelper.h>
#include "Exception.h"
#include "QuestBook.h"
#include "Quest.h"
#include "RulesSubsystem.h"
using namespace rl;
using CEGUI::PropertyHelper;
QuestPartsPredicates::QuestPartsPredicates()
{
}
QuestPartsPredicates::~QuestPartsPredicates(void)
{
}
CeGuiString QuestPartsPredicates::getPredicate(const CeGuiString& name) const
{
Quest* quest = RulesSubsystem::getSingletonPtr()->getQuestBook()
->getQuest(name);
if (quest == NULL)
{
Throw(
IllegalArgumentException,
("Quest '"
+ name
+ "' not found").c_str());
}
return PropertyHelper::intToString(quest->getPartsDone());
}
void QuestPartsPredicates::setPredicate(const CeGuiString& name, const CeGuiString& value)
{
Quest* quest = RulesSubsystem::getSingletonPtr()->getQuestBook()
->getQuest(name);
if (quest == NULL)
{
Throw(
IllegalArgumentException,
("Quest '"
+ name
+ "' not found").c_str());
}
static CeGuiString INCREASE = "increase";
static CeGuiString DECREASE = "decrease";
if (value == INCREASE)
{
quest->increasePartsDone();
}
else if (value.substr(0, INCREASE.length()) == INCREASE)
{
int parts = PropertyHelper::stringToInt(value.substr(INCREASE.length()));
quest->increasePartsDone(parts);
}
else if (value == DECREASE)
{
quest->decreasePartsDone();
}
else if (value.substr(0, DECREASE.length()) == DECREASE)
{
int parts = PropertyHelper::stringToInt(value.substr(DECREASE.length()));
quest->decreasePartsDone(parts);
}
else
{
int parts = PropertyHelper::stringToInt(value);
quest->setPartsDone(parts);
}
}
CeGuiString QuestPartsPredicates::getType() const
{
return "questparts";
}
| [
"tanis@4c79e8ff-cfd4-0310-af45-a38c79f83013"
]
| [
[
[
1,
98
]
]
]
|
9b2c7d1ccea89fb0a6016751d8edfca92b60c368 | d882fb01057dce320a56a978b9a3c0af6cc937ea | /Clusterization/Clusterization/Clusterization.cpp | 01ebb127b0f4298c4844a5abeb6eb63ce6137f14 | []
| no_license | hksonngan/arraypointsprocessingproject | 6e63240e80ea027324be37a78a44213ec26ba558 | 5dbe48207672e97a3697e567d6fe89d136165183 | refs/heads/master | 2021-01-10T10:04:51.318928 | 2011-02-27T11:50:08 | 2011-02-27T11:50:08 | 46,898,830 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 454 | cpp | // Clusterization.cpp : main project file.
#include "stdafx.h"
#include "MainForm.h"
using namespace Clusterization;
[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
// Enabling Windows XP visual effects before any controls are created
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
// Create the main window and run it
Application::Run(gcnew MainForm());
return 0;
}
| [
"imhojob@9f64be17-c248-32b9-2fe5-dc10fbaacc9c"
]
| [
[
[
1,
18
]
]
]
|
58df6a950a47954bfd0015f11f96eb5cc60df9b8 | 656aba8d1c0379c82261b34de6875704d7133645 | /trunk/Sources/Common/libCommon/CLog.h | 6a34f429a31281e38fd42fbfe94fd6829dee01a1 | []
| no_license | BackupTheBerlios/exspecto-svn | 7ac87d6f30896add78adeebc68fffe720ec46d56 | c0cd6af554231680e5bf404e25330907b194bd24 | refs/heads/master | 2020-12-24T13:28:04.023732 | 2008-03-10T15:04:43 | 2008-03-10T15:04:43 | 40,664,795 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 831 | h | //-------------------------------------------------------------------------------------//
//Module: CLog class
//Author: Bezborodov Dmitry
//Description:
//-------------------------------------------------------------------------------------//
#ifndef _CLOG_H
#define _CLOG_H
#include <string>
#include "Singleton.hpp"
#ifdef WIN32
#include "windows.h"
#else
#define BYTE unsigned char
#endif
class CLog
{
public:
CLog();
~CLog();
void SetModuleName( const std::string& strModuleName );
void Trace(int iLevel, char* trace_text, ...);
void Dump(int iLevel, BYTE* pbDumpData, int iDataSize, char* about, ...);
void SetLoglevel( int iLoglevel );
private:
CLog( const CLog& );
CLog& operator=( const CLog& );
std::string m_strFileName;
CMutex m_mutex;
int m_iLogLevel;
};
typedef CSingleton< CLog > Log;
#endif
| [
"parshind@284ff1dd-de15-0410-891b-f61abf421a23"
]
| [
[
[
1,
44
]
]
]
|
9f3786d53fa74e83fa117f3badb192a1d81182c7 | 772405dd6b80ce5dd8a5bd80f0c8e2289d5c75b9 | /TipPop/TP_DesktopTag.cpp | 78395431d827ed5c47b02cf0652afac361b64a88 | []
| no_license | osoft/tippop | 92c1b9fcd0e5d0388a0625174c4a009bd44f3bf3 | e04dd2910af15e0cb51a4834a98bc0a836191e72 | refs/heads/master | 2021-01-10T06:02:43.793701 | 2008-12-12T15:32:20 | 2008-12-12T15:32:20 | 45,257,933 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 10,625 | cpp | #include "stdafx.h"
#include "TP_DesktopTag.h"
#include <GdiPlus.h>
//#include "gdiplus.h"
#define MAX_LOADSTRING 100
#define DT_WIDTH (100)
#define DT_HEIGHT (30)
#define DT_HDLWIDTH (5)
TCHAR szDTClassName[MAX_LOADSTRING] = L"DesktopTagWndCls"; // Ö÷´°¿ÚÀàÃû
TCHAR szDTWndName[MAX_LOADSTRING] = L"DesktopTag";
extern HINSTANCE hInst;
static int tagCount = 0;
static TP_DT_TagCB_t tcb[256];
static POINT ptOld;
static HANDLE hMutex;
// Window Procedure
static LRESULT CALLBACK TP_DT_WndProc(HWND hWnd, UINT nMsg, WPARAM wParam, LPARAM lParam);
// Event handlers
static int TP_DT_OnPaint(HWND hWnd);
static int TP_DT_OnMouseMove(HWND hWnd, WPARAM wParam, int x, int y);
static int TP_DT_OnMouseLeave(HWND hWnd, int x, int y);
// Private data query functions
static bool MouseInWnd(HWND);
static void SetMouseInWnd(HWND hWnd, bool bIn);
static WCHAR* GetTagTitle(HWND);
static char* GetTagContent(HWND);
static HANDLE GetTagSem(HWND hWnd);
static int TP_DT_OnPaint(HWND hWnd)
{
PAINTSTRUCT ps;
HDC hdc;
HBRUSH hBrush;
HPEN hPen;
HGDIOBJ hPenOld, hBrushOld;
hdc = BeginPaint(hWnd, &ps);
// Draw the background
hBrush = CreateSolidBrush(RGB(33,33,33));
hPen = CreatePen(PS_SOLID, 0, RGB(33,33,33));
hBrushOld = SelectObject(hdc, hBrush);
hPenOld = SelectObject(hdc, hPen);
Rectangle(hdc, 0,0,DT_WIDTH,DT_HEIGHT);
SelectObject(hdc, hBrushOld);
DeleteObject(hBrush);
SelectObject(hdc, hPenOld);
DeleteObject(hPen);
// Draw the handle
hBrush = CreateSolidBrush(RGB(230,55,55));
hPen = CreatePen(PS_SOLID, 0, RGB(230,55,55));
hBrushOld = SelectObject(hdc, hBrush);
hPenOld = SelectObject(hdc, hPen);
Rectangle(hdc, 0, 0, DT_HDLWIDTH, DT_HEIGHT);
SelectObject(hdc, hBrushOld);
DeleteObject(hBrush);
SelectObject(hdc, hPenOld);
DeleteObject(hPen);
//hdc = BeginPaint(hWnd, &ps);
Graphics graphics(hdc);
FontFamily fontFamily(DEFAULTFONT);
Font font(&fontFamily, 20, FontStyleRegular, UnitPixel);
SolidBrush solidBrush(Color(255, 255, 255, 255));
graphics.SetTextRenderingHint(TextRenderingHintAntiAlias);
graphics.DrawString(GetTagTitle(hWnd), -1, &font, PointF(1.0f, 1.0f), &solidBrush);
EndPaint(hWnd, &ps);
return 0;
}
DWORD WINAPI TP_DT_PaintHandleTask(LPVOID lpParam)
{
HDC hdc;
hdc = GetWindowDC((HWND)lpParam);
short gValue;
HBRUSH hBrush;
HPEN hPen;
HGDIOBJ hBrushOld, hPenOld;
HWND hWnd = (HWND)lpParam;
while (1)
{
WaitForSingleObject(GetTagSem((HWND)lpParam), INFINITE);
gValue = GetGValue(GetPixel(hdc, 1, 1));
do
{
if(MouseInWnd(hWnd) && gValue < 255)
gValue+=10;
else if(!MouseInWnd(hWnd) && gValue > 55)
gValue-=10;
else
{
break;
}
hBrush = CreateSolidBrush(RGB(230, gValue, gValue));
hPen = CreatePen(PS_SOLID, 0, RGB(230, gValue, gValue));
hBrushOld = SelectObject(hdc, hBrush);
hPenOld = SelectObject(hdc, hPen);
Rectangle(hdc, 0, 0, DT_HDLWIDTH, DT_HEIGHT);
SelectObject(hdc, hBrushOld);
DeleteObject(hBrush);
SelectObject(hdc, hPenOld);
DeleteObject(hPen);
Sleep(10);
} while (gValue > 55 || gValue < 255);
//ReleaseMutex(GetTagSem((HWND)lpParam));
}
}
/*
DWORD WINAPI TP_DT_DrawHandleTask(LPVOID lpParam)
{
HDC hdc;
HBRUSH hBrush;
HPEN hPen;
HGDIOBJ hBrushOld, hPenOld;
int i,j;
hdc = GetWindowDC((HWND)lpParam);
//WaitForSingleObject(hMutex, INFINITE);
for(i = 0; i < 20; i++)
{
j = i * 10;
hBrush = CreateSolidBrush(RGB(230,55 + j,55 + j));
hPen = CreatePen(PS_SOLID, 0, RGB(230,55 + j,55 + j));
hBrushOld = SelectObject(hdc, hBrush);
hPenOld = SelectObject(hdc, hPen);
Rectangle(hdc, 0, 0, DT_HDLWIDTH, DT_HEIGHT);
SelectObject(hdc, hBrushOld);
DeleteObject(hBrush);
SelectObject(hdc, hPenOld);
DeleteObject(hPen);
Sleep(10);
}
//ReleaseMutex(hMutex);
return 0;
}
DWORD WINAPI TP_DT_EraseHandleTask(LPVOID lpParam)
{
HDC hdc;
HBRUSH hBrush;
HPEN hPen;
HGDIOBJ hBrushOld, hPenOld;
int i,j;
hdc = GetWindowDC((HWND)lpParam);
//WaitForSingleObject(hMutex, INFINITE);
for(i = 0; i < 20; i++)
{
j = 190 - i * 10;
hBrush = CreateSolidBrush(RGB(230,55 + j,55 + j));
hPen = CreatePen(PS_SOLID, 0, RGB(230,55 + j,55 + j));
hBrushOld = SelectObject(hdc, hBrush);
hPenOld = SelectObject(hdc, hPen);
Rectangle(hdc, 0, 0, DT_HDLWIDTH, DT_HEIGHT);
SelectObject(hdc, hBrushOld);
DeleteObject(hBrush);
SelectObject(hdc, hPenOld);
DeleteObject(hPen);
Sleep(10);
}
hBrush = CreateSolidBrush(RGB(230,55,55));
hPen = CreatePen(PS_SOLID, 0, RGB(230,55,55));
hBrushOld = SelectObject(hdc, hBrush);
hPenOld = SelectObject(hdc, hPen);
Rectangle(hdc, 0, 0, DT_HDLWIDTH, DT_HEIGHT);
SelectObject(hdc, hBrushOld);
DeleteObject(hBrush);
SelectObject(hdc, hPenOld);
DeleteObject(hPen);
//ReleaseMutex(hMutex);
return 0;
}
*/
int TP_DT_OnMouseMove(HWND hWnd, WPARAM wParam, int x, int y)
{
POINT pt;
if(wParam == MK_LBUTTON)
{
pt.x = x;
pt.y = y;
ClientToScreen(hWnd, &pt);
SetWindowPos(hWnd, HWND_TOPMOST, pt.x - ptOld.x, pt.y - ptOld.y, NULL, NULL, SWP_NOSIZE);
return 0;
}
if(MouseInWnd(hWnd))
{
return 0;
}
else
{
SetMouseInWnd(hWnd, true);
TRACKMOUSEEVENT meTrack;
meTrack.cbSize = sizeof(TRACKMOUSEEVENT);
meTrack.dwFlags = TME_LEAVE;
meTrack.hwndTrack = hWnd;
if(0 == TrackMouseEvent(&meTrack))
{
MessageBox(hWnd, L"track mouse event failed", NULL, NULL);
}
}
ReleaseSemaphore(GetTagSem(hWnd), 1, NULL);
return 0;
}
int TP_DT_OnMouseLeave(HWND hWnd, int x, int y)
{
#if 0
HDC hdc;
HBRUSH hBrush;
HPEN hPen;
HGDIOBJ hBrushOld, hPenOld;
int i,j;
hdc = GetWindowDC(hWnd);
SetMouseInWnd(hWnd, false);
for(i = 0; i < 2000; i++)
{
//Sleep(1);
j = 200 - i / 10;
hBrush = CreateSolidBrush(RGB(230,55 + j,55 + j));
hPen = CreatePen(PS_SOLID, 0, RGB(230,55 + j,55 + j));
hBrushOld = SelectObject(hdc, hBrush);
hPenOld = SelectObject(hdc, hPen);
Rectangle(hdc, 0, 0, DT_HDLWIDTH, DT_HEIGHT);
SelectObject(hdc, hBrushOld);
DeleteObject(hBrush);
SelectObject(hdc, hPenOld);
DeleteObject(hPen);
for(j =0; j<10000; j++)
{
}
}
#else
SetMouseInWnd(hWnd, false);
ReleaseSemaphore(GetTagSem(hWnd), 1, NULL);
#endif
return 0;
}
tp_error_e InitTagCB()
{
int i;
for(i = 0; i < 256; i++)
{
tcb[i].hWnd = 0;
}
hMutex = CreateMutex(NULL, FALSE, NULL);
if(hMutex == NULL)
return TP_ERROR_FAILED;
ReleaseMutex(hMutex);
return TP_NO_ERROR;
}
static tp_error_e tcbCreateTag(HWND hWnd)
{
int i;
for(i = 0; i < 256; i++)
{
if(tcb[i].hWnd == 0)
{
tcb[i].hWnd = hWnd;
tcb[i].pStrTitle = (WCHAR *)malloc(sizeof(WCHAR)*64);
if(NULL == tcb[i].pStrTitle)
return TP_ERROR_MEM;
memset(tcb[i].pStrTitle, 0, 64);
tcb[i].hSem = CreateSemaphore(NULL, 0, 1, NULL);
CreateThread(NULL, 4096, TP_DT_PaintHandleTask, hWnd, NULL, NULL);
return TP_NO_ERROR;
}
}
return TP_ERROR_INVALID_HANDLE;
}
static bool MouseInWnd(HWND hWnd)
{
int i;
for(i = 0; i < 256; i++)
{
if(tcb[i].hWnd == hWnd)
return tcb[i].bMouseIn;
}
return false;
}
static void SetMouseInWnd(HWND hWnd, bool bIn)
{
int i;
//WaitForSingleObject(hMutex, INFINITE);
for(i = 0; i < 256; i++)
{
if(tcb[i].hWnd == hWnd)
{
tcb[i].bMouseIn = bIn;
return;
}
}
//ReleaseMutex(hMutex);
return;
}
static tp_error_e SetTagTitle(HWND hWnd, WCHAR *str)
{
int i;
for(i = 0; i < 256; i++)
{
if(tcb[i].hWnd == hWnd)
{
wcscpy_s(tcb[i].pStrTitle, 64, str);
return TP_NO_ERROR;
}
}
return TP_ERROR_INVALID_HANDLE;
}
static WCHAR* GetTagTitle(HWND hWnd)
{
int i;
for(i = 0; i < 256; i++)
{
if(tcb[i].hWnd == hWnd)
{
return tcb[i].pStrTitle;
}
}
return NULL;
}
static HANDLE GetTagSem(HWND hWnd)
{
int i;
for(i = 0; i < 256; i++)
{
if(tcb[i].hWnd == hWnd)
{
return tcb[i].hSem;
}
}
return NULL;
}
static LRESULT CALLBACK TP_DT_WndProc(HWND hWnd, UINT nMsg, WPARAM wParam, LPARAM lParam)
{
//int wmId, wmEvent;
switch (nMsg)
{
case WM_CREATE:
SetLayeredWindowAttributes(hWnd, NULL, 200, LWA_ALPHA);
//TRACKMOUSEEVENT meTrack;
//meTrack.cbSize = sizeof(TRACKMOUSEEVENT);
//meTrack.dwFlags = TME_LEAVE;
//meTrack.hwndTrack = hWnd;
//if(0 == TrackMouseEvent(&meTrack))
//{
// MessageBox(hWnd, L"track mouse event failed", NULL, NULL);
//}
break;
case WM_PAINT:
return TP_DT_OnPaint(hWnd);
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_MOUSEMOVE:
return TP_DT_OnMouseMove(hWnd, wParam, LOWORD(lParam), HIWORD(lParam));
case WM_MOUSELEAVE:
case WM_NCMOUSELEAVE:
TP_DT_OnMouseLeave(hWnd, LOWORD(lParam), HIWORD(lParam));
//TRACKMOUSEEVENT meTrack;
//meTrack.cbSize = sizeof(TRACKMOUSEEVENT);
//meTrack.dwFlags = TME_LEAVE;
//meTrack.hwndTrack = hWnd;
//if(0 == TrackMouseEvent(&meTrack))
//{
// MessageBox(hWnd, L"track mouse event failed", NULL, NULL);
//}
break;
case WM_LBUTTONDOWN:
ptOld.x = LOWORD(lParam);
ptOld.y = HIWORD(lParam);
break;
default:
return DefWindowProc(hWnd, nMsg, wParam, lParam);
}
return 0;
}
INT TP_DT_RegistWindow()
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = TP_DT_WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInst;
wcex.hIcon = NULL;//LoadIcon(hInstance, MAKEINTRESOURCE(IDI_TIPPOP));
wcex.hCursor = NULL;//LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = NULL;//(HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = NULL;//MAKEINTRESOURCE(IDC_TIPPOP);
wcex.lpszClassName = szDTClassName;
wcex.hIconSm = NULL;//LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassEx(&wcex);
}
HWND TP_DT_CreateWindow(HWND hParent, WCHAR *str, bool bClickThrough, bool bTopMost, short iAlpha)
{
HWND hWnd = NULL;
unsigned long wsEx = 0;
if(!hParent)
{
hParent = GetDesktopWindow();
}
wsEx = WS_EX_LAYERED;
if(bClickThrough)
{
wsEx |= WS_EX_TRANSPARENT;
}
if(bTopMost)
{
wsEx |= WS_EX_TOPMOST;
}
hWnd = CreateWindowEx(wsEx, szDTClassName, szDTWndName, WS_POPUP | WS_VISIBLE, 500, 200 + tagCount * 35, DT_WIDTH, DT_HEIGHT, hParent, NULL, hInst, NULL);
if(hWnd)
{
tagCount += 1;
}
tcbCreateTag(hWnd);
SetTagTitle(hWnd, str);
return hWnd;
} | [
"xiuyuanshang@b34755a6-b97f-11dd-a503-ed2d4bea8bb5",
"[email protected]"
]
| [
[
[
1,
414
],
[
416,
473
]
],
[
[
415,
415
]
]
]
|
a525379e1ce7bdaa084184ee823195b20de31042 | 86de5f04e4c62431f8b67392b476660e05427fcb | /RayCaster.cpp | 3201081c20fd64b660aec80bd1a0ba9ad6b9beb7 | []
| no_license | mjlong/Rendering | c78bacc3380eb44ab1163168beda78ed9ca8be47 | 6320119243418db13bb25336f99f680ff45f91a2 | refs/heads/master | 2021-01-15T16:16:05.314526 | 2011-11-30T15:21:59 | 2011-11-30T15:21:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,889 | cpp | // 02562 Rendering Framework
// Written by Jeppe Revall Frisvad, 2011
// Copyright (c) DTU Informatics 2011
#include <iostream>
#include <optix_world.h>
#include "mt_random.h"
#include "Shader.h"
#include "HitInfo.h"
#include "RayCaster.h"
using namespace std;
using namespace optix;
float3 RayCaster::compute_pixel(unsigned int x, unsigned int y) const
{
float3 rtn;
rtn.x = 0.0;
rtn.y = 0.0;
rtn.z = 0.0;
for (int i = 0; i < subdivs*subdivs; i++) {
optix::float2 pixel = optix::make_float2(x, y)*win_to_ip-lower_left;
optix::Ray r = scene->get_camera()->get_ray(pixel + jitter[i]);
HitInfo hit;
scene->closest_hit(r, hit);
if (hit.has_hit) {
rtn += get_shader(hit)->shade(r, hit);
} else {
rtn += get_background();
}
}
return rtn/jitter.size();
// Use the scene and its camera
// to cast a ray that computes the color of the pixel at index (x, y).
//
// Input: x, y (pixel index)
//
// Return: Result of tracing a ray through the pixel at index (x, y).
//
// Relevant data fields that are available (see RayCaster.h and Scene.h)
// win_to_ip (pixel size (width, height) in the image plane)
// lower_left (lower left corner of the film in the image plane)
// scene (scene with access to the functions closest_hit and any_hit)
// scene->get_camera() (camera in the scene)
//
// Hints: (a) Use the function get_shader(...) to get the shader of the
// intersected material after the ray has been traced.
// (b) Use get_background(...) if the ray does not hit anything.
}
float3 RayCaster::get_background(const float3& dir) const
{
if(!sphere_tex)
return background;
return make_float3(sphere_tex->sample_linear(dir));
}
void RayCaster::increment_pixel_subdivs()
{
++subdivs;
compute_jitters();
cout << "Rays per pixel: " << subdivs*subdivs << endl;
}
void RayCaster::decrement_pixel_subdivs()
{
if(subdivs > 1)
{
--subdivs;
compute_jitters();
}
cout << "Rays per pixel: " << subdivs*subdivs << endl;
}
void RayCaster::compute_jitters()
{
float aspect = width/static_cast<float>(height);
win_to_ip.x = aspect/static_cast<float>(width);
win_to_ip.y = 1.0f/static_cast<float>(height);
lower_left = make_float2(aspect*0.5f + win_to_ip.x*0.5f, 0.5f - win_to_ip.y*0.25f);
step = win_to_ip/static_cast<float>(subdivs);
jitter.resize(subdivs*subdivs);
for(unsigned int i = 0; i < subdivs; ++i)
for(unsigned int j = 0; j < subdivs; ++j)
{
jitter[i*subdivs + j].x = static_cast<float>(safe_mt_random() + j)*step.x;
jitter[i*subdivs + j].y = static_cast<float>(safe_mt_random() + i)*step.y;
}
}
| [
"[email protected]"
]
| [
[
[
1,
97
]
]
]
|
1b91cb932a2da081b315c1792548853ad139b602 | 7707c79fe6a5b216a62bb175133249663a0fa12b | /trunk/FootprintView.cpp | ac572849723a8924a92314c39ebacc02fb606d57 | []
| no_license | BackupTheBerlios/freepcb-svn | 51be4b266e80f336045e2242b3388928c0b731f1 | 0ae28845832421c80bbdb10eae514a6e13d01034 | refs/heads/master | 2021-01-20T12:42:11.484059 | 2010-06-03T04:43:44 | 2010-06-03T04:43:44 | 40,441,767 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 89,173 | cpp | // FootprintView.cpp : implementation of the CFootprintView class
//
#include "stdafx.h"
#include "DlgFpText.h"
#include "DlgAssignNet.h"
#include "DlgSetSegmentWidth.h"
#include "DlgEditBoardCorner.h"
#include "DlgAddArea.h"
#include "DlgFpRefText.h"
#include "MyToolBar.h"
#include <Mmsystem.h>
#include <sys/timeb.h>
#include <time.h>
#include <math.h>
#include "FootprintView.h"
#include "DlgAddPart.h"
#include "DlgAddPin.h"
#include "DlgSaveFootprint.h"
#include "DlgAddPoly.h"
#include "DlgImportFootprint.h"
#include "DlgWizQuad.h"
#include "FootprintView.h"
#include "DlgLibraryManager.h"
#include "DlgMoveOrigin.h"
#include "DlgCentroid.h"
#include "DlgGlue.h"
#include "DlgHole.h"
#include "DlgSlot.h"
#include ".\footprintview.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define ZOOM_RATIO 1.4
#define FKEY_OFFSET_X 4
#define FKEY_OFFSET_Y 4
#define FKEY_R_W 70
#define FKEY_R_H 30
#define FKEY_STEP (FKEY_R_W+5)
#define FKEY_GAP 20
#define FKEY_SEP_W 16
extern CFreePcbApp theApp;
// NB: these must be changed if context menu is edited
enum {
CONTEXT_FP_NONE = 0,
CONTEXT_FP_PAD,
CONTEXT_FP_SIDE,
CONTEXT_FP_CORNER,
CONTEXT_FP_REF,
CONTEXT_FP_TEXT,
CONTEXT_FP_CENTROID,
CONTEXT_FP_ADHESIVE,
CONTEXT_FP_VALUE
};
/////////////////////////////////////////////////////////////////////////////
// CFootprintView
IMPLEMENT_DYNCREATE(CFootprintView, CView)
BEGIN_MESSAGE_MAP(CFootprintView, CView)
//{{AFX_MSG_MAP(CFootprintView)
ON_WM_SIZE()
ON_WM_LBUTTONDOWN()
ON_WM_KEYDOWN()
ON_WM_MOUSEMOVE()
ON_WM_RBUTTONDOWN()
ON_WM_LBUTTONDBLCLK()
ON_WM_SYSKEYDOWN()
ON_WM_SYSKEYUP()
ON_WM_MOUSEWHEEL()
//}}AFX_MSG_MAP
// Standard printing commands
ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview)
// ON_WM_SYSCHAR()
//ON_WM_SYSCOMMAND()
ON_WM_CONTEXTMENU()
ON_COMMAND(ID_ADD_PIN, OnAddPin)
ON_COMMAND(ID_FOOTPRINT_FILE_SAVE_AS, OnFootprintFileSaveAs)
ON_COMMAND(ID_ADD_POLYLINE, OnAddPolyline)
ON_COMMAND(ID_FOOTPRINT_FILE_IMPORT, OnFootprintFileImport)
ON_COMMAND(ID_FOOTPRINT_FILE_CLOSE, OnFootprintFileClose)
ON_COMMAND(ID_FOOTPRINT_FILE_NEW, OnFootprintFileNew)
ON_COMMAND(ID_VIEW_ENTIREFOOTPRINT, OnViewEntireFootprint)
//ON_COMMAND(ID_FP_EDIT_UNDO, OnFpEditUndo)
ON_WM_ERASEBKGND()
ON_COMMAND(ID_FP_MOVE, OnFpMove)
ON_COMMAND(ID_FP_EDITPROPERTIES, OnFpEditproperties)
ON_COMMAND(ID_FP_DELETE, OnFpDelete)
ON_COMMAND(ID_FP_INSERTCORNER, OnPolylineSideAddCorner)
ON_COMMAND(ID_FP_CONVERTTOSTRAIGHT, OnPolylineSideConvertToStraightLine)
ON_COMMAND(ID_FP_CONVERTTOARC, OnPolylineSideConvertToArcCw)
ON_COMMAND(ID_FP_CONVERTTOARC32778, OnPolylineSideConvertToArcCcw)
ON_COMMAND(ID_FP_DELETEOUTLINE, OnPolylineDelete)
ON_COMMAND(ID_FP_MOVE32780, OnPolylineCornerMove)
ON_COMMAND(ID_FP_SETPOSITION, OnPolylineCornerEdit)
ON_COMMAND(ID_FP_DELETECORNER, OnPolylineCornerDelete)
ON_COMMAND(ID_FP_DELETEPOLYLINE, OnPolylineDelete)
ON_COMMAND(ID_FP_MOVE_REF, OnRefMove)
ON_COMMAND(ID_FP_CHANGESIZE_REF, OnRefProperties)
ON_COMMAND(ID_FP_TOOLS_RETURN, OnFootprintFileClose)
ON_COMMAND(ID_FP_TOOLS_FOOTPRINTWIZARD, OnFpToolsFootprintwizard)
ON_COMMAND(ID_TOOLS_FOOTPRINTLIBRARYMANAGER, OnToolsFootprintLibraryManager)
ON_COMMAND(ID_ADD_TEXT32805, OnAddText)
ON_COMMAND(ID_FP_TEXT_EDIT, OnFpTextEdit)
ON_COMMAND(ID_FP_TEXT_MOVE, OnFpTextMove)
ON_COMMAND(ID_FP_TEXT_DELETE, OnFpTextDelete)
ON_COMMAND(ID_FP_ADD_PIN, OnAddPin)
ON_COMMAND(ID_FP_ADD_POLY, OnAddPolyline)
ON_COMMAND(ID_FP_ADD_TEXT, OnAddText)
ON_COMMAND(ID_NONE_RETURNTOPCB, OnFootprintFileClose)
ON_COMMAND(ID_TOOLS_MOVEORIGIN_FP, OnToolsMoveOriginFP)
ON_COMMAND(ID_NONE_MOVEORIGIN, OnToolsMoveOriginFP)
ON_COMMAND(ID_EDIT_REDO, OnEditRedo)
ON_COMMAND(ID_ADD_ADHESIVESPOT, OnAddAdhesive)
ON_COMMAND(ID_CENTROID_SETPARAMETERS, OnCentroidEdit)
ON_COMMAND(ID_CENTROID_MOVE, OnCentroidMove)
ON_COMMAND(ID_ADD_SLOT, OnAddSlot)
ON_COMMAND(ID_ADD_VALUETEXT, OnAddValueText)
ON_COMMAND(ID_ADD_HOLE, OnAddHole)
ON_COMMAND(ID_FP_EDIT, OnValueEdit)
ON_COMMAND(ID_FP_MOVE32923, OnValueMove)
ON_COMMAND(ID_ADHESIVE_EDIT, OnAdhesiveEdit)
ON_COMMAND(ID_ADHESIVE_MOVE, OnAdhesiveMove)
ON_COMMAND(ID_ADHESIVE_DELETE, OnAdhesiveDelete)
ON_COMMAND(ID_CENTROID_ROTATEAXIS, OnCentroidRotateAxis)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CFootprintView construction/destruction
// GetDocument() is not available at this point, so actual initialization
// is in InitInstance()
//
CFootprintView::CFootprintView()
{
m_small_font.CreateFont( 14, 0, 0, 0, FW_NORMAL, 0, 0, 0, DEFAULT_CHARSET,
OUT_CHARACTER_PRECIS, CLIP_CHARACTER_PRECIS, DEFAULT_QUALITY,
DEFAULT_PITCH | FF_DONTCARE, "Arial" );
#if 0
m_small_font.CreateFont( 10, 0, 0, 0, FW_NORMAL, 0, 0, 0, DEFAULT_CHARSET,
OUT_CHARACTER_PRECIS, CLIP_CHARACTER_PRECIS, DEFAULT_QUALITY,
DEFAULT_PITCH | FF_DONTCARE, "MS Sans Serif" );
#endif
m_Doc = NULL;
m_dlist = 0;
m_last_mouse_point.x = 0;
m_last_mouse_point.y = 0;
m_last_cursor_point.x = 0;
m_last_cursor_point.y = 0;
m_left_pane_w = 110; // the left pane on screen is this wide (pixels)
m_bottom_pane_h = 40; // the bottom pane on screen is this high (pixels)
m_memDC_created = FALSE;
m_dragging_new_item = FALSE;
m_units = MIL;
m_active_layer = LAY_FP_TOP_COPPER;
}
// Initialize data for view
// Should only be called after the document is created
// Don't try to draw window until this function has been called
// Enter with fp = pointer to footprint to be edited, or NULL
//
void CFootprintView::InitInstance( CShape * fp )
{
m_Doc = GetDocument();
ASSERT_VALID(m_Doc);
m_dlist = m_Doc->m_dlist_fp;
InitializeView();
CRect screen_r;
GetWindowRect( &screen_r );
m_dlist->SetMapping( &m_client_r, &screen_r, m_left_pane_w, m_bottom_pane_h,
m_pcbu_per_pixel, m_org_x, m_org_y );
for(int i=0; i<m_Doc->m_fp_num_layers; i++ )
{
m_dlist->SetLayerRGB( i, m_Doc->m_fp_rgb[i][0], m_Doc->m_fp_rgb[i][1], m_Doc->m_fp_rgb[i][2] );
m_dlist->SetLayerVisible( i, 1 );
}
// set up footprint to be edited (if provided)
m_units = m_Doc->m_fp_units;
if( fp )
{
m_fp.Copy( fp );
if( m_fp.m_units == NM || m_fp.m_units == MM )
m_units = MM;
else
m_units = MIL;
CMainFrame * frm = (CMainFrame*)AfxGetMainWnd();
frm->m_wndMyToolBar.SetUnits( m_units );
OnViewEntireFootprint();
}
else
{
m_fp.m_name = "untitled";
}
SetWindowTitle( &m_fp.m_name );
// set up footprint library map (if necessary)
if( *m_Doc->m_footlibfoldermap.GetDefaultFolder() == "" )
m_Doc->MakeLibraryMaps( &m_Doc->m_full_lib_dir );
// initialize window
m_dlist->RemoveAll();
m_fp.Draw( m_dlist, m_Doc->m_smfontutil );
FootprintModified( FALSE );
m_Doc->m_footprint_name_changed = FALSE;
ClearUndo();
ClearRedo();
ShowSelectStatus();
ShowActiveLayer();
Invalidate( FALSE );
}
// Initialize view with application defaults
//
void CFootprintView::InitializeView()
{
if( !m_dlist )
ASSERT(0);
// set defaults
SetCursorMode( CUR_FP_NONE_SELECTED );
m_sel_id.Clear();
m_debug_flag = 0;
m_dragging_new_item = 0;
// default screen coords
m_pcbu_per_pixel = 5.0*PCBU_PER_MIL; // 5 mils per pixel
m_org_x = -100.0*PCBU_PER_MIL; // lower left corner of window
m_org_y = -100.0*PCBU_PER_MIL;
// grid defaults
m_Doc->m_fp_snap_angle = 45;
CancelSelection();
m_left_pane_invalid = TRUE;
// CDC * pDC = GetDC();
// OnDraw( pDC );
// ReleaseDC( pDC );
EnableUndo( FALSE );
EnableRedo( FALSE );
Invalidate( FALSE );
}
CFootprintView::~CFootprintView()
{
}
BOOL CFootprintView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return CView::PreCreateWindow(cs);
}
/////////////////////////////////////////////////////////////////////////////
// CFootprintView drawing
void CFootprintView::OnDraw(CDC* pDC)
{
#define VSTEP 14
if( !m_Doc )
{
// don't try to draw until InitInstance() has been called
return;
}
// get client rectangle
GetClientRect( &m_client_r );
// draw stuff on left pane
if( m_left_pane_invalid )
{
// erase previous contents if changed
CBrush brush( RGB(255, 255, 255) );
CPen pen( PS_SOLID, 1, RGB(255, 255, 255) );
CBrush * old_brush = pDC->SelectObject( &brush );
CPen * old_pen = pDC->SelectObject( &pen );
// erase left pane
CRect r = m_client_r;
r.right = m_left_pane_w;
r.bottom -= m_bottom_pane_h;
pDC->Rectangle( &r );
// erase bottom pane
r = m_client_r;
r.top = r.bottom - m_bottom_pane_h;
pDC->Rectangle( &r );
pDC->SelectObject( old_brush );
pDC->SelectObject( old_pen );
m_left_pane_invalid = FALSE;
}
CFont * old_font = pDC->SelectObject( &m_small_font );
int y_off = 10;
int x_off = 10;
for( int i=0; i<m_Doc->m_fp_num_layers; i++ )
{
// i = position index
CRect r( x_off, i*VSTEP+y_off, x_off+12, i*VSTEP+12+y_off );
CBrush brush( RGB(m_Doc->m_fp_rgb[i][0], m_Doc->m_fp_rgb[i][1], m_Doc->m_fp_rgb[i][2]) );
if( m_Doc->m_fp_vis[i] )
{
// draw colored rectangle
CBrush * old_brush = pDC->SelectObject( &brush );
pDC->Rectangle( &r );
pDC->SelectObject( old_brush );
}
else
{
// if layer is invisible, draw box with X
pDC->Rectangle( &r );
pDC->MoveTo( r.left, r.top );
pDC->LineTo( r.right, r.bottom );
pDC->MoveTo( r.left, r.bottom );
pDC->LineTo( r.right, r.top );
}
r.left += 20;
r.right += 120;
r.bottom += 5;
if( i == LAY_FP_PAD_THRU )
pDC->DrawText( "drilled hole", -1, &r, 0 );
else
pDC->DrawText( &fp_layer_str[i][0], -1, &r, 0 );
if( i >= LAY_FP_TOP_COPPER && i <= LAY_FP_BOTTOM_COPPER )
{
CString num_str;
num_str.Format( "[%d*]", i-LAY_FP_TOP_COPPER+1 );
CRect nr = r;
nr.left = nr.right - 55;
pDC->DrawText( num_str, -1, &nr, DT_TOP );
}
CRect ar = r;
ar.left = 2;
ar.right = 8;
ar.bottom -= 5;
if( i == m_active_layer )
{
// draw arrowhead
pDC->MoveTo( ar.left, ar.top+1 );
pDC->LineTo( ar.right-1, (ar.top+ar.bottom)/2 );
pDC->LineTo( ar.left, ar.bottom-1 );
pDC->LineTo( ar.left, ar.top+1 );
}
else
{
// erase arrowhead
pDC->FillSolidRect( &ar, RGB(255,255,255) );
}
}
CRect r( x_off, NUM_FP_LAYERS*VSTEP+y_off, x_off+120, NUM_FP_LAYERS*VSTEP+12+y_off );
pDC->DrawText( "* Use numeric", -1, &r, DT_TOP );
r.bottom += VSTEP;
r.top += VSTEP;
pDC->DrawText( "keys to display", -1, &r, DT_TOP );
r.bottom += VSTEP;
r.top += VSTEP;
pDC->DrawText( "layer on top", -1, &r, DT_TOP );
// draw function keys on bottom pane
DrawBottomPane();
// clip to pcb drawing region
pDC->SelectClipRgn( &m_pcb_rgn );
// now draw the display list
SetDCToWorldCoords( pDC );
m_dlist->Draw( pDC );
}
/////////////////////////////////////////////////////////////////////////////
// CFootprintView printing
BOOL CFootprintView::OnPreparePrinting(CPrintInfo* pInfo)
{
// default preparation
return DoPreparePrinting(pInfo);
}
void CFootprintView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add extra initialization before printing
}
void CFootprintView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add cleanup after printing
}
/////////////////////////////////////////////////////////////////////////////
// CFootprintView diagnostics
#ifdef _DEBUG
void CFootprintView::AssertValid() const
{
CView::AssertValid();
}
void CFootprintView::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
CFreePcbDoc* CFootprintView::GetDocument() // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CFreePcbDoc)));
return (CFreePcbDoc*)m_pDocument;
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CFootprintView message handlers
// Window was resized
//
void CFootprintView::OnSize(UINT nType, int cx, int cy)
{
CView::OnSize(nType, cx, cy);
// update client rect and create clipping region
GetClientRect( &m_client_r );
m_pcb_rgn.DeleteObject();
m_pcb_rgn.CreateRectRgn( m_left_pane_w, m_client_r.bottom-m_bottom_pane_h,
m_client_r.right, m_client_r.top );
// update display mapping for display list
if( m_dlist )
{
CRect screen_r;
GetWindowRect( &screen_r );
m_dlist->SetMapping( &m_client_r, &screen_r, m_left_pane_w, m_bottom_pane_h, m_pcbu_per_pixel,
m_org_x, m_org_y );
}
// create memory DC and DDB
if( !m_memDC_created && m_client_r.right != 0 )
{
CDC * pDC = GetDC();
m_memDC.CreateCompatibleDC( pDC );
m_memDC_created = TRUE;
m_bitmap.CreateCompatibleBitmap( pDC, m_client_r.right, m_client_r.bottom );
m_old_bitmap = m_memDC.SelectObject( &m_bitmap );
m_bitmap_rect = m_client_r;
ReleaseDC( pDC );
}
else if( m_memDC_created && (m_bitmap_rect != m_client_r) )
{
CDC * pDC = GetDC();
m_memDC.SelectObject( m_old_bitmap );
m_bitmap.DeleteObject();
m_bitmap.CreateCompatibleBitmap( pDC, m_client_r.right, m_client_r.bottom );
m_old_bitmap = m_memDC.SelectObject( &m_bitmap );
m_bitmap_rect = m_client_r;
ReleaseDC( pDC );
}
}
// Left mouse button pressed down, we should probably do something
//
void CFootprintView::OnLButtonDown(UINT nFlags, CPoint point)
{
CDC * pDC = NULL; // !! remember to ReleaseDC() at end, if necessary
CPoint tp = WindowToPCB( point );
if( point.y > (m_client_r.bottom-m_bottom_pane_h) )
{
// clicked in bottom pane, test for hit on function key rectangle
for( int i=0; i<8; i++ )
{
CRect r( FKEY_OFFSET_X+i*FKEY_STEP+(i/4)*FKEY_GAP,
m_client_r.bottom-FKEY_OFFSET_Y-FKEY_R_H,
FKEY_OFFSET_X+i*FKEY_STEP+(i/4)*FKEY_GAP+FKEY_R_W,
m_client_r.bottom-FKEY_OFFSET_Y );
if( r.PtInRect( point ) )
{
// fake function key pressed
int nChar = i + 112;
HandleKeyPress( nChar, 0, 0 );
if( i == 7 )
return;
}
}
}
else if( point.x < m_left_pane_w )
{
// clicked in left pane
CRect r = m_client_r;
int y_off = 10;
int x_off = 10;
for( int i=0; i<m_Doc->m_fp_num_layers; i++ )
{
// i = position index
// get color square
r.left = x_off;
r.right = x_off+12;
r.top = i*VSTEP+y_off;
r.bottom = i*VSTEP+12+y_off;
if( r.PtInRect( point ) && i > LAY_BACKGND )
{
// clicked in color square
m_Doc->m_fp_vis[i] = !m_Doc->m_fp_vis[i];
m_dlist->SetLayerVisible( i, m_Doc->m_fp_vis[i] );
Invalidate( FALSE );
}
else
{
// get layer name rect
r.left += 20;
r.right += 120;
r.bottom += 5;
if( r.PtInRect( point ) )
{
// clicked on layer name
switch( i )
{
case LAY_FP_TOP_COPPER: HandleKeyPress( '1', 0, 0 ); Invalidate( FALSE ); break;
case LAY_FP_TOP_COPPER+1: HandleKeyPress( '2', 0, 0 ); Invalidate( FALSE ); break;
case LAY_FP_TOP_COPPER+2: HandleKeyPress( '3', 0, 0 ); Invalidate( FALSE ); break;
}
}
}
}
y_off = r.bottom + 2*VSTEP;
}
else if( point.x > m_left_pane_w )
{
// clicked in PCB pane
if( CurNone() || CurSelected() )
{
// we are not dragging anything, see if new item selected
CPoint p = WindowToPCB( point );
id id;
void * sel_ptr = NULL;
void * ptr = m_dlist->TestSelect( p.x, p.y, &id, &m_sel_layer, &m_sel_id, sel_ptr );
// deselect previously selected item
CancelSelection();
// now check for new selection
if( id.type == ID_PART )
{
// something was selected
m_sel_id = id;
if( id.st == ID_SEL_PAD )
{
// pad selected
m_fp.SelectPad( id.i );
SetCursorMode( CUR_FP_PAD_SELECTED );
Invalidate( FALSE );
}
else if( id.st == ID_SEL_REF_TXT )
{
// ref text selected
m_fp.SelectRef();
SetCursorMode( CUR_FP_REF_SELECTED );
}
else if( id.st == ID_SEL_VALUE_TXT )
{
// value text selected
m_fp.SelectValue();
SetCursorMode( CUR_FP_VALUE_SELECTED );
}
else if( id.st == ID_OUTLINE )
{
// outline polyline selected
int i = m_sel_id.i;
if( id.sst == ID_SEL_CORNER )
{
// corner selected
int ic = m_sel_id.ii;
m_fp.m_outline_poly[i].HighlightCorner( ic );
SetCursorMode( CUR_FP_POLY_CORNER_SELECTED );
}
else if( id.sst == ID_SEL_SIDE )
{
// side selected
int is = m_sel_id.ii;
m_fp.m_outline_poly[i].HighlightSide( is );
SetCursorMode( CUR_FP_POLY_SIDE_SELECTED );
}
}
}
else if( id.type == ID_TEXT )
{
// text selected
m_sel_id = id;
m_sel_text = (CText*)ptr;
SetCursorMode( CUR_FP_TEXT_SELECTED );
m_fp.m_tl->HighlightText( m_sel_text );
}
else if( id.type == ID_CENTROID )
{
// centroid selected
m_sel_id = id;
SetCursorMode( CUR_FP_CENTROID_SELECTED );
m_fp.SelectCentroid();
Invalidate( FALSE );
}
else if( id.type == ID_GLUE )
{
// glue spot selected
m_sel_id = id;
SetCursorMode( CUR_FP_ADHESIVE_SELECTED );
m_fp.SelectAdhesive( id.i );
Invalidate( FALSE );
}
else
{
// nothing selected
m_sel_id.Clear();
SetCursorMode( CUR_FP_NONE_SELECTED );
}
}
else if( m_cursor_mode == CUR_FP_DRAG_PAD )
{
// we were dragging pad, move it
if( !m_dragging_new_item )
PushUndo();
int i = m_sel_id.i; // pin number (zero-based)
CPoint p = m_last_cursor_point;
m_dlist->StopDragging();
int dx = p.x - m_fp.m_padstack[i].x_rel;
int dy = p.y - m_fp.m_padstack[i].y_rel;
for( int ip=i; ip<(i+m_drag_num_pads); ip++ )
{
m_fp.m_padstack[ip].x_rel += dx;
m_fp.m_padstack[ip].y_rel += dy;
}
if( m_drag_num_pads == 1 )
{
// only rotate if single pad (not row)
int old_angle = m_fp.m_padstack[m_sel_id.i].angle;
int angle = old_angle + m_dlist->GetDragAngle();
if( angle>270 )
angle = angle - 360;
m_fp.m_padstack[i].angle = angle;
}
m_dragging_new_item = FALSE;
m_fp.Draw( m_dlist, m_Doc->m_smfontutil );
SetCursorMode( CUR_FP_PAD_SELECTED );
m_fp.SelectPad( m_sel_id.i );
FootprintModified( TRUE );
}
else if( m_cursor_mode == CUR_FP_DRAG_REF )
{
// we were dragging ref, move it
PushUndo();
CPoint p = m_last_cursor_point;
m_dlist->StopDragging();
int old_angle = m_fp.m_ref_angle;
int angle = old_angle + m_dlist->GetDragAngle();
if( angle>270 )
angle = angle - 360;
m_fp.m_ref_xi = p.x;
m_fp.m_ref_yi = p.y;
m_fp.m_ref_angle = angle;
m_fp.Draw( m_dlist, m_Doc->m_smfontutil );
SetCursorMode( CUR_FP_REF_SELECTED );
m_fp.SelectRef();
FootprintModified( TRUE );
}
else if( m_cursor_mode == CUR_FP_DRAG_VALUE )
{
// we were dragging value, move it
PushUndo();
CPoint p = m_last_cursor_point;
m_dlist->StopDragging();
int old_angle = m_fp.m_value_angle;
int angle = old_angle + m_dlist->GetDragAngle();
if( angle>270 )
angle = angle - 360;
m_fp.m_value_xi = p.x;
m_fp.m_value_yi = p.y;
m_fp.m_value_angle = angle;
m_fp.Draw( m_dlist, m_Doc->m_smfontutil );
SetCursorMode( CUR_FP_VALUE_SELECTED );
m_fp.SelectValue();
FootprintModified( TRUE );
}
else if( m_cursor_mode == CUR_FP_DRAG_POLY_MOVE )
{
// move corner of polyline
PushUndo();
pDC = GetDC();
SetDCToWorldCoords( pDC );
pDC->SelectClipRgn( &m_pcb_rgn );
CPoint p;
p = m_last_cursor_point;
m_dlist->StopDragging();
m_fp.m_outline_poly[m_sel_id.i].MoveCorner( m_sel_id.ii, p.x, p.y );
m_fp.m_outline_poly[m_sel_id.i].HighlightCorner( m_sel_id.ii );
SetCursorMode( CUR_FP_POLY_CORNER_SELECTED );
FootprintModified( TRUE );
}
else if( m_cursor_mode == CUR_FP_DRAG_POLY_INSERT )
{
// insert new corner into polyline
PushUndo();
pDC = GetDC();
SetDCToWorldCoords( pDC );
pDC->SelectClipRgn( &m_pcb_rgn );
CPoint p;
p = m_last_cursor_point;
m_dlist->StopDragging();
m_fp.m_outline_poly[m_sel_id.i].InsertCorner( m_sel_id.ii+1, p.x, p.y );
// now select new corner
m_fp.m_outline_poly[m_sel_id.i].HighlightCorner( m_sel_id.ii+1 );
m_sel_id.Set( ID_PART, ID_OUTLINE, m_sel_id.i, ID_SEL_CORNER, m_sel_id.ii+1 );
SetCursorMode( CUR_FP_POLY_CORNER_SELECTED );
FootprintModified( TRUE );
}
else if( m_cursor_mode == CUR_FP_ADD_POLY )
{
// place first corner of polyline
PushUndo();
pDC = GetDC();
SetDCToWorldCoords( pDC );
pDC->SelectClipRgn( &m_pcb_rgn );
CPoint p;
p = m_last_cursor_point;
// make new polyline
int ip = m_fp.m_outline_poly.GetSize();
m_sel_id.Set( ID_PART, ID_OUTLINE, ip, ID_SEL_CORNER, 0 );
m_fp.m_outline_poly.SetSize( ip+1 );
m_fp.m_outline_poly[ip].Start( LAY_FP_SILK_TOP, m_polyline_width,
20*NM_PER_MIL, p.x, p.y, 0, &m_sel_id, NULL );
m_dlist->StartDraggingArc( pDC, m_polyline_style, p.x, p.y, p.x, p.y, LAY_FP_SELECTION, 1, 1 );
SetCursorMode( CUR_FP_DRAG_POLY_1 );
FootprintModified( TRUE );
m_snap_angle_ref = m_last_cursor_point;
}
else if( m_cursor_mode == CUR_FP_DRAG_POLY_1 )
{
// place second corner of polyline
// PushUndo();
pDC = GetDC();
SetDCToWorldCoords( pDC );
pDC->SelectClipRgn( &m_pcb_rgn );
CPoint p;
p = m_last_cursor_point;
m_fp.m_outline_poly[m_sel_id.i].AppendCorner( p.x, p.y, m_polyline_style );
m_fp.m_outline_poly[m_sel_id.i].Draw( m_dlist );
m_dlist->StartDraggingArc( pDC, m_polyline_style, p.x, p.y, p.x, p.y, LAY_FP_SELECTION, 1, 1 );
m_sel_id.ii++;
SetCursorMode( CUR_FP_DRAG_POLY );
FootprintModified( TRUE );
m_snap_angle_ref = m_last_cursor_point;
}
else if( m_cursor_mode == CUR_FP_DRAG_POLY )
{
// place subsequent corners of board outline
PushUndo();
pDC = GetDC();
SetDCToWorldCoords( pDC );
pDC->SelectClipRgn( &m_pcb_rgn );
CPoint p;
p = m_last_cursor_point;
if( p.x == m_fp.m_outline_poly[m_sel_id.i].GetX(0)
&& p.y == m_fp.m_outline_poly[m_sel_id.i].GetY(0) )
{
// this point is the start point, close the polyline and quit
m_fp.m_outline_poly[m_sel_id.i].Close( m_polyline_style );
SetCursorMode( CUR_FP_NONE_SELECTED );
m_dlist->StopDragging();
}
else
{
// add corner to polyline
m_fp.m_outline_poly[m_sel_id.i].AppendCorner( p.x, p.y, m_polyline_style );
m_dlist->StartDraggingArc( pDC, m_polyline_style, p.x, p.y, p.x, p.y, LAY_FP_SELECTION, 1, 1 );
m_sel_id.ii++;
m_snap_angle_ref = m_last_cursor_point;
}
FootprintModified( TRUE );
}
else if( m_cursor_mode == CUR_FP_DRAG_TEXT )
{
if( !m_dragging_new_item )
PushUndo(); // if new item, PushUndo() has already been called
CPoint p;
p = m_last_cursor_point;
m_dlist->StopDragging();
int old_angle = m_sel_text->m_angle;
int angle = old_angle + m_dlist->GetDragAngle();
if( angle>270 )
angle = angle - 360;
int old_mirror = m_sel_text->m_mirror;
BOOL negative = m_sel_text->m_bNegative;
int mirror = (old_mirror + m_dlist->GetDragSide())%2;
int layer = m_sel_text->m_layer;
m_fp.m_tl->MoveText( m_sel_text, p.x, p.y,
angle, mirror, negative, layer );
m_dragging_new_item = FALSE;
SetCursorMode( CUR_FP_TEXT_SELECTED );
m_fp.m_tl->HighlightText( m_sel_text );
FootprintModified( TRUE );
}
else if( m_cursor_mode == CUR_FP_MOVE_ORIGIN )
{
CPoint p;
p = m_last_cursor_point;
m_dlist->StopDragging();
PushUndo();
MoveOrigin( p.x, p.y );
SetCursorMode( CUR_FP_NONE_SELECTED );
FootprintModified( TRUE );
OnViewEntireFootprint();
}
else if( m_cursor_mode == CUR_FP_DRAG_CENTROID )
{
CPoint p;
p = m_last_cursor_point;
m_fp.CancelDraggingCentroid();
PushUndo();
m_fp.Undraw();
m_fp.m_centroid_x = p.x;
m_fp.m_centroid_y = p.y;
m_fp.m_centroid_type = CENTROID_DEFINED;
for( int idot=0; idot<m_fp.m_glue.GetSize(); idot++ )
{
glue * g = &m_fp.m_glue[idot];
if( g->type == GLUE_POS_CENTROID )
{
g->x_rel = p.x;
g->y_rel = p.y;
}
}
m_fp.Draw( m_dlist, m_Doc->m_smfontutil );
m_fp.SelectCentroid();
SetCursorMode( CUR_FP_CENTROID_SELECTED );
FootprintModified( TRUE );
}
else if( m_cursor_mode == CUR_FP_DRAG_ADHESIVE )
{
int idot = m_sel_id.i;
CPoint p;
p = m_last_cursor_point;
m_fp.CancelDraggingAdhesive( idot );
m_fp.Undraw();
m_fp.m_glue[idot].x_rel = p.x;
m_fp.m_glue[idot].y_rel = p.y;
m_fp.m_glue[idot].type = GLUE_POS_DEFINED;
m_fp.Draw( m_dlist, m_Doc->m_smfontutil );
m_fp.SelectAdhesive( idot );
SetCursorMode( CUR_FP_ADHESIVE_SELECTED );
FootprintModified( TRUE );
m_dragging_new_item = FALSE; // default
}
ShowSelectStatus();
}
Invalidate( FALSE );
if( pDC )
ReleaseDC( pDC );
CView::OnLButtonDown(nFlags, point);
}
// left double-click
//
void CFootprintView::OnLButtonDblClk(UINT nFlags, CPoint point)
{
#if 0
if( m_cursor_mode == CUR_PART_SELECTED )
{
SetCursorMode( CUR_DRAG_PART );
CDC *pDC = GetDC();
pDC->SelectClipRgn( &m_pcb_rgn );
SetDCToWorldCoords( pDC );
CPoint p = m_last_mouse_point;
m_dlist->StartDraggingSelection( pDC, p.x, p.y );
}
if( m_cursor_mode == CUR_REF_SELECTED )
{
SetCursorMode( CUR_DRAG_REF );
CDC *pDC = GetDC();
pDC->SelectClipRgn( &m_pcb_rgn );
SetDCToWorldCoords( pDC );
CPoint p = m_last_mouse_point;
m_dlist->StartDraggingSelection( pDC, p.x, p.y );
}
#endif
CView::OnLButtonDblClk(nFlags, point);
}
// right mouse button
//
void CFootprintView::OnRButtonDown(UINT nFlags, CPoint point)
{
m_disable_context_menu = 1;
if( m_cursor_mode == CUR_FP_DRAG_PAD )
{
m_fp.CancelDraggingPad( m_sel_id.i );
if( m_dragging_new_item )
{
UndoNoRedo();
CancelSelection();
}
else
{
m_fp.CancelDraggingPad( m_sel_id.i );
m_fp.SelectPad( m_sel_id.i );
SetCursorMode( CUR_FP_PAD_SELECTED );
}
}
else if( m_cursor_mode == CUR_FP_DRAG_REF )
{
m_fp.CancelDraggingRef();
m_fp.SelectRef();
SetCursorMode( CUR_FP_REF_SELECTED );
}
else if( m_cursor_mode == CUR_FP_DRAG_VALUE )
{
m_fp.CancelDraggingValue();
m_fp.SelectValue();
SetCursorMode( CUR_FP_VALUE_SELECTED );
Invalidate( FALSE );
}
else if( m_cursor_mode == CUR_FP_ADD_POLY )
{
m_dlist->StopDragging();
CancelSelection();
}
else if( m_cursor_mode == CUR_FP_DRAG_POLY_1 )
{
m_dlist->StopDragging();
OnPolylineDelete();
}
else if( ( m_cursor_mode == CUR_FP_DRAG_POLY
&& m_fp.m_outline_poly[m_sel_id.i].GetNumCorners()<3
&& m_polyline_closed_flag )
|| ( m_cursor_mode == CUR_FP_DRAG_POLY
&& m_fp.m_outline_poly[m_sel_id.i].GetNumCorners()<2
&& !m_polyline_closed_flag ) )
{
m_dlist->StopDragging();
OnPolylineDelete();
}
else if( m_cursor_mode == CUR_FP_DRAG_POLY )
{
m_dlist->StopDragging();
if( m_polyline_closed_flag )
{
PushUndo();
m_fp.m_outline_poly[m_sel_id.i].Close( m_polyline_style );
}
CancelSelection();
FootprintModified( TRUE );
}
else if( m_cursor_mode == CUR_FP_DRAG_POLY_INSERT )
{
m_dlist->StopDragging();
m_fp.m_outline_poly[m_sel_id.i].MakeVisible();
m_fp.m_outline_poly[m_sel_id.i].HighlightSide( m_sel_id.ii );
SetCursorMode( CUR_FP_POLY_SIDE_SELECTED );
}
else if( m_cursor_mode == CUR_FP_DRAG_POLY_MOVE )
{
m_dlist->StopDragging();
m_fp.m_outline_poly[m_sel_id.i].MakeVisible();
SetCursorMode( CUR_FP_POLY_CORNER_SELECTED );
m_fp.m_outline_poly[m_sel_id.i].HighlightCorner( m_sel_id.ii );
}
else if( m_cursor_mode == CUR_FP_DRAG_TEXT )
{
m_fp.m_tl->CancelDraggingText( m_sel_text );
if( m_dragging_new_item )
{
m_fp.m_tl->RemoveText( m_sel_text );
CancelSelection();
}
else
{
SetCursorMode( CUR_FP_TEXT_SELECTED );
}
}
else if( m_cursor_mode == CUR_FP_MOVE_ORIGIN )
{
m_dlist->StopDragging();
SetCursorMode( CUR_FP_NONE_SELECTED );
}
else if( m_cursor_mode == CUR_FP_DRAG_CENTROID )
{
m_fp.CancelDraggingCentroid();
m_fp.SelectCentroid();
SetCursorMode( CUR_FP_CENTROID_SELECTED );
}
else if( m_cursor_mode == CUR_FP_DRAG_ADHESIVE )
{
m_fp.CancelDraggingAdhesive( m_sel_id.i );
UndoNoRedo(); // restore state before dragging
if( m_dragging_new_item )
{
// cancel new item
CancelSelection();
}
else
{
// reselect item and change mode
m_fp.SelectAdhesive( m_sel_id.i );
SetCursorMode( CUR_FP_ADHESIVE_SELECTED );
}
}
else
{
m_disable_context_menu = 0;
}
m_dragging_new_item = FALSE;
Invalidate( FALSE );
ShowSelectStatus();
CView::OnRButtonDown(nFlags, point);
}
// System Key on keyboard pressed down
//
void CFootprintView::OnSysKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
if( nChar == 121 )
OnKeyDown( nChar, nRepCnt, nFlags);
else
CView::OnSysKeyDown(nChar, nRepCnt, nFlags);
}
// System Key on keyboard pressed down
//
void CFootprintView::OnSysKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags)
{
if( nChar != 121 )
CView::OnSysKeyUp(nChar, nRepCnt, nFlags);
}
// Key on keyboard pressed down
//
void CFootprintView::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
HandleKeyPress( nChar, nRepCnt, nFlags );
// don't pass through SysKey F10
if( nChar != 121 )
CView::OnKeyDown(nChar, nRepCnt, nFlags);
}
// Key on keyboard pressed down
//
void CFootprintView::HandleKeyPress(UINT nChar, UINT nRepCnt, UINT nFlags)
{
int fk = FK_FP_NONE;
if( nChar >= 112 && nChar <= 123 ) // Function key
{
fk = m_fkey_option[nChar-112];
}
if( nChar == '1' || nChar == '2' || nChar == '3' )
{
// change visibility of layers
if( nChar == '1' )
{
m_active_layer = LAY_FP_TOP_COPPER;
ShowActiveLayer();
}
else if( nChar == '2' )
{
m_active_layer = LAY_FP_INNER_COPPER;
ShowActiveLayer();
}
else if( nChar == '3' )
{
m_active_layer = LAY_FP_BOTTOM_COPPER;
ShowActiveLayer();
}
}
CDC *pDC = GetDC();
pDC->SelectClipRgn( &m_pcb_rgn );
SetDCToWorldCoords( pDC );
// get cursor position and convert to PCB coords
CPoint p;
GetCursorPos( &p ); // cursor pos in screen coords
p = ScreenToPCB( p ); // convert to PCB coords
// now handle key-press
switch( m_cursor_mode )
{
case CUR_FP_NONE_SELECTED:
if( fk == FK_FP_ADD_PAD )
OnAddPin();
else if( fk == FK_FP_ADD_TEXT )
OnAddText();
else if( fk == FK_FP_ADD_POLYLINE )
OnAddPolyline();
break;
case CUR_FP_PAD_SELECTED:
if( fk == FK_FP_DELETE_PAD || nChar == 46 )
OnPadDelete( m_sel_id.i );
else if( fk == FK_FP_EDIT_PAD )
OnPadEdit( m_sel_id.i );
else if( fk == FK_FP_MOVE_PAD )
OnPadMove( m_sel_id.i );
break;
case CUR_FP_REF_SELECTED:
if( fk == FK_FP_EDIT_PROPERTIES )
OnRefProperties();
else if( fk == FK_FP_MOVE_REF )
OnRefMove();
break;
case CUR_FP_VALUE_SELECTED:
if( fk == FK_FP_EDIT_PROPERTIES )
OnValueEdit();
else if( fk == FK_FP_MOVE_VALUE )
OnValueMove();
break;
case CUR_FP_POLY_CORNER_SELECTED:
if( fk == FK_FP_SET_POSITION )
OnPolylineCornerEdit();
else if( fk == FK_FP_MOVE_CORNER )
OnPolylineCornerMove();
else if( fk == FK_FP_DELETE_CORNER || nChar == 46 )
{
OnPolylineCornerDelete();
FootprintModified( TRUE );
}
else if( fk == FK_FP_DELETE_POLYLINE )
{
OnPolylineDelete();
FootprintModified( TRUE );
}
break;
case CUR_FP_POLY_SIDE_SELECTED:
if( fk == FK_FP_POLY_STRAIGHT )
OnPolylineSideConvertToStraightLine();
else if( fk == FK_FP_POLY_ARC_CW )
OnPolylineSideConvertToArcCw();
else if( fk == FK_FP_POLY_ARC_CCW )
OnPolylineSideConvertToArcCcw();
else if( fk == FK_FP_ADD_CORNER )
OnPolylineSideAddCorner();
else if( fk == FK_FP_DELETE_POLYLINE || nChar == 46 )
OnPolylineDelete();
FootprintModified( TRUE );
break;
case CUR_FP_TEXT_SELECTED:
if( fk == FK_FP_EDIT_TEXT )
OnFpTextEdit();
else if( fk == FK_FP_MOVE_TEXT )
OnFpTextMove();
else if( fk == FK_FP_DELETE_TEXT || nChar == 46 )
OnFpTextDelete();
break;
case CUR_FP_CENTROID_SELECTED:
if( fk == FK_FP_EDIT_CENTROID )
OnCentroidEdit();
else if( fk == FK_FP_ROTATE_CENTROID )
OnCentroidRotateAxis();
else if( fk == FK_FP_MOVE_CENTROID )
OnCentroidMove();
break;
case CUR_FP_ADHESIVE_SELECTED:
if( fk == FK_FP_EDIT_ADHESIVE )
OnAdhesiveEdit();
else if( fk == FK_FP_MOVE_ADHESIVE )
OnAdhesiveMove();
else if( fk == FK_FP_DELETE_ADHESIVE || nChar == 46 )
OnAdhesiveDelete();
break;
case CUR_FP_DRAG_PAD:
if( fk == FK_FP_ROTATE_PAD )
m_dlist->IncrementDragAngle( pDC );
break;
case CUR_FP_DRAG_VALUE:
if( fk == FK_FP_ROTATE_VALUE )
m_dlist->IncrementDragAngle( pDC );
break;
case CUR_FP_DRAG_REF:
if( fk == FK_FP_ROTATE_REF )
m_dlist->IncrementDragAngle( pDC );
break;
case CUR_FP_DRAG_POLY_1:
case CUR_FP_DRAG_POLY:
if( fk == FK_FP_POLY_STRAIGHT )
{
m_polyline_style = CPolyLine::STRAIGHT;
m_dlist->SetDragArcStyle( m_polyline_style );
m_dlist->Drag( pDC, p.x, p.y );
}
else if( fk == FK_FP_POLY_ARC_CW )
{
m_polyline_style = CPolyLine::ARC_CW;
m_dlist->SetDragArcStyle( m_polyline_style );
m_dlist->Drag( pDC, p.x, p.y );
}
else if( fk == FK_FP_POLY_ARC_CCW )
{
m_polyline_style = CPolyLine::ARC_CCW;
m_dlist->SetDragArcStyle( m_polyline_style );
m_dlist->Drag( pDC, p.x, p.y );
}
break;
case CUR_FP_DRAG_TEXT:
if( fk == FK_FP_ROTATE_TEXT )
m_dlist->IncrementDragAngle( pDC );
break;
default:
break;
} // end switch
if( nChar == VK_HOME )
{
// Home key pressed
OnViewEntireFootprint();
}
if( nChar == ' ' )
{
// space bar pressed, center window on cursor then center cursor
m_org_x = p.x - ((m_client_r.right-m_left_pane_w)*m_pcbu_per_pixel)/2;
m_org_y = p.y - ((m_client_r.bottom-m_bottom_pane_h)*m_pcbu_per_pixel)/2;
CRect screen_r;
GetWindowRect( &screen_r );
m_dlist->SetMapping( &m_client_r, &screen_r, m_left_pane_w, m_bottom_pane_h, m_pcbu_per_pixel,
m_org_x, m_org_y );
Invalidate( FALSE );
p = PCBToScreen( p );
SetCursorPos( p.x, p.y - 4 );
}
else if( nChar == 33 )
{
// PgUp pressed, zoom in
if( m_pcbu_per_pixel > 254 )
{
m_pcbu_per_pixel = m_pcbu_per_pixel/ZOOM_RATIO;
m_org_x = p.x - ((m_client_r.right-m_left_pane_w)*m_pcbu_per_pixel)/2;
m_org_y = p.y - ((m_client_r.bottom-m_bottom_pane_h)*m_pcbu_per_pixel)/2;
CRect screen_r;
GetWindowRect( &screen_r );
m_dlist->SetMapping( &m_client_r, &screen_r, m_left_pane_w, m_bottom_pane_h, m_pcbu_per_pixel,
m_org_x, m_org_y );
Invalidate( FALSE );
p = PCBToScreen( p );
SetCursorPos( p.x, p.y - 4 );
}
}
else if( nChar == 34 )
{
// PgDn pressed, zoom out
// first, make sure that window boundaries will be OK
int org_x = p.x - ((m_client_r.right-m_left_pane_w)*m_pcbu_per_pixel*ZOOM_RATIO)/2;
int org_y = p.y - ((m_client_r.bottom-m_bottom_pane_h)*m_pcbu_per_pixel*ZOOM_RATIO)/2;
int max_x = org_x + (m_client_r.right-m_left_pane_w)*m_pcbu_per_pixel*ZOOM_RATIO;
int max_y = org_y + (m_client_r.bottom-m_bottom_pane_h)*m_pcbu_per_pixel*ZOOM_RATIO;
if( org_x > -PCB_BOUND && org_x < PCB_BOUND && max_x > -PCB_BOUND && max_x < PCB_BOUND
&& org_y > -PCB_BOUND && org_y < PCB_BOUND && max_y > -PCB_BOUND && max_y < PCB_BOUND )
{
// OK, do it
m_org_x = org_x;
m_org_y = org_y;
m_pcbu_per_pixel = m_pcbu_per_pixel*ZOOM_RATIO;
CRect screen_r;
GetWindowRect( &screen_r );
m_dlist->SetMapping( &m_client_r, &screen_r, m_left_pane_w, m_bottom_pane_h, m_pcbu_per_pixel,
m_org_x, m_org_y );
Invalidate( FALSE );
p = PCBToScreen( p );
SetCursorPos( p.x, p.y - 4 );
}
}
else if( nChar == 27 )
{
// ESC key, simulate a right-click
OnRButtonDown( 0, NULL );
}
ReleaseDC( pDC );
ShowSelectStatus();
}
// Mouse moved
//
void CFootprintView::OnMouseMove(UINT nFlags, CPoint point)
{
m_last_mouse_point = WindowToPCB( point );
SnapCursorPoint( m_last_mouse_point );
}
/////////////////////////////////////////////////////////////////////////
// Utility functions
//
// Set the device context to world coords
//
int CFootprintView::SetDCToWorldCoords( CDC * pDC )
{
m_dlist->SetDCToWorldCoords( pDC, &m_memDC, m_org_x, m_org_y );
return 0;
}
// Convert point in window coords to PCB units (i.e. nanometers)
//
CPoint CFootprintView::WindowToPCB( CPoint point )
{
CPoint p;
p.x = (point.x-m_left_pane_w)*m_pcbu_per_pixel + m_org_x;
p.y = (m_client_r.bottom-m_bottom_pane_h-point.y)*m_pcbu_per_pixel + m_org_y;
return p;
}
// Convert point in screen coords to PCB units
//
CPoint CFootprintView::ScreenToPCB( CPoint point )
{
CPoint p;
CRect wr;
GetWindowRect( &wr ); // client rect in screen coords
p.x = point.x - wr.left;
p.y = point.y - wr.top;
p = WindowToPCB( p );
return p;
}
// Convert point in PCB units to screen coords
//
CPoint CFootprintView::PCBToScreen( CPoint point )
{
CPoint p;
CRect wr;
GetWindowRect( &wr ); // client rect in screen coords
p.x = (point.x - m_org_x)/m_pcbu_per_pixel+m_left_pane_w+wr.left;
p.y = (m_org_y - point.y)/m_pcbu_per_pixel-m_bottom_pane_h+wr.bottom;
return p;
}
// Set cursor mode, update function key menu if necessary
//
void CFootprintView::SetCursorMode( int mode )
{
if( mode != m_cursor_mode )
{
SetFKText( mode );
m_cursor_mode = mode;
ShowSelectStatus();
}
}
// Set function key shortcut text
//
void CFootprintView::SetFKText( int mode )
{
for( int i=0; i<12; i++ )
{
m_fkey_option[i] = 0;
m_fkey_command[i] = 0;
}
switch( mode )
{
case CUR_FP_NONE_SELECTED:
m_fkey_option[1] = FK_FP_ADD_TEXT;
m_fkey_option[2] = FK_FP_ADD_POLYLINE;
m_fkey_option[3] = FK_FP_ADD_PAD;
break;
case CUR_FP_PAD_SELECTED:
m_fkey_option[0] = FK_FP_EDIT_PAD;
m_fkey_option[3] = FK_FP_MOVE_PAD;
m_fkey_option[6] = FK_FP_DELETE_PAD;
break;
case CUR_FP_REF_SELECTED:
m_fkey_option[0] = FK_FP_EDIT_PROPERTIES;
m_fkey_option[3] = FK_FP_MOVE_REF;
break;
case CUR_FP_VALUE_SELECTED:
m_fkey_option[0] = FK_FP_EDIT_PROPERTIES;
m_fkey_option[3] = FK_FP_MOVE_VALUE;
break;
case CUR_FP_POLY_CORNER_SELECTED:
m_fkey_option[0] = FK_FP_SET_POSITION;
m_fkey_option[3] = FK_FP_MOVE_CORNER;
m_fkey_option[4] = FK_FP_DELETE_CORNER;
m_fkey_option[6] = FK_FP_DELETE_POLYLINE;
break;
case CUR_FP_POLY_SIDE_SELECTED:
m_fkey_option[0] = FK_FP_POLY_STRAIGHT;
m_fkey_option[1] = FK_FP_POLY_ARC_CW;
m_fkey_option[2] = FK_FP_POLY_ARC_CCW;
{
int style = m_fp.m_outline_poly[m_sel_id.i].GetSideStyle( m_sel_id.ii );
if( style == CPolyLine::STRAIGHT )
m_fkey_option[3] = FK_FP_ADD_CORNER;
}
m_fkey_option[6] = FK_FP_DELETE_POLYLINE;
break;
case CUR_FP_TEXT_SELECTED:
m_fkey_option[0] = FK_FP_EDIT_TEXT;
m_fkey_option[3] = FK_FP_MOVE_TEXT;
m_fkey_option[6] = FK_FP_DELETE_TEXT;
break;
case CUR_FP_CENTROID_SELECTED:
m_fkey_option[0] = FK_FP_EDIT_CENTROID;
m_fkey_option[2] = FK_FP_ROTATE_CENTROID;
m_fkey_option[3] = FK_FP_MOVE_CENTROID;
break;
case CUR_FP_ADHESIVE_SELECTED:
m_fkey_option[0] = FK_FP_EDIT_ADHESIVE;
m_fkey_option[3] = FK_FP_MOVE_ADHESIVE;
m_fkey_option[6] = FK_FP_DELETE_ADHESIVE;
break;
case CUR_FP_DRAG_PAD:
if( m_drag_num_pads == 1 )
m_fkey_option[2] = FK_FP_ROTATE_PAD;
break;
case CUR_FP_DRAG_REF:
m_fkey_option[2] = FK_FP_ROTATE_REF;
break;
case CUR_FP_DRAG_VALUE:
m_fkey_option[2] = FK_FP_ROTATE_VALUE;
break;
case CUR_FP_DRAG_POLY_1:
m_fkey_option[0] = FK_FP_POLY_STRAIGHT;
m_fkey_option[1] = FK_FP_POLY_ARC_CW;
m_fkey_option[2] = FK_FP_POLY_ARC_CCW;
break;
case CUR_FP_DRAG_POLY:
m_fkey_option[0] = FK_FP_POLY_STRAIGHT;
m_fkey_option[1] = FK_FP_POLY_ARC_CW;
m_fkey_option[2] = FK_FP_POLY_ARC_CCW;
break;
case CUR_FP_DRAG_TEXT:
m_fkey_option[2] = FK_FP_ROTATE_TEXT;
break;
}
for( int i=0; i<12; i++ )
{
strcpy( m_fkey_str[2*i], fk_fp_str[2*m_fkey_option[i]] );
strcpy( m_fkey_str[2*i+1], fk_fp_str[2*m_fkey_option[i]+1] );
}
InvalidateLeftPane();
Invalidate( FALSE );
}
// Draw bottom pane
//
void CFootprintView::DrawBottomPane()
{
CDC * pDC = GetDC();
CFont * old_font = pDC->SelectObject( &m_small_font );
// get client rectangle
GetClientRect( &m_client_r );
// draw labels for function keys at bottom of client area
for( int j=0; j<2; j++ )
{
for( int i=0; i<4; i++ )
{
CRect r( FKEY_OFFSET_X+(j*4+i)*FKEY_STEP+j*FKEY_GAP,
m_client_r.bottom-FKEY_OFFSET_Y-FKEY_R_H,
FKEY_OFFSET_X+(j*4+i)*FKEY_STEP+j*FKEY_GAP+FKEY_R_W,
m_client_r.bottom-FKEY_OFFSET_Y );
pDC->Rectangle( &r );
pDC->MoveTo( r.left+FKEY_SEP_W, r.top );
pDC->LineTo( r.left+FKEY_SEP_W, r.top + FKEY_R_H/2 + 1 );
pDC->MoveTo( r.left, r.top + FKEY_R_H/2 );
pDC->LineTo( r.left+FKEY_SEP_W, r.top + FKEY_R_H/2 );
r.top += 1;
r.left += 2;
char fkstr[3] = "F1";
fkstr[1] = '1' + j*4+i;
pDC->DrawText( fkstr, -1, &r, 0 );
r.left += FKEY_SEP_W;
char * str1 = &m_fkey_str[2*(j*4+i)][0];
char * str2 = &m_fkey_str[2*(j*4+i)+1][0];
pDC->DrawText( str1, -1, &r, 0 );
r.top += FKEY_R_H/2 - 2;
pDC->DrawText( str2, -1, &r, 0 );
}
}
pDC->SelectObject( old_font );
ReleaseDC( pDC );
}
// display selected item in status bar
//
int CFootprintView::ShowSelectStatus()
{
CMainFrame * pMain = (CMainFrame*) AfxGetApp()->m_pMainWnd;
if( !pMain )
return 1;
CString str;
switch( m_cursor_mode )
{
case CUR_FP_NONE_SELECTED:
str.Format( "No selection" );
break;
case CUR_FP_PAD_SELECTED:
str.Format( "Pin %s", m_fp.GetPinNameByIndex( m_sel_id.i ) );
break;
case CUR_FP_DRAG_PAD:
str.Format( "Moving pin %s", m_fp.GetPinNameByIndex( m_sel_id.i ) );
break;
case CUR_FP_POLY_CORNER_SELECTED:
str.Format( "Polyline %d, corner %d", m_sel_id.i+1, m_sel_id.ii+1 );
break;
case CUR_FP_POLY_SIDE_SELECTED:
{
CString style_str;
if( m_fp.m_outline_poly[m_sel_id.i].GetSideStyle( m_sel_id.ii ) == CPolyLine::STRAIGHT )
style_str = "straight";
else if( m_fp.m_outline_poly[m_sel_id.i].GetSideStyle( m_sel_id.ii ) == CPolyLine::ARC_CW )
style_str = "arc(cw)";
else if( m_fp.m_outline_poly[m_sel_id.i].GetSideStyle( m_sel_id.ii ) == CPolyLine::ARC_CCW )
style_str = "arc(ccw)";
str.Format( "Polyline %d, side %d, style = %s", m_sel_id.i+1, m_sel_id.ii+1,
style_str );
}
break;
case CUR_FP_CENTROID_SELECTED:
{
CString type_str, x_str, y_str;
if( m_fp.m_centroid_type == CENTROID_DEFAULT )
type_str = "default position";
else
type_str = "defined";
::MakeCStringFromDimension( &x_str, m_fp.m_centroid_x, m_units, TRUE, TRUE, TRUE, 3 );
::MakeCStringFromDimension( &y_str, m_fp.m_centroid_y, m_units, TRUE, TRUE, TRUE, 3 );
str.Format( "Centroid (%s), x %s, y %s, angle %d",
type_str, x_str, y_str, m_fp.m_centroid_angle );
}
break;
case CUR_FP_ADHESIVE_SELECTED:
{
int idot = m_sel_id.i;
CString w_str, x_str, y_str;
int w = m_fp.m_glue[idot].w;
if( w > 0 )
::MakeCStringFromDimension( &w_str, m_fp.m_glue[idot].w, m_units, TRUE, TRUE, TRUE, 3 );
else
{
w_str = "<project default>";
w = 15*NM_PER_MIL;
}
::MakeCStringFromDimension( &x_str, m_fp.m_glue[idot].x_rel, m_units, TRUE, TRUE, TRUE, 3 );
::MakeCStringFromDimension( &y_str, m_fp.m_glue[idot].y_rel, m_units, TRUE, TRUE, TRUE, 3 );
if( m_fp.m_glue[idot].type == GLUE_POS_DEFINED )
str.Format( "Adhesive spot %d: w %s, x %s, y %s",
idot+1, w_str, x_str, y_str );
else
str.Format( "Adhesive spot %d: w %s at <centroid>",
idot+1, w_str );
}
break;
case CUR_FP_DRAG_POLY_MOVE:
str.Format( "Moving corner %d of polyline %d",
m_sel_id.ii+1, m_sel_id.i+1 );
break;
}
pMain->DrawStatus( 3, &str );
return 0;
}
// display cursor coords in status bar
//
int CFootprintView::ShowCursor()
{
CMainFrame * pMain = (CMainFrame*) AfxGetApp()->m_pMainWnd;
if( !pMain )
return 1;
CString str;
CPoint p;
p = m_last_cursor_point;
if( m_units == MIL )
{
str.Format( "X: %d", m_last_cursor_point.x/PCBU_PER_MIL );
pMain->DrawStatus( 1, &str );
str.Format( "Y: %d", m_last_cursor_point.y/PCBU_PER_MIL );
pMain->DrawStatus( 2, &str );
}
else
{
str.Format( "X: %8.3f", m_last_cursor_point.x/1000000.0 );
pMain->DrawStatus( 1, &str );
str.Format( "Y: %8.3f", m_last_cursor_point.y/1000000.0 );
pMain->DrawStatus( 2, &str );
}
return 0;
}
// handle mouse scroll wheel
//
BOOL CFootprintView::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt)
{
#define MIN_WHEEL_DELAY 1.0
static struct _timeb current_time;
static struct _timeb last_time;
static int first_time = 1;
double diff;
// get current time
_ftime( ¤t_time );
if( first_time )
{
diff = 999.0;
first_time = 0;
}
else
{
// get elapsed time since last wheel event
diff = difftime( current_time.time, last_time.time );
double diff_mil = (double)(current_time.millitm - last_time.millitm)*0.001;
diff = diff + diff_mil;
}
if( diff > MIN_WHEEL_DELAY )
{
// first wheel movement in a while
// center window on cursor then center cursor
CPoint p;
GetCursorPos( &p ); // cursor pos in screen coords
p = ScreenToPCB( p );
m_org_x = p.x - ((m_client_r.right-m_left_pane_w)*m_pcbu_per_pixel)/2;
m_org_y = p.y - ((m_client_r.bottom-m_bottom_pane_h)*m_pcbu_per_pixel)/2;
CRect screen_r;
GetWindowRect( &screen_r );
m_dlist->SetMapping( &m_client_r, &screen_r, m_left_pane_w, m_bottom_pane_h, m_pcbu_per_pixel, m_org_x, m_org_y );
Invalidate( FALSE );
p = PCBToScreen( p );
SetCursorPos( p.x, p.y - 4 );
}
else
{
// serial movements, zoom in or out
if( zDelta > 0 && m_pcbu_per_pixel > NM_PER_MIL/1000 )
{
// wheel pushed, zoom in then center world coords and cursor
CPoint p;
GetCursorPos( &p ); // cursor pos in screen coords
p = ScreenToPCB( p ); // convert to PCB coords
m_pcbu_per_pixel = m_pcbu_per_pixel/ZOOM_RATIO;
m_org_x = p.x - ((m_client_r.right-m_left_pane_w)*m_pcbu_per_pixel)/2.0;
m_org_y = p.y - ((m_client_r.bottom-m_bottom_pane_h)*m_pcbu_per_pixel)/2.0;
CRect screen_r;
GetWindowRect( &screen_r );
m_dlist->SetMapping( &m_client_r, &screen_r, m_left_pane_w, m_bottom_pane_h, m_pcbu_per_pixel, m_org_x, m_org_y );
Invalidate( FALSE );
p = PCBToScreen( p );
SetCursorPos( p.x, p.y - 4 );
}
else if( zDelta < 0 )
{
// wheel pulled, zoom out then center
// first, make sure that window boundaries will be OK
CPoint p;
GetCursorPos( &p ); // cursor pos in screen coords
p = ScreenToPCB( p );
int org_x = p.x - ((m_client_r.right-m_left_pane_w)*m_pcbu_per_pixel*ZOOM_RATIO)/2.0;
int org_y = p.y - ((m_client_r.bottom-m_bottom_pane_h)*m_pcbu_per_pixel*ZOOM_RATIO)/2.0;
int max_x = org_x + (m_client_r.right-m_left_pane_w)*m_pcbu_per_pixel*ZOOM_RATIO;
int max_y = org_y + (m_client_r.bottom-m_bottom_pane_h)*m_pcbu_per_pixel*ZOOM_RATIO;
if( org_x > -PCB_BOUND && org_x < PCB_BOUND && max_x > -PCB_BOUND && max_x < PCB_BOUND
&& org_y > -PCB_BOUND && org_y < PCB_BOUND && max_y > -PCB_BOUND && max_y < PCB_BOUND )
{
// OK, do it
m_org_x = org_x;
m_org_y = org_y;
m_pcbu_per_pixel = m_pcbu_per_pixel*ZOOM_RATIO;
CRect screen_r;
GetWindowRect( &screen_r );
m_dlist->SetMapping( &m_client_r, &screen_r, m_left_pane_w, m_bottom_pane_h, m_pcbu_per_pixel, m_org_x, m_org_y );
Invalidate( FALSE );
p = PCBToScreen( p );
SetCursorPos( p.x, p.y - 4 );
}
}
}
last_time = current_time;
return CView::OnMouseWheel(nFlags, zDelta, pt);
}
// cancel selection
//
void CFootprintView::CancelSelection()
{
m_dlist->CancelHighLight();
m_sel_id.Clear();
m_dragging_new_item = FALSE;
SetCursorMode( CUR_FP_NONE_SELECTED );
}
// context-sensitive menu invoked by right-click
//
void CFootprintView::OnContextMenu(CWnd* pWnd, CPoint point )
{
if( m_disable_context_menu )
{
// right-click already handled, don't pop up menu
m_disable_context_menu = 0;
return;
}
// OK, pop-up context menu
CMenu menu;
VERIFY(menu.LoadMenu(IDR_FP_CONTEXT));
CMenu* pPopup;
int style;
switch( m_cursor_mode )
{
case CUR_FP_NONE_SELECTED:
pPopup = menu.GetSubMenu(CONTEXT_FP_NONE);
ASSERT(pPopup != NULL);
pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, pWnd );
break;
case CUR_FP_PAD_SELECTED:
pPopup = menu.GetSubMenu(CONTEXT_FP_PAD);
ASSERT(pPopup != NULL);
pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, pWnd );
break;
case CUR_FP_POLY_SIDE_SELECTED:
pPopup = menu.GetSubMenu(CONTEXT_FP_SIDE);
ASSERT(pPopup != NULL);
style = m_fp.m_outline_poly[m_sel_id.i].GetSideStyle( m_sel_id.ii );
if( style == CPolyLine::STRAIGHT )
{
int xi = m_fp.m_outline_poly[m_sel_id.i].GetX( m_sel_id.ii );
int yi = m_fp.m_outline_poly[m_sel_id.i].GetY( m_sel_id.ii );
int xf, yf;
if( m_sel_id.ii != (m_fp.m_outline_poly[m_sel_id.i].GetNumCorners()-1) )
{
xf = m_fp.m_outline_poly[m_sel_id.i].GetX( m_sel_id.ii+1 );
yf = m_fp.m_outline_poly[m_sel_id.i].GetY( m_sel_id.ii+1 );
}
else
{
xf = m_fp.m_outline_poly[m_sel_id.i].GetX( 0 );
yf = m_fp.m_outline_poly[m_sel_id.i].GetY( 0 );
}
if( xi == xf || yi == yf )
{
pPopup->EnableMenuItem( ID_FP_CONVERTTOARC, MF_GRAYED );
pPopup->EnableMenuItem( ID_FP_CONVERTTOARC32778, MF_GRAYED );
}
pPopup->EnableMenuItem( ID_FP_CONVERTTOSTRAIGHT, MF_GRAYED );
}
else if( style == CPolyLine::ARC_CW )
{
pPopup->EnableMenuItem( ID_FP_CONVERTTOARC, MF_GRAYED );
pPopup->EnableMenuItem( ID_FP_INSERTCORNER, MF_GRAYED );
}
else if( style == CPolyLine::ARC_CCW )
{
pPopup->EnableMenuItem( ID_FP_CONVERTTOARC32778, MF_GRAYED );
pPopup->EnableMenuItem( ID_FP_INSERTCORNER, MF_GRAYED );
}
pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, pWnd );
break;
case CUR_FP_POLY_CORNER_SELECTED:
pPopup = menu.GetSubMenu(CONTEXT_FP_CORNER);
ASSERT(pPopup != NULL);
{
if( m_fp.m_outline_poly[m_sel_id.i].GetNumCorners() < 4 )
pPopup->EnableMenuItem( ID_FP_DELETECORNER, MF_GRAYED );
}
pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, pWnd );
break;
case CUR_FP_REF_SELECTED:
pPopup = menu.GetSubMenu(CONTEXT_FP_REF);
ASSERT(pPopup != NULL);
pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, pWnd );
break;
case CUR_FP_VALUE_SELECTED:
pPopup = menu.GetSubMenu(CONTEXT_FP_VALUE);
ASSERT(pPopup != NULL);
pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, pWnd );
break;
case CUR_FP_TEXT_SELECTED:
pPopup = menu.GetSubMenu(CONTEXT_FP_TEXT);
ASSERT(pPopup != NULL);
pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, pWnd );
break;
case CUR_FP_CENTROID_SELECTED:
pPopup = menu.GetSubMenu(CONTEXT_FP_CENTROID);
ASSERT(pPopup != NULL);
pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, pWnd );
break;
case CUR_FP_ADHESIVE_SELECTED:
pPopup = menu.GetSubMenu(CONTEXT_FP_ADHESIVE);
ASSERT(pPopup != NULL);
pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, pWnd );
break;
}
}
// Delete pad
//
void CFootprintView::OnPadDelete( int i )
{
PushUndo();
CancelSelection();
m_fp.m_padstack.RemoveAt( i );
m_fp.Draw( m_dlist, m_Doc->m_smfontutil );
FootprintModified( TRUE );
}
// edit pad
//
void CFootprintView::OnPadEdit( int i )
{
// save original position and angle of pad, in case we decide
// to drag the pad, and then cancel dragging
int m_orig_x = m_fp.m_padstack[i].x_rel;
int m_orig_y = m_fp.m_padstack[i].y_rel;
int m_orig_angle = m_fp.m_padstack[i].angle;
// save undo info, since dialog may make lots of changes
PushUndo();
// now launch dialog
CDlgAddPin dlg;
dlg.InitDialog( &m_fp, CDlgAddPin::EDIT, i, m_units );
m_dlist->CancelHighLight();
int ret = dlg.DoModal();
if( ret == IDOK )
{
// if OK, footprint has already been undrawn by dlg
if( dlg.m_drag_flag )
{
// if dragging, move pad back to original position and start
m_fp.m_padstack[i].x_rel = m_orig_x;
m_fp.m_padstack[i].y_rel = m_orig_y;
m_fp.m_padstack[i].angle = m_orig_angle;
m_fp.Draw( m_dlist, m_Doc->m_smfontutil );
OnPadMove( i );
return;
}
else
{
// not dragging, just redraw
m_fp.Draw( m_dlist, m_Doc->m_smfontutil );
FootprintModified( TRUE );
}
}
else
{
Undo(); // restore to original state
}
m_fp.SelectPad( i );
Invalidate( FALSE );
}
// move pad, don't push undo, this will be done when move completed
//
void CFootprintView::OnPadMove( int i, int num )
{
// drag pad
CDC *pDC = GetDC();
pDC->SelectClipRgn( &m_pcb_rgn );
SetDCToWorldCoords( pDC );
// move cursor to pad
CPoint p;
p.x = m_fp.m_padstack[i].x_rel;
p.y = m_fp.m_padstack[i].y_rel;
CPoint cur_p = PCBToScreen( p );
SetCursorPos( cur_p.x, cur_p.y );
// start dragging
m_drag_num_pads = num;
m_fp.StartDraggingPadRow( pDC, i, num );
SetCursorMode( CUR_FP_DRAG_PAD );
Invalidate( FALSE );
ReleaseDC( pDC );
}
// move ref. designator text for part
//
void CFootprintView::OnRefMove()
{
// move reference ID
CDC *pDC = GetDC();
pDC->SelectClipRgn( &m_pcb_rgn );
SetDCToWorldCoords( pDC );
// move cursor to ref
CPoint p;
p.x = m_fp.m_ref_xi;
p.y = m_fp.m_ref_yi;
CPoint cur_p = PCBToScreen( p );
SetCursorPos( cur_p.x, cur_p.y );
// start dragging
m_dragging_new_item = 0;
m_fp.StartDraggingRef( pDC );
SetCursorMode( CUR_FP_DRAG_REF );
ReleaseDC( pDC );
Invalidate( FALSE );
}
// start adding board outline by dragging line for first side
//
void CFootprintView::OnAddBoardOutline()
{
}
void CFootprintView::OnPolylineDelete()
{
PushUndo();
m_fp.m_outline_poly.RemoveAt( m_sel_id.i );
CancelSelection();
m_fp.Draw( m_dlist, m_Doc->m_smfontutil );
FootprintModified( TRUE );
}
// move an outline polyline corner
//
void CFootprintView::OnPolylineCornerMove()
{
CDC *pDC = GetDC();
pDC->SelectClipRgn( &m_pcb_rgn );
SetDCToWorldCoords( pDC );
CPoint p = m_last_mouse_point;
m_fp.m_outline_poly[m_sel_id.i].StartDraggingToMoveCorner( pDC, m_sel_id.ii, p.x, p.y );
SetCursorMode( CUR_FP_DRAG_POLY_MOVE );
ReleaseDC( pDC );
Invalidate( FALSE );
}
// edit an outline polyline corner
//
void CFootprintView::OnPolylineCornerEdit()
{
DlgEditBoardCorner dlg;
CString str = "Corner Position";
int x = m_fp.m_outline_poly[m_sel_id.i].GetX(m_sel_id.ii);
int y = m_fp.m_outline_poly[m_sel_id.i].GetY(m_sel_id.ii);
dlg.Init( &str, m_units, x, y );
int ret = dlg.DoModal();
if( ret == IDOK )
{
PushUndo();
m_fp.m_outline_poly[m_sel_id.i].MoveCorner( m_sel_id.ii,
dlg.GetX(), dlg.GetY() );
CancelSelection();
Invalidate( FALSE );
FootprintModified( TRUE );
}
}
// delete an outline polyline board corner
//
void CFootprintView::OnPolylineCornerDelete()
{
PushUndo();
CPolyLine * poly = &m_fp.m_outline_poly[m_sel_id.i];
if( poly->GetClosed() && poly->GetNumCorners() < 4
|| !poly->GetClosed() && poly->GetNumCorners() < 3 )
{
AfxMessageBox( "Polyline has too few corners" );
return;
}
m_fp.m_outline_poly[m_sel_id.i].DeleteCorner( m_sel_id.ii );
CancelSelection();
FootprintModified( TRUE );
Invalidate( FALSE );
}
// insert a new corner in a side of a polyline
//
void CFootprintView::OnPolylineSideAddCorner()
{
CDC *pDC = GetDC();
pDC->SelectClipRgn( &m_pcb_rgn );
SetDCToWorldCoords( pDC );
CPoint p = m_last_mouse_point;
m_fp.m_outline_poly[m_sel_id.i].StartDraggingToInsertCorner( pDC, m_sel_id.ii, p.x, p.y );
SetCursorMode( CUR_FP_DRAG_POLY_INSERT );
ReleaseDC( pDC );
Invalidate( FALSE );
}
// detect state where nothing is selected or being dragged
//
BOOL CFootprintView::CurNone()
{
return( m_cursor_mode == CUR_FP_NONE_SELECTED );
}
// detect any selected state
//
BOOL CFootprintView::CurSelected()
{
return( m_cursor_mode > CUR_FP_NONE_SELECTED && m_cursor_mode < CUR_FP_NUM_SELECTED_MODES );
}
// detect any dragging state
//
BOOL CFootprintView::CurDragging()
{
return( m_cursor_mode > CUR_FP_NUM_SELECTED_MODES );
}
// detect states using placement grid
//
BOOL CFootprintView::CurDraggingPlacement()
{
return( m_cursor_mode == CUR_FP_DRAG_PAD
|| m_cursor_mode == CUR_FP_DRAG_REF
|| m_cursor_mode == CUR_FP_DRAG_POLY_1
|| m_cursor_mode == CUR_FP_DRAG_POLY
|| m_cursor_mode == CUR_FP_DRAG_POLY_MOVE
|| m_cursor_mode == CUR_FP_DRAG_POLY_INSERT
);
}
// snap cursor if required and set m_last_cursor_point
//
void CFootprintView::SnapCursorPoint( CPoint wp )
{
if( CurDragging() )
{
int grid_spacing;
grid_spacing = m_Doc->m_fp_part_grid_spacing;
// snap angle if needed
if( m_Doc->m_fp_snap_angle && (wp != m_snap_angle_ref)
&& ( m_cursor_mode == CUR_FP_DRAG_POLY_1
|| m_cursor_mode == CUR_FP_DRAG_POLY ) )
{
// snap to angle only if the starting point is on-grid
double ddx = fmod( (double)(m_snap_angle_ref.x), grid_spacing );
double ddy = fmod( (double)(m_snap_angle_ref.y), grid_spacing );
if( fabs(ddx) < 0.5 && fabs(ddy) < 0.5 )
{
// starting point is on-grid, snap to angle
// snap to n*45 degree angle
const double pi = 3.14159265359;
double dx = wp.x - m_snap_angle_ref.x;
double dy = wp.y - m_snap_angle_ref.y;
double dist = sqrt( dx*dx + dy*dy );
double dist45 = dist/sqrt(2.0);
{
int d;
d = (int)(dist/grid_spacing+0.5);
dist = d*grid_spacing;
d = (int)(dist45/grid_spacing+0.5);
dist45 = d*grid_spacing;
}
if( m_Doc->m_fp_snap_angle == 45 )
{
// snap angle = 45 degrees, divide circle into 8 octants
double angle = atan2( dy, dx );
if( angle < 0.0 )
angle = 2.0*pi + angle;
angle += pi/8.0;
double d_quad = angle/(pi/4.0);
int oct = d_quad;
switch( oct )
{
case 0:
wp.x = m_snap_angle_ref.x + dist;
wp.y = m_snap_angle_ref.y;
break;
case 1:
wp.x = m_snap_angle_ref.x + dist45;
wp.y = m_snap_angle_ref.y + dist45;
break;
case 2:
wp.x = m_snap_angle_ref.x;
wp.y = m_snap_angle_ref.y + dist;
break;
case 3:
wp.x = m_snap_angle_ref.x - dist45;
wp.y = m_snap_angle_ref.y + dist45;
break;
case 4:
wp.x = m_snap_angle_ref.x - dist;
wp.y = m_snap_angle_ref.y;
break;
case 5:
wp.x = m_snap_angle_ref.x - dist45;
wp.y = m_snap_angle_ref.y - dist45;
break;
case 6:
wp.x = m_snap_angle_ref.x;
wp.y = m_snap_angle_ref.y - dist;
break;
case 7:
wp.x = m_snap_angle_ref.x + dist45;
wp.y = m_snap_angle_ref.y - dist45;
break;
case 8:
wp.x = m_snap_angle_ref.x + dist;
wp.y = m_snap_angle_ref.y;
break;
default:
ASSERT(0);
break;
}
}
else
{
// snap angle is 90 degrees, divide into 4 quadrants
double angle = atan2( dy, dx );
if( angle < 0.0 )
angle = 2.0*pi + angle;
angle += pi/4.0;
double d_quad = angle/(pi/2.0);
int quad = d_quad;
switch( quad )
{
case 0:
wp.x = m_snap_angle_ref.x + dist;
wp.y = m_snap_angle_ref.y;
break;
case 1:
wp.x = m_snap_angle_ref.x;
wp.y = m_snap_angle_ref.y + dist;
break;
case 2:
wp.x = m_snap_angle_ref.x - dist;
wp.y = m_snap_angle_ref.y;
break;
case 3:
wp.x = m_snap_angle_ref.x;
wp.y = m_snap_angle_ref.y - dist;
break;
case 4:
wp.x = m_snap_angle_ref.x + dist;
wp.y = m_snap_angle_ref.y;
break;
default:
ASSERT(0);
break;
}
}
}
}
// snap to grid
{
// get position in integral units of grid_spacing
if( wp.x > 0 )
wp.x = (wp.x + grid_spacing/2)/grid_spacing;
else
wp.x = (wp.x - grid_spacing/2)/grid_spacing;
if( wp.y > 0 )
wp.y = (wp.y + grid_spacing/2)/grid_spacing;
else
wp.y = (wp.y - grid_spacing/2)/grid_spacing;
// thrn multiply by grid spacing, adding or subracting 0.5 to prevent round-off
// when using a fractional grid
double test = wp.x * grid_spacing;
if( test > 0.0 )
test += 0.5;
else
test -= 0.5;
wp.x = test;
test = wp.y * grid_spacing;
if( test > 0.0 )
test += 0.5;
else
test -= 0.5;
wp.y = test;
}
}
if( CurDragging() )
{
// update drag operation
if( wp != m_last_cursor_point )
{
CDC *pDC = GetDC();
pDC->SelectClipRgn( &m_pcb_rgn );
SetDCToWorldCoords( pDC );
m_dlist->Drag( pDC, wp.x, wp.y );
ReleaseDC( pDC );
}
}
else
// m_dragging_new_item = FALSE; // just in case
if( m_dragging_new_item )
ASSERT(0); // debugging, this shouldn't happen
// update cursor position
m_last_cursor_point = wp;
ShowCursor();
}
LONG CFootprintView::OnChangeVisibleGrid( UINT wp, LONG lp )
{
if( wp == WM_BY_INDEX )
m_Doc->m_fp_visual_grid_spacing = fabs( m_Doc->m_fp_visible_grid[lp] );
else
ASSERT(0);
m_dlist->SetVisibleGrid( TRUE, m_Doc->m_fp_visual_grid_spacing );
Invalidate( FALSE );
SetFocus();
return 0;
}
LONG CFootprintView::OnChangePlacementGrid( UINT wp, LONG lp )
{
if( wp == WM_BY_INDEX )
m_Doc->m_fp_part_grid_spacing = fabs( m_Doc->m_fp_part_grid[lp] );
else
ASSERT(0);
SetFocus();
return 0;
}
LONG CFootprintView::OnChangeSnapAngle( UINT wp, LONG lp )
{
if( wp == WM_BY_INDEX )
{
if( lp == 0 )
m_Doc->m_fp_snap_angle = 45;
else if( lp == 1 )
m_Doc->m_fp_snap_angle = 90;
else
m_Doc->m_fp_snap_angle = 0;
}
else
ASSERT(0);
SetFocus();
return 0;
}
LONG CFootprintView::OnChangeUnits( UINT wp, LONG lp )
{
if( wp == WM_BY_INDEX )
{
if( lp == 0 )
m_units = MIL;
else if( lp == 1 )
m_units = MM;
}
else
ASSERT(0);
FootprintModified(TRUE);
SetFocus();
return 0;
}
void CFootprintView::OnRefProperties()
{
CDlgFpRefText dlg;
dlg.Initialize( m_fp.m_ref_size, m_fp.m_ref_w, m_units );
int ret = dlg.DoModal();
if( ret == IDOK )
{
PushUndo();
m_dlist->CancelHighLight();
m_fp.m_ref_w = dlg.GetWidth();
m_fp.m_ref_size = dlg.GetHeight();
m_fp.Draw( m_dlist, m_Doc->m_smfontutil );
m_fp.SelectRef();
FootprintModified( TRUE );
Invalidate( FALSE );
}
}
BOOL CFootprintView::OnEraseBkgnd(CDC* pDC)
{
// Erase the left and bottom panes, the PCB area is always redrawn
m_left_pane_invalid = TRUE;
return FALSE;
}
void CFootprintView::OnPolylineSideConvertToStraightLine()
{
PushUndo();
m_dlist->CancelHighLight();
m_fp.m_outline_poly[m_sel_id.i].SetSideStyle( m_sel_id.ii, CPolyLine::STRAIGHT );
m_fp.m_outline_poly[m_sel_id.i].HighlightSide( m_sel_id.ii );
ShowSelectStatus();
SetFKText( m_cursor_mode );
Invalidate( FALSE );
}
void CFootprintView::OnPolylineSideConvertToArcCw()
{
PushUndo();
m_dlist->CancelHighLight();
m_fp.m_outline_poly[m_sel_id.i].SetSideStyle( m_sel_id.ii, CPolyLine::ARC_CW );
m_fp.m_outline_poly[m_sel_id.i].HighlightSide( m_sel_id.ii );
ShowSelectStatus();
SetFKText( m_cursor_mode );
Invalidate( FALSE );
}
void CFootprintView::OnPolylineSideConvertToArcCcw()
{
PushUndo();
m_dlist->CancelHighLight();
m_fp.m_outline_poly[m_sel_id.i].SetSideStyle( m_sel_id.ii, CPolyLine::ARC_CCW );
m_fp.m_outline_poly[m_sel_id.i].HighlightSide( m_sel_id.ii );
ShowSelectStatus();
SetFKText( m_cursor_mode );
Invalidate( FALSE );
}
void CFootprintView::OnAddPin()
{
PushUndo();
CDlgAddPin dlg;
dlg.InitDialog( &m_fp, CDlgAddPin::ADD, m_fp.GetNumPins() + 1, m_units );
int ret = dlg.DoModal();
if( ret == IDOK )
{
// if OK, footprint has been undrawn by dialog
// and new pin added to footprint
if( dlg.m_drag_flag )
{
// if dragging, move new pad(s) to cursor position
int ip = dlg.m_pin_num;
int num = dlg.m_num_pins;
CPoint p;
GetCursorPos( &p ); // cursor pos in screen coords
p = ScreenToPCB( p ); // convert to PCB coords
int dx = p.x - m_fp.m_padstack[ip].x_rel;
int dy = p.y - m_fp.m_padstack[ip].y_rel;
for( int i=ip; i<(ip+num); i++ )
{
m_fp.m_padstack[i].x_rel += dx;
m_fp.m_padstack[i].y_rel += dy;
}
m_fp.Draw( m_dlist, m_Doc->m_smfontutil );
// now start dragging
m_sel_id.type = ID_PART;
m_sel_id.st = ID_SEL_PAD;
m_sel_id.i = ip;
m_dragging_new_item = TRUE;
OnPadMove( ip, num );
return;
}
else
{
m_fp.Draw( m_dlist, m_Doc->m_smfontutil );
}
}
Invalidate( FALSE );
}
void CFootprintView::OnFootprintFileSaveAs()
{
CString str_name = m_fp.m_name;
CRect r;
BOOL bOK = m_fp.GenerateSelectionRectangle( &r );
if( !bOK )
{
AfxMessageBox( "Unable to save: empty footprint", MB_OK );
return;
}
m_fp.Draw( m_dlist, m_Doc->m_smfontutil );
// now save it
CDlgSaveFootprint dlg;
dlg.Initialize( &str_name, &m_fp, m_units, "",
&m_Doc->m_footprint_cache_map, &m_Doc->m_footlibfoldermap, m_Doc->m_dlg_log );
int ret = dlg.DoModal();
if( ret == IDOK )
{
FootprintModified( FALSE );
ClearUndo();
ClearRedo();
FootprintNameChanged( &m_fp.m_name );
}
}
void CFootprintView::OnAddPolyline()
{
CDlgAddPoly dlg;
dlg.Initialize( m_units );
int ret = dlg.DoModal();
if( ret == IDOK )
{
// start new outline by dragging first point
CDC *pDC = GetDC();
pDC->SelectClipRgn( &m_pcb_rgn );
SetDCToWorldCoords( pDC );
CPoint p = m_last_mouse_point;
m_dlist->CancelHighLight();
m_sel_id.Set( ID_PART, ID_OUTLINE,
m_fp.m_outline_poly.GetSize(), ID_SEL_CORNER, 0 );
m_polyline_closed_flag = dlg.GetClosedFlag();
m_polyline_style = CPolyLine::STRAIGHT;
m_polyline_width = dlg.GetWidth();
m_dlist->StartDraggingArray( pDC, p.x, p.y, 0, LAY_FP_SELECTION );
SetCursorMode( CUR_FP_ADD_POLY );
ReleaseDC( pDC );
Invalidate( FALSE );
}
}
void CFootprintView::OnFootprintFileImport()
{
CDlgImportFootprint dlg;
dlg.InitInstance( &m_Doc->m_footprint_cache_map, &m_Doc->m_footlibfoldermap, m_Doc->m_dlg_log );
int ret = dlg.DoModal();
// now import if OK
if( ret == IDOK && dlg.m_footprint_name != "" && dlg.m_shape.m_name != "" )
{
m_fp.Copy( &dlg.m_shape );
m_fp.Draw( m_dlist, m_Doc->m_smfontutil );
// update window title and units
SetWindowTitle( &m_fp.m_name );
m_Doc->m_footprint_name_changed = TRUE;
m_Doc->m_footprint_modified = FALSE;
CMainFrame * frm = (CMainFrame*)AfxGetMainWnd();
m_units = m_fp.m_units;
frm->m_wndMyToolBar.SetUnits( m_units );
ClearUndo();
ClearRedo();
OnViewEntireFootprint();
}
Invalidate( FALSE );
}
void CFootprintView::OnFootprintFileClose()
{
// set units
m_fp.m_units = m_units;
// reset selection rectangle
CRect br;
br.left = br.bottom = INT_MAX;
br.right = br.top = INT_MIN;
for( int ip=0; ip<m_fp.GetNumPins(); ip++ )
{
CRect padr = m_fp.GetPadBounds( ip );
br.left = min( br.left, padr.left );
br.bottom = min( br.bottom, padr.bottom );
br.right = max( br.right, padr.right );
br.top = max( br.top, padr.top );
}
for( int ip=0; ip<m_fp.m_outline_poly.GetSize(); ip++ )
{
CRect polyr = m_fp.m_outline_poly[ip].GetBounds();
br.left = min( br.left, polyr.left );
br.bottom = min( br.bottom, polyr.bottom );
br.right = max( br.right, polyr.right );
br.top = max( br.top, polyr.top );
}
m_fp.m_sel_xi = br.left - 10*NM_PER_MIL;
m_fp.m_sel_xf = br.right + 10*NM_PER_MIL;
m_fp.m_sel_yi = br.bottom - 10*NM_PER_MIL;
m_fp.m_sel_yf = br.top + 10*NM_PER_MIL;
m_fp.Draw( m_dlist, m_Doc->m_smfontutil );
if( m_Doc->m_footprint_modified )
{
int ret = AfxMessageBox( "Save footprint before exiting ?", MB_YESNOCANCEL );
m_Doc->m_file_close_ret = ret;
if( ret == IDCANCEL )
return;
else if( ret == IDYES )
OnFootprintFileSaveAs();
}
ClearUndo();
ClearRedo();
theApp.OnViewPcbEditor();
}
void CFootprintView::OnFootprintFileNew()
{
if( m_Doc->m_footprint_modified )
{
int ret = AfxMessageBox( "Save footprint ?", MB_YESNOCANCEL );
if( ret == IDCANCEL )
return;
else if( ret == IDYES )
OnFootprintFileSaveAs();
}
m_dlist->CancelHighLight();
m_fp.Clear();
m_fp.Draw( m_dlist, m_Doc->m_smfontutil );
SetWindowTitle( &m_fp.m_name );
FootprintModified( FALSE, TRUE );
ClearUndo();
ClearRedo();
Invalidate( FALSE );
}
void CFootprintView::FootprintModified( BOOL flag, BOOL force, BOOL clear_redo )
{
// if requested, clear redo stack (this is the default)
if( clear_redo )
ClearRedo();
// see if we need to do anything
if( flag == m_Doc->m_footprint_modified && !force )
return; // no!
// OK, set state and window title
m_Doc->m_footprint_modified = flag;
if( flag == TRUE )
{
// add "*" to end of window title
if( m_Doc->m_fp_window_title.Right(1) != "*" )
m_Doc->m_fp_window_title = m_Doc->m_fp_window_title + "*";
}
else if( flag == FALSE )
{
// remove "*" from end of window title
if( m_Doc->m_fp_window_title.Right(1) == "*" )
m_Doc->m_fp_window_title = m_Doc->m_fp_window_title.Left( m_Doc->m_fp_window_title.GetLength()-1 );
}
CMainFrame * pMain = (CMainFrame*)AfxGetMainWnd();
pMain->SetWindowText( m_Doc->m_fp_window_title );
}
void CFootprintView::FootprintNameChanged( CString * str )
{
m_Doc->m_footprint_name_changed = TRUE;
SetWindowTitle( &m_fp.m_name );
}
void CFootprintView::OnViewEntireFootprint()
{
CRect r;
r = m_fp.GetBounds();
int max_x = (3*r.right - r.left)/2;
int min_x = (3*r.left - r.right)/2;
int max_y = (3*r.top - r.bottom)/2;
int min_y = (3*r.bottom - r.top)/2;
double win_x = m_client_r.right - m_left_pane_w;
double win_y = m_client_r.bottom - m_bottom_pane_h;
// reset window to enclose footprint
double x_pcbu_per_pixel = (double)(max_x - min_x)/win_x;
double y_pcbu_per_pixel = (double)(max_y - min_y)/win_y;
if( x_pcbu_per_pixel > y_pcbu_per_pixel )
m_pcbu_per_pixel = x_pcbu_per_pixel;
else
m_pcbu_per_pixel = y_pcbu_per_pixel;
m_org_x = (max_x + min_x)/2 - win_x*m_pcbu_per_pixel/2;
m_org_y = (max_y + min_y)/2 - win_y*m_pcbu_per_pixel/2;
CRect screen_r;
GetWindowRect( &screen_r );
m_dlist->SetMapping( &m_client_r, &screen_r, m_left_pane_w, m_bottom_pane_h, m_pcbu_per_pixel,
m_org_x, m_org_y );
Invalidate( FALSE );
}
void CFootprintView::ClearUndo()
{
int n = undo_stack.GetSize();
for( int i=0; i<n; i++ )
delete undo_stack[i];
undo_stack.RemoveAll();
EnableUndo( FALSE );
}
void CFootprintView::ClearRedo()
{
int n = redo_stack.GetSize();
for( int i=0; i<n; i++ )
delete redo_stack[i];
redo_stack.RemoveAll();
EnableRedo( FALSE );
}
void CFootprintView::PushUndo()
{
if( undo_stack.GetSize() > 100 )
{
delete undo_stack[0];
undo_stack.RemoveAt( 0 );
}
CEditShape * sh = new CEditShape;
sh->Copy( &m_fp );
undo_stack.Add( sh );
EnableUndo( TRUE );
}
void CFootprintView::PushRedo()
{
if( redo_stack.GetSize() > 100 )
{
delete redo_stack[0];
redo_stack.RemoveAt( 0 );
}
CEditShape * sh = new CEditShape;
sh->Copy( &m_fp );
redo_stack.Add( sh );
EnableRedo( TRUE );
}
// normal undo, push redo info
//
void CFootprintView::Undo()
{
PushRedo();
UndoNoRedo();
}
// undo but don't push redo info
// may be used to undo a temporary state
//
void CFootprintView::UndoNoRedo()
{
int n = undo_stack.GetSize();
if( n )
{
CancelSelection();
m_fp.Clear();
CEditShape * sh = undo_stack[n-1];
m_fp.Copy( sh );
m_fp.Draw( m_dlist, m_Doc->m_smfontutil );
delete sh;
undo_stack.SetSize( n-1 );
}
EnableUndo( undo_stack.GetSize() );
FootprintModified( TRUE, 0, 0 ); // don't clear redo stack
Invalidate( FALSE );
}
void CFootprintView::Redo()
{
PushUndo();
int n = redo_stack.GetSize();
if( n )
{
CancelSelection();
m_fp.Clear();
CEditShape * sh = redo_stack[n-1];
m_fp.Copy( sh );
m_fp.Draw( m_dlist, m_Doc->m_smfontutil );
delete sh;
redo_stack.SetSize( n-1 );
}
EnableRedo( redo_stack.GetSize() );
FootprintModified( TRUE, 0, 0 ); // don't clear redo stack
Invalidate( FALSE );
}
void CFootprintView::OnEditUndo()
{
Undo();
}
void CFootprintView::OnEditRedo()
{
Redo();
}
void CFootprintView::OnFpMove()
{
OnPadMove( m_sel_id.i, 1 );
}
void CFootprintView::OnFpEditproperties()
{
OnPadEdit( m_sel_id.i );
}
void CFootprintView::OnFpDelete()
{
OnPadDelete( m_sel_id.i );
}
void CFootprintView::OnFpToolsFootprintwizard()
{
// ask about saving
if( m_Doc->m_footprint_modified )
{
int ret = AfxMessageBox( "Save footprint before launching Wizard ?", MB_YESNOCANCEL );
m_Doc->m_file_close_ret = ret;
if( ret == IDCANCEL )
return;
else if( ret == IDYES )
OnFootprintFileSaveAs();
}
// OK, launch wizard
CDlgWizQuad dlg;
dlg.Initialize( &m_Doc->m_footprint_cache_map, &m_Doc->m_footlibfoldermap,
FALSE, m_Doc->m_dlg_log );
int ret = dlg.DoModal();
if( ret == IDOK )
{
// import wizard-created footprint
m_fp.Clear();
m_fp.Copy( &dlg.m_footprint );
m_fp.Draw( m_dlist, m_Doc->m_smfontutil );
SetWindowTitle( &m_fp.m_name );
FootprintModified( TRUE, TRUE );
// switch to wizard units
CMainFrame * frm = (CMainFrame*)AfxGetMainWnd();
frm->m_wndMyToolBar.SetUnits( dlg.m_units );
ClearUndo();
ClearRedo();
OnViewEntireFootprint();
Invalidate( FALSE );
}
}
void CFootprintView::SetWindowTitle( CString * str )
{
m_Doc->m_fp_window_title = "Footprint Editor - " + *str;
CMainFrame * pMain = (CMainFrame*)AfxGetMainWnd();
pMain->SetWindowText( m_Doc->m_fp_window_title );
}
void CFootprintView::OnToolsFootprintLibraryManager()
{
CDlgLibraryManager dlg;
dlg.Initialize( &m_Doc->m_footlibfoldermap, m_Doc->m_dlg_log );
dlg.DoModal();
}
void CFootprintView::OnAddText()
{
CString str = "";
CDlgFpText dlg;
dlg.Initialize( TRUE, FALSE, NULL, m_units, 0, 0, 0, 0, 0 );
int ret = dlg.DoModal();
if( ret == IDOK )
{
int x = dlg.m_x;
int y = dlg.m_y;
int angle = dlg.m_angle;
int font_size = dlg.m_height;
int stroke_width = dlg.m_width;
CString str = dlg.m_str;
// get cursor position and convert to PCB coords
PushUndo();
CPoint p;
GetCursorPos( &p ); // cursor pos in screen coords
p = ScreenToPCB( p ); // convert to PCB coords
// set pDC to PCB coords
CDC *pDC = GetDC();
pDC->SelectClipRgn( &m_pcb_rgn );
SetDCToWorldCoords( pDC );
if( dlg.m_bDrag )
{
m_sel_text = m_fp.m_tl->AddText( p.x, p.y, angle, FALSE, FALSE,
LAY_FP_SILK_TOP, font_size, stroke_width, &str );
m_dragging_new_item = 1;
m_fp.m_tl->StartDraggingText( pDC, m_sel_text );
SetCursorMode( CUR_FP_DRAG_TEXT );
}
else
{
m_sel_text = m_fp.m_tl->AddText( x, y, angle, FALSE, FALSE,
LAY_FP_SILK_TOP, font_size, stroke_width, &str );
m_fp.m_tl->HighlightText( m_sel_text );
}
}
}
void CFootprintView::OnFpTextEdit()
{
// create dialog and pass parameters
CDlgFpText dlg;
CString test_str = m_sel_text->m_str;
dlg.Initialize( FALSE, FALSE, &test_str, m_units,
m_sel_text->m_angle, m_sel_text->m_font_size,
m_sel_text->m_stroke_width, m_sel_text->m_x, m_sel_text->m_y );
int ret = dlg.DoModal();
if( ret == IDCANCEL )
return;
// replace old text with new one
PushUndo();
int x = dlg.m_x;
int y = dlg.m_y;
int angle = dlg.m_angle;
int font_size = dlg.m_height;
int stroke_width = dlg.m_width;
CString str = dlg.m_str;
m_dlist->CancelHighLight();
m_fp.m_tl->RemoveText( m_sel_text );
CText * new_text = m_fp.m_tl->AddText( x, y, angle, FALSE, FALSE,
LAY_FP_SILK_TOP, font_size, stroke_width, &str );
m_sel_text = new_text;
m_fp.m_tl->HighlightText( m_sel_text );
// start dragging if requested in dialog
if( dlg.m_bDrag )
OnFpTextMove();
else
Invalidate( FALSE );
FootprintModified( TRUE );
}
// move text
void CFootprintView::OnFpTextMove()
{
CDC *pDC = GetDC();
pDC->SelectClipRgn( &m_pcb_rgn );
SetDCToWorldCoords( pDC );
// move cursor to ref
CPoint p;
p.x = m_sel_text->m_x;
p.y = m_sel_text->m_y;
CPoint cur_p = PCBToScreen( p );
SetCursorPos( cur_p.x, cur_p.y );
// start dragging
m_dragging_new_item = 0;
m_fp.m_tl->StartDraggingText( pDC, m_sel_text );
SetCursorMode( CUR_FP_DRAG_TEXT );
ReleaseDC( pDC );
Invalidate( FALSE );
}
void CFootprintView::OnFpTextDelete()
{
PushUndo();
m_fp.m_tl->RemoveText( m_sel_text );
m_dlist->CancelHighLight();
SetCursorMode( CUR_FP_NONE_SELECTED );
FootprintModified( TRUE );
Invalidate( FALSE );
}
// display active layer in status bar and change layer order for DisplayList
//
int CFootprintView::ShowActiveLayer()
{
CMainFrame * pMain = (CMainFrame*) AfxGetApp()->m_pMainWnd;
if( !pMain )
return 1;
CString str;
if( m_active_layer == LAY_FP_TOP_COPPER )
{
str.Format( "Top" );
m_dlist->SetLayerDrawOrder( LAY_FP_TOP_MASK, LAY_FP_TOP_MASK );
m_dlist->SetLayerDrawOrder( LAY_FP_TOP_PASTE, LAY_FP_TOP_PASTE );
m_dlist->SetLayerDrawOrder( LAY_FP_BOTTOM_MASK, LAY_FP_BOTTOM_MASK );
m_dlist->SetLayerDrawOrder( LAY_FP_BOTTOM_PASTE, LAY_FP_BOTTOM_PASTE );
m_dlist->SetLayerDrawOrder( LAY_FP_TOP_COPPER, LAY_FP_TOP_COPPER );
m_dlist->SetLayerDrawOrder( LAY_FP_INNER_COPPER, LAY_FP_INNER_COPPER );
m_dlist->SetLayerDrawOrder( LAY_FP_BOTTOM_COPPER, LAY_FP_BOTTOM_COPPER );
}
else if( m_active_layer == LAY_FP_INNER_COPPER )
{
str.Format( "Inner" );
m_dlist->SetLayerDrawOrder( LAY_FP_TOP_MASK, LAY_FP_TOP_MASK );
m_dlist->SetLayerDrawOrder( LAY_FP_TOP_PASTE, LAY_FP_TOP_PASTE );
m_dlist->SetLayerDrawOrder( LAY_FP_BOTTOM_MASK, LAY_FP_BOTTOM_MASK );
m_dlist->SetLayerDrawOrder( LAY_FP_BOTTOM_PASTE, LAY_FP_BOTTOM_PASTE );
m_dlist->SetLayerDrawOrder( LAY_FP_INNER_COPPER, LAY_FP_TOP_COPPER );
m_dlist->SetLayerDrawOrder( LAY_FP_TOP_COPPER, LAY_FP_INNER_COPPER );
m_dlist->SetLayerDrawOrder( LAY_FP_BOTTOM_COPPER, LAY_FP_BOTTOM_COPPER );
}
else if( m_active_layer == LAY_FP_BOTTOM_COPPER )
{
str.Format( "Bottom" );
m_dlist->SetLayerDrawOrder( LAY_FP_BOTTOM_MASK, LAY_FP_TOP_MASK );
m_dlist->SetLayerDrawOrder( LAY_FP_BOTTOM_PASTE, LAY_FP_TOP_PASTE );
m_dlist->SetLayerDrawOrder( LAY_FP_TOP_MASK, LAY_FP_BOTTOM_MASK );
m_dlist->SetLayerDrawOrder( LAY_FP_TOP_PASTE, LAY_FP_BOTTOM_PASTE );
m_dlist->SetLayerDrawOrder( LAY_FP_BOTTOM_COPPER, LAY_FP_TOP_COPPER );
m_dlist->SetLayerDrawOrder( LAY_FP_TOP_COPPER, LAY_FP_INNER_COPPER );
m_dlist->SetLayerDrawOrder( LAY_FP_INNER_COPPER, LAY_FP_BOTTOM_COPPER );
}
pMain->DrawStatus( 4, &str );
Invalidate( FALSE );
return 0;
}
void CFootprintView::OnToolsMoveOriginFP()
{
CDlgMoveOrigin dlg;
dlg.Initialize( m_Doc->m_units );
int ret = dlg.DoModal();
if( ret == IDOK )
{
if( dlg.m_drag )
{
CDC *pDC = GetDC();
pDC->SelectClipRgn( &m_pcb_rgn );
SetDCToWorldCoords( pDC );
m_dlist->CancelHighLight();
SetCursorMode( CUR_FP_MOVE_ORIGIN );
m_dlist->StartDraggingArray( pDC, m_last_cursor_point.x,
m_last_cursor_point.y, 0, LAY_SELECTION, 2 );
Invalidate( FALSE );
ReleaseDC( pDC );
}
else
{
PushUndo();
CancelSelection();
MoveOrigin( dlg.m_x, dlg.m_y );
OnViewEntireFootprint();
}
}
}
void CFootprintView::MoveOrigin( int x, int y )
{
m_fp.Undraw();
m_fp.m_sel_xi -= x;
m_fp.m_sel_xf -= x;
m_fp.m_sel_yi -= y;
m_fp.m_sel_yf -= y;
m_fp.m_ref_xi -= x;
m_fp.m_ref_yi -= y;
m_fp.m_value_xi -= x;
m_fp.m_value_yi -= y;
m_fp.m_centroid_x -= x;
m_fp.m_centroid_y -= y;
for( int ip=0; ip<m_fp.m_padstack.GetSize(); ip++ )
{
padstack * ps = &m_fp.m_padstack[ip];
ps->x_rel -= x;
ps->y_rel -= y;
}
for( int ip=0; ip<m_fp.m_outline_poly.GetSize(); ip++ )
{
CPolyLine * poly = &m_fp.m_outline_poly[ip];
poly->MoveOrigin( -x, -y );
}
m_fp.m_tl->MoveOrigin( -x, -y );
m_fp.Draw( m_dlist, m_Doc->m_smfontutil );
FootprintModified( TRUE );
}
void CFootprintView::EnableUndo( BOOL bEnable )
{
CWnd* pMain = AfxGetMainWnd();
if (pMain != NULL)
{
CMenu* pMenu = pMain->GetMenu();
CMenu* submenu = pMenu->GetSubMenu(1); // "Edit" submenu
if( bEnable )
submenu->EnableMenuItem( ID_EDIT_UNDO, MF_BYCOMMAND | MF_ENABLED );
else
submenu->EnableMenuItem( ID_EDIT_UNDO, MF_BYCOMMAND | MF_DISABLED |MF_GRAYED );
pMain->DrawMenuBar();
}
}
void CFootprintView::EnableRedo( BOOL bEnable )
{
CWnd* pMain = AfxGetMainWnd();
if (pMain != NULL)
{
CMenu* pMenu = pMain->GetMenu();
CMenu* submenu = pMenu->GetSubMenu(1); // "Edit" submenu
if( bEnable )
submenu->EnableMenuItem( ID_EDIT_REDO, MF_BYCOMMAND | MF_ENABLED );
else
submenu->EnableMenuItem( ID_EDIT_REDO, MF_BYCOMMAND | MF_DISABLED |MF_GRAYED );
pMain->DrawMenuBar();
}
}
void CFootprintView::OnCentroidEdit()
{
CDlgCentroid dlg;
dlg.Initialize( m_fp.m_centroid_type, m_units,
m_fp.m_centroid_x, m_fp.m_centroid_y, m_fp.m_centroid_angle );
int ret = dlg.DoModal();
if( ret == IDOK )
{
PushUndo();
m_dlist->CancelHighLight();
m_fp.Undraw();
m_fp.m_centroid_type = dlg.m_type;
if( m_fp.m_centroid_type == CENTROID_DEFAULT )
{
CPoint c = m_fp.GetDefaultCentroid();
m_fp.m_centroid_x = c.x;
m_fp.m_centroid_y = c.y;
}
else
{
m_fp.m_centroid_x = dlg.m_x;
m_fp.m_centroid_y = dlg.m_y;
}
m_fp.m_centroid_angle = dlg.m_angle;
m_fp.Draw( m_dlist, m_Doc->m_smfontutil );
m_fp.SelectCentroid();
FootprintModified( TRUE );
Invalidate( FALSE );
}
}
void CFootprintView::OnCentroidMove()
{
CDC *pDC = GetDC();
pDC->SelectClipRgn( &m_pcb_rgn );
SetDCToWorldCoords( pDC );
// move cursor to centroid
CPoint p;
p.x = m_fp.m_centroid_x;
p.y = m_fp.m_centroid_y;
CPoint cur_p = PCBToScreen( p );
SetCursorPos( cur_p.x, cur_p.y );
// start dragging
m_dragging_new_item = 0;
m_fp.StartDraggingCentroid( pDC );
SetCursorMode( CUR_FP_DRAG_CENTROID );
ReleaseDC( pDC );
Invalidate( FALSE );
}
void CFootprintView::OnAddSlot()
{
CDlgSlot dlg;
dlg.Initialize( m_units, 0, 0, 0, 0, 0 );
dlg.DoModal();
}
void CFootprintView::OnAddValueText()
{
CancelSelection();
CString str = "";
CDlgFpText dlg;
CString value_str = "VALUE";
dlg.Initialize( TRUE, TRUE, &value_str, m_units, 0, 0, 0, 0, 0 );
int ret = dlg.DoModal();
if( ret == IDOK )
{
m_fp.Undraw();
m_fp.m_value_xi = dlg.m_x;
m_fp.m_value_yi = dlg.m_y;
m_fp.m_value_angle = dlg.m_angle;
m_fp.m_value_size = dlg.m_height;
m_fp.m_value_w = dlg.m_width;
m_fp.Draw( m_dlist, m_Doc->m_smfontutil );
if( dlg.m_bDrag )
{
m_dragging_new_item = TRUE;
OnValueMove();
}
Invalidate( FALSE );
}
}
void CFootprintView::OnAddHole()
{
CDlgHole dlg;
dlg.Initialize( m_units, 0, 0, 0 );
dlg.DoModal();
}
void CFootprintView::OnValueEdit()
{
CString str = "";
CDlgFpText dlg;
CString value_str = "VALUE";
dlg.Initialize( FALSE, TRUE, &value_str, m_units,
m_fp.m_value_angle, m_fp.m_value_size, m_fp.m_value_w,
m_fp.m_value_xi, m_fp.m_value_yi );
int ret = dlg.DoModal();
if( ret == IDOK )
{
CancelSelection();
if( dlg.m_bDrag )
{
OnValueMove();
}
else
{
PushUndo();
m_fp.Undraw();
m_fp.m_value_xi = dlg.m_x;
m_fp.m_value_yi = dlg.m_y;
m_fp.m_value_angle = dlg.m_angle;
m_fp.m_value_size = dlg.m_height;
m_fp.m_value_w = dlg.m_width;
m_fp.Draw( m_dlist, m_Doc->m_smfontutil );
if( m_fp.m_value_size )
{
m_fp.SelectValue();
SetCursorMode( CUR_FP_VALUE_SELECTED );
}
else
CancelSelection();
}
Invalidate( FALSE );
}
}
void CFootprintView::OnValueMove()
{
CDC *pDC = GetDC();
pDC->SelectClipRgn( &m_pcb_rgn );
SetDCToWorldCoords( pDC );
// move cursor to ref
CPoint p;
p.x = m_fp.m_value_xi;
p.y = m_fp.m_value_yi;
CPoint cur_p = PCBToScreen( p );
SetCursorPos( cur_p.x, cur_p.y );
// start dragging
CancelSelection();
m_dragging_new_item = 0;
m_fp.StartDraggingValue( pDC );
SetCursorMode( CUR_FP_DRAG_VALUE );
ReleaseDC( pDC );
Invalidate( FALSE );
}
void CFootprintView::OnAddAdhesive()
{
CDlgGlue dlg;
dlg.Initialize( GLUE_POS_CENTROID, m_units, 0, 0, 0 );
int ret = dlg.DoModal();
if( ret == IDOK )
{
PushUndo(); // save state before creation of dot
m_fp.Undraw();
int i_spot = m_fp.m_glue.GetSize();
m_fp.m_glue.SetSize( i_spot + 1 );
m_fp.m_glue[i_spot].w = dlg.m_w;
m_fp.m_glue[i_spot].type = dlg.m_pos_type;
if( dlg.m_pos_type == GLUE_POS_DEFINED )
{
m_fp.m_glue[i_spot].x_rel = dlg.m_x;
m_fp.m_glue[i_spot].y_rel = dlg.m_y;
}
else
{
m_fp.m_glue[i_spot].x_rel = m_fp.m_centroid_x;
m_fp.m_glue[i_spot].y_rel = m_fp.m_centroid_y;
}
m_fp.Draw( m_dlist, m_Doc->m_smfontutil );
m_sel_id.Set( ID_GLUE, ID_SEL_SPOT, i_spot );
if( dlg.m_bDrag )
{
m_dragging_new_item = TRUE;
OnAdhesiveDrag();
}
else
FootprintModified( TRUE );
Invalidate( FALSE );
}
}
void CFootprintView::OnAdhesiveEdit()
{
CDlgGlue dlg;
int idot = m_sel_id.i;
glue * g = &m_fp.m_glue[idot];
dlg.Initialize( g->type, m_units, g->w, g->x_rel, g->y_rel );
int ret = dlg.DoModal();
if( ret == IDOK )
{
PushUndo();
g->w = dlg.m_w; // 0 to use project default
g->type = dlg.m_pos_type; // position flag
if( g->type == GLUE_POS_CENTROID )
{
// use centroid position
g->x_rel = m_fp.m_centroid_x;
g->y_rel = m_fp.m_centroid_y;
}
else
{
// use position from dialog
g->x_rel = dlg.m_x;
g->y_rel = dlg.m_y;
}
if ( dlg.m_bDrag )
{
// start dragging
m_dragging_new_item = FALSE;
OnAdhesiveDrag();
}
else
{
m_dlist->CancelHighLight();
m_fp.Draw( m_dlist, m_Doc->m_smfontutil );
m_fp.SelectAdhesive( m_sel_id.i );
FootprintModified( TRUE );
Invalidate( FALSE );
}
}
}
// move glue spot
//
void CFootprintView::OnAdhesiveMove()
{
PushUndo();
m_dragging_new_item = FALSE;
OnAdhesiveDrag();
}
// used for both moving and adding glue spots
// on entry:
// adhesive dot should already be added to footprint and selected
// undo info already pushed
// m_dragging_new_item already set
//
void CFootprintView::OnAdhesiveDrag()
{
CDC *pDC = GetDC();
pDC->SelectClipRgn( &m_pcb_rgn );
SetDCToWorldCoords( pDC );
// move cursor to dot
int idot = m_sel_id.i;
CPoint p;
p.x = m_fp.m_glue[idot].x_rel;
p.y = m_fp.m_glue[idot].y_rel;
CPoint cur_p = PCBToScreen( p );
SetCursorPos( cur_p.x, cur_p.y );
// start dragging
m_fp.StartDraggingAdhesive( pDC, idot );
SetCursorMode( CUR_FP_DRAG_ADHESIVE );
ReleaseDC( pDC );
Invalidate( FALSE );
}
void CFootprintView::OnAdhesiveDelete()
{
PushUndo();
m_fp.Undraw();
m_fp.m_glue.RemoveAt( m_sel_id.i );
m_fp.Draw( m_dlist, m_Doc->m_smfontutil );
CancelSelection();
FootprintModified( TRUE );
Invalidate( FALSE );
}
void CFootprintView::OnCentroidRotateAxis()
{
PushUndo();
m_fp.Undraw();
m_fp.m_centroid_angle += 90;
if( m_fp.m_centroid_angle > 270 )
m_fp.m_centroid_angle = 0;
m_fp.Draw( m_dlist, m_Doc->m_smfontutil );
FootprintModified( TRUE );
Invalidate( FALSE );
}
| [
"allanwright@21cd2c34-3bff-0310-83e0-c30e317e0b48"
]
| [
[
[
1,
3294
]
]
]
|
cbdb20edf07b034a67643337bdde505e884858b6 | 5095bbe94f3af8dc3b14a331519cfee887f4c07e | /apsim/Plant/source/Phenology/WaitingPhase.cpp | 9693fbcb26a626b8f5cd536caea33896d8cb7da9 | []
| no_license | sativa/apsim_development | efc2b584459b43c89e841abf93830db8d523b07a | a90ffef3b4ed8a7d0cce1c169c65364be6e93797 | refs/heads/master | 2020-12-24T06:53:59.364336 | 2008-09-17T05:31:07 | 2008-09-17T05:31:07 | 64,154,433 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 226 | cpp | #include "StdPlant.h"
#include "WaitingPhase.h"
WaitingPhase::WaitingPhase(ScienceAPI& scienceAPI, plantInterface& p, const string& stage_name)
: Phase (scienceAPI, p, stage_name)
{
target = 10000000;
}
| [
"hol353@8bb03f63-af10-0410-889a-a89e84ef1bc8"
]
| [
[
[
1,
9
]
]
]
|
64294b005c5465c7ca698ea5f54d9500e6e05482 | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/Dependencies/Xerces/include/xercesc/util/XMLURL.cpp | 29d9d1ece7e5861229a5c91193d65c5ba2d3cbbb | []
| 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 | 43,921 | cpp | /*
* Copyright 1999-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: XMLURL.cpp 231102 2005-08-09 20:19:06Z dbertoni $
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/BinFileInputStream.hpp>
#include <xercesc/util/Janitor.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/RuntimeException.hpp>
#include <xercesc/util/TransService.hpp>
#include <xercesc/util/XMLURL.hpp>
#include <xercesc/util/XMLNetAccessor.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/util/XMLUni.hpp>
#include <xercesc/util/XMLUri.hpp>
#include <xercesc/util/OutOfMemoryException.hpp>
#include <xercesc/util/XMLChar.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Local types
//
// TypeEntry
// This structure defines a single entry in the list of URL types. Each
// entry indicates the prefix for that type of URL, and the SourceTypes
// value it maps to.
// ---------------------------------------------------------------------------
struct ProtoEntry
{
XMLURL::Protocols protocol;
const XMLCh* prefix;
unsigned int defPort;
};
// ---------------------------------------------------------------------------
// Local data
//
// gXXXString
// These are the strings for our prefix types. They all have to be
// Unicode strings all the time, so we can't just do regular strings.
//
// gProtoList
// The list of URL types that we support and some info related to each
// one.
//
// gMaxProtoLen
// The length of the longest protocol string
//
// NOTE:!!! Be sure to keep this up to date if new protocols are added!
// ---------------------------------------------------------------------------
static const XMLCh gFileString[] =
{
chLatin_f, chLatin_i, chLatin_l, chLatin_e, chNull
};
static const XMLCh gFTPString[] =
{
chLatin_f, chLatin_t, chLatin_p, chNull
};
static const XMLCh gHTTPString[] =
{
chLatin_h, chLatin_t, chLatin_t, chLatin_p, chNull
};
static ProtoEntry gProtoList[XMLURL::Protocols_Count] =
{
{ XMLURL::File , gFileString , 0 }
, { XMLURL::HTTP , gHTTPString , 80 }
, { XMLURL::FTP , gFTPString , 21 }
};
// !!! Keep these up to date with list above!
static const unsigned int gMaxProtoLen = 4;
static const XMLCh gListOne[] = { chColon, chForwardSlash, chNull };
static const XMLCh gListTwo[] = { chAt, chNull };
static const XMLCh gListThree[] = { chColon, chNull };
static const XMLCh gListFour[] = { chForwardSlash, chNull };
static const XMLCh gListFive[] = { chPound, chQuestion, chNull };
static const XMLCh gListSix[] = { chPound, chNull };
// ---------------------------------------------------------------------------
// Local methods
// ---------------------------------------------------------------------------
static bool isHexDigit(const XMLCh toCheck)
{
if ((toCheck >= chDigit_0) && (toCheck <= chDigit_9)
|| (toCheck >= chLatin_A) && (toCheck <= chLatin_Z)
|| (toCheck >= chLatin_a) && (toCheck <= chLatin_z))
{
return true;
}
return false;
}
static unsigned int xlatHexDigit(const XMLCh toXlat)
{
if ((toXlat >= chDigit_0) && (toXlat <= chDigit_9))
return (unsigned int)(toXlat - chDigit_0);
if ((toXlat >= chLatin_A) && (toXlat <= chLatin_Z))
return (unsigned int)(toXlat - chLatin_A) + 10;
return (unsigned int)(toXlat - chLatin_a) + 10;
}
// ---------------------------------------------------------------------------
// XMLURL: Public, static methods
// ---------------------------------------------------------------------------
XMLURL::Protocols XMLURL::lookupByName(const XMLCh* const protoName)
{
for (unsigned int index = 0; index < XMLURL::Protocols_Count; index++)
{
if (!XMLString::compareIStringASCII(protoName, gProtoList[index].prefix))
return gProtoList[index].protocol;
}
return XMLURL::Unknown;
}
// ---------------------------------------------------------------------------
// XMLURL: Constructors and Destructor
// ---------------------------------------------------------------------------
XMLURL::XMLURL(MemoryManager* const manager) :
fMemoryManager(manager)
, fFragment(0)
, fHost(0)
, fPassword(0)
, fPath(0)
, fPortNum(0)
, fProtocol(XMLURL::Unknown)
, fQuery(0)
, fUser(0)
, fURLText(0)
, fHasInvalidChar(false)
{
}
typedef JanitorMemFunCall<XMLURL> CleanupType;
XMLURL::XMLURL(const XMLCh* const baseURL
, const XMLCh* const relativeURL
, MemoryManager* const manager) :
fMemoryManager(manager)
, fFragment(0)
, fHost(0)
, fPassword(0)
, fPath(0)
, fPortNum(0)
, fProtocol(XMLURL::Unknown)
, fQuery(0)
, fUser(0)
, fURLText(0)
, fHasInvalidChar(false)
{
CleanupType cleanup(this, &XMLURL::cleanUp);
try
{
setURL(baseURL, relativeURL);
}
catch(const OutOfMemoryException&)
{
cleanup.release();
throw;
}
cleanup.release();
}
XMLURL::XMLURL(const XMLCh* const baseURL
, const char* const relativeURL
, MemoryManager* const manager) :
fMemoryManager(manager)
, fFragment(0)
, fHost(0)
, fPassword(0)
, fPath(0)
, fPortNum(0)
, fProtocol(XMLURL::Unknown)
, fQuery(0)
, fUser(0)
, fURLText(0)
, fHasInvalidChar(false)
{
CleanupType cleanup(this, &XMLURL::cleanUp);
XMLCh* tmpRel = XMLString::transcode(relativeURL, fMemoryManager);
ArrayJanitor<XMLCh> janRel(tmpRel, fMemoryManager);
try
{
setURL(baseURL, tmpRel);
}
catch(const OutOfMemoryException&)
{
cleanup.release();
throw;
}
cleanup.release();
}
XMLURL::XMLURL(const XMLURL& baseURL
, const XMLCh* const relativeURL) :
fMemoryManager(baseURL.fMemoryManager)
, fFragment(0)
, fHost(0)
, fPassword(0)
, fPath(0)
, fPortNum(0)
, fProtocol(XMLURL::Unknown)
, fQuery(0)
, fUser(0)
, fURLText(0)
, fHasInvalidChar(false)
{
CleanupType cleanup(this, &XMLURL::cleanUp);
try
{
setURL(baseURL, relativeURL);
}
catch(const OutOfMemoryException&)
{
cleanup.release();
throw;
}
cleanup.release();
}
XMLURL::XMLURL(const XMLURL& baseURL
, const char* const relativeURL) :
fMemoryManager(baseURL.fMemoryManager)
, fFragment(0)
, fHost(0)
, fPassword(0)
, fPath(0)
, fPortNum(0)
, fProtocol(XMLURL::Unknown)
, fQuery(0)
, fUser(0)
, fURLText(0)
, fHasInvalidChar(false)
{
CleanupType cleanup(this, &XMLURL::cleanUp);
XMLCh* tmpRel = XMLString::transcode(relativeURL, fMemoryManager);
ArrayJanitor<XMLCh> janRel(tmpRel, fMemoryManager);
try
{
setURL(baseURL, tmpRel);
}
catch(const OutOfMemoryException&)
{
cleanup.release();
throw;
}
cleanup.release();
}
XMLURL::XMLURL(const XMLCh* const urlText,
MemoryManager* const manager) :
fMemoryManager(manager)
, fFragment(0)
, fHost(0)
, fPassword(0)
, fPath(0)
, fPortNum(0)
, fProtocol(XMLURL::Unknown)
, fQuery(0)
, fUser(0)
, fURLText(0)
, fHasInvalidChar(false)
{
CleanupType cleanup(this, &XMLURL::cleanUp);
try
{
setURL(urlText);
}
catch(const OutOfMemoryException&)
{
cleanup.release();
throw;
}
cleanup.release();
}
XMLURL::XMLURL(const char* const urlText,
MemoryManager* const manager) :
fMemoryManager(manager)
, fFragment(0)
, fHost(0)
, fPassword(0)
, fPath(0)
, fPortNum(0)
, fProtocol(XMLURL::Unknown)
, fQuery(0)
, fUser(0)
, fURLText(0)
, fHasInvalidChar(false)
{
CleanupType cleanup(this, &XMLURL::cleanUp);
XMLCh* tmpText = XMLString::transcode(urlText, fMemoryManager);
ArrayJanitor<XMLCh> janRel(tmpText, fMemoryManager);
try
{
setURL(tmpText);
}
catch(const OutOfMemoryException&)
{
cleanup.release();
throw;
}
cleanup.release();
}
XMLURL::XMLURL(const XMLURL& toCopy) :
XMemory(toCopy)
, fMemoryManager(toCopy.fMemoryManager)
, fFragment(0)
, fHost(0)
, fPassword(0)
, fPath(0)
, fPortNum(toCopy.fPortNum)
, fProtocol(toCopy.fProtocol)
, fQuery(0)
, fUser(0)
, fURLText(0)
, fHasInvalidChar(toCopy.fHasInvalidChar)
{
CleanupType cleanup(this, &XMLURL::cleanUp);
try
{
fFragment = XMLString::replicate(toCopy.fFragment, fMemoryManager);
fHost = XMLString::replicate(toCopy.fHost, fMemoryManager);
fPassword = XMLString::replicate(toCopy.fPassword, fMemoryManager);
fPath = XMLString::replicate(toCopy.fPath, fMemoryManager);
fQuery = XMLString::replicate(toCopy.fQuery, fMemoryManager);
fUser = XMLString::replicate(toCopy.fUser, fMemoryManager);
fURLText = XMLString::replicate(toCopy.fURLText, fMemoryManager);
}
catch(const OutOfMemoryException&)
{
cleanup.release();
throw;
}
cleanup.release();
}
XMLURL::~XMLURL()
{
cleanUp();
}
// ---------------------------------------------------------------------------
// XMLURL: Public operators
// ---------------------------------------------------------------------------
XMLURL& XMLURL::operator=(const XMLURL& toAssign)
{
if (this == &toAssign)
return *this;
// Clean up our stuff
cleanUp();
// And copy his stuff
fMemoryManager = toAssign.fMemoryManager;
fFragment = XMLString::replicate(toAssign.fFragment, fMemoryManager);
fHost = XMLString::replicate(toAssign.fHost, fMemoryManager);
fPassword = XMLString::replicate(toAssign.fPassword, fMemoryManager);
fPath = XMLString::replicate(toAssign.fPath, fMemoryManager);
fPortNum = toAssign.fPortNum;
fProtocol = toAssign.fProtocol;
fQuery = XMLString::replicate(toAssign.fQuery, fMemoryManager);
fUser = XMLString::replicate(toAssign.fUser, fMemoryManager);
fURLText = XMLString::replicate(toAssign.fURLText, fMemoryManager);
fHasInvalidChar = toAssign.fHasInvalidChar;
return *this;
}
bool XMLURL::operator==(const XMLURL& toCompare) const
{
//
// Compare the two complete URLs (which have been processed the same
// way so they should now be the same even if they came in via different
// relative parts.
//
if (!XMLString::equals(getURLText(), toCompare.getURLText()))
return false;
return true;
}
// ---------------------------------------------------------------------------
// XMLURL: Getter methods
// ---------------------------------------------------------------------------
unsigned int XMLURL::getPortNum() const
{
//
// If it was not provided explicitly, then lets return the default one
// for the protocol.
//
if (!fPortNum)
{
if (fProtocol == Unknown)
return 0;
return gProtoList[fProtocol].defPort;
}
return fPortNum;
}
const XMLCh* XMLURL::getProtocolName() const
{
// Check to see if its ever been set
if (fProtocol == Unknown)
ThrowXMLwithMemMgr(MalformedURLException, XMLExcepts::URL_NoProtocolPresent, fMemoryManager);
return gProtoList[fProtocol].prefix;
}
// ---------------------------------------------------------------------------
// XMLURL: Setter methods
// ---------------------------------------------------------------------------
void XMLURL::setURL(const XMLCh* const urlText)
{
//
// Try to parse the URL.
//
cleanUp();
parse(urlText);
}
void XMLURL::setURL(const XMLCh* const baseURL
, const XMLCh* const relativeURL)
{
cleanUp();
// Parse our URL string
parse(relativeURL);
//
// If its relative and the base is non-null and non-empty, then
// parse the base URL string and conglomerate them.
//
if (isRelative() && baseURL)
{
if (*baseURL)
{
XMLURL basePart(baseURL, fMemoryManager);
if (!conglomerateWithBase(basePart, false))
{
cleanUp();
ThrowXMLwithMemMgr(MalformedURLException, XMLExcepts::URL_RelativeBaseURL, fMemoryManager);
}
}
}
}
// this version of setURL doesn't throw a malformedurl exception
// instead it returns false when it failed (or when it would of
// thrown a malformedurl exception)
bool XMLURL::setURL(const XMLCh* const baseURL
, const XMLCh* const relativeURL
, XMLURL& xmlURL)
{
cleanUp();
// Parse our URL string
if (parse(relativeURL, xmlURL))
{
// If its relative and the base is non-null and non-empty, then
// parse the base URL string and conglomerate them.
//
if (isRelative() && baseURL && *baseURL)
{
XMLURL basePart(fMemoryManager);
if (parse(baseURL, basePart) && conglomerateWithBase(basePart, false))
{
return true;
}
}
else
return true;
}
return false;
}
void XMLURL::setURL(const XMLURL& baseURL
, const XMLCh* const relativeURL)
{
cleanUp();
// Parse our URL string
parse(relativeURL);
// If its relative, then conglomerate with the base URL
if (isRelative())
conglomerateWithBase(baseURL);
}
// ---------------------------------------------------------------------------
// XMLURL: Miscellaneous methods
// ---------------------------------------------------------------------------
bool XMLURL::isRelative() const
{
// If no protocol then relative
if (fProtocol == Unknown)
return true;
// If no path, or the path is not absolute, then relative
if (!fPath)
return true;
if (*fPath != chForwardSlash)
return true;
return false;
}
bool XMLURL::hasInvalidChar() const {
return fHasInvalidChar;
}
BinInputStream* XMLURL::makeNewStream() const
{
//
// If its a local host, then we short circuit it and use our own file
// stream support. Otherwise, we just let it fall through and let the
// installed network access object provide a stream.
//
if (fProtocol == XMLURL::File)
{
if (!fHost || !XMLString::compareIStringASCII(fHost, XMLUni::fgLocalHostString))
{
XMLCh* realPath = XMLString::replicate(fPath, fMemoryManager);
ArrayJanitor<XMLCh> basePathName(realPath, fMemoryManager);
//
// Need to manually replace any character reference %xx first
// HTTP protocol will be done automatically by the netaccessor
//
int end = XMLString::stringLen(realPath);
int percentIndex = XMLString::indexOf(realPath, chPercent, 0, fMemoryManager);
while (percentIndex != -1) {
if (percentIndex+2 >= end ||
!isHexDigit(realPath[percentIndex+1]) ||
!isHexDigit(realPath[percentIndex+2]))
{
XMLCh value1[4];
XMLString::moveChars(value1, &(realPath[percentIndex]), 3);
value1[3] = chNull;
ThrowXMLwithMemMgr2(MalformedURLException
, XMLExcepts::XMLNUM_URI_Component_Invalid_EscapeSequence
, realPath
, value1
, fMemoryManager);
}
unsigned int value = (xlatHexDigit(realPath[percentIndex+1]) * 16) + xlatHexDigit(realPath[percentIndex+2]);
realPath[percentIndex] = XMLCh(value);
int i =0;
for (i = percentIndex + 1; i < end - 2 ; i++)
realPath[i] = realPath[i+2];
realPath[i] = chNull;
end = i;
percentIndex = XMLString::indexOf(realPath, chPercent, percentIndex, fMemoryManager);
}
BinFileInputStream* retStrm = new (fMemoryManager) BinFileInputStream(realPath, fMemoryManager);
if (!retStrm->getIsOpen())
{
delete retStrm;
return 0;
}
return retStrm;
}
}
//
// If we don't have have an installed net accessor object, then we
// have to just throw here.
//
if (!XMLPlatformUtils::fgNetAccessor)
ThrowXMLwithMemMgr(MalformedURLException, XMLExcepts::URL_UnsupportedProto, fMemoryManager);
// Else ask the net accessor to create the stream
return XMLPlatformUtils::fgNetAccessor->makeNew(*this);
}
void XMLURL::makeRelativeTo(const XMLCh* const baseURLText)
{
// If this one is not relative, don't bother
if (!isRelative())
return;
XMLURL baseURL(baseURLText, fMemoryManager);
conglomerateWithBase(baseURL);
}
void XMLURL::makeRelativeTo(const XMLURL& baseURL)
{
// If this one is not relative, don't bother
if (!isRelative())
return;
conglomerateWithBase(baseURL);
}
// ---------------------------------------------------------------------------
// XMLURL: Private helper methods
// ---------------------------------------------------------------------------
//
// This method will take the broken out parts of the URL and build up the
// full text. We don't do this unless someone asks us to, since its often
// never required.
//
void XMLURL::buildFullText()
{
// Calculate the worst case size of the buffer required
unsigned int bufSize = gMaxProtoLen + 1
+ XMLString::stringLen(fFragment) + 1
+ XMLString::stringLen(fHost) + 2
+ XMLString::stringLen(fPassword) + 1
+ XMLString::stringLen(fPath)
+ XMLString::stringLen(fQuery) + 1
+ XMLString::stringLen(fUser) + 1
+ 32;
// Clean up the existing buffer and allocate another
fMemoryManager->deallocate(fURLText);//delete [] fURLText;
fURLText = (XMLCh*) fMemoryManager->allocate((bufSize) * sizeof(XMLCh));//new XMLCh[bufSize];
*fURLText = 0;
XMLCh* outPtr = fURLText;
if (fProtocol != Unknown)
{
XMLString::catString(fURLText, getProtocolName());
outPtr += XMLString::stringLen(fURLText);
*outPtr++ = chColon;
*outPtr++ = chForwardSlash;
*outPtr++ = chForwardSlash;
}
if (fUser)
{
XMLString::copyString(outPtr, fUser);
outPtr += XMLString::stringLen(fUser);
if (fPassword)
{
*outPtr++ = chColon;
XMLString::copyString(outPtr, fPassword);
outPtr += XMLString::stringLen(fPassword);
}
*outPtr++ = chAt;
}
if (fHost)
{
XMLString::copyString(outPtr, fHost);
outPtr += XMLString::stringLen(fHost);
//
// If the port is zero, then we don't put it in. Else we need
// to because it was explicitly provided.
//
if (fPortNum)
{
*outPtr++ = chColon;
XMLCh tmpBuf[17];
XMLString::binToText(fPortNum, tmpBuf, 16, 10, fMemoryManager);
XMLString::copyString(outPtr, tmpBuf);
outPtr += XMLString::stringLen(tmpBuf);
}
}
if (fPath)
{
XMLString::copyString(outPtr, fPath);
outPtr += XMLString::stringLen(fPath);
}
if (fQuery)
{
*outPtr++ = chQuestion;
XMLString::copyString(outPtr, fQuery);
outPtr += XMLString::stringLen(fQuery);
}
if (fFragment)
{
*outPtr++ = chPound;
XMLString::copyString(outPtr, fFragment);
outPtr += XMLString::stringLen(fFragment);
}
// Cap it off in case the last op was not a string copy
*outPtr = 0;
}
//
// Just a central place to handle cleanup, since its done from a number
// of different spots.
//
void XMLURL::cleanUp()
{
fMemoryManager->deallocate(fFragment);//delete [] fFragment;
fMemoryManager->deallocate(fHost);//delete [] fHost;
fMemoryManager->deallocate(fPassword);//delete [] fPassword;
fMemoryManager->deallocate(fPath);//delete [] fPath;
fMemoryManager->deallocate(fQuery);//delete [] fQuery;
fMemoryManager->deallocate(fUser);//delete [] fUser;
fMemoryManager->deallocate(fURLText);//delete [] fURLText;
fFragment = 0;
fHost = 0;
fPassword = 0;
fPath = 0;
fQuery = 0;
fUser = 0;
fURLText = 0;
fProtocol = Unknown;
fPortNum = 0;
fHasInvalidChar = false;
}
//This function has been modified to take a bool parameter and the
//functionality inside looks irrational but is only to make
//solaris 2.7 CC 5.0 optimized build happy.
bool XMLURL::conglomerateWithBase(const XMLURL& baseURL, bool useExceptions)
{
// The base URL cannot be relative
if (baseURL.isRelative())
{
if (useExceptions)
ThrowXMLwithMemMgr(MalformedURLException, XMLExcepts::URL_RelativeBaseURL, fMemoryManager);
else
return false;
}
//
// Check a special case. If all we have is a fragment, then we want
// to just take the base host and path, plus our fragment.
//
if ((fProtocol == Unknown)
&& !fHost
&& !fPath
&& fFragment)
{
// Just in case, make sure we don't leak the user or password values
fMemoryManager->deallocate(fUser);//delete [] fUser;
fUser = 0;
fMemoryManager->deallocate(fPassword);//delete [] fPassword;
fPassword = 0;
// Copy over the protocol and port number as is
fProtocol = baseURL.fProtocol;
fPortNum = baseURL.fPortNum;
// Replicate the base fields that are provided
fHost = XMLString::replicate(baseURL.fHost, fMemoryManager);
fUser = XMLString::replicate(baseURL.fUser, fMemoryManager);
fPassword = XMLString::replicate(baseURL.fPassword, fMemoryManager);
fPath = XMLString::replicate(baseURL.fPath, fMemoryManager);
return true;
}
//
// All we have to do is run up through our fields and, for each one
// that we don't have, use the based URL's. Once we hit one field
// that we have, we stop.
//
if (fProtocol != Unknown)
return true;
fProtocol = baseURL.fProtocol;
//
// If the protocol is not file, and we either already have our own
// host, or the base does not have one, then we are done.
//
if (fProtocol != File)
{
if (fHost || !baseURL.fHost)
return true;
}
// Replicate all of the hosty stuff if the base has one
if (baseURL.fHost)
{
// Just in case, make sure we don't leak a user or password field
fMemoryManager->deallocate(fUser);//delete [] fUser;
fUser = 0;
fMemoryManager->deallocate(fPassword);//delete [] fPassword;
fPassword = 0;
fMemoryManager->deallocate(fHost);//delete [] fHost;
fHost = 0;
fHost = XMLString::replicate(baseURL.fHost, fMemoryManager);
fUser = XMLString::replicate(baseURL.fUser, fMemoryManager);
fPassword = XMLString::replicate(baseURL.fPassword, fMemoryManager);
fPortNum = baseURL.fPortNum;
}
// If we have a path and its absolute, then we are done
const bool hadPath = (fPath != 0);
if (hadPath)
{
if (*fPath == chForwardSlash)
return true;
}
// Its a relative path, so weave them together.
if (baseURL.fPath) {
XMLCh* temp = XMLPlatformUtils::weavePaths(baseURL.fPath, fPath ,fMemoryManager);
fMemoryManager->deallocate(fPath);//delete [] fPath;
fPath = temp;
}
// If we had any original path, then we are done
if (hadPath)
return true;
// We had no original path, so go on to deal with the query/fragment parts
if (fQuery || !baseURL.fQuery)
return true;
fQuery = XMLString::replicate(baseURL.fQuery, fMemoryManager);
if (fFragment || !baseURL.fFragment)
return true;
fFragment = XMLString::replicate(baseURL.fFragment, fMemoryManager);
return true;
}
void XMLURL::parse(const XMLCh* const urlText)
{
// Simplify things by checking for the psycho scenarios first
if (!*urlText)
ThrowXMLwithMemMgr(MalformedURLException, XMLExcepts::URL_NoProtocolPresent, fMemoryManager);
// Before we start, check if this urlText contains valid uri characters
if (!XMLUri::isURIString(urlText))
fHasInvalidChar = true;
else
fHasInvalidChar = false;
//
// The first thing we will do is to check for a file name, so that
// we don't waste time thinking its a URL. If its in the form x:\ or x:/
// and x is an ASCII letter, then assume that's the deal.
//
if (((*urlText >= chLatin_A) && (*urlText <= chLatin_Z))
|| ((*urlText >= chLatin_a) && (*urlText <= chLatin_z)))
{
if (*(urlText + 1) == chColon)
{
if ((*(urlText + 2) == chForwardSlash)
|| (*(urlText + 2) == chBackSlash))
{
ThrowXMLwithMemMgr(MalformedURLException, XMLExcepts::URL_NoProtocolPresent, fMemoryManager);
}
}
}
// Get a copy of the URL that we can modify
XMLCh* srcCpy = XMLString::replicate(urlText, fMemoryManager);
ArrayJanitor<XMLCh> janSrcCopy(srcCpy, fMemoryManager);
//
// Get a pointer now that we can run up thrown the source as we parse
// bits and pieces out of it.
//
XMLCh* srcPtr = srcCpy;
// Run up past any spaces
while (*srcPtr)
{
if (!XMLChar1_0::isWhitespace(*srcPtr))
break;
srcPtr++;
}
// Make sure it wasn't all space
if (!*srcPtr)
ThrowXMLwithMemMgr(MalformedURLException, XMLExcepts::URL_NoProtocolPresent, fMemoryManager);
//
// Ok, the next thing we have to do is to find either a / or : character.
// If the : is first, we assume we have a protocol. If the / is first,
// then we skip to the host processing.
//
XMLCh* ptr1 = XMLString::findAny(srcPtr, gListOne);
XMLCh* ptr2;
// If we found a protocol, then deal with it
if (ptr1)
{
if (*ptr1 == chColon)
{
// Cap the string at the colon
*ptr1 = 0;
// And try to find it in our list of protocols
fProtocol = lookupByName(srcPtr);
if (fProtocol == Unknown)
{
ThrowXMLwithMemMgr1
(
MalformedURLException
, XMLExcepts::URL_UnsupportedProto1
, srcPtr
, fMemoryManager
);
}
// And move our source pointer up past what we've processed
srcPtr = (ptr1 + 1);
}
}
//
// Ok, next we need to see if we have any host part. If the next
// two characters are //, then we need to check, else move on.
//
if ((*srcPtr == chForwardSlash) && (*(srcPtr + 1) == chForwardSlash))
{
// Move up past the slashes
srcPtr += 2;
//
// If we aren't at the end of the string, then there has to be a
// host part at this point. we will just look for the next / char
// or end of string and make all of that the host for now.
//
if (*srcPtr)
{
// Search from here for a / character
ptr1 = XMLString::findAny(srcPtr, gListFour);
//
// If we found something, then the host is between where
// we are and what we found. Else the host is the rest of
// the content and we are done. If its empty, leave it null.
//
if (ptr1)
{
if (ptr1 != srcPtr)
{
fMemoryManager->deallocate(fHost);//delete [] fHost;
fHost = (XMLCh*) fMemoryManager->allocate
(
((ptr1 - srcPtr) + 1) * sizeof(XMLCh)
);//new XMLCh[(ptr1 - srcPtr) + 1];
ptr2 = fHost;
while (srcPtr < ptr1)
*ptr2++ = *srcPtr++;
*ptr2 = 0;
}
}
else
{
fMemoryManager->deallocate(fHost);//delete [] fHost;
fHost = XMLString::replicate(srcPtr, fMemoryManager);
// Update source pointer to the end
srcPtr += XMLString::stringLen(fHost);
}
}
}
else
{
//
// http protocol requires two forward slashes
// we didn't get them, so throw an exception
//
if (fProtocol == HTTP) {
ThrowXMLwithMemMgr
(
MalformedURLException
, XMLExcepts::URL_ExpectingTwoSlashes
, fMemoryManager
);
}
}
//
// If there was a host part, then we have to grovel through it for
// all the bits and pieces it can hold.
//
if (fHost)
{
//
// Look for a '@' character, which indicates a user name. If we
// find one, then everything between the start of the host data
// and the character is the user name.
//
ptr1 = XMLString::findAny(fHost, gListTwo);
if (ptr1)
{
// Get this info out as the user name
*ptr1 = 0;
fMemoryManager->deallocate(fUser);//delete [] fUser;
fUser = XMLString::replicate(fHost, fMemoryManager);
ptr1++;
// And now cut these chars from the host string
XMLString::cut(fHost, ptr1 - fHost);
// Is there a password inside the user string?
ptr2 = XMLString::findAny(fUser, gListThree);
if (ptr2)
{
// Remove it from the user name string
*ptr2 = 0;
// And copy out the remainder to the password field
ptr2++;
fMemoryManager->deallocate(fPassword);//delete [] fPassword;
fPassword = XMLString::replicate(ptr2, fMemoryManager);
}
}
//
// Ok, so now we are at the actual host name, if any. If we are
// not at the end of the host data, then lets see if we have a
// port trailing the
//
ptr1 = XMLString::findAny(fHost, gListThree);
if (ptr1)
{
// Remove it from the host name
*ptr1 = 0;
// Try to convert it to a numeric port value and store it
ptr1++;
if (!XMLString::textToBin(ptr1, fPortNum, fMemoryManager))
ThrowXMLwithMemMgr(MalformedURLException, XMLExcepts::URL_BadPortField, fMemoryManager);
}
// If the host ended up empty, then toss is
if (!*fHost)
{
fMemoryManager->deallocate(fHost);//delete[] fHost;
fHost = 0;
}
}
// If we are at the end, then we are done now
if (!*srcPtr)
{
return;
}
//
// Next is the path part. It can be absolute, i.e. starting with a
// forward slash character, or relative. Its basically everything up
// to the end of the string or to any trailing query or fragment.
//
ptr1 = XMLString::findAny(srcPtr, gListFive);
if (!ptr1)
{
fMemoryManager->deallocate(fPath);//delete [] fPath;
fPath = XMLString::replicate(srcPtr, fMemoryManager);
return;
}
// Everything from where we are to what we found is the path
if (ptr1 > srcPtr)
{
fMemoryManager->deallocate(fPath);//delete [] fPath;
fPath = (XMLCh*) fMemoryManager->allocate
(
((ptr1 - srcPtr) + 1) * sizeof(XMLCh)
);//new XMLCh[(ptr1 - srcPtr) + 1];
ptr2 = fPath;
while (srcPtr < ptr1)
*ptr2++ = *srcPtr++;
*ptr2 = 0;
}
//
// If we found a fragment, then it is the rest of the string and we
// are done.
//
if (*srcPtr == chPound)
{
srcPtr++;
fMemoryManager->deallocate(fFragment);//delete [] fFragment;
fFragment = XMLString::replicate(srcPtr, fMemoryManager);
return;
}
//
// The query is either the rest of the string, or up to the fragment
// separator.
//
srcPtr++;
ptr1 = XMLString::findAny(srcPtr, gListSix);
fMemoryManager->deallocate(fQuery);//delete [] fQuery;
if (!ptr1)
{
fQuery = XMLString::replicate(srcPtr, fMemoryManager);
return;
}
else
{
fQuery = (XMLCh*) fMemoryManager->allocate
(
((ptr1 - srcPtr) + 1) * sizeof(XMLCh)
);//new XMLCh[(ptr1 - srcPtr) + 1];
ptr2 = fQuery;
while (srcPtr < ptr1)
*ptr2++ = *srcPtr++;
*ptr2 = 0;
}
// If we are not at the end now, then everything else is the fragment
if (*srcPtr == chPound)
{
srcPtr++;
fMemoryManager->deallocate(fFragment);//delete [] fFragment;
fFragment = XMLString::replicate(srcPtr, fMemoryManager);
}
}
bool XMLURL::parse(const XMLCh* const urlText, XMLURL& xmlURL)
{
// Simplify things by checking for the psycho scenarios first
if (!*urlText)
return false;
// Before we start, check if this urlText contains valid uri characters
if (!XMLUri::isURIString(urlText))
xmlURL.fHasInvalidChar = true;
else
xmlURL.fHasInvalidChar = false;
//
// The first thing we will do is to check for a file name, so that
// we don't waste time thinking its a URL. If its in the form x:\ or x:/
// and x is an ASCII letter, then assume that's the deal.
//
if (((*urlText >= chLatin_A) && (*urlText <= chLatin_Z))
|| ((*urlText >= chLatin_a) && (*urlText <= chLatin_z)))
{
if (*(urlText + 1) == chColon)
{
if ((*(urlText + 2) == chForwardSlash)
|| (*(urlText + 2) == chBackSlash))
{
return false;
}
}
}
// Get a copy of the URL that we can modify
XMLCh* srcCpy = XMLString::replicate(urlText, xmlURL.fMemoryManager);
ArrayJanitor<XMLCh> janSrcCopy(srcCpy, xmlURL.fMemoryManager);
//
// Get a pointer now that we can run up thrown the source as we parse
// bits and pieces out of it.
//
XMLCh* srcPtr = srcCpy;
// Run up past any spaces
while (*srcPtr)
{
if (!XMLChar1_0::isWhitespace(*srcPtr))
break;
srcPtr++;
}
// Make sure it wasn't all space
if (!*srcPtr)
return false;
//
// Ok, the next thing we have to do is to find either a / or : character.
// If the : is first, we assume we have a protocol. If the / is first,
// then we skip to the host processing.
//
XMLCh* ptr1 = XMLString::findAny(srcPtr, gListOne);
XMLCh* ptr2;
// If we found a protocol, then deal with it
if (ptr1)
{
if (*ptr1 == chColon)
{
// Cap the string at the colon
*ptr1 = 0;
// And try to find it in our list of protocols
xmlURL.fProtocol = lookupByName(srcPtr);
if (xmlURL.fProtocol == Unknown)
return false;
// And move our source pointer up past what we've processed
srcPtr = (ptr1 + 1);
}
}
//
// Ok, next we need to see if we have any host part. If the next
// two characters are //, then we need to check, else move on.
//
if ((*srcPtr == chForwardSlash) && (*(srcPtr + 1) == chForwardSlash))
{
// Move up past the slashes
srcPtr += 2;
//
// If we aren't at the end of the string, then there has to be a
// host part at this point. we will just look for the next / char
// or end of string and make all of that the host for now.
//
if (*srcPtr)
{
// Search from here for a / character
ptr1 = XMLString::findAny(srcPtr, gListFour);
//
// If we found something, then the host is between where
// we are and what we found. Else the host is the rest of
// the content and we are done. If its empty, leave it null.
//
if (ptr1)
{
if (ptr1 != srcPtr)
{
xmlURL.fHost = (XMLCh*) xmlURL.fMemoryManager->allocate
(
((ptr1 - srcPtr) + 1) * sizeof(XMLCh)
);//new XMLCh[(ptr1 - srcPtr) + 1];
ptr2 = xmlURL.fHost;
while (srcPtr < ptr1)
*ptr2++ = *srcPtr++;
*ptr2 = 0;
}
}
else
{
xmlURL.fHost = XMLString::replicate(srcPtr, xmlURL.fMemoryManager);
// Update source pointer to the end
srcPtr += XMLString::stringLen(xmlURL.fHost);
}
}
}
else
{
//
// http protocol requires two forward slashes
// we didn't get them, so throw an exception
//
if (xmlURL.fProtocol == HTTP)
return false;
}
//
// If there was a host part, then we have to grovel through it for
// all the bits and pieces it can hold.
//
if (xmlURL.fHost)
{
//
// Look for a '@' character, which indicates a user name. If we
// find one, then everything between the start of the host data
// and the character is the user name.
//
ptr1 = XMLString::findAny(xmlURL.fHost, gListTwo);
if (ptr1)
{
// Get this info out as the user name
*ptr1 = 0;
xmlURL.fUser = XMLString::replicate(xmlURL.fHost, xmlURL.fMemoryManager);
ptr1++;
// And now cut these chars from the host string
XMLString::cut(xmlURL.fHost, ptr1 - xmlURL.fHost);
// Is there a password inside the user string?
ptr2 = XMLString::findAny(xmlURL.fUser, gListThree);
if (ptr2)
{
// Remove it from the user name string
*ptr2 = 0;
// And copy out the remainder to the password field
ptr2++;
xmlURL.fPassword = XMLString::replicate(ptr2, xmlURL.fMemoryManager);
}
}
//
// Ok, so now we are at the actual host name, if any. If we are
// not at the end of the host data, then lets see if we have a
// port trailing the
//
ptr1 = XMLString::findAny(xmlURL.fHost, gListThree);
if (ptr1)
{
// Remove it from the host name
*ptr1 = 0;
// Try to convert it to a numeric port value and store it
ptr1++;
if (!XMLString::textToBin(ptr1, xmlURL.fPortNum, xmlURL.fMemoryManager))
return false;
}
// If the host ended up empty, then toss is
if (!*(xmlURL.fHost))
{
xmlURL.fMemoryManager->deallocate(xmlURL.fHost);//delete[] fHost;
xmlURL.fHost = 0;
}
}
// If we are at the end, then we are done now
if (!*srcPtr)
{
return true;
}
//
// Next is the path part. It can be absolute, i.e. starting with a
// forward slash character, or relative. Its basically everything up
// to the end of the string or to any trailing query or fragment.
//
ptr1 = XMLString::findAny(srcPtr, gListFive);
if (!ptr1)
{
xmlURL.fPath = XMLString::replicate(srcPtr, xmlURL.fMemoryManager);
return true;
}
// Everything from where we are to what we found is the path
if (ptr1 > srcPtr)
{
xmlURL.fPath = (XMLCh*) xmlURL.fMemoryManager->allocate
(
((ptr1 - srcPtr) + 1) * sizeof(XMLCh)
);//new XMLCh[(ptr1 - srcPtr) + 1];
ptr2 = xmlURL.fPath;
while (srcPtr < ptr1)
*ptr2++ = *srcPtr++;
*ptr2 = 0;
}
//
// If we found a fragment, then it is the rest of the string and we
// are done.
//
if (*srcPtr == chPound)
{
srcPtr++;
xmlURL.fFragment = XMLString::replicate(srcPtr, xmlURL.fMemoryManager);
return true;
}
//
// The query is either the rest of the string, or up to the fragment
// separator.
//
srcPtr++;
ptr1 = XMLString::findAny(srcPtr, gListSix);
if (!ptr1)
{
xmlURL.fQuery = XMLString::replicate(srcPtr, xmlURL.fMemoryManager);
return true;
}
else
{
xmlURL.fQuery = (XMLCh*) xmlURL.fMemoryManager->allocate
(
((ptr1 - srcPtr) + 1) * sizeof(XMLCh)
);//new XMLCh[(ptr1 - srcPtr) + 1];
ptr2 = xmlURL.fQuery;
while (srcPtr < ptr1)
*ptr2++ = *srcPtr++;
*ptr2 = 0;
}
// If we are not at the end now, then everything else is the fragment
if (*srcPtr == chPound)
{
srcPtr++;
xmlURL.fFragment = XMLString::replicate(srcPtr, xmlURL.fMemoryManager);
}
return true;
}
XERCES_CPP_NAMESPACE_END
| [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
]
| [
[
[
1,
1476
]
]
]
|
eb4d1324c058f4858e25655083bf9072b7c40600 | bfe8eca44c0fca696a0031a98037f19a9938dd26 | /libjingle-0.4.0/talk/base/taskrunner.h | ebb5161b0db3c745189f75cf17227dcedfca016c | [
"BSD-3-Clause"
]
| permissive | luge/foolject | a190006bc0ed693f685f3a8287ea15b1fe631744 | 2f4f13a221a0fa2fecab2aaaf7e2af75c160d90c | refs/heads/master | 2021-01-10T07:41:06.726526 | 2011-01-21T10:25:22 | 2011-01-21T10:25:22 | 36,303,977 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,570 | h | /*
* libjingle
* Copyright 2004--2006, Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TALK_BASE_TASKRUNNER_H__
#define TALK_BASE_TASKRUNNER_H__
#include <vector>
#include "talk/base/sigslot.h"
#include "talk/base/task.h"
namespace talk_base {
class Task;
const int64 kSecToMsec = 1000;
const int64 kMsecTo100ns = 10000;
const int64 kSecTo100ns = kSecToMsec * kMsecTo100ns;
class TaskRunner : public Task, public sigslot::has_slots<> {
public:
TaskRunner();
virtual ~TaskRunner();
virtual void WakeTasks() = 0;
// This method returns the current time in 100ns units since 1/1/1601. This
// Is the GetSystemTimeAsFileTime method on windows.
virtual int64 CurrentTime() = 0 ;
void StartTask(Task *task);
void RunTasks();
void PollTasks();
void UpdateTaskTimeout(Task *task);
// dummy state machine - never run.
virtual int ProcessStart() { return STATE_DONE; }
private:
std::vector<Task *> tasks_;
Task *next_timeout_task_;
bool tasks_running_;
void RecalcNextTimeout(Task *exclude_task);
};
} // namespace talk_base
#endif // TASK_BASE_TASKRUNNER_H__
| [
"[email protected]@756bb6b0-a119-0410-8338-473b6f1ccd30"
]
| [
[
[
1,
74
]
]
]
|
2ffc6275d58a9f9655bad50f923656c979c8055d | 14298a990afb4c8619eea10988f9c0854ec49d29 | /PowerBill四川电信专用版本/ibill_source/RecordDetailFrm.cpp | 9921b54744f489f7d1c0b5f08a27b36f24674f78 | []
| no_license | sridhar19091986/xmlconvertsql | 066344074e932e919a69b818d0038f3d612e6f17 | bbb5bbaecbb011420d701005e13efcd2265aa80e | refs/heads/master | 2021-01-21T17:45:45.658884 | 2011-05-30T12:53:29 | 2011-05-30T12:53:29 | 42,693,560 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 9,583 | cpp | //---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "RecordDetailFrm.h"
#include "MainFrm.h"
#include <Clipbrd.hpp>
#include "FieldFrm.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "RzPanel"
#pragma link "RzButton"
#pragma link "RzListVw"
#pragma link "RzEdit"
#pragma link "RzSplit"
#pragma link "RzRadChk"
#pragma resource "*.dfm"
TfrmRecordDetail *frmRecordDetail;
//---------------------------------------------------------------------------
__fastcall TfrmRecordDetail::TfrmRecordDetail(TComponent* Owner)
: TForm(Owner)
{
Buffer = NULL;
RecordIndex = 0;
}
//---------------------------------------------------------------------------
void __fastcall TfrmRecordDetail::btnCancelClick(TObject *Sender)
{
Close();
}
//---------------------------------------------------------------------------
void __fastcall TfrmRecordDetail::SetBuffer(char * ABuffer,int Length)
{
if(Buffer != NULL)
{
delete[] Buffer;
Buffer = NULL;
}
Buffer = new char[Length];
memcpy(Buffer,ABuffer,Length);
RecordLength = Length;
}
//---------------------------------------------------------------------------
void __fastcall TfrmRecordDetail::FormKeyPress(TObject *Sender, char &Key)
{
if(Key == 27)
{
Key = 0;
Close();
}
}
//---------------------------------------------------------------------------
void __fastcall TfrmRecordDetail::SetBillName(TBillFile * ABillFile,AnsiString BillName,AnsiString FileName)
{
BillFile = ABillFile;
if(BillName != txtBillName->Text)
{
lvFields->Items->Clear();
TBillField * BillField;
TListItem * Item;
for(int n = 0;n < BillFile->FieldCount;n++)
{
BillField = BillFile->GetBillField(n);
Item = lvFields->Items->Add();
Item->Caption = BillField->Label;
Item->SubItems->Add("");
Item->SubItems->Add("");
Item->SubItems->Add("");
Item->Data = (void *)BillField;
}
txtBillName->Text = BillName;
}
txtFileName->Text = FileName;
}
void __fastcall TfrmRecordDetail::ShowFieldValues(int ARecordIndex)
{
RecordIndex = ARecordIndex;
TBillField * BillField;
TListItem * Item;
for(int n = 0;n < lvFields->Items->Count;n++)
{
Item = lvFields->Items->Item[n];
Item->SubItems->Strings[0] = "";
Item->SubItems->Strings[1] = "";
Item->SubItems->Strings[2] = "";
BillField = (TBillField *)Item->Data;
Item->SubItems->Strings[0] = BillField->GetFieldValue(false);
Item->SubItems->Strings[1] = BillField->GetFieldValue(true);
/*switch(BillFile->FileType)
{
case TXT_BILL_FORMAT:
{
char * Buffer = (char *)BillField->GetFieldOriData();
Item->SubItems->Strings[2] = AnsiString(Buffer);
}
break;
case BIN_BILL_FORMAT:
{
int Len = BillField->FieldLength;
unsigned char * Buffer = (unsigned char *)BillField->GetFieldOriData();
int Position = -1;
AnsiString str;
do
{
++Position;
if(Position >= Len)
break;
str = str + IntToHex( * (Buffer + Position),2) + " ";
}while(Position < Len);
Item->SubItems->Strings[2] = str;
}
break;
}*/
}
lvFieldsSelectItem(NULL,lvFields->Selected,true);
}
void __fastcall TfrmRecordDetail::btnCapyClick(TObject *Sender)
{
AnsiString Text = "话单记录详细信息\r\n"\
"话单类型:" + txtBillName->Text + "\r\n"\
"话单文件:" + txtFileName->Text + "\r\n"\
"记录位置:" + txtRecordPosition->Text + "\r\n"\
"记录长度:" + txtRecordLength->Text + "\r\n"\
"以下是该记录中各字段的值\r\n\r\n"\
"字段名称\t字段内容(翻译前)\t字段内容(翻译后)\r\n";
TListItem * Item;
for(int n = 0;n < lvFields->Items->Count;n++)
{
Item = lvFields->Items->Item[n];
Text += Item->Caption + "\t"
+ Item->SubItems->Strings[0] + "\t"\
+ Item->SubItems->Strings[1] + "\t"\
+ Item->SubItems->Strings[2] + "\r\n";
}
Text += "原始数据内容:\r\n" + txtRecordData->Text;
TClipboard * Clipboard = new TClipboard();
Clipboard->AsText = Text;
delete Clipboard;
MessageBox(Handle,"记录的详细信息已复制到剪贴板!","信息",MB_OK | MB_ICONINFORMATION);
}
//---------------------------------------------------------------------------
void __fastcall TfrmRecordDetail::FormDestroy(TObject *Sender)
{
if(Buffer != NULL)
{
delete[] Buffer;
Buffer = NULL;
}
}
//---------------------------------------------------------------------------
void __fastcall TfrmRecordDetail::PopupMenu1Popup(TObject *Sender)
{
menuCopy->Enabled = txtRecordData->SelLength > 0;
menuSaveAsOri->Enabled = Buffer != NULL;
}
//---------------------------------------------------------------------------
void __fastcall TfrmRecordDetail::menuCopyClick(TObject *Sender)
{
if(txtRecordData->SelLength == 0)
return;
txtRecordData->CopyToClipboard();
}
//---------------------------------------------------------------------------
void __fastcall TfrmRecordDetail::menuSaveAsTextClick(TObject *Sender)
{
SaveDialog1->Title = "保存为文本";
SaveDialog1->DefaultExt = "txt";
SaveDialog1->Filter = "文本文件(*.txt)|*.txt";
if(!SaveDialog1->Execute())
return;
FILE * file = fopen(SaveDialog1->FileName.c_str(),"w");
if(file == NULL)
{
MessageBox(Handle,"写入文件失败!","错误",MB_OK | MB_ICONSTOP);
return;
}
fprintf(file,"%s",txtRecordData->Text);
fclose(file);
}
//---------------------------------------------------------------------------
void __fastcall TfrmRecordDetail::menuSaveAsOriClick(TObject *Sender)
{
SaveDialog1->Title = "保存为原始数据";
SaveDialog1->DefaultExt = "";
SaveDialog1->Filter = "原始数据文件(*.*)|*.*";
if(!SaveDialog1->Execute())
return;
FILE * file = fopen(SaveDialog1->FileName.c_str(),"w+b");
if(file == NULL)
{
MessageBox(Handle,"写入文件失败!","错误",MB_OK | MB_ICONSTOP);
return;
}
fwrite(Buffer,RecordLength,1,file);
fclose(file);
}
//---------------------------------------------------------------------------
void __fastcall TfrmRecordDetail::lvFieldsSelectItem(TObject *Sender,
TListItem *Item, bool Selected)
{
if(Item == NULL)
return;
TBillField * BillField = (TBillField * )Item->Data;
if(Selected)
{
if(BillFile->FileType == TXT_BILL_FORMAT|| cbxViewAsText->Checked)
{
if(BillField->Offset < 0)
return;
TStringList * List = new TStringList;
Split(txtRecordData->Text,BillFile->Separator,List);
int pos = 1;
int n;
for(n = 0;n < BillField->Offset;n++)
{
pos += List->Strings[n].Length();
}
if(pos > 0)
{
txtRecordData->SelStart = pos + BillField->Offset - 1;
txtRecordData->SelLength = List->Strings[n].Length();
}
else
{
txtRecordData->SelStart = 0;
txtRecordData->SelLength = 0;
}
delete List;
}
else //BIN_BILL_FORMAT:
{
if((BillField->Offset * 2 + BillField->Offset < 0) ||
(BillField->FieldLength * 2 + BillField->FieldLength - 1) < 0)
{
txtRecordData->SelStart = 0;
txtRecordData->SelLength = 0;
}
else
{
Label6->Enabled = BillField->DataType == DATATYPE_BIT;
txtBitContext->Enabled = Label6->Enabled;
if(Label6->Enabled)
{
if(!BillFile->ReadSingleRecord(RecordIndex))
{
return;
}
txtBitContext->Text = GetFieldValue_FIELD_DISPLAY_AS_BITS(BillField);
txtBitContext->SelStart = 8 - BillField->BitPosition - BillField->BitWidth;
txtBitContext->SelLength = BillField->BitWidth;
Label6->Caption = "Bit位置:" + IntToStr(BillField->BitPosition) + ",Bit宽度:" + IntToStr(BillField->BitWidth);
}
else
{
txtBitContext->Text = "";
Label6->Caption = "";
}
txtRecordData->SelStart = BillField->Offset * 2 + BillField->Offset;
txtRecordData->SelLength = BillField->FieldLength * 2 + BillField->FieldLength - 1;
}
}
}
}
//---------------------------------------------------------------------------
void __fastcall TfrmRecordDetail::lvFieldsDblClick(TObject *Sender)
{
if(lvFields->Selected == NULL)
return;
AnsiString FieldName = ((TBillField * )lvFields->Selected->Data)->FieldName;
_di_IXMLNode FieldNode = frmMain->BillConfig->GetFieldNode(BillFile->GetBillName(),FieldName);
if(FieldNode == NULL)
{
MessageBox(Handle,("找不到字段节点[" + FieldName + "]!").c_str(),"错误",MB_OK | MB_ICONSTOP);
return;
}
TfrmField * frmField = new TfrmField(this,BillFile->GetBillName(),frmMain->BillConfig,FieldNode,true);
frmField->ShowModal();
delete frmField;
}
//---------------------------------------------------------------------------
void __fastcall TfrmRecordDetail::cbxViewAsTextClick(TObject *Sender)
{
//lvFieldsSelectItem(NULL,lvFields->Selected,true);
}
//---------------------------------------------------------------------------
| [
"cn.wei.hp@e7bd78f4-57e5-8052-e4e7-673d445fef99"
]
| [
[
[
1,
297
]
]
]
|
6d20176fe1293b3c5c11c60f6529dddf754aeb8a | 2e5bc0ec41f772109b48082961b791ce8ef13e37 | /classes/PairCount.h | 04b0b84f872abff81151ac9af6cd0922c78db92e | []
| no_license | Chefslayer/Translator | 41fde25e143218c4cdd4cb9cf4889dadf31848d7 | 7ecf27cbc0dffedb4cf9b624cb50d6aab979443f | refs/heads/master | 2016-09-05T14:18:12.645917 | 2009-07-31T17:01:38 | 2009-07-31T17:01:38 | 190,734 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,100 | h | /**
* @file
* @author Gruppe 2
* @version 1.0
*
* @section DESCRIPTION
*
* The PairCount class holds and counts the occurrence of word-pairs.
*/
#ifndef __PAIRCOUNT_H__
#define __PAIRCOUNT_H__
#include <map>
#include <utility>
using namespace std;
/**
* The PairCount class holds and counts the occurrence of word-pairs.
*/
class PairCount
{
private:
/// holds and counts the occurrences of the wordpairs
map<pair<unsigned int, unsigned int>, unsigned int> pairCounts;
/// map-iterator used to walk through the map in the functions begin(), next(), isEnd()
map<pair<unsigned int, unsigned int>, unsigned int>::iterator it;
public:
/**
* inserts and/or increments the count of a word-pair.
*
* \param wordpair the word-pair to insert
*/
inline void insert(pair<unsigned int, unsigned int> wordpair)
{
pairCounts[wordpair]++;
}
/**
* gets the count of occurrence of a word-pair.
*
* \param wordpair the word-pair to get the count for.
* \return count of occurrence of the given word pair.
*/
inline unsigned int getFreq(pair<unsigned int, unsigned int> wordpair)
{
return (pairCounts.find(wordpair))->second;
}
/**
* gets the count of inserted pairs.
*
* \return count of inserted pairs = size of the pairCoutns-map.
*/
inline unsigned int getSize()
{
return pairCounts.size();
}
/**
* sets the map-iterator to the begin of the pairCount-map.
*/
inline void begin()
{
it = pairCounts.begin();
}
/**
* sets the map-iterator to the next position.
*/
inline void next()
{
it++;
}
/**
* checks whether the map-iterator is at the end of the pairCount-map.
*
* \return true if the map iterator is at the end, false otherwise.
*/
inline bool isEnd()
{
return it == pairCounts.end();
}
/**
* gets the current pair at the map-iterators position.
*
* \return the pair at the map-iterators position.
*/
inline pair<unsigned int, unsigned int> current()
{
return it->first;
}
};
#endif
| [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
]
| [
[
[
1,
10
],
[
18,
21
],
[
30,
35
],
[
39,
46
],
[
50,
56
],
[
60,
64
],
[
69,
72
],
[
76,
82
],
[
86,
92
],
[
98,
98
]
],
[
[
11,
14
],
[
22,
23
],
[
36,
38
],
[
47,
49
],
[
57,
59
],
[
65,
68
],
[
73,
75
],
[
83,
85
],
[
93,
97
]
],
[
[
15,
17
],
[
29,
29
]
],
[
[
24,
28
]
]
]
|
24f5d82fb43f899819c612443463311f24dba347 | f0c08b3ddefc91f1fa342f637b0e947a9a892556 | /branches/develop/calcioIA/Calcio/Draw.h | 008ea4216ee6671d51560f8c9cefac7b6298be52 | []
| no_license | BackupTheBerlios/coffeestore-svn | 1db0f60ddb85ccbbdfeb9b3271a687b23e29fc8f | ddee83284fe9875bf0d04e6b7da7a2113e85a040 | refs/heads/master | 2021-01-01T05:30:22.345767 | 2009-10-11T08:55:35 | 2009-10-11T08:55:35 | 40,725,038 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 384 | h | #ifndef DRAW_H
#define DRAW_H
class Ball;
class Team;
class Player;
class Field;
class Game;
class Draw
{
public:
virtual ~Draw() {}
virtual void draw(const Ball& ball) = 0;
virtual void draw(const Team& team) = 0;
virtual void draw(const Player& player) = 0;
virtual void draw(const Field& field) = 0;
virtual void draw(const Game& game) = 0;
};
#endif
| [
"fabioppp@e591b805-c13a-0410-8b2d-a75de64125fb"
]
| [
[
[
1,
21
]
]
]
|
ab75d9de7f22c66e914d12d428fd19deefbc76c9 | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Modules/UiCtrl/AudioCtrlNo.h | 98091d087e34584340f85bee699eb5e8cef31f1b | [
"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 | 2,354 | 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 AUDIO_CONTROL_No_H
#define AUDIO_CONTROL_No_H
#include "AudioCtrlStd.h"
namespace isab{
class AudioCtrlLanguageNo : public AudioCtrlLanguageStd
{
public:
AudioCtrlLanguageNo();
static class AudioCtrlLanguage* New();
virtual int newCameraSoundList(
DistanceInfo &deadlines,
SoundClipsList &soundClips);
private:
void ActionAndWhen();
void Distance();
void When();
void RoundaboutExit();
void NumberedExit();
virtual void Action();
virtual void FirstCrossing();
virtual void AdditionalCrossing();
virtual void genericDeviatedFromRoute();
virtual void genericReachedDest();
}; /* AudioCtrlLanguage */
} /* namespace isab */
#endif
| [
"[email protected]"
]
| [
[
[
1,
50
]
]
]
|
422f12ccf8237cc9b18d7d3f5d49bb35f7dfc9bc | d3cb6453d0cbf7836791bf770d3c3ec8753efd71 | /objects/channel.cpp | f37207b912237e86be890f7857510218a554b8e5 | []
| no_license | philippebataille/gps-sdr | 086dfb0e3ab74391044976aa598411e9bad47ea0 | 1bee82b19151a808ad75fa0774e8bc56bfba3056 | refs/heads/master | 2021-01-24T01:04:57.875143 | 2009-08-05T14:05:52 | 2009-08-05T14:05:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,201 | cpp | /*----------------------------------------------------------------------------------------------*/
/*! \file channel.cpp
//
// FILENAME: channel.cpp
//
// DESCRIPTION: Implements member functions of Channel class.
//
// DEVELOPERS: Gregory W. Heckler (2003-2009)
//
// LICENSE TERMS: Copyright (c) Gregory W. Heckler 2009
//
// This file is part of the GPS Software Defined Radio (GPS-SDR)
//
// The GPS-SDR 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. The GPS-SDR 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.
//
// Note: Comments within this file follow a syntax that is compatible with
// DOXYGEN and are utilized for automated document extraction
//
// Reference:
*/
/*----------------------------------------------------------------------------------------------*/
#include "channel.h"
/*----------------------------------------------------------------------------------------------*/
Channel::Channel(int32 _chan):Threaded_Object("CHNTASK")
{
char fname[1024];
chan = _chan;
if(gopt.verbose)
fprintf(stdout,"Creating Channel %d\n",chan);
if(gopt.log_channel)
{
sprintf(fname,"chan%02d.dat",chan);
fp = fopen(fname, "wb");
}
pFFT = new FFT(FREQ_LOCK_POINTS);
Clear();
}
/*----------------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------------*/
Channel::~Channel()
{
delete pFFT;
if(gopt.log_channel)
fclose(fp);
if(gopt.verbose)
fprintf(stdout,"Destructing Channel %d\n",chan);
}
/*----------------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------------*/
void Channel::Clear()
{
/* Status info */
len = 1;
count = 0;
state = CHANNEL_EMPTY;
sv = 666;
/* Loop data */
memset(&aPLL, 0x0, sizeof(Phase_lock_loop));
memset(&aDLL, 0x0, sizeof(Delay_lock_loop));
/* Correlations */
I[0] = I[1] = I[2] = 1;
Q[0] = Q[1] = Q[2] = 1;
P[0] = P[1] = P[2] = 1;
I_prev = Q_prev = 1; //Important to prevent divide by zero
I_avg = 1;
Q_var = 1;
P_avg = 8e4;
cn0 = 40.0;
/* Bit lock stuff */
bit_lock = false;
bit_lock_pend = false;
bit_lock_ticks = 0;
I_sum20 = 0;
Q_sum20 = 0;
memset(&I_buff, 0x0, 20*sizeof(int32));
memset(&Q_buff, 0x0, 20*sizeof(int32));
memset(&P_buff, 0x0, 20*sizeof(int32));
_20ms_epoch = 0;
_1ms_epoch = 0;
best_epoch = 0;
/* Data message sheit */
memset(&valid_frame, 0x0, 5*sizeof(int32));
converged = false;
navigate = false;
z_lock = false;
frame_z = 0;
z_count = 0;
memset(&word_buff, 0x0, FRAME_SIZE_PLUS_2*sizeof(uint32));
/* Frame synch, process data bit sheit */
frame_lock = false;
frame_lock_pend = false;
bit_number = 0;
subframe = 0;
/* FFT and buffer for FFT estimate of frequency after initial lock */
freq_lock_ticks = 0;
freq_lock = false;
memset(&fft_buff[0], 0x0, FREQ_LOCK_POINTS*sizeof(CPX));
}
/*----------------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------------*/
void Channel::Start(int32 _sv, Acq_Command_S result, int32 _corr_len)
{
/* Clear out the channel */
Clear();
sv = _sv;
code_nco = CODE_RATE + result.doppler*CODE_RATE/L1;
carrier_nco = IF_FREQUENCY + result.doppler;
aDLL.x = 2.0*result.doppler*CODE_RATE/L1;
aPLL.w = 0;
aPLL.x = 2.0*result.doppler;
aPLL.z = result.doppler;
switch(_corr_len)
{
case 1:
len = 1;
PLL_W(18.0);
break;
case 20:
len = 20;
PLL_W(18.0);
break;
default:
len = 1;
PLL_W(18.0);
break;
}
DLL_W(1.0);
state = CHANNEL_NORMAL;
}
/*----------------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------------*/
Channel_M Channel::getPacket()
{
return(packet);
}
/*----------------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------------*/
void Channel::Accum(Correlation_S *corr, NCO_Command_S *_feedback)
{
corr->I[0] >>= 2;
corr->I[1] >>= 2;
corr->I[2] >>= 2;
corr->Q[0] >>= 2;
corr->Q[1] >>= 2;
corr->Q[2] >>= 2;
/* Integrate */
I[0] += corr->I[0];
I[1] += corr->I[1];
I[2] += corr->I[2];
Q[0] += corr->Q[0];
Q[1] += corr->Q[1];
Q[2] += corr->Q[2];
/* Always do these, a running sum of past 20 1ms accumulations */
I_sum20 += corr->I[1] - I_buff[_1ms_epoch];
Q_sum20 += corr->Q[1] - Q_buff[_1ms_epoch];
/* Buffer storing past 20 1ms accumulations */
I_buff[_1ms_epoch] = corr->I[1];
Q_buff[_1ms_epoch] = corr->Q[1];
if((I_buff[_1ms_epoch] > 0) != (I_buff[(_1ms_epoch + 19) % 20] > 0))
{
P_buff[_1ms_epoch]++;
}
/* Lowpass filter */
//P_buff[_1ms_epoch] = (63 * P_buff[_1ms_epoch] + (I_sum20 >> 6) * (I_sum20 >> 6) + (Q_sum20 >> 6)*(Q_sum20 >> 6) + 32) >> 6;
//P_buff[_1ms_epoch] = (63 * P_buff[_1ms_epoch] + (I_sum20 >> 6) * (I_sum20 >> 6) + 32) >> 6;
/* Dump accumulation and do tracking according to integration length */
if((_1ms_epoch % len) == 0)
{
Export();
DumpAccum();
}
/* These functions must be called every ms */
EstCN0();
BitLock();
BitStuff();
Epoch();
/* Kill the correlator if the channel has stopped itself */
if(state == CHANNEL_EMPTY)
_feedback->kill = true;
else
_feedback->kill = false;
/* copy over the updated NCO values */
_feedback->carrier_nco = carrier_nco;
_feedback->code_nco = code_nco;
/* send frame and bit lock resets */
if(bit_lock_pend && (_1ms_epoch == 0))
{
_feedback->reset_1ms = true;
bit_lock_pend = false;
}
else
_feedback->reset_1ms = false;
if(frame_lock_pend)
{
_feedback->reset_20ms = true;
frame_lock_pend = false;
}
else
_feedback->reset_20ms = false;
if(z_count_pend)
{
_feedback->set_z_count = 1;
_feedback->z_count = z_count;
z_count_pend = false;
}
else
_feedback->set_z_count = false;
if(converged)
{
navigate = true;
_feedback->navigate = navigate;
}
else
{
navigate = false;
_feedback->navigate = navigate;
}
}
/*----------------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------------*/
void Channel::DumpAccum()
{
/* Compute the powers */
P[0] = (I[0]) * (I[0]) + (Q[0]) * (Q[0]);
P[1] = (I[1]) * (I[1]) + (Q[1]) * (Q[1]);
P[2] = (I[2]) * (I[2]) + (Q[2]) * (Q[2]);
/* Lowpass filtered values here */
I_avg += (fabs((float)I[1]) - I_avg) * .02;
Q_var += ((float)Q[1]*(float)Q[1] - Q_var) * .02;
P_avg += ((float)P[1]/len - P_avg) * .02;
/* First do estimate of frequency offset via FFT */
if(freq_lock == false)
{
FrequencyLock();
}
else
{
PLL();
}
DLL();
/* Dump pertinent data */
Error();
/* Save Previous Correlations for Loops */
I_prev = I[1];
Q_prev = Q[1];
/* Zero out the correlations */
I[0] = I[1] = I[2] = 0;
Q[0] = Q[1] = Q[2] = 0;
}
/*----------------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------------*/
void Channel::EstCN0()
{
int32 lcv;
float NP;
float NBP;
float WBP;
float ncn0;
/* Try out new cn0 estimate, PG 393 of Global Positioning System, Theory and Applications */
if((_1ms_epoch == 19) && bit_lock)
{
NBP = I_sum20*I_sum20 + Q_sum20*Q_sum20;
WBP = 0;
for(lcv = 0; lcv < 20; lcv++)
WBP += I_buff[lcv]*I_buff[lcv] + Q_buff[lcv]*Q_buff[lcv];
if(WBP > 0.0)
NP = NBP/WBP;
ncn0 = 10*log10((NP - 1.0)/(20.0 - NP)) + 30.0 + .25;
if((NP - 1.0)/(20.0 - NP) > 0.0)
{
ncn0 = 10*log10((NP - 1.0)/(20.0 - NP)) + 30.0 + .25;
cn0 += (ncn0 - cn0)*.02;
}
if(cn0 < 15.0)
{
cn0 = 15.0;
}
}
}
/*----------------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------------*/
void Channel::FrequencyLock()
{
int32 it, qt;
int32 max, mind, lcv;
float df;
int32 *p;
it = I[1] >> 3;
qt = Q[1] >> 3;
/* First frequency double to remove data bits */
if(count > 1000)
{
fft_buff[freq_lock_ticks].i = (int16)(it*it - qt*qt);
fft_buff[freq_lock_ticks].q = (int16)(2*it*qt);
freq_lock_ticks++;
}
if(freq_lock_ticks >= FREQ_LOCK_POINTS)
{
p = (int32 *)&fft_buff[0];
/* Now do the FFT */
pFFT->doFFT(&fft_buff[0], true);
/* Convert to power */
x86_cmag(&fft_buff[0], FREQ_LOCK_POINTS);
/* Get peak */
max = mind = 0;
for(lcv = 0; lcv < FREQ_LOCK_POINTS; lcv++)
{
if(p[lcv] > max)
{
max = p[lcv];
mind = lcv;
}
}
/* Positive and negative frequency adjustment */
if(mind >= (FREQ_LOCK_POINTS/2))
mind -= FREQ_LOCK_POINTS;
/* Convert to frequency correction */
df = 1000.0/((float)2.0*len); // Bandwidth of FFT
df /= (float)FREQ_LOCK_POINTS; // Spacing of FFT bins
df *= (float)mind; // Convert to frequency offset
/* Update the loop filters */
aDLL.x += 2.0*df*CODE_RATE/L1;
aPLL.x += 2.0*df;
freq_lock = true;
freq_lock_ticks = 0;
}
}
/*----------------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------------*/
/*! Make this 2nd order ? */
void Channel::DLL()
{
float code_err;
float ep, lp, sp;
ep = sqrt(float(P[0]));
lp = sqrt(float(P[2]));
sp = sqrt(float(P_avg));
code_err = (ep - lp) / sp;
/* Not working too well right now, debug some later */
// aDLL.x += aDLL.t*(code_err*aDLL.w02);
// aDLL.z = 0.5*aDLL.x + aDLL.a*aDLL.w02*code_err;
// code_nco = CODE_RATE + (0.5*aPLL.x*CODE_RATE*INVERSE_L1) + aDLL.z;
if((count < 1000) && (P_avg < 8e4))
{
code_nco = CODE_RATE + (0.5 * aPLL.x * CODE_RATE * INVERSE_L1) - 5.0;
}
else
{
code_nco = CODE_RATE + (0.5 * aPLL.x * CODE_RATE * INVERSE_L1) + code_err;
}
}
/*----------------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------------*/
void Channel::PLL()
{
float df;
float dp;
float dot;
float cross;
int32 I1, I2, Q1, Q2, lcv;
df = dp = 0;
// if(bit_lock)
// {
// /* FLL discriminator */
// dot = I_prev*I[1] + Q_prev*Q[1];
// cross = I_prev*Q[1] - Q_prev*I[1];
//
// /* No FLL for now */
// if((dot != 0.0) && (cross != 0.0))
// {
// df = atan2(cross, dot);
// df /= (TWO_PI * aPLL.t);
// }
// }
// df = 0;
/* PLL discriminator */
if(I[1] != 0)
{
dp = atan((float)Q[1]/(float)I[1])/TWO_PI;
}
/* Lock indicators */
aPLL.pll_lock += (dp - aPLL.pll_lock) * .1;
aPLL.pll_lock = dp;
aPLL.fll_lock += (cross/P_avg - aPLL.fll_lock) * .1;
/* 3rd order PLL wioth 2nd order FLL assist */
aPLL.w += aPLL.t * (aPLL.w0p3 * dp + aPLL.w0f2 * df);
aPLL.x += aPLL.t * (0.5*aPLL.w + aPLL.a2 * aPLL.w0f * df + aPLL.a3 * aPLL.w0p2 * dp);
aPLL.z = 0.5*aPLL.x + aPLL.b3 * aPLL.w0p * dp;
carrier_nco = IF_FREQUENCY + aPLL.z;
}
/*----------------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------------*/
void Channel::Epoch()
{
_1ms_epoch++;
if(_1ms_epoch >= 20)
{
_1ms_epoch = 0;
_20ms_epoch++;
if(_20ms_epoch >= 300)
{
z_count += 6;
_20ms_epoch = 0;
}
}
count++;
}
/*----------------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------------*/
void Channel::BitLock()
{
int32 power_buff[20];
int32 lcv, new_epoch;
int32 thresh_high, thresh_low, bit_lock_err;
/* Set bitlock threshold */
thresh_high = 100;
thresh_low = 25;
if(_1ms_epoch == 19)
{
if(bit_lock == false)
{
/* Find the maximum of the power buffer */
bit_lock_err = 0; new_epoch = 0;
for(lcv = 0; lcv < 20; lcv++)
{
if(P_buff[lcv] > thresh_high)
{
bit_lock = true;
new_epoch = lcv;
}
if(P_buff[lcv] > thresh_low)
{
bit_lock_err++;
}
}
/* Bin counter exceeded threshold */
if(bit_lock == true)
{
best_epoch = 19;
bit_lock_pend = 1;
bit_lock_ticks = 0;
_1ms_epoch = (38 - new_epoch) % 20;
/* Copy over the power buffer to put the max in element 19 */
for(lcv = 0 ; lcv < 20; lcv++)
power_buff[lcv] = P_buff[lcv];
for(lcv = 0 ; lcv < 20; lcv++)
P_buff[lcv] = power_buff[(lcv + new_epoch + 1) % 20];
}
/* Bit lock failure, reset! */
if(bit_lock_err > 1)
{
best_epoch = 0;
bit_lock_ticks = 0;
bit_lock = false;
frame_lock = false;
for(lcv = 0 ; lcv < 20; lcv++)
P_buff[lcv] = 0;
}
}
else if(bit_lock_ticks < 60000) /* Bitlock obtained, keep monitoring it up to 1 minute */
{
/* Find the maximum of the power buffer */
bit_lock_err = 0; new_epoch = 0;
for(lcv = 0; lcv < 20; lcv++)
{
if(P_buff[lcv] > bit_lock_err)
{
bit_lock_err = P_buff[lcv];
new_epoch = lcv;
}
}
/* Best epoch not in the correct place! */
if(new_epoch != 19)
{
best_epoch = 0;
bit_lock_ticks = 0;
bit_lock = false;
frame_lock = false;
for(lcv = 0 ; lcv < 20; lcv++)
P_buff[lcv] = 0;
}
}
}
bit_lock_ticks++;
}
/*----------------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------------*/
void Channel::BitStuff()
{
uint32 lcv, temp_bit, feedbit;
if(bit_lock && (_1ms_epoch == 19))
{
/* Make a bit decision */
if(I_sum20 > 0)
temp_bit = 1;
else
temp_bit = 0;
/* Now add the bit into the buffer */
/* Each word in wordbuff is composed of:
Bits 0 to 29 = the GPS data word
Bits 30 to 31 = 2 LSBs of the GPS word ahead. */
for(lcv = 0; lcv <= (FRAME_SIZE_PLUS_2-2); lcv++)
{
/* Shift the data word 1 place to the left. */
word_buff[lcv] <<= 1;
/* Add the MSB of the following GPS word (bit 29 of a wordbuff word). */
feedbit = (word_buff[lcv+1] >> 29) & 0x00000001;
word_buff[lcv] += feedbit;
}
/* The bit added for the 12th word is the new data bit. */
word_buff[FRAME_SIZE_PLUS_2-1] <<= 1;
word_buff[FRAME_SIZE_PLUS_2-1] += temp_bit;
ProcessDataBit();
}
}
/*----------------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------------*/
void Channel::ProcessDataBit()
{
int32 sid, lcv;
uint32 word0, word1;
/* Else attempt frame sync. */
if(!frame_lock)
{
word0 = word_buff[FRAME_SIZE_PLUS_2-2];
word1 = word_buff[FRAME_SIZE_PLUS_2-1];
if(FrameSync(word0, word1))
{
frame_lock = true;
frame_lock_pend = 1;
bit_number = 299;
_20ms_epoch = 60;
}
}
if(frame_lock)
{
bit_number = (bit_number + 1) % 300;
if(bit_number == 0)
{
memcpy(&ephem_packet.word_buff[0], word_buff, FRAME_SIZE_PLUS_2*sizeof(uint32));
if(ValidFrameFormat(&ephem_packet.word_buff[0]))
{
sid = (int32)((ephem_packet.word_buff[1] >> 8) & 0x00000007);
frame_z = 4*((ephem_packet.word_buff[1] >> 13) & 0x0001FFFF);
if((sid > 0) && (sid < 6))
{
subframe = sid;
valid_frame[sid-1] = true;
ephem_packet.subframe = subframe;
ephem_packet.sv = sv;
write(CHN_2_EPH_P[WRITE], &ephem_packet, sizeof(Channel_2_Ephemeris_S));
if(!z_lock)
{
z_count_pend = true;
z_count = 3*frame_z/2;
z_lock = true;
navigate = true;
converged = true;
}
}
else
{
subframe = 0;
valid_frame[0] = valid_frame[1] = valid_frame[2] = valid_frame[3] = valid_frame[4] = false;
frame_lock = false;
}
} //end valid subframe
else
{
subframe = 0;
valid_frame[0] = valid_frame[1] = valid_frame[2] = valid_frame[3] = valid_frame[4] = false;
frame_lock = false;
}
} //end if bit_number = 300;
}
}
/*----------------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------------*/
bool Channel::FrameSync(uint32 word0, uint32 word1)
{
uint32 preamble; /* The TLM word preamble sequence 10001011. */
uint32 sid; /* The subframe ID (1 to 5). */
uint32 zerobits; /* The zero bits (the last 2 bits of word 2). */
/* Extract the preamble. */
preamble = (word0 >> 22) & 0x000000FF;
/* Extract the subframe ID. */
sid = (word1 >> 8) & 0x00000007;
/* Extract the zero bits. */
zerobits = word1 & 0x00000003;
/* Invert the extracted data according to bit 30 of the previous word. */
if (word0 & 0x40000000)
{
preamble ^= 0x000000FF;
zerobits ^= 0x00000003;
}
if (word1 & 0x40000000)
sid ^= 0x00000007;
/* Check that the preamble, subframe and zero bits are ok. */
if(preamble != PREAMBLE)
return false;
/* Check if the subframe ID is ok. */
if(sid < 1 || sid > 5)
return false;
/* Check that the zero bits are ok. */
if(zerobits!=0)
return false;
/* Check that the 2 most recently logged words pass parity. Have to first
invert the data bits according to bit 30 of the previous word. */
if(word0 & 0x40000000)
word0 ^= 0x3FFFFFC0;
if(word1 & 0x40000000)
word1 ^= 0x3FFFFFC0;
if(!this->ParityCheck(word0) || !this->ParityCheck(word1))
return false;
return true;
}
/*----------------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------------*/
bool Channel::ParityCheck(uint32 gpsword)
{
uint32 d1,d2,d3,d4,d5,d6,d7,t,parity;
/* XOR as many bits in parallel as possible. The magic constants pick
up bits which are to be XOR'ed together to implement the GPS parity
check algorithm described in ICD-GPS-200. This avoids lengthy shift-
and-xor loops. */
d1 = gpsword & 0xFBFFBF00;
d2 = _lrotl(gpsword,1) & 0x07FFBF01;
d3 = _lrotl(gpsword,2) & 0xFC0F8100;
d4 = _lrotl(gpsword,3) & 0xF81FFE02;
d5 = _lrotl(gpsword,4) & 0xFC00000E;
d6 = _lrotl(gpsword,5) & 0x07F00001;
d7 = _lrotl(gpsword,6) & 0x00003000;
t = d1 ^ d2 ^ d3 ^ d4 ^ d5 ^ d6 ^ d7;
// Now XOR the 5 6-bit fields together to produce the 6-bit final result.
parity = t ^ _lrotl(t,6) ^ _lrotl(t,12) ^ _lrotl(t,18) ^ _lrotl(t,24);
parity = parity & 0x3F;
if (parity == (gpsword&0x3F))
return(true);
else
return(false);
}
/*----------------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------------*/
bool Channel::ValidFrameFormat(uint32 *subframe)
{
uint32 preamble,next_preamble;
uint32 zerobits,next_zerobits;
uint32 sid,next_sid;
uint32 wordcounter;
uint32 parity_errors;
/* Extract the preamble. */
preamble = (subframe[0] >> 22) & 0x000000FF;
/* Extract the subframe ID. */
sid = (subframe[1] >> 8) & 0x00000007;
/* Extract the zero bits. */
zerobits = subframe[1] & 0x00000003;
/* Invert the extracted data according to bit 30 of the previous word. */
if(subframe[0] & 0x40000000)
{
preamble ^= 0x000000FF;
zerobits ^= 0x00000003;
}
if(subframe[1] & 0x40000000)
sid ^= 0x00000007;
/* Check that the preamble, subframe and zero bits are ok. */
if(preamble != PREAMBLE)
return(false);
if(sid < 1 || sid > 5)
return(false);
if(zerobits != 0)
return(false);
/* Extract the next preamble (10001011). */
next_preamble = (subframe[FRAME_SIZE_PLUS_2-2] >> 22) & 0x000000FF;
/* Extract the next subframe ID. */
next_sid = (subframe[FRAME_SIZE_PLUS_2-1] >> 8) & 0x00000007;
/* Extract the next zero bits. */
next_zerobits = (subframe[FRAME_SIZE_PLUS_2-1] & 0x00000003);
/* Invert the extracted data according to bit 30 of the previous word. */
if(subframe[FRAME_SIZE_PLUS_2-2] & 0x40000000)
{
next_preamble ^= 0x000000FF;
next_zerobits ^= 0x00000003;
}
if(subframe[FRAME_SIZE_PLUS_2-1] & 0x40000000)
next_sid ^= 0x00000007;
/* Check that the preamble, subframe and zero bits are ok. */
if(next_preamble != PREAMBLE)
return(false);
if(next_sid < 1 || next_sid > 5)
return(false);
if(next_zerobits != 0)
return(false);
/* Check that the subframe IDs are consistent. */
if((next_sid-sid) != 1 && (next_sid-sid) != -4)
return(false);
/* Check that all 12 words have correct parity. Have to first
invert the data bits according to bit 30 of the previous word. */
parity_errors = 0;
for(wordcounter = 0; wordcounter < FRAME_SIZE_PLUS_2; wordcounter++)
if (subframe[wordcounter] & 0x40000000)
subframe[wordcounter] ^= 0x3FFFFFC0;
for(wordcounter = 0; wordcounter < FRAME_SIZE_PLUS_2; wordcounter++)
if (!this->ParityCheck(subframe[wordcounter]))
parity_errors++;
if(parity_errors != 0)
return(false);
return(true);
}
/*----------------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------------*/
void Channel::PLL_W(float _bwpll)
{
aPLL.PLLBW = _bwpll;
aPLL.FLLBW = 4.0;
aPLL.b3 = 2.40;
aPLL.a3 = 1.10;
aPLL.a2 = 1.414;
aPLL.w0p = aPLL.PLLBW/0.7845;
aPLL.w0p2 = aPLL.w0p*aPLL.w0p;
aPLL.w0p3 = aPLL.w0p2*aPLL.w0p;
aPLL.w0f = aPLL.FLLBW/0.53;
aPLL.w0f2 = aPLL.w0f*aPLL.w0f;
aPLL.gain = 1.0;
aPLL.t = .001*(float)len;
}
/*----------------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------------*/
void Channel::DLL_W(float _bwdll)
{
aDLL.DLLBW = _bwdll;
aDLL.a = 1.414;
aDLL.w0 = aDLL.DLLBW/0.7845;
aDLL.w02 = aDLL.w0*aDLL.w0;
aDLL.t = .001*(float)len;
}
/*----------------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------------*/
void Channel::Error()
{
/* Monitor DLL */
if((P_avg < 8e4) && (count > 1000))
Kill();
/* Monitor cn0 for false PLL lock */
if((count == 15000) && (bit_lock == false) && (freq_lock == true))
{
freq_lock_ticks = 0;
freq_lock = false;
}
/* If 30 seconds have passed and channel has not converged dump it */
if((count > 30000) && (converged == false))
Kill();
/* The channel should be killed if the nco goes outside the pre generated wipeoff table */
if(fabs(carrier_nco-IF_FREQUENCY) > CARRIER_BINS*CARRIER_SPACING)
Kill();
/* Adjust integration length based on cn0 */
if(bit_lock)
{
if((cn0 > 39.0) && (len != 1))
{
len = 1;
PLL_W(18.0);
}
if((cn0 < 37.0) && (len != 20))
{
len = 20;
PLL_W(18.0);
}
}
}
/*----------------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------------*/
void Channel::Kill()
{
state = CHANNEL_EMPTY;
Clear();
}
/*----------------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------------*/
void Channel::Export()
{
int32 bwrote;
packet.chan = chan;
packet.state = state;
packet.sv = sv;
packet.antenna = antenna;
packet.len = len;
packet.w = aPLL.w;
packet.x = aPLL.x;
packet.z = aPLL.z;
packet.cn0 = cn0;
packet.p_avg = P_avg;
packet.bit_lock = bit_lock;
packet.frame_lock = frame_lock;
packet.navigate = navigate;
packet.count = count;
packet.subframe = subframe;
packet.best_epoch = best_epoch;
packet.code_nco = code_nco;
packet.carrier_nco = carrier_nco;
/* Dump the extra info */
if(gopt.log_channel && (fp != NULL))
{
fwrite(&packet, sizeof(Channel_M), 1, fp);
fwrite(&I[0], sizeof(int32), 3, fp);
fwrite(&Q[0], sizeof(int32), 3, fp);
fwrite(&P_buff[0], sizeof(int32), 20, fp);
}
}
/*----------------------------------------------------------------------------------------------*/
| [
"gheckler@mesa3081994.(none)",
"gheckler@core2duo.(none)",
"gheckler@gs-mesa3079963w.(none)",
"gheckler@gs-mesa3079693.(none)",
"gpssim@gpsdevc.(none)",
"[email protected]"
]
| [
[
[
1,
24
],
[
26,
26
],
[
31,
31
],
[
77,
77
],
[
133,
133
],
[
166,
168
],
[
231,
231
],
[
330,
330
],
[
350,
350
],
[
352,
352
],
[
698,
698
],
[
954,
954
],
[
962,
962
],
[
969,
969
],
[
992,
992
],
[
1004,
1021
]
],
[
[
25,
25
],
[
27,
30
],
[
32,
33
],
[
35,
35
],
[
37,
37
],
[
40,
46
],
[
48,
56
],
[
58,
58
],
[
60,
61
],
[
63,
63
],
[
65,
72
],
[
74,
75
],
[
78,
82
],
[
84,
90
],
[
94,
114
],
[
116,
120
],
[
122,
123
],
[
125,
126
],
[
128,
132
],
[
134,
134
],
[
136,
141
],
[
147,
147
],
[
151,
151
],
[
154,
155
],
[
158,
159
],
[
163,
163
],
[
165,
165
],
[
169,
173
],
[
175,
183
],
[
192,
194
],
[
196,
197
],
[
199,
206
],
[
213,
213
],
[
217,
217
],
[
219,
219
],
[
221,
224
],
[
226,
228
],
[
233,
235
],
[
237,
238
],
[
240,
255
],
[
257,
264
],
[
269,
269
],
[
271,
271
],
[
276,
284
],
[
288,
288
],
[
294,
303
],
[
329,
329
],
[
332,
334
],
[
336,
336
],
[
339,
339
],
[
344,
344
],
[
351,
351
],
[
353,
354
],
[
356,
362
],
[
364,
367
],
[
371,
371
],
[
380,
383
],
[
385,
386
],
[
388,
389
],
[
391,
400
],
[
402,
404
],
[
406,
409
],
[
413,
413
],
[
415,
424
],
[
437,
438
],
[
449,
455
],
[
457,
460
],
[
463,
464
],
[
481,
488
],
[
490,
495
],
[
497,
511
],
[
513,
518
],
[
521,
528
],
[
531,
532
],
[
537,
537
],
[
539,
540
],
[
542,
543
],
[
545,
545
],
[
547,
549
],
[
554,
555
],
[
558,
558
],
[
560,
561
],
[
563,
568
],
[
606,
610
],
[
612,
621
],
[
623,
623
],
[
625,
629
],
[
633,
633
],
[
635,
650
],
[
652,
658
],
[
660,
661
],
[
663,
665
],
[
668,
675
],
[
678,
689
],
[
691,
696
],
[
700,
704
],
[
706,
707
],
[
709,
725
],
[
728,
768
],
[
770,
805
],
[
807,
812
],
[
814,
825
],
[
828,
842
],
[
844,
858
],
[
860,
871
],
[
873,
889
],
[
891,
896
],
[
898,
900
],
[
902,
903
],
[
905,
910
],
[
912,
912
],
[
917,
926
],
[
939,
939
],
[
942,
948
],
[
950,
950
],
[
953,
953
],
[
965,
965
],
[
985,
989
],
[
991,
991
],
[
993,
1000
],
[
1002,
1002
],
[
1024,
1024
],
[
1031,
1033
]
],
[
[
34,
34
],
[
36,
36
],
[
39,
39
],
[
47,
47
],
[
57,
57
],
[
59,
59
],
[
62,
62
],
[
73,
73
],
[
76,
76
],
[
83,
83
],
[
93,
93
],
[
115,
115
],
[
121,
121
],
[
127,
127
],
[
135,
135
],
[
142,
142
],
[
148,
148
],
[
150,
150
],
[
164,
164
],
[
174,
174
],
[
184,
184
],
[
191,
191
],
[
195,
195
],
[
198,
198
],
[
207,
207
],
[
216,
216
],
[
220,
220
],
[
230,
230
],
[
232,
232
],
[
236,
236
],
[
239,
239
],
[
256,
256
],
[
265,
265
],
[
335,
335
],
[
337,
338
],
[
343,
343
],
[
349,
349
],
[
355,
355
],
[
363,
363
],
[
368,
368
],
[
372,
372
],
[
379,
379
],
[
384,
384
],
[
387,
387
],
[
390,
390
],
[
401,
401
],
[
405,
405
],
[
410,
410
],
[
414,
414
],
[
425,
426
],
[
429,
429
],
[
431,
431
],
[
433,
433
],
[
435,
436
],
[
456,
456
],
[
462,
462
],
[
480,
480
],
[
496,
496
],
[
512,
512
],
[
519,
520
],
[
535,
535
],
[
624,
624
],
[
630,
632
],
[
634,
634
],
[
651,
651
],
[
659,
659
],
[
662,
662
],
[
666,
667
],
[
676,
677
],
[
690,
690
],
[
697,
697
],
[
699,
699
],
[
705,
705
],
[
708,
708
],
[
726,
727
],
[
769,
769
],
[
806,
806
],
[
813,
813
],
[
826,
827
],
[
843,
843
],
[
859,
859
],
[
872,
872
],
[
890,
890
],
[
897,
897
],
[
901,
901
],
[
904,
904
],
[
913,
913
],
[
916,
916
],
[
927,
927
],
[
935,
935
],
[
941,
941
],
[
949,
949
],
[
952,
952
],
[
960,
960
],
[
963,
964
],
[
967,
968
],
[
984,
984
],
[
990,
990
],
[
1001,
1001
],
[
1003,
1003
],
[
1022,
1022
],
[
1026,
1026
]
],
[
[
38,
38
],
[
64,
64
],
[
92,
92
],
[
124,
124
],
[
225,
225
],
[
266,
268
],
[
270,
270
],
[
272,
275
],
[
289,
291
],
[
293,
293
],
[
306,
324
],
[
326,
327
],
[
331,
331
],
[
538,
538
],
[
581,
581
],
[
583,
586
],
[
588,
589
],
[
591,
591
],
[
593,
597
],
[
599,
599
],
[
601,
605
],
[
622,
622
],
[
970,
971
],
[
977,
977
],
[
979,
980
],
[
982,
983
],
[
1023,
1023
],
[
1025,
1025
],
[
1027,
1030
]
],
[
[
91,
91
],
[
144,
145
],
[
149,
149
],
[
152,
153
],
[
156,
157
],
[
160,
162
],
[
185,
190
],
[
208,
212
],
[
214,
215
],
[
285,
287
],
[
292,
292
],
[
304,
305
],
[
325,
325
],
[
328,
328
],
[
340,
342
],
[
345,
348
],
[
373,
378
],
[
428,
428
],
[
432,
432
],
[
434,
434
],
[
439,
448
],
[
461,
461
],
[
465,
479
],
[
529,
530
],
[
533,
534
],
[
536,
536
],
[
541,
541
],
[
544,
544
],
[
546,
546
],
[
550,
553
],
[
556,
557
],
[
559,
559
],
[
562,
562
],
[
569,
580
],
[
582,
582
],
[
587,
587
],
[
590,
590
],
[
592,
592
],
[
598,
598
],
[
600,
600
],
[
611,
611
],
[
915,
915
],
[
929,
929
],
[
932,
932
],
[
951,
951
],
[
955,
959
],
[
972,
976
],
[
978,
978
],
[
981,
981
]
],
[
[
143,
143
],
[
146,
146
],
[
218,
218
],
[
229,
229
],
[
369,
370
],
[
411,
412
],
[
427,
427
],
[
430,
430
],
[
489,
489
],
[
911,
911
],
[
914,
914
],
[
928,
928
],
[
930,
931
],
[
933,
934
],
[
936,
938
],
[
940,
940
],
[
961,
961
],
[
966,
966
]
]
]
|
e1f9354a3d8b3b7654696ed170d26593a53cd1d2 | 208475bcab65438eed5d8380f26eacd25eb58f70 | /QianExe/LN_Socket.cpp | 80b0aa54a0610fbf6cbcbe1fe2798eccc369348d | []
| no_license | awzhang/MyWork | 83b3f0b9df5ff37330c0e976310d75593f806ec4 | 075ad5d0726c793a0c08f9158080a144e0bb5ea5 | refs/heads/master | 2021-01-18T07:57:03.219372 | 2011-07-05T02:41:55 | 2011-07-05T02:46:30 | 15,523,223 | 1 | 2 | null | null | null | null | GB18030 | C++ | false | false | 4,626 | cpp | #include "yx_QianStdAfx.h"
#undef MSG_HEAD
#define MSG_HEAD ("QianExe-Socket ")
void *G_ThreadSocketSend()
{
g_objSocket.P_ThreadSend();
}
void *G_ThreadSocketRecv()
{
g_objSocket.P_ThreadRecv();
}
//////////////////////////////////////////////////////////////////////////
CLN_Socket::CLN_Socket()
{
m_sockUdp = -1;
m_pthreadSend = m_pthreadRecv = 0;
m_bInit = false;
m_objSendMng.InitCfg(100*1024, 10000);
}
CLN_Socket::~CLN_Socket()
{
}
int CLN_Socket::Init()
{
if( pthread_create( &m_pthreadSend, NULL, G_ThreadSocketSend, NULL )
||
pthread_create( &m_pthreadRecv, NULL, G_ThreadSocketRecv, NULL ) )
{
PRTMSG(MSG_ERR, "Create socket send/recv thread failed\n");
perror("");
return ERR_THREAD;
}
return 0;
}
void CLN_Socket::Release()
{
if( -1 != m_sockUdp )
{
shutdown( m_sockUdp, 2 ); //参数2表示终止读取及传送操作
close( m_sockUdp );
m_sockUdp = -1;
}
}
int CLN_Socket::CreateSock()
{
int iRet = 0;
BOOL blVal;
int iVal;
LINGER ling;
SOCKADDR_IN localaddr;
unsigned long ulIP = INADDR_ANY;
tag1QIpCfg obj1QIpCfg;
if( GetImpCfg( (void*)&obj1QIpCfg, sizeof(obj1QIpCfg), offsetof(tagImportantCfg, m_uni1QComuCfg.m_ary1QIpCfg), sizeof(obj1QIpCfg) ) )
return ERR_READCFGFAILED;
m_ulIp = obj1QIpCfg.m_ulDvrUdpIP;
m_usPort = obj1QIpCfg.m_usDvrUdpPort;
DetroySock();
m_sockUdp = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP );
if( -1 == m_sockUdp )
{
iRet = ERR_SOCK;
return iRet;
}
localaddr.sin_family = AF_INET;
localaddr.sin_port = htons(DVR_UDP_LOCAL_PROT);
localaddr.sin_addr.s_addr = ulIP;
if( bind( m_sockUdp, (SOCKADDR*)&localaddr, sizeof(localaddr) ) )
{
return ERR_SOCK;
}
ling.l_onoff = 1; // 强制关闭且立即释放资源
ling.l_linger = 0;
setsockopt( m_sockUdp, SOL_SOCKET, SO_LINGER, (char*)&ling, sizeof(ling) );
blVal = FALSE; // 禁止带外数据
setsockopt( m_sockUdp, SOL_SOCKET, SO_OOBINLINE, (char*)&blVal, sizeof(blVal) );
iVal = UDP_RECVSIZE;
setsockopt( m_sockUdp, SOL_SOCKET, SO_RCVBUF, (char*)&iVal, sizeof(iVal) );
iVal = UDP_SENDSIZE;
setsockopt( m_sockUdp, SOL_SOCKET, SO_SNDBUF, (char*)&iVal, sizeof(iVal) );
m_bInit = true;
// 通知应用层,套接字已初始化
return 0;
}
int CLN_Socket::DetroySock()
{
if( -1 != m_sockUdp )
{
shutdown( m_sockUdp, 2 );
close( m_sockUdp );
m_sockUdp = -1;
}
m_bInit = false;
}
// 发送UDP队列中的数据
void CLN_Socket::P_ThreadSend()
{
char szSendBuf[ UDP_SENDSIZE ] = {0};
DWORD dwSendLen = 0;
int iResult;
BYTE bytLvl;
BYTE bytSymb = 0;
DWORD dwPushTm = 0;
struct sockaddr_in adrTo;
int iPack = 0;
int iBytes = 0;
while(!g_bProgExit)
{
if(!m_bInit)
{
usleep(20000);
continue;
}
iResult = m_objSendMng.PopData( bytLvl, sizeof(szSendBuf), dwSendLen, szSendBuf, dwPushTm, &bytSymb);
if( iResult )
{
usleep(20000);
continue;
}
if( !dwSendLen || dwSendLen > sizeof(szSendBuf) )
continue;
adrTo.sin_family = AF_INET;
adrTo.sin_port = m_usPort;
adrTo.sin_addr.s_addr = m_ulIp;
iResult = sendto( m_sockUdp, szSendBuf, int(dwSendLen), 0, (struct sockaddr*)&adrTo, sizeof(adrTo) );
if( iResult < 0 )
{
PRTMSG(MSG_ERR, "Udp Send Fail\n");
perror("");
// 发送出错,通知应用层
// 销毁套接字
DetroySock();
continue;
}
else
{
PRTMSG(MSG_DBG, "socket send:");
PrintString(szSendBuf, iResult);
}
#if NETWORK_TYPE == NETWORK_EVDO
usleep(20000);
#elif NETWORK_TYPE == NETWORK_TD
usleep(60000);
#else
usleep(200000);
#endif
}
}
void CLN_Socket::P_ThreadRecv()
{
int iResult;
char buf[ UDP_RECVSIZE ];
struct sockaddr_in addrFrom;
int iLen = sizeof(addrFrom);
while(!g_bProgExit)
{
if(!m_bInit)
{
usleep(20000);
continue;
}
iResult = recvfrom( m_sockUdp, buf, sizeof(buf), 0, (struct sockaddr*)&addrFrom, (socklen_t*)&iLen );
if( iResult > 0 )
{
PRTMSG(MSG_NOR, "socket recv: ");
PrintString(buf, iResult);
// 接收的数据调用网络层的数据处理接口
g_objNetWork.DealSocketData(buf, iResult);
}
else if( iResult < 0 )
{
PRTMSG(MSG_ERR, "Udp Read Err\n" );
perror("");
// 接收出错,通知应用层
// 销毁套接字
DetroySock();
continue;
}
}
}
bool CLN_Socket::SetIPandPort(unsigned long v_ulIp, unsigned short v_usPort)
{
m_ulIp = v_ulIp;
m_usPort = v_usPort;
}
| [
"[email protected]"
]
| [
[
[
1,
227
]
]
]
|
71ed6a0284397f691dd58693a161a1b67d026cd2 | 7acbb1c1941bd6edae0a4217eb5d3513929324c0 | /GLibrary-CPP/sources/GError.h | 12e9dc401953b40c68dd81132f96f2ac3f298931 | []
| no_license | hungconcon/geofreylibrary | a5bfc96e0602298b5a7b53d4afe7395a993498f1 | 3abf3e1c31a245a79fa26b4bcf2e6e86fa258e4d | refs/heads/master | 2021-01-10T10:11:51.535513 | 2009-11-30T15:29:34 | 2009-11-30T15:29:34 | 46,771,895 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 165 | h | #ifndef __GERROR_H__
# define __GERROR_H__
#include "GOStream.h"
#include "GExport.h"
class GEXPORTED GError : public GOStream
{
public:
};
#endif
| [
"mvoirgard@34e8d5ee-a372-11de-889f-a79cef5dd62c"
]
| [
[
[
1,
13
]
]
]
|
410b1a881607389b00630f631b89152d4dca4730 | 6e563096253fe45a51956dde69e96c73c5ed3c18 | /dhnetsdk/Demo/DevMgr.cpp | c87b2e6648e673ba4c64bf105296c193a6fbc369 | []
| no_license | 15831944/phoebemail | 0931b76a5c52324669f902176c8477e3bd69f9b1 | e10140c36153aa00d0251f94bde576c16cab61bd | refs/heads/master | 2023-03-16T00:47:40.484758 | 2010-10-11T02:31:02 | 2010-10-11T02:31:02 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 9,577 | cpp | // DevMgr.cpp: implementation of the CDevMgr class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "netsdkdemo.h"
#include "DevMgr.h"
#include <algorithm>
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Get CDevMgr object
//////////////////////////////////////////////////////////////////////
CDevMgr& CDevMgr::GetDevMgr(void)
{
static CDevMgr devmgr;
return devmgr;
}
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CDevMgr::CDevMgr()
{
::InitializeCriticalSection(&m_csDev);
::InitializeCriticalSection(&m_csAlarm);
::InitializeCriticalSection(&m_csAlmList);
}
CDevMgr::~CDevMgr()
{
list<DeviceNode*>::iterator it = m_lstDevice.begin();
for(; it != m_lstDevice.end(); ++it)
{
if (*it)
{
delete (*it);
}
}
list<AlarmNode*>::iterator it2 = m_lstAlarm.begin();
for(; it2 != m_lstAlarm.end(); ++it2)
{
if (*it2)
{
delete (*it2);
}
}
m_lstDevice.clear();
m_lstAlarm.clear();
::DeleteCriticalSection(&m_csDev);
::DeleteCriticalSection(&m_csAlarm);
::DeleteCriticalSection(&m_csAlmList);
}
void CDevMgr::For_EachDev(int (* cbForEach)(const DeviceNode& node, DWORD dwUser), DWORD dwUser)
{
::EnterCriticalSection(&m_csDev);
list<DeviceNode*>::iterator it = m_lstDevice.begin();
for(; it != m_lstDevice.end(); ++it)
{
int nRet = cbForEach(**it, dwUser);
if (1 == nRet)
{
break;
}
}
::LeaveCriticalSection(&m_csDev);
}
void CDevMgr::For_EachAlmNode(int (* cbForEachAlm)(const AlarmNode& node, DWORD dwUser), DWORD dwUser)
{
::EnterCriticalSection(&m_csAlmList);
list<AlarmNode*>::iterator it = m_lstAlarm.begin();
for(; it != m_lstAlarm.end(); ++it)
{
int nRet = cbForEachAlm(**it, dwUser);
if (1 == nRet)
{
break;
}
}
list<AlarmNode*>::iterator itdel = m_lstAlarm.begin();
while(itdel != it)
{
if (*itdel)
{
delete (*itdel);
m_lstAlarm.erase(itdel++);
}
}
::LeaveCriticalSection(&m_csAlmList);
}
int CDevMgr::GetDev(LONG lLoginID, DeviceNode& node)
{
int nRet = -1;
::EnterCriticalSection(&m_csDev);
list<DeviceNode*>::iterator it =
find_if(m_lstDevice.begin(), m_lstDevice.end(),
CDevMgr::SearchDevByHandle(lLoginID));
if (it != m_lstDevice.end())
{
memcpy(&node, *it, sizeof(DeviceNode));
nRet = 0;
}
::LeaveCriticalSection(&m_csDev);
return nRet;
}
int CDevMgr::SetAlarmInfo(LONG lLoginID, LONG lCommand, char *pchDVRIP, LONG nDVRPort,
char *pBuf, DWORD dwBufLen)
{
int nRet = 0;
::EnterCriticalSection(&m_csAlarm);
list<DeviceNode*>::iterator it =
find_if(m_lstDevice.begin(), m_lstDevice.end(),
CDevMgr::SearchDevByHandle(lLoginID));
AlarmNode *thisNode = new AlarmNode;
if (!thisNode)
{
return -1;
}
memset(thisNode, 0, sizeof(AlarmNode));
thisNode->timeStamp = CTime::GetCurrentTime();
if (it != m_lstDevice.end())
{
thisNode->alarmType = lCommand;
switch(lCommand)
{
case COMM_ALARM:
{
if (dwBufLen != sizeof(NET_CLIENT_STATE))
{
nRet = -1;
break;
}
NET_CLIENT_STATE *State = (NET_CLIENT_STATE *)pBuf;
if(!State)
{
nRet = -1;
break;
}
//设备列表中信息刷新
(*it)->State.cState.channelcount = State->channelcount;
(*it)->State.cState.alarminputcount = State->alarminputcount;
memcpy((*it)->State.cState.alarm, State->alarm, 16);
memcpy((*it)->State.cState.motiondection, State->motiondection, 16);
memcpy((*it)->State.cState.videolost, State->videolost, 16);
thisNode->alarmType = COMM_ALARM;
memcpy(&thisNode->state, &(*it)->State, sizeof(DEV_STATE));
nRet = 0;
break;
}
case SHELTER_ALARM:
{
if (dwBufLen != 16)
{
nRet = -1;
break;
}
memcpy((*it)->State.shelter, pBuf, 16);
thisNode->alarmType = SHELTER_ALARM;
memcpy(&thisNode->state, &(*it)->State, sizeof(DEV_STATE));
nRet = 0;
break;
}
case DISK_FULL_ALARM:
{
if (dwBufLen != sizeof(DWORD))
{
nRet = -1;
break;
}
(*it)->State.dFull = *(DWORD*)pBuf;
thisNode->alarmType = DISK_FULL_ALARM;
memcpy(&thisNode->state, &(*it)->State, sizeof(DEV_STATE));
nRet = 0;
break;
}
case DISK_ERROR_ALARM:
{
if (dwBufLen != sizeof(DWORD))
{
nRet = -1;
break;
}
(*it)->State.dError = *(DWORD*)pBuf;
thisNode->alarmType = DISK_ERROR_ALARM;
memcpy(&thisNode->state, &(*it)->State, sizeof(DEV_STATE));
nRet = 0;
break;
}
case SOUND_DETECT_ALARM:
{
if (dwBufLen != 16)
{
nRet = -1;
break;
}
memcpy((*it)->State.soundalarm, pBuf, 16);
thisNode->alarmType = SOUND_DETECT_ALARM;
memcpy(&thisNode->state, &(*it)->State, sizeof(DEV_STATE));
nRet = 0;
break;
}
case ALARM_DECODER_ALARM_EX:
{
if (dwBufLen != 16)
{
nRet = -1;
break;
}
memcpy((*it)->State.almDecoder, pBuf, 16);
thisNode->alarmType = ALARM_DECODER_ALARM_EX;
memcpy(&thisNode->state, &(*it)->State, sizeof(DEV_STATE));
nRet = 0;
}
break;
case POS_TICKET_ALARM:
{
memcpy((*it)->State.PosTicket, pBuf, 1024);
thisNode->alarmType = POS_TICKET_ALARM;
memcpy(&thisNode->state, &(*it)->State, sizeof(DEV_STATE));
nRet = 0;
}
break;
case POS_TICKET_RAWDATA:
{
memcpy((*it)->State.PosTicketRawData, pBuf, 1024);
thisNode->alarmType = POS_TICKET_RAWDATA;
memcpy(&thisNode->state, &(*it)->State, sizeof(DEV_STATE));
nRet = 0;
}
break;
case REBOOT_EVENT_EX:
{
AfxMessageBox(ConvertString("Reboot?(y/n)"));
}
break;
/*
//以下针对新的报警接口
case ALARM_ALARM_EX:
if (dwBufLen != 16)
{
break;
}
memcpy((*it)->State.alarmout, pBuf, 16);
break;
case MOTION_ALARM_EX:
if (dwBufLen != 16)
{
break;
}
memcpy((*it)->State.motion, pBuf, 16);
break;
case VIDEOLOST_ALARM_EX:
if (dwBufLen != 16)
{
break;
}
memcpy((*it)->State.videolost, pBuf, 16);
break;
case SHELTER_ALARM_EX:
if (dwBufLen != 16)
{
break;
}
memcpy((*it)->State.shelter, pBuf, 16);
break;
case SOUND_DETECT_ALARM_EX:
if (dwBufLen != 16)
{
break;
}
memcpy((*it)->State.soundalarm, pBuf, 16);
break;
case DISKFULL_ALARM_EX:
if (dwBufLen != 1)
{
break;
}
(*it)->State.diskfull = *pBuf;
break;
case DISKERROR_ALARM_EX:
if (dwBufLen != 32)
{
break;
}
memcpy((*it)->State.diskerror, pBuf, 32);
break;
*/
default:
nRet = -1;
break;
}
memcpy(&thisNode->state, &(*it)->State, sizeof(DEV_STATE));
}
::LeaveCriticalSection(&m_csAlarm);
if (nRet >= 0)
{
::EnterCriticalSection(&m_csAlmList);
m_lstAlarm.push_back(thisNode);
::LeaveCriticalSection(&m_csAlmList);
}
else
{
delete thisNode;
}
return nRet;
}
int CDevMgr::GetAlarmInfo(LONG lLoginID, DEV_STATE *des)
{
int nRet = -1;
::EnterCriticalSection(&m_csAlarm);
list<DeviceNode*>::iterator it =
find_if(m_lstDevice.begin(), m_lstDevice.end(),
CDevMgr::SearchDevByHandle(lLoginID));
if (it != m_lstDevice.end())
{
memcpy(des, &(*it)->State, sizeof(DEV_STATE));
nRet = 0;
}
::LeaveCriticalSection(&m_csAlarm);
return nRet;
}
//add node to list
int CDevMgr::PushBack(DeviceNode* node)
{
if (!node)
{
return -1;
}
int nRet = 0;
::EnterCriticalSection(&m_csDev);
memset(&node->State, 0, sizeof(DEV_STATE));
m_lstDevice.push_back(node);
::LeaveCriticalSection(&m_csDev);
return nRet;
}
//delete node from list
int CDevMgr::DelNode(LONG lLoginID)
{
int nRet = -1;
::EnterCriticalSection(&m_csDev);
list<DeviceNode*>::iterator it =
find_if(m_lstDevice.begin(), m_lstDevice.end(),
SearchDevByHandle(lLoginID));
if (it != m_lstDevice.end())
{
delete *it;
m_lstDevice.erase(it);
nRet = 0;
}
::LeaveCriticalSection(&m_csDev);
return nRet;
}
int CDevMgr::ModifyNode(LONG lLoginID, BOOL bIsOnline)
{
int nRet = -1;
::EnterCriticalSection(&m_csDev);
list<DeviceNode*>::iterator it =
find_if(m_lstDevice.begin(), m_lstDevice.end(),
SearchDevByHandle(lLoginID));
if (it != m_lstDevice.end())
{
DeviceNode *pDevNode = (*it);
pDevNode->bIsOnline = bIsOnline;
nRet = 0;
}
::LeaveCriticalSection(&m_csDev);
return nRet;
}
BOOL CDevMgr::IsOnline(LONG lLoginID)
{
BOOL b = FALSE;
::EnterCriticalSection(&m_csDev);
list<DeviceNode*>::iterator it =
find_if(m_lstDevice.begin(), m_lstDevice.end(),
CDevMgr::SearchDevByHandle(lLoginID));
if (it != m_lstDevice.end())
{
b = TRUE;
}
::LeaveCriticalSection(&m_csDev);
return b;
}
BOOL CDevMgr::IsOnline(DeviceNode* node)
{
BOOL b = FALSE;
::EnterCriticalSection(&m_csDev);
list<DeviceNode*>::iterator it =
find(m_lstDevice.begin(), m_lstDevice.end(), node);
if (it != m_lstDevice.end())
{
b = TRUE;
}
::LeaveCriticalSection(&m_csDev);
return b;
} | [
"guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd"
]
| [
[
[
1,
463
]
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.