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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a42bfa2acedb172a3fa0d3512ce1cb9168a085f4 | b73f27ba54ad98fa4314a79f2afbaee638cf13f0 | /driver/drivertest/stdafx.h | 6ddb3f1d078f1d67bc13cd30351f5bb63083880e | [] | no_license | weimingtom/httpcontentparser | 4d5ed678f2b38812e05328b01bc6b0c161690991 | 54554f163b16a7c56e8350a148b1bd29461300a0 | refs/heads/master | 2021-01-09T21:58:30.326476 | 2009-09-23T08:05:31 | 2009-09-23T08:05:31 | 48,733,304 | 3 | 0 | null | null | null | null | GB18030 | C++ | false | false | 265 | h | // stdafx.h : 标准系统包含文件的包含文件,
// 或是常用但不常更改的项目特定的包含文件
//
#pragma once
#include <iostream>
#include <tchar.h>
#include <windows.h>
// TODO: 在此处引用程序要求的附加头文件
| [
"[email protected]"
] | [
[
[
1,
12
]
]
] |
df8fd7d453f4b5da4c8347de11ea1331017d8eaa | 1cacbe790f7c6e04ca6b0068c7b2231ed2b827e1 | /Oolong Engine2/Examples/Renderer/Tutorials/08 Shaders Demo (3DShaders.com)/Classes/Shader/3DShaders.src/Adjuster.cpp | 264347b93dd36b2609d20a3ad547dea41eed2664 | [
"BSD-3-Clause"
] | permissive | tianxiao/oolongengine | f3d2d888afb29e19ee93f28223fce6ea48f194ad | 8d80085c65ff3eed548549657e7b472671789e6a | refs/heads/master | 2020-05-30T06:02:32.967513 | 2010-05-05T05:52:03 | 2010-05-05T05:52:03 | 8,245,292 | 3 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 4,328 | cpp | //
// Author: Philip Rideout
// Copyright: 2002-2006 3Dlabs Inc. Ltd. All rights reserved.
// License: see 3Dlabs-license.txt
//
#include "App.h"
#include <wx/wx.h>
#include <wx/colordlg.h>
#include "Frame.h"
#include "Adjuster.h"
#include "Tables.h"
const int MaxSliderValue = 1000;
IMPLEMENT_DYNAMIC_CLASS(TAdjuster, wxDialog)
BEGIN_EVENT_TABLE(TAdjuster, wxDialog)
EVT_CLOSE(TAdjuster::OnClose)
EVT_SCROLL(TAdjuster::OnSlide)
EVT_COMMAND_RANGE(-65535, 65535, wxEVT_COMMAND_BUTTON_CLICKED, TAdjuster::OnClick)
END_EVENT_TABLE()
void TAdjuster::Create(wxWindow* parent)
{
wxDialog::Create(parent, -1, "Adjuster", wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxCLIP_CHILDREN);
}
void TAdjuster::OnClose(wxCloseEvent& event)
{
wxGetApp().Frame()->Uncheck(Id::ViewAdjuster);
wxGetApp().Frame()->UpdateViewAnimate();
event.Skip();
}
void TAdjuster::Set(const TUniformList& uniforms)
{
bool shown = IsShown();
if (shown)
Hide();
// Remove the old controls.
for (wxWindowListNode* node = GetChildren().GetFirst(); node;) {
wxWindow* current = node->GetData();
node = node->GetNext();
delete current;
}
GetChildren().Clear();
sliders.clear();
// Work around a problem with Fit() by resizing to bigger than need be.
SetSize(500, 500);
// Create a new vertical layout and iterate through each adjustustable uniform.
wxBoxSizer* vertical = new wxBoxSizer(wxVERTICAL);
bool empty = true;
for (TUniformList::const_iterator u = uniforms.begin(); u != uniforms.end(); ++u) {
if (u->IsColor()) {
empty = false;
wxBoxSizer* horizontal = new wxBoxSizer(wxHORIZONTAL);
wxButton* button = new wxButton(this, -1, "", wxDefaultPosition);
button->SetBackgroundColour(u->GetColor());
wxStaticText* label = new wxStaticText(this, -1, u->GetName(), wxDefaultPosition, wxDefaultSize, wxALIGN_CENTRE);
horizontal->Add(label, 0, wxALIGN_CENTRE_VERTICAL, 5);
horizontal->Add(button, 1, wxALIGN_CENTRE_VERTICAL | wxEXPAND | wxALL, 5);
vertical->Add(horizontal, 1, wxEXPAND | wxALL, 10);
// Add this to the id-uniform map.
pickers[button->GetId()] = const_cast<TUniform*>(&*u);
continue;
}
if (!u->HasSlider())
continue;
// Insert a label-slider pair using a horizontal layout.
empty = false;
wxBoxSizer* horizontal = new wxBoxSizer(wxHORIZONTAL);
wxStaticText* label = new wxStaticText(this, -1, u->GetName(), wxDefaultPosition, wxDefaultSize, wxALIGN_CENTRE);
horizontal->Add(label, 0, wxALIGN_CENTRE_VERTICAL, 5);
for (int i = 0; i < u->NumComponents(); ++i) {
float value = u->GetSlider(i) * MaxSliderValue;
wxSlider* slider = new wxSlider(this, -1, (int) value, 1, MaxSliderValue);
horizontal->Add(slider, 1, wxALIGN_CENTRE_VERTICAL | wxEXPAND | wxALL, 5);
sliders[slider->GetId()] = TUniformComponent(const_cast<TUniform*>(&*u), i);
}
vertical->Add(horizontal, 1, wxEXPAND | wxALL, 10);
}
if (empty) {
wxStaticText* label = new wxStaticText(this, -1, "The current shader does not have any adjustable uniforms.", wxDefaultPosition, wxDefaultSize, wxALIGN_CENTRE);
vertical->Add(label, 1, wxEXPAND | wxALL, 10);
}
SetSizerAndFit(vertical, true);
if (shown)
Show();
}
void TAdjuster::OnSlide(wxScrollEvent& event)
{
int value = event.GetInt();
TUniform* uniform = sliders[event.GetId()].first;
int component = sliders[event.GetId()].second;
uniform->SetSlider((float) value / MaxSliderValue, component);
uniform->UpdateSlider();
event.Skip();
}
void TAdjuster::OnClick(wxCommandEvent& event)
{
if (pickers.find(event.GetId()) != pickers.end()) {
TUniform* uniform = pickers[event.GetId()];
wxColour color = uniform->GetColor();
color = wxGetColourFromUser(this, color);
uniform->SetColor(color);
FindWindowById(event.GetId())->SetBackgroundColour(color);
}
event.Skip();
}
| [
"mozeal@7fa7efda-f44a-0410-a86a-c1fddb4bcab7"
] | [
[
[
1,
125
]
]
] |
7e7b475d39dbc59a7a3ae9fa6de8d5a06f9c17cd | 83ed25c6e6b33b2fabd4f81bf91d5fae9e18519c | /code/IRRMeshLoader.cpp | 97984e842c6ad63ccb5be3d3a88b2324d1b97235 | [
"BSD-3-Clause"
] | permissive | spring/assimp | fb53b91228843f7677fe8ec18b61d7b5886a6fd3 | db29c9a20d0dfa9f98c8fd473824bba5a895ae9e | refs/heads/master | 2021-01-17T23:19:56.511185 | 2011-11-08T12:15:18 | 2011-11-08T12:15:18 | 2,017,841 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 15,876 | cpp | /*
---------------------------------------------------------------------------
Open Asset Import Library (ASSIMP)
---------------------------------------------------------------------------
Copyright (c) 2006-2010, ASSIMP Development Team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the ASSIMP team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the ASSIMP Development Team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
/** @file Implementation of the IrrMesh importer class */
#include "AssimpPCH.h"
#include "IRRMeshLoader.h"
#include "ParsingUtils.h"
#include "fast_atof.h"
using namespace Assimp;
using namespace irr;
using namespace irr::io;
// ------------------------------------------------------------------------------------------------
// Constructor to be privately used by Importer
IRRMeshImporter::IRRMeshImporter()
{}
// ------------------------------------------------------------------------------------------------
// Destructor, private as well
IRRMeshImporter::~IRRMeshImporter()
{}
// ------------------------------------------------------------------------------------------------
// Returns whether the class can handle the format of the given file.
bool IRRMeshImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
{
/* NOTE: A simple check for the file extension is not enough
* here. Irrmesh and irr are easy, but xml is too generic
* and could be collada, too. So we need to open the file and
* search for typical tokens.
*/
const std::string extension = GetExtension(pFile);
if (extension == "irrmesh")return true;
else if (extension == "xml" || checkSig)
{
/* If CanRead() is called to check whether the loader
* supports a specific file extension in general we
* must return true here.
*/
if (!pIOHandler)return true;
const char* tokens[] = {"irrmesh"};
return SearchFileHeaderForToken(pIOHandler,pFile,tokens,1);
}
return false;
}
// ------------------------------------------------------------------------------------------------
// Get a list of all file extensions which are handled by this class
void IRRMeshImporter::GetExtensionList(std::set<std::string>& extensions)
{
extensions.insert("xml");
extensions.insert("irrmesh");
}
// ------------------------------------------------------------------------------------------------
// Imports the given file into the given scene structure.
void IRRMeshImporter::InternReadFile( const std::string& pFile,
aiScene* pScene, IOSystem* pIOHandler)
{
boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile));
// Check whether we can read from the file
if( file.get() == NULL)
throw DeadlyImportError( "Failed to open IRRMESH file " + pFile + "");
// Construct the irrXML parser
CIrrXML_IOStreamReader st(file.get());
reader = createIrrXMLReader((IFileReadCallBack*) &st);
// final data
std::vector<aiMaterial*> materials;
std::vector<aiMesh*> meshes;
materials.reserve (5);
meshes.reserve (5);
// temporary data - current mesh buffer
aiMaterial* curMat = NULL;
aiMesh* curMesh = NULL;
unsigned int curMatFlags = 0;
std::vector<aiVector3D> curVertices,curNormals,curTangents,curBitangents;
std::vector<aiColor4D> curColors;
std::vector<aiVector3D> curUVs,curUV2s;
// some temporary variables
int textMeaning = 0;
int vertexFormat = 0; // 0 = normal; 1 = 2 tcoords, 2 = tangents
bool useColors = false;
// Parse the XML file
while (reader->read()) {
switch (reader->getNodeType()) {
case EXN_ELEMENT:
if (!ASSIMP_stricmp(reader->getNodeName(),"buffer") && (curMat || curMesh)) {
// end of previous buffer. A material and a mesh should be there
if ( !curMat || !curMesh) {
DefaultLogger::get()->error("IRRMESH: A buffer must contain a mesh and a material");
delete curMat;
delete curMesh;
}
else {
materials.push_back(curMat);
meshes.push_back(curMesh);
}
curMat = NULL;
curMesh = NULL;
curVertices.clear();
curColors.clear();
curNormals.clear();
curUV2s.clear();
curUVs.clear();
curTangents.clear();
curBitangents.clear();
}
if (!ASSIMP_stricmp(reader->getNodeName(),"material")) {
if (curMat) {
DefaultLogger::get()->warn("IRRMESH: Only one material description per buffer, please");
delete curMat;curMat = NULL;
}
curMat = ParseMaterial(curMatFlags);
}
/* no else here! */ if (!ASSIMP_stricmp(reader->getNodeName(),"vertices"))
{
int num = reader->getAttributeValueAsInt("vertexCount");
if (!num) {
// This is possible ... remove the mesh from the list and skip further reading
DefaultLogger::get()->warn("IRRMESH: Found mesh with zero vertices");
delete curMat;curMat = NULL;
curMesh = NULL;
textMeaning = 0;
continue;
}
curVertices.reserve (num);
curNormals.reserve (num);
curColors.reserve (num);
curUVs.reserve (num);
// Determine the file format
const char* t = reader->getAttributeValueSafe("type");
if (!ASSIMP_stricmp("2tcoords", t)) {
curUV2s.reserve (num);
vertexFormat = 1;
if (curMatFlags & AI_IRRMESH_EXTRA_2ND_TEXTURE) {
// *********************************************************
// We have a second texture! So use this UV channel
// for it. The 2nd texture can be either a normal
// texture (solid_2layer or lightmap_xxx) or a normal
// map (normal_..., parallax_...)
// *********************************************************
int idx = 1;
aiMaterial* mat = ( aiMaterial* ) curMat;
if (curMatFlags & AI_IRRMESH_MAT_lightmap){
mat->AddProperty(&idx,1,AI_MATKEY_UVWSRC_LIGHTMAP(0));
}
else if (curMatFlags & AI_IRRMESH_MAT_normalmap_solid){
mat->AddProperty(&idx,1,AI_MATKEY_UVWSRC_NORMALS(0));
}
else if (curMatFlags & AI_IRRMESH_MAT_solid_2layer) {
mat->AddProperty(&idx,1,AI_MATKEY_UVWSRC_DIFFUSE(1));
}
}
}
else if (!ASSIMP_stricmp("tangents", t)) {
curTangents.reserve (num);
curBitangents.reserve (num);
vertexFormat = 2;
}
else if (ASSIMP_stricmp("standard", t)) {
delete curMat;
DefaultLogger::get()->warn("IRRMESH: Unknown vertex format");
}
else vertexFormat = 0;
textMeaning = 1;
}
else if (!ASSIMP_stricmp(reader->getNodeName(),"indices")) {
if (curVertices.empty() && curMat) {
delete curMat;
throw DeadlyImportError("IRRMESH: indices must come after vertices");
}
textMeaning = 2;
// start a new mesh
curMesh = new aiMesh();
// allocate storage for all faces
curMesh->mNumVertices = reader->getAttributeValueAsInt("indexCount");
if (!curMesh->mNumVertices) {
// This is possible ... remove the mesh from the list and skip further reading
DefaultLogger::get()->warn("IRRMESH: Found mesh with zero indices");
// mesh - away
delete curMesh; curMesh = NULL;
// material - away
delete curMat;curMat = NULL;
textMeaning = 0;
continue;
}
if (curMesh->mNumVertices % 3) {
DefaultLogger::get()->warn("IRRMESH: Number if indices isn't divisible by 3");
}
curMesh->mNumFaces = curMesh->mNumVertices / 3;
curMesh->mFaces = new aiFace[curMesh->mNumFaces];
// setup some members
curMesh->mMaterialIndex = (unsigned int)materials.size();
curMesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
// allocate storage for all vertices
curMesh->mVertices = new aiVector3D[curMesh->mNumVertices];
if (curNormals.size() == curVertices.size()) {
curMesh->mNormals = new aiVector3D[curMesh->mNumVertices];
}
if (curTangents.size() == curVertices.size()) {
curMesh->mTangents = new aiVector3D[curMesh->mNumVertices];
}
if (curBitangents.size() == curVertices.size()) {
curMesh->mBitangents = new aiVector3D[curMesh->mNumVertices];
}
if (curColors.size() == curVertices.size() && useColors) {
curMesh->mColors[0] = new aiColor4D[curMesh->mNumVertices];
}
if (curUVs.size() == curVertices.size()) {
curMesh->mTextureCoords[0] = new aiVector3D[curMesh->mNumVertices];
}
if (curUV2s.size() == curVertices.size()) {
curMesh->mTextureCoords[1] = new aiVector3D[curMesh->mNumVertices];
}
}
break;
case EXN_TEXT:
{
const char* sz = reader->getNodeData();
if (textMeaning == 1) {
textMeaning = 0;
// read vertices
do {
SkipSpacesAndLineEnd(&sz);
aiVector3D temp;aiColor4D c;
// Read the vertex position
sz = fast_atof_move(sz,(float&)temp.x);
SkipSpaces(&sz);
sz = fast_atof_move(sz,(float&)temp.y);
SkipSpaces(&sz);
sz = fast_atof_move(sz,(float&)temp.z);
SkipSpaces(&sz);
curVertices.push_back(temp);
// Read the vertex normals
sz = fast_atof_move(sz,(float&)temp.x);
SkipSpaces(&sz);
sz = fast_atof_move(sz,(float&)temp.y);
SkipSpaces(&sz);
sz = fast_atof_move(sz,(float&)temp.z);
SkipSpaces(&sz);
curNormals.push_back(temp);
// read the vertex colors
uint32_t clr = strtoul16(sz,&sz);
ColorFromARGBPacked(clr,c);
if (!curColors.empty() && c != *(curColors.end()-1))
useColors = true;
curColors.push_back(c);
SkipSpaces(&sz);
// read the first UV coordinate set
sz = fast_atof_move(sz,(float&)temp.x);
SkipSpaces(&sz);
sz = fast_atof_move(sz,(float&)temp.y);
SkipSpaces(&sz);
temp.z = 0.f;
temp.y = 1.f - temp.y; // DX to OGL
curUVs.push_back(temp);
// read the (optional) second UV coordinate set
if (vertexFormat == 1) {
sz = fast_atof_move(sz,(float&)temp.x);
SkipSpaces(&sz);
sz = fast_atof_move(sz,(float&)temp.y);
temp.y = 1.f - temp.y; // DX to OGL
curUV2s.push_back(temp);
}
// read optional tangent and bitangent vectors
else if (vertexFormat == 2) {
// tangents
sz = fast_atof_move(sz,(float&)temp.x);
SkipSpaces(&sz);
sz = fast_atof_move(sz,(float&)temp.z);
SkipSpaces(&sz);
sz = fast_atof_move(sz,(float&)temp.y);
SkipSpaces(&sz);
temp.y *= -1.0f;
curTangents.push_back(temp);
// bitangents
sz = fast_atof_move(sz,(float&)temp.x);
SkipSpaces(&sz);
sz = fast_atof_move(sz,(float&)temp.z);
SkipSpaces(&sz);
sz = fast_atof_move(sz,(float&)temp.y);
SkipSpaces(&sz);
temp.y *= -1.0f;
curBitangents.push_back(temp);
}
}
/* IMPORTANT: We assume that each vertex is specified in one
line. So we can skip the rest of the line - unknown vertex
elements are ignored.
*/
while (SkipLine(&sz));
}
else if (textMeaning == 2) {
textMeaning = 0;
// read indices
aiFace* curFace = curMesh->mFaces;
aiFace* const faceEnd = curMesh->mFaces + curMesh->mNumFaces;
aiVector3D* pcV = curMesh->mVertices;
aiVector3D* pcN = curMesh->mNormals;
aiVector3D* pcT = curMesh->mTangents;
aiVector3D* pcB = curMesh->mBitangents;
aiColor4D* pcC0 = curMesh->mColors[0];
aiVector3D* pcT0 = curMesh->mTextureCoords[0];
aiVector3D* pcT1 = curMesh->mTextureCoords[1];
unsigned int curIdx = 0;
unsigned int total = 0;
while(SkipSpacesAndLineEnd(&sz)) {
if (curFace >= faceEnd) {
DefaultLogger::get()->error("IRRMESH: Too many indices");
break;
}
if (!curIdx) {
curFace->mNumIndices = 3;
curFace->mIndices = new unsigned int[3];
}
unsigned int idx = strtoul10(sz,&sz);
if (idx >= curVertices.size()) {
DefaultLogger::get()->error("IRRMESH: Index out of range");
idx = 0;
}
curFace->mIndices[curIdx] = total++;
*pcV++ = curVertices[idx];
if (pcN)*pcN++ = curNormals[idx];
if (pcT)*pcT++ = curTangents[idx];
if (pcB)*pcB++ = curBitangents[idx];
if (pcC0)*pcC0++ = curColors[idx];
if (pcT0)*pcT0++ = curUVs[idx];
if (pcT1)*pcT1++ = curUV2s[idx];
if (++curIdx == 3) {
++curFace;
curIdx = 0;
}
}
if (curFace != faceEnd)
DefaultLogger::get()->error("IRRMESH: Not enough indices");
// Finish processing the mesh - do some small material workarounds
if (curMatFlags & AI_IRRMESH_MAT_trans_vertex_alpha && !useColors) {
// Take the opacity value of the current material
// from the common vertex color alpha
aiMaterial* mat = (aiMaterial*)curMat;
mat->AddProperty(&curColors[0].a,1,AI_MATKEY_OPACITY);
}
}}
break;
default:
// GCC complains here ...
break;
};
}
// End of the last buffer. A material and a mesh should be there
if (curMat || curMesh) {
if ( !curMat || !curMesh) {
DefaultLogger::get()->error("IRRMESH: A buffer must contain a mesh and a material");
delete curMat;
delete curMesh;
}
else {
materials.push_back(curMat);
meshes.push_back(curMesh);
}
}
if (materials.empty())
throw DeadlyImportError("IRRMESH: Unable to read a mesh from this file");
// now generate the output scene
pScene->mNumMeshes = (unsigned int)meshes.size();
pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
for (unsigned int i = 0; i < pScene->mNumMeshes;++i) {
pScene->mMeshes[i] = meshes[i];
// clean this value ...
pScene->mMeshes[i]->mNumUVComponents[3] = 0;
}
pScene->mNumMaterials = (unsigned int)materials.size();
pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials];
::memcpy(pScene->mMaterials,&materials[0],sizeof(void*)*pScene->mNumMaterials);
pScene->mRootNode = new aiNode();
pScene->mRootNode->mName.Set("<IRRMesh>");
pScene->mRootNode->mNumMeshes = pScene->mNumMeshes;
pScene->mRootNode->mMeshes = new unsigned int[pScene->mNumMeshes];
for (unsigned int i = 0; i < pScene->mNumMeshes;++i)
pScene->mRootNode->mMeshes[i] = i;
// clean up and return
delete reader;
AI_DEBUG_INVALIDATE_PTR(reader);
}
| [
"aramis_acg@67173fc5-114c-0410-ac8e-9d2fd5bffc1f",
"ulfjorensen@67173fc5-114c-0410-ac8e-9d2fd5bffc1f"
] | [
[
[
1,
50
],
[
53,
499
]
],
[
[
51,
52
]
]
] |
bbff4d6be5c70ac517e3a083856a9509ce257e66 | 71db16f07e91c3d49691f99c3edbfcba6a604189 | /tag/0.01.001/FahProxy/ProxyHandlerArbitrator.cpp | 278454da2b8216eb1655f09e7223cb9d53ac2050 | [] | no_license | jaboles/fahproxy | 503832879d9c1081e69b642d8cfe32fd0334a3b2 | 131b97ddf86220e4ba52878ba22d06f97003a023 | refs/heads/master | 2022-12-07T13:26:03.522052 | 2008-08-26T11:29:01 | 2008-08-26T11:29:01 | 290,090,861 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,280 | cpp | #include "ProxyHandlerArbitrator.h"
#include "NormalProxyHandler.h"
#include "FahUploadProxyHandler.h"
#include "UploadManager.h"
#include "Utils.h"
using namespace FahProxy;
using namespace System::Net::Sockets;
using namespace System::Net;
using namespace System::IO;
using namespace System;
ProxyHandlerArbitrator::ProxyHandlerArbitrator(Socket^ clientSocket, UploadManager^ uploadManager)
{
m_clientSocket = clientSocket;
m_networkStream = gcnew NetworkStream(m_clientSocket);
m_uploadManager = uploadManager;
}
ProxyHandlerArbitrator::~ProxyHandlerArbitrator()
{
}
void ProxyHandlerArbitrator::HandleIt()
{
try
{
String^ requestLine = Utils::ReadLineFromStream(m_networkStream);
array<wchar_t>^ splitChars = {' '};
array<String^>^ requestComponents = requestLine->Split(splitChars);
String^ method = requestComponents[0];
String^ url = requestComponents[1];
String^ protocol = requestComponents[2];
System::IO::MemoryStream^ headers = gcnew System::IO::MemoryStream();
int contentLength = 0;
for
(
String^ line = Utils::ReadLineFromStream(m_networkStream);
line != "";
line = Utils::ReadLineFromStream(m_networkStream)
)
{
Utils::WriteLineToStream(headers, line);
if (line->StartsWith("Content-Length:"))
{
contentLength = Convert::ToInt32(line->Substring(16));
}
}
// Blank line to separate
Utils::WriteLineToStream(headers, "");
NormalProxyHandler^ h;
String^ localHost = static_cast<IPEndPoint^>(m_clientSocket->RemoteEndPoint)->Address->ToString();
if
(
method == "POST" && contentLength > 2048 &&
(
url->StartsWith("http://171.64.") &&
(url->EndsWith(":8080/") || url->EndsWith(":80/"))
/*url == "http://171.64.65.20:8080/" ||
url == "http://171.64.122.76:8080/" ||
url == "http://171.64.122.74:8080/" ||
false*/
)
)
{
h = gcnew FahUploadProxyHandler(localHost, method, url, protocol, m_networkStream, headers, m_uploadManager);
}
else
{
h = gcnew NormalProxyHandler(localHost, method, url, protocol, m_networkStream, headers);
}
h->HandleIt();
}
catch (System::IO::IOException^)
{
}
finally
{
m_networkStream->Close();
m_clientSocket->Close();
}
} | [
"jb@dc620d95-ca3a-fc45-9de6-42b3e20515ab"
] | [
[
[
1,
86
]
]
] |
5c0097509dae00cb368d865afedc7c2ed1e89469 | 222bc22cb0330b694d2c3b0f4b866d726fd29c72 | /src/brookbox/wm2/WmlShader.inl | 6a6f799c416b78160a3271635b261c978c51622b | [
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | darwin/inferno | 02acd3d05ca4c092aa4006b028a843ac04b551b1 | e87017763abae0cfe09d47987f5f6ac37c4f073d | refs/heads/master | 2021-03-12T22:15:47.889580 | 2009-04-17T13:29:39 | 2009-04-17T13:29:39 | 178,477 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,477 | inl | // Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2003. All Rights Reserved
//
// The Wild Magic Library (WML) source code is supplied under the terms of
// the license agreement http://www.magic-software.com/License/WildMagic.pdf
// and may not be copied or disclosed except in accordance with the terms of
// that agreement.
//----------------------------------------------------------------------------
inline char* Shader::GetProgram (ProgramType iType)
{
return m_aacProgram[iType];
}
//----------------------------------------------------------------------------
inline Shader::ShaderVersion Shader::GetVersion (ProgramType iType) const
{
return m_aiVersion[iType];
}
//----------------------------------------------------------------------------
inline Shader::ShaderType Shader::GetType () const
{
return NONE;
}
//----------------------------------------------------------------------------
inline void Shader::SetUserData (int iSize, const void* pvData)
{
assert( 1 <= iSize && iSize <= 8 );
memcpy(m_acUserData,pvData,iSize*sizeof(char));
}
//----------------------------------------------------------------------------
inline void Shader::GetUserData (int iSize, void* pvData)
{
assert( 1 <= iSize && iSize <= 8 );
memcpy(pvData,m_acUserData,iSize*sizeof(char));
}
//----------------------------------------------------------------------------
| [
"[email protected]"
] | [
[
[
1,
38
]
]
] |
53ff4694b189496021afc5c8c5993024663e342b | 9c62af23e0a1faea5aaa8dd328ba1d82688823a5 | /rl/tags/v0-1/engine/dialog/include/processors/ConditionProcessor.h | ef68f99693df06c97495d8cfeaa29606cbfd2b18 | [
"ClArtistic",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | jacmoe/dsa-hl-svn | 55b05b6f28b0b8b216eac7b0f9eedf650d116f85 | 97798e1f54df9d5785fb206c7165cd011c611560 | refs/heads/master | 2021-04-22T12:07:43.389214 | 2009-11-27T22:01:03 | 2009-11-27T22:01:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,260 | 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 CONDITION_PROCESSOR_H
#define CONDITION_PROCESSOR_H
#include "DialogPrerequisites.h"
#include "../AimlProcessor.h"
#include "../NaturalLanguageProcessor.h"
#include <string>
using namespace std;
namespace rl
{
/**
* Base class for checking conditions in dialogs
*
* @author Philipp Walser
*/
class ConditionProcessor : public AimlProcessor
{
public:
~ConditionProcessor() { }
CeGuiString process(DOMNode* node,Match* m, const CeGuiString& str, NaturalLanguageProcessor* nlp);
};
}
#endif
| [
"blakharaz@4c79e8ff-cfd4-0310-af45-a38c79f83013"
] | [
[
[
1,
42
]
]
] |
4b7b202e17e030b1f0993905b54469006e3e93af | 06ff805f168597297a87642c951867b453e401f7 | /Algorithm/headers/GraphTest.h | 58debbb43b6659ea1c57860a95c505878fd72a32 | [] | no_license | fredska/algorithms | 58459720295f8cf36edc88f68e4b37962235e533 | 10538d9677894b450f359db9301108b459b604ca | refs/heads/master | 2021-01-02T09:38:34.466733 | 2011-11-09T17:32:57 | 2011-11-09T17:32:57 | 2,652,603 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 236 | h | /*
* GraphTest.h
*
* Created on: Oct 27, 2011
* Author: Work
*/
#ifndef GRAPHTEST_H_
#define GRAPHTEST_H_
class GraphTest
{
public:
GraphTest();
void runGraphTestSuite();
};
#endif /* GRAPHTEST_H_ */
| [
"[email protected]"
] | [
[
[
1,
19
]
]
] |
43c9fce25acba9e89327908a08b1b2645dd356e0 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK5.0/bctestmix50/src/bctestmix50appui.cpp | ca71e5539ac5d9bdba07333cce33ecdb6e91c00b | [] | 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 | 3,430 | cpp | /*
* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: appui
*
*/
#include <avkon.hrh>
#include <aknsutils.h>
#include "bctestmix50appui.h"
#include "bctestmix50.hrh"
#include "bctestmix50view.h"
#include "bctestutil.h"
#include "bctestmix50case.h"
#include "bctestmix50patchcontrolcase.h"
#include "bctestmix50patchviewcase.h"
#include "bctestmix50patchcolumncase.h"
_LIT( KTestCaseTitle, "mix test case" );
_LIT( KTestControlPatchTitle, "CBCTestMix50PatchControlCase test case" );
_LIT( KTestListboxTitle, "CBCTestMix50ListColumnCase test case" );
_LIT( KTestViewCaseTitle, "CBCTestMix50PatchViewCase test case");
// ======== MEMBER FUNCTIONS ========
// ---------------------------------------------------------------------------
// CBCTestMix50AppUi::CBCTestMix50AppUi()
// constructor do nothing
// ---------------------------------------------------------------------------
//
CBCTestMix50AppUi::CBCTestMix50AppUi()
{
}
// ---------------------------------------------------------------------------
// CBCTestMix50AppUi::ConstructL()
// symbian 2nd phase constructor
// ---------------------------------------------------------------------------
//
void CBCTestMix50AppUi::ConstructL()
{
BaseConstructL();
AknsUtils::SetAvkonSkinEnabledL( ETrue );
// init test util
iTestUtil = CBCTestUtil::NewL();
// init view
CBCTestMix50View* view = CBCTestMix50View::NewL( iTestUtil );
CleanupStack::PushL( view );
AddViewL( view );
CleanupStack::Pop( view );
ActivateLocalViewL( view->Id() );
// Add test case here.
iTestUtil->AddTestCaseL( CBCTestMix50Case::NewL( view->Container() ),
KTestCaseTitle );
iTestUtil->AddTestCaseL( CBCTestMix50ListColumnCase::NewL( view->Container(),
CEikonEnv::Static()), KTestListboxTitle );
iTestUtil->AddTestCaseL( CBCTestMix50PatchControlCase::NewL( view->Container() ),
KTestControlPatchTitle );
iTestUtil->AddTestCaseL( CBCTestMix50PatchViewCase::NewL( view->Container(), view ),
KTestViewCaseTitle );
}
// ---------------------------------------------------------------------------
// CBCTestMix50AppUi::~CBCTestMix50AppUi()
// Destructor.
// ---------------------------------------------------------------------------
//
CBCTestMix50AppUi::~CBCTestMix50AppUi()
{
delete iTestUtil;
}
// ---------------------------------------------------------------------------
// CBCTestMix50AppUi::HandleCommandL()
// handle menu command events
// ---------------------------------------------------------------------------
//
void CBCTestMix50AppUi::HandleCommandL( TInt aCommand )
{
switch ( aCommand )
{
case EAknSoftkeyBack:
case EEikCmdExit:
{
Exit();
return;
}
default:
break;
}
}
| [
"none@none"
] | [
[
[
1,
111
]
]
] |
b22f1c8478c0e05f0d7773e4d3d3f9eaec2b1631 | a5301cc32d0a44e2a560436a92f2c3a71823f079 | /Facial Recognition/CamCapture.cpp | b3a786e4f34ff3b66691ecac839a9b8bef8ac4b0 | [] | no_license | bblonski/head-gesture-rec | 3577a26a600af4a9432b520509efe80b8b780c8e | 7f44d72331966d8f717fa6faab57f4f065ea2bbb | refs/heads/master | 2020-05-25T12:02:36.472112 | 2010-06-08T01:09:56 | 2010-06-08T01:09:56 | 32,485,651 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,752 | cpp | // $Id$
// Copyright (c) 2010 by Brian Blonski
#include "Resource.h"
#include "GestureEvent.h"
#ifdef _WINDOWS_
#include <windows.h>
#else
#include <sys/time.h>
#endif
/// Name to display in the Main Window
const char* const CamCapture::MAIN_WINDOW = "Main";
const char* const CamCapture::VIDEO_FILE_NAME = "log.avi";
/// Constructor for CamCapture
CamCapture::CamCapture(void) : writer(NULL),
capture(cvCaptureFromCAM(0))
{
#if SHOW_WINDOWS
cvNamedWindow(MAIN_WINDOW, 1);
#endif
// if capture fails, display connect camera message
if(!capture)
{
noCamMsg();
}
#ifdef _WINDOWS_
SYSTEMTIME st;
GetSystemTime(&st);
lastCheckTime = st.wSecond + st.wMilliseconds * 1e-3;
#else
struct timeval time;
gettimeofday(&time, NULL);
lastCheckTime = time.tv_sec + time.tv_usec*1e-3;
#endif
}
/// Deconstructor for CamCapture
CamCapture::~CamCapture(void)
{
if(writer)
cvReleaseVideoWriter(&writer);
cvReleaseCapture(&capture);
#if SHOW_WINDOWS
cvDestroyWindow(MAIN_WINDOW);
#endif
}
/**
\brief
Grabs a frame from the camera and displays it in a window.
\returns
Image from the camera.
Write detailed description for getFrame here.
*/
IplImage*
CamCapture::getFrame()
{
IplImage* frame = 0; // Original frame taken from camera
IplImage* image = 0; // Copy of image from the frame taken from the camera
if(frame)
cvReleaseImage(&frame);
// grab the frame
frame = cvQueryFrame(capture);
if(!frame)
return NULL;
// create image size of frame
if(!image)
{
image = cvCreateImage(cvGetSize(frame), 8, 1);
image->origin = frame->origin;
}
// copy frame contents into image
//cvCopy(frame, image, 0);
cvCvtColor(frame, image, CV_BGR2GRAY);
frame = Utils::printTime(frame, cvPoint(20, 20));
#ifdef _WINDOWS_
SYSTEMTIME st;
GetSystemTime(&st);
double currentTime = st.wSecond + st.wMilliseconds * 1e-3;
#else
struct timeval time;
gettimeofday(&time, NULL);
double currentTime = time.tv_sec + time.tv_usec * 1e-3;
#endif
double fps = 1/(currentTime - lastCheckTime);
lastCheckTime = currentTime;
char fpsDisplay[1000];
sprintf_s(fpsDisplay, "%.2f", fps);
frame = Utils::printMsg(frame, fpsDisplay, cvPoint(frame->width - 50, 20));
if(!writer)
writer = cvCreateVideoWriter(VIDEO_FILE_NAME,
CV_FOURCC('I','Y','U','V'), 20, cvGetSize(frame));
cvWriteFrame(writer, frame);
#if SHOW_WINDOWS
cvShowImage(MAIN_WINDOW, frame);
#endif
return image;
}
void
CamCapture::noCamMsg()
{
CvFont font;
int textX = 20;
int textY = 50;
int textOffset = 10;
CvPoint pt = cvPoint(textX, textY);
// 320x240 blank image
IplImage* msg = cvCreateImage(cvSize(320, 240), 8, 3);
// initialize the font
cvInitFont(&font, CV_FONT_HERSHEY_COMPLEX, 0.3, 0.3, 0, 1, CV_AA);
// starting point of text
cvZero(msg);
// write message to the image
cvPutText(msg, "No Camera Detected.", pt, &font, CV_RGB(250, 250, 250));
pt = cvPoint(textX, textY + textOffset);
cvPutText(msg, "Please connect camera and restart the program.", pt, &font,
CV_RGB(250, 250, 250));
pt = cvPoint(textX, textY + 2*textOffset);
cvPutText(msg, "Press any key to exit.", pt, &font, CV_RGB(250, 250, 250));
// display the image in the container
cvNamedWindow("Error", 1);
cvShowImage("Error", msg);
// wait till user presses a key
cvWaitKey(0);
cvReleaseImage(&msg);
#if SHOW_WINDOW
cvDestroyWindow("Error");
#endif
exit(-1);
} | [
"Brian Blonski@localhost",
"bblonski@localhost"
] | [
[
[
1,
3
],
[
10,
12
],
[
14,
15
],
[
18,
18
],
[
24,
24
],
[
26,
26
],
[
36,
40
],
[
47,
57
],
[
61,
61
],
[
64,
64
],
[
142,
142
]
],
[
[
4,
9
],
[
13,
13
],
[
16,
17
],
[
19,
23
],
[
25,
25
],
[
27,
35
],
[
41,
46
],
[
58,
60
],
[
62,
63
],
[
65,
141
]
]
] |
aa1a86a495f0ca8253b76bbda3aa36bbebaca79b | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SEFoundation/SEShaders/SEImageCatalog.cpp | 334e99521208f536b22ce04072b850da5b84b921 | [] | 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 | 6,189 | cpp | // Swing Engine Version 1 Source Code
// Most of techniques in the engine are mainly based on David Eberly's
// Wild Magic 4 open-source code.The author of Swing Engine learned a lot
// from Eberly's experience of architecture and algorithm.
// Several sub-systems are totally new,and others are re-implimented or
// re-organized based on Wild Magic 4's sub-systems.
// Copyright (c) 2007-2010. All Rights Reserved
//
// Eberly's permission:
// Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or (at
// your option) any later version. The license is available for reading at
// the location:
// http://www.gnu.org/copyleft/lgpl.html
#include "SEFoundationPCH.h"
#include "SEImageCatalog.h"
#include "SEImage.h"
using namespace Swing;
const std::string SEImageCatalog::ms_NullString("");
const std::string SEImageCatalog::ms_DefaultString("Default");
SEImageCatalog* SEImageCatalog::ms_pActive = 0;
//----------------------------------------------------------------------------
SEImageCatalog::SEImageCatalog(const std::string& rName)
:
m_Name(rName),
m_Entry(IMAGE_MAP_SIZE)
{
// 由于有些图形管线不支持1D image,
// 因此创建一个默认2x2 image,用于无法找到指定资源时提醒用户.
unsigned char* pData = SE_NEW unsigned char[16];
pData[0] = 255;
pData[1] = 0;
pData[2] = 0;
pData[3] = 0;
pData[4] = 255;
pData[5] = 0;
pData[6] = 0;
pData[7] = 0;
pData[8] = 255;
pData[9] = 0;
pData[10] = 0;
pData[11] = 0;
pData[12] = 255;
pData[13] = 0;
pData[14] = 0;
pData[15] = 0;
m_spDefaultImage = SE_NEW SEImage(SEImage::IT_RGBA8888, 2, 2, pData,
ms_DefaultString.c_str());
}
//----------------------------------------------------------------------------
SEImageCatalog::~SEImageCatalog()
{
}
//----------------------------------------------------------------------------
const std::string& SEImageCatalog::GetName() const
{
return m_Name;
}
//----------------------------------------------------------------------------
bool SEImageCatalog::Insert(SEImage* pImage)
{
if( !pImage )
{
SE_ASSERT( false );
return false;
}
std::string StrImageName(pImage->GetName());
if( StrImageName == ms_NullString
|| StrImageName == ms_DefaultString
|| pImage == m_spDefaultImage )
{
return false;
}
// 首先在资源目录中查找
SEImage** ppTempImage = m_Entry.Find(StrImageName);
if( ppTempImage )
{
// 该image已经存在
return true;
}
// 该image不存在,则插入
m_Entry.Insert(StrImageName, pImage);
return true;
}
//----------------------------------------------------------------------------
bool SEImageCatalog::Remove(SEImage* pImage)
{
if( !pImage )
{
SE_ASSERT( false );
return false;
}
std::string StrImageName(pImage->GetName());
if( StrImageName == ms_NullString
|| StrImageName == ms_DefaultString
|| pImage == m_spDefaultImage )
{
return false;
}
// 首先在资源目录中查找
SEImage** ppTempImage = m_Entry.Find(StrImageName);
if( !ppTempImage )
{
// 该image不存在
return false;
}
// image存在,则移除
m_Entry.Remove(StrImageName);
return true;
}
//----------------------------------------------------------------------------
SEImage* SEImageCatalog::Find(const std::string& rImageName)
{
if( rImageName == ms_NullString
|| rImageName == ms_DefaultString )
{
return StaticCast<SEImage>(m_spDefaultImage);
}
// 首先在资源目录中查找
SEImage** ppTempImage = m_Entry.Find(rImageName);
if( ppTempImage )
{
// 找到则返回
return *ppTempImage;
}
// 在磁盘中查找
SEImage* pImage = SEImage::Load(rImageName.c_str());
if( pImage )
{
// 该资源存在,且已经在Load后被加入资源目录,不用再次调用Insert函数
return pImage;
}
// image不存在,则使用默认image
return StaticCast<SEImage>(m_spDefaultImage);
}
//----------------------------------------------------------------------------
bool SEImageCatalog::PrintContents(const std::string& rFileName) const
{
const char* pDecorated = SESystem::SE_GetPath(rFileName.c_str(),
SESystem::SM_WRITE);
if( pDecorated )
{
std::ofstream OStream(pDecorated);
SE_ASSERT( OStream );
std::string StrImageName;
SEImage** ppTempImage = m_Entry.GetFirst(&StrImageName);
while( ppTempImage )
{
SEImage* pImage = *ppTempImage;
OStream << StrImageName.c_str() << ":" << std::endl;
OStream << " dimension = " << pImage->GetDimension()
<< std::endl;
for( int i = 0; i < pImage->GetDimension(); i++ )
{
OStream << " bound(" << i << ") = " << pImage->GetBound(i)
<< std::endl;
}
OStream << " format = " << pImage->GetFormatName().c_str() <<
std::endl;
OStream << std::endl;
ppTempImage = m_Entry.GetNext(&StrImageName);
}
OStream.close();
return true;
}
return false;
}
//----------------------------------------------------------------------------
void SEImageCatalog::SetActive(SEImageCatalog* pActive)
{
ms_pActive = pActive;
}
//----------------------------------------------------------------------------
SEImageCatalog* SEImageCatalog::GetActive()
{
return ms_pActive;
}
//----------------------------------------------------------------------------
| [
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
] | [
[
[
1,
206
]
]
] |
3db919d60f4afcf5d4e66c1e059ea40bd63b6a3a | b2d46af9c6152323ce240374afc998c1574db71f | /cursovideojuegos/theflostiproject/3rdParty/boost/libs/config/test/no_iter_construct_pass.cpp | fa83e184d21859bd4bd25fb1aa0822717ba9de18 | [] | no_license | bugbit/cipsaoscar | 601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4 | 52aa8b4b67d48f59e46cb43527480f8b3552e96d | refs/heads/master | 2021-01-10T21:31:18.653163 | 2011-09-28T16:39:12 | 2011-09-28T16:39:12 | 33,032,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,295 | cpp |
// This file was automatically generated on Sun Jul 25 11:47:49 GMTDT 2004,
// by libs/config/tools/generate
// Copyright John Maddock 2002-4.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/config for the most recent version.
// Test file for macro BOOST_NO_TEMPLATED_ITERATOR_CONSTRUCTORS
// This file should compile, if it does not then
// BOOST_NO_TEMPLATED_ITERATOR_CONSTRUCTORS needs to be defined.
// see boost_no_iter_construct.ipp for more details
// Do not edit this file, it was generated automatically by
// ../tools/generate from boost_no_iter_construct.ipp on
// Sun Jul 25 11:47:49 GMTDT 2004
// Must not have BOOST_ASSERT_CONFIG set; it defeats
// the objective of this file:
#ifdef BOOST_ASSERT_CONFIG
# undef BOOST_ASSERT_CONFIG
#endif
#include <boost/config.hpp>
#include "test.hpp"
#ifndef BOOST_NO_TEMPLATED_ITERATOR_CONSTRUCTORS
#include "boost_no_iter_construct.ipp"
#else
namespace boost_no_templated_iterator_constructors = empty_boost;
#endif
int main( int, char *[] )
{
return boost_no_templated_iterator_constructors::test();
}
| [
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
] | [
[
[
1,
39
]
]
] |
d102c6f85c641bb3393b17405374eb322219f1f1 | 3c2dc480d637cc856a1be74be1bbc197a0b24bd2 | /S34Anim.cpp | 469db059c41cd55b15de0341006ced22c6f3c039 | [] | no_license | cjus/s34mme | d49ff5ede63fbae83fa0694eeea66b0024a4b72b | 77d372c9f55d2053c11e41bdfd9d2f074329e451 | refs/heads/master | 2020-04-14T19:30:39.690545 | 2010-09-05T18:23:37 | 2010-09-05T18:23:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,330 | cpp | // Anim.cpp: implementation of the CS34Anim class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "s34Anim.h"
#include "stdlib.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CS34Anim::CS34Anim()
{
m_bAnimDragable = TRUE;
m_iPitch =-1;
m_State = VISIBLE;
m_TotalFrames = 0;
m_CurrentFrame = 0;
m_Location = CS34Point(0,0);
m_ZOrder = 0;
m_bZHasChanged = FALSE;
m_Size = CS34Size(0,0);
m_Delta = CS34Point(0,0);
m_CurrentRect.SetRectEmpty();
m_BoundingMovementRect.SetRectEmpty();
m_bFrameLoop = FALSE;
m_bAnimScript = FALSE;
m_iScriptInstruction = CS34AnimScript::S34ANIM_START;
m_dwTimeDelay = 0;
m_bScriptState = FALSE;
m_iAnimPathLocation = 0;
m_iAnimPathSteps = 0;
m_pAnimPathPoints = NULL;
SetAnimPathUpdateDelay(5);
m_dwTimeDelayCount = 0;
}
CS34Anim::~CS34Anim()
{
}
BOOL CS34Anim::AddFrame(CS34Image* pImg, CS34Rect *pClipRect)
{
if (m_TotalFrames > MAX_ANIM_FRAMES)
return FALSE;
CS34Size size;
CS34Rect Rect;
if (pClipRect == NULL)
{
pImg->GetSize(&size.cx, &size.cy);
Rect = CS34Rect(0,0,size.cx, size.cy);
}
else
{
size.cx = pClipRect->right - pClipRect->left;
size.cy = pClipRect->bottom - pClipRect->top;
Rect = *pClipRect;
}
AnimFrames[m_TotalFrames].ClipRect = Rect;
AnimFrames[m_TotalFrames].pFrame = pImg;
m_Size = size;
m_TotalFrames++;
return TRUE;
}
void CS34Anim::SetState(int state)
{
m_State = state;
m_bDirty = TRUE;
}
BOOL CS34Anim::SetFrame(int nFrameNumber)
{
if (nFrameNumber < m_TotalFrames)
{
m_CurrentFrame = nFrameNumber;
m_bDirty = TRUE;
return TRUE;
}
return FALSE;
}
BOOL CS34Anim::SetNextFrame()
{
if ((m_CurrentFrame + 1) < m_TotalFrames)
{
m_CurrentFrame++;
m_bDirty = TRUE;
return TRUE;
}
else
{
if (m_bFrameLoop)
{
m_CurrentFrame = 0;
m_bDirty = TRUE;
return TRUE;
}
}
return FALSE;
}
BOOL CS34Anim::SetPriorFrame()
{
if ((m_CurrentFrame - 1) > -1)
{
m_CurrentFrame--;
m_bDirty = TRUE;
return TRUE;
}
else
{
if (m_bFrameLoop)
{
m_CurrentFrame = m_TotalFrames-1;
m_bDirty = TRUE;
return TRUE;
}
}
return FALSE;
}
void CS34Anim::SetLocation(CS34Point location)
{
CS34Rect LastRect = m_CurrentRect;
if (m_CurrentRect.IsRectEmpty())
{
m_CurrentRect = CS34Rect(location.x, location.y, location.x + m_Size.cx, location.y + m_Size.cy);
m_BoundingMovementRect = m_CurrentRect;
}
else
{
m_CurrentRect = CS34Rect(location.x, location.y, location.x + m_Size.cx, location.y + m_Size.cy);
m_BoundingMovementRect.UnionRect(LastRect);
m_BoundingMovementRect.UnionRect(m_CurrentRect);
}
m_Location = location;
m_bDirty = TRUE;
}
void CS34Anim::SetLocation(int x, int y, int z)
{
SetLocation(CS34Point(x,y));
if (z != (int)0x80000001)
{
m_ZOrder = z;
m_bZHasChanged = TRUE;
}
}
void CS34Anim::SetZOrder(int ZOrder)
{
m_bDirty = TRUE;
m_ZOrder = ZOrder;
m_bZHasChanged = TRUE;
}
/*
void CS34Anim::MoveWithDelta()
{
if (m_Delta.x != 0 || m_Delta.y != 0)
{
m_Location.x += m_Delta.x;
m_Location.y += m_Delta.y;
m_bDirty = TRUE;
}
}
*/
void CS34Anim::GetState(int *pState)
{
*pState = m_State;
}
int CS34Anim::GetState()
{
return m_State;
}
void CS34Anim::GetDelta(CS34Point *pDelta)
{
pDelta->x = m_Delta.x;
pDelta->y = m_Delta.y;
}
void CS34Anim::GetLocation(CS34Point *pPoint)
{
pPoint->x = m_Location.x; pPoint->y = m_Location.y;
}
void CS34Anim::GetSize(CS34Size *pSize)
{
pSize->cx = m_Size.cx; pSize->cy = m_Size.cy;
}
void CS34Anim::GetRect(CS34Rect *pRect)
{
pRect->left = m_Location.x;
pRect->top = m_Location.y;
pRect->right = m_Location.x + m_Size.cx;
pRect->bottom = m_Location.y + m_Size.cy;
}
CS34Rect& CS34Anim::GetBoundingMovementRect()
{
return m_BoundingMovementRect;
}
void CS34Anim::Update(int iColorDepth, CS34Rect *pClipRect)
{
if (m_State==HIDDEN)
return;
CS34Rect rect;
GetRect(&rect);
// if ClipRect is valid see if this CS34Anim is within the cliprect
if (pClipRect && !rect.IntersectRect(*pClipRect, rect))
return; // CS34Anim isn't within the supplied clip rect
if (iColorDepth>8)
((CS34Image*)AnimFrames[m_CurrentFrame].pFrame)->Render(m_CompositeImg, m_iPitch,
rect.left, rect.top,
AnimFrames[m_CurrentFrame].ClipRect.left + (rect.left - m_Location.x),
AnimFrames[m_CurrentFrame].ClipRect.top + (rect.top - m_Location.y),
rect.right - rect.left, rect.bottom - rect.top);
else
((CS34Image*)AnimFrames[m_CurrentFrame].pFrame)->Render256(m_CompositeImg, m_iPitch,
rect.left, rect.top,
AnimFrames[m_CurrentFrame].ClipRect.left + (rect.left - m_Location.x),
AnimFrames[m_CurrentFrame].ClipRect.top + (rect.top - m_Location.y),
rect.right - rect.left, rect.bottom - rect.top);
m_bDirty = FALSE;
m_BoundingMovementRect = m_CurrentRect;
}
void CS34Anim::Render(int iColorDepth, BYTE *pDstBuffer, int iPitch, CS34Rect *pClipRect)
{
if (m_State==HIDDEN)
return;
CS34Rect rect;
GetRect(&rect);
// if ClipRect is valid see if this CS34Anim is within the cliprect
if (pClipRect && !rect.IntersectRect(*pClipRect, rect))
return; // CS34Anim isn't within the supplied clip rect
if (iColorDepth>8)
((CS34Image*)AnimFrames[m_CurrentFrame].pFrame)->Render(pDstBuffer, iPitch,
rect.left, rect.top,
AnimFrames[m_CurrentFrame].ClipRect.left + (rect.left - m_Location.x),
AnimFrames[m_CurrentFrame].ClipRect.top + (rect.top - m_Location.y),
rect.right - rect.left, rect.bottom - rect.top);
else
((CS34Image*)AnimFrames[m_CurrentFrame].pFrame)->Render256(pDstBuffer, iPitch,
rect.left, rect.top,
AnimFrames[m_CurrentFrame].ClipRect.left + (rect.left - m_Location.x),
AnimFrames[m_CurrentFrame].ClipRect.top + (rect.top - m_Location.y),
rect.right - rect.left, rect.bottom - rect.top);
}
int CS34Anim::LoadAnimScript(char *pFileName)
{
if (m_AnimScript.LoadAnimScript(pFileName) != S34ANM_E_NOERROR)
return S34ANM_E_SCRIPT_UNABLE_TO_LOAD;
m_bAnimScript = TRUE;
m_bScriptState = TRUE;
return S34ANM_E_NOERROR;
}
void CS34Anim::OnChron()
{
if (m_pAnimPathPoints)
{
if (GetTickCount() > m_dwPathUpdateDelay)
{
SetLocation(CS34Point(m_pAnimPathPoints[m_iAnimPathLocation].x, m_pAnimPathPoints[m_iAnimPathLocation].y));
if (m_iAnimPathLocation > m_iAnimPathSteps)
m_iAnimPathLocation = 0;
else
m_iAnimPathLocation++;
m_dwPathUpdateDelay = GetTickCount() + m_dwPathUpdateDelayCount;
}
}
if (m_bScriptState)
{
BOOL bInternalLoop = TRUE; // used instead of a recursive function call!
if (m_iScriptInstruction != CS34AnimScript::S34ANIM_WAIT)
{
if (GetTickCount() < m_dwTimeDelay)
return;
else
m_dwTimeDelay = GetTickCount() + m_dwTimeDelayCount;
}
while (bInternalLoop)
{
switch (m_iScriptInstruction)
{
case CS34AnimScript::S34ANIM_START:
// this command marks the beginning of the script processing
// do initialization stuff, then get the first command!
//
m_AnimScript.GotoStart();
m_AnimScript.GetCommand(m_iScriptInstruction, m_iScriptInstructionValue);
m_AnimScript.GotoNext();
m_bForwardFlag = FALSE;
m_bBackwardFlag = FALSE;
m_bWaitFlag = FALSE;
bInternalLoop = TRUE;
break;
case CS34AnimScript::S34ANIM_SPEED:
m_dwTimeDelayCount = m_iScriptInstructionValue;
m_dwTimeDelay = GetTickCount() + m_iScriptInstructionValue;
m_AnimScript.GetCommand(m_iScriptInstruction, m_iScriptInstructionValue);
m_AnimScript.GotoNext();
bInternalLoop = TRUE;
break;
case CS34AnimScript::S34ANIM_GO:
SetFrame(m_iScriptInstructionValue);
m_AnimScript.GetCommand(m_iScriptInstruction, m_iScriptInstructionValue);
m_AnimScript.GotoNext();
bInternalLoop = FALSE;
break;
case CS34AnimScript::S34ANIM_FORWARD:
if (!m_bForwardFlag)
{
m_iScriptMovementLoopCount = m_iScriptInstructionValue;
m_bForwardFlag = TRUE;
}
SetNextFrame();
if (--m_iScriptMovementLoopCount==0)
{
m_AnimScript.GetCommand(m_iScriptInstruction, m_iScriptInstructionValue);
m_AnimScript.GotoNext();
m_bForwardFlag = FALSE;
bInternalLoop = TRUE;
continue;
}
bInternalLoop = FALSE;
break;
case CS34AnimScript::S34ANIM_BACKWARD:
if (!m_bBackwardFlag)
{
m_iScriptMovementLoopCount = m_iScriptInstructionValue;
m_bBackwardFlag = TRUE;
}
SetPriorFrame();
if (--m_iScriptMovementLoopCount==0)
{
m_AnimScript.GetCommand(m_iScriptInstruction, m_iScriptInstructionValue);
m_AnimScript.GotoNext();
m_bBackwardFlag = FALSE;
bInternalLoop = TRUE;
continue;
}
bInternalLoop = FALSE;
break;
case CS34AnimScript::S34ANIM_WAIT:
if (!m_bWaitFlag)
{
m_dwTimeWait = m_iScriptInstructionValue + GetTickCount();
m_bWaitFlag = TRUE;
}
if (GetTickCount() > m_dwTimeWait)
{
m_bWaitFlag = FALSE;
m_AnimScript.GetCommand(m_iScriptInstruction, m_iScriptInstructionValue);
m_AnimScript.GotoNext();
}
bInternalLoop = FALSE;
break;
// case CS34AnimScript::S34ANIM_STOP:
// m_AnimScript.GotoNext();
// bInternalLoop = FALSE;
// break
case CS34AnimScript::S34ANIM_END:
// we're at the end of the script, restart it
//
m_iScriptInstruction = CS34AnimScript::S34ANIM_START;
bInternalLoop = TRUE;
break;
};
}
}
}
BOOL CS34Anim::IsPointInAnim(int x, int y)
{
if (m_State==HIDDEN)
return FALSE;
return GetCurrentImageFrame()->IsPointInImage(x,y);
}
void CS34Anim::SetAnimPath(POINT *p, int iSteps, int iLocation)
{
m_iAnimPathLocation = iLocation;
m_pAnimPathPoints = p;
m_iAnimPathSteps = iSteps;
}
| [
"[email protected]"
] | [
[
[
1,
417
]
]
] |
9acd6829a9e0f89c2a39818f5d40303b5ce45fdc | 037faae47a5b22d3e283555e6b5ac2a0197faf18 | /pcsx2v2/windows/DebugMemory.cpp | a8c89758bb7a347fc8f319c7743c2ff50293a6a4 | [] | no_license | isabella232/pcsx2-sourceforge | 6e5aac8d0b476601bfc8fa83ded66c1564b8c588 | dbb2c3a010081b105a8cba0c588f1e8f4e4505c6 | refs/heads/master | 2023-03-18T22:23:15.102593 | 2008-11-17T20:10:17 | 2008-11-17T20:10:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,528 | cpp | /* Pcsx2 - Pc Ps2 Emulator
* Copyright (C) 2002-2008 Pcsx2 Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "Common.h"
#include "resource.h"
unsigned long memory_addr;
BOOL mem_inupdate = FALSE;
HWND memoryhWnd,hWnd_memscroll,hWnd_memorydump;
unsigned long memory_patch;
unsigned long data_patch;
///MEMORY DUMP
unsigned char Debug_Read8(unsigned long addr)//just for anycase..
{
#ifdef _WIN32
__try
{
#endif
u8 val8;
memRead8(addr, &val8);
return val8;
#ifdef _WIN32
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
return 0;
}
#endif
}
void RefreshMemory(void)
{
int x, y;
unsigned long addr;
unsigned char b;
char buf[128], text[32], temp[8];
addr = memory_addr;
if (!mem_inupdate)
{
sprintf(buf, "%08X", addr);
SetDlgItemText(memoryhWnd, IDC_MEMORY_ADDR, buf);
}
SendMessage(hWnd_memorydump, LB_RESETCONTENT, 0, 0);
for (y = 0; y < 21; y++)
{
memset(text, 0, 32);
sprintf(buf, "%08X: ", addr);
for (x = 0; x < 16; x++)
{
b = Debug_Read8(addr++);
sprintf(temp, "%02X ", b);
strcat(buf, temp);
if (b < 32 || b > 127) b = 32;
sprintf(temp, "%c", b);
strcat(text, temp);
if (x == 7) strcat(buf, " ");
}
strcat(buf, " ");
strcat(buf, text);
SendMessage(hWnd_memorydump, LB_ADDSTRING, 0, (LPARAM)buf);
}
}
BOOL APIENTRY DumpMemProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
char start[16], end[16], fname[128], buf[128];
u32 start_pc, end_pc, addr;
u8 data;
FILE *fp;
switch (message)
{
case WM_INITDIALOG:
sprintf(buf, "%08X", cpuRegs.pc);
SetDlgItemText(hDlg, IDC_DUMPMEM_START, buf);
SetDlgItemText(hDlg, IDC_DUMPMEM_END, buf);
SetDlgItemText(hDlg, IDC_DUMPMEM_FNAME, "dump.raw");
return TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK)
{
GetDlgItemText(hDlg, IDC_DUMPMEM_START, start, 9);
start[8] = 0;
sscanf(start, "%x", &start_pc);
start_pc &= 0xFFFFFFFC;
GetDlgItemText(hDlg, IDC_DUMPMEM_END, end, 9);
end[8] = 0;
sscanf(end, "%x", &end_pc);
end_pc &= 0xFFFFFFFC;
GetDlgItemText(hDlg, IDC_DUMPMEM_FNAME, fname, 128);
fp = fopen(fname, "wb");
if (fp == NULL)
{
SysMessage("Can't open file '%s' for writing!\n", fname);
}
else
{
for (addr = start_pc; addr < end_pc; addr ++) {
memRead8( addr, &data );
fwrite(&data, 1, 1, fp);
}
fclose(fp);
}
EndDialog(hDlg, TRUE);
} else if (LOWORD(wParam) == IDCANCEL) {
EndDialog(hDlg, TRUE);
}
return TRUE;
}
return FALSE;
}
BOOL APIENTRY MemoryProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
char buf[16];
switch (message)
{
case WM_INITDIALOG:
memory_addr = cpuRegs.pc;
sprintf(buf, "%08X", memory_addr);
SetDlgItemText(hDlg, IDC_MEMORY_ADDR, buf);
memory_patch= 0;
sprintf(buf, "%08X", memory_patch);
SetDlgItemText(hDlg, IDC_ADDRESS_PATCH, buf);
data_patch=0;
sprintf(buf, "%08X", data_patch);
SetDlgItemText(hDlg, IDC_DATA_PATCH, buf);
hWnd_memorydump = GetDlgItem(hDlg, IDC_MEMORY_DUMP);
hWnd_memscroll = GetDlgItem(hDlg, IDC_MEM_SCROLL);
SendMessage(hWnd_memorydump, LB_INITSTORAGE, 11, 1280);
SendMessage(hWnd_memscroll, SBM_SETRANGE, 0, MAXLONG);
SendMessage(hWnd_memscroll, SBM_SETPOS, MAXLONG / 2, TRUE);
RefreshMemory();
return TRUE;
case WM_VSCROLL:
switch ((int) LOWORD(wParam))
{
case SB_LINEDOWN: memory_addr += 0x00000010; RefreshMemory(); break;
case SB_LINEUP: memory_addr -= 0x00000010; RefreshMemory(); break;
case SB_PAGEDOWN: memory_addr += 0x00000150; RefreshMemory(); break;
case SB_PAGEUP: memory_addr -= 0x00000150; RefreshMemory(); break;
}
return TRUE;
case WM_CLOSE:
EndDialog(hDlg, TRUE );
return TRUE;
case WM_COMMAND:
if (HIWORD(wParam) == EN_UPDATE)
{
mem_inupdate = TRUE;
GetDlgItemText(hDlg, IDC_MEMORY_ADDR, buf, 9);
buf[8] = 0;
sscanf(buf, "%x", &memory_addr);
RefreshMemory();
mem_inupdate = FALSE;
return TRUE;
}
switch (LOWORD(wParam)) {
case IDC_PATCH:
GetDlgItemText(hDlg, IDC_ADDRESS_PATCH, buf, 9);//32bit address
buf[8] = 0;
sscanf(buf, "%x", &memory_patch);
GetDlgItemText(hDlg, IDC_DATA_PATCH, buf, 9);//32 bit data only for far
buf[8] = 0;
sscanf(buf, "%x", &data_patch);
memWrite32( memory_patch, data_patch );
sprintf(buf, "%08X", memory_patch);
SetDlgItemText(hDlg, IDC_MEMORY_ADDR, buf);
RefreshMemory();
return TRUE;
case IDC_DUMPRAW:
DialogBox(gApp.hInstance, MAKEINTRESOURCE(IDD_DUMPMEM), hDlg, (DLGPROC)DumpMemProc);
return TRUE;
case IDC_MEMORY_CLOSE:
EndDialog(hDlg, TRUE );
return TRUE;
}
break;
}
return FALSE;
}
| [
"saqibakhtar@23c756db-88ba-2448-99d7-e6e4c676ec84"
] | [
[
[
1,
239
]
]
] |
79842c931494c00df7bc20ea0504df3ae11b4a22 | 22438bd0a316b62e88380796f0a8620c4d129f50 | /displays/displays.cpp | da998bd5e2999ab220fa3ab15ce24df0b9e71574 | [
"BSL-1.0"
] | permissive | DannyHavenith/NAPL | 1578f5e09f1b825f776bea9575f76518a84588f4 | 5db7bf823bdc10587746d691cb8d94031115b037 | refs/heads/master | 2021-01-20T02:17:01.186461 | 2010-11-26T22:26:25 | 2010-11-26T22:26:25 | 1,856,141 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,091 | cpp | // Displays.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "Displays.h"
#include "DisplaysDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CDisplaysApp
BEGIN_MESSAGE_MAP(CDisplaysApp, CWinApp)
//{{AFX_MSG_MAP(CDisplaysApp)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG
ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CDisplaysApp construction
CDisplaysApp::CDisplaysApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
/////////////////////////////////////////////////////////////////////////////
// The one and only CDisplaysApp object
CDisplaysApp theApp;
/////////////////////////////////////////////////////////////////////////////
// CDisplaysApp initialization
BOOL CDisplaysApp::InitInstance()
{
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need.
#ifdef _AFXDLL
Enable3dControls(); // Call this when using MFC in a shared DLL
#else
Enable3dControlsStatic(); // Call this when linking to MFC statically
#endif
CDisplaysDlg dlg;
m_pMainWnd = &dlg;
int nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
| [
"[email protected]"
] | [
[
[
1,
74
]
]
] |
68495b9d40b3a2ccdb5f5d5b6803c1885ef1a7ac | 6477cf9ac119fe17d2c410ff3d8da60656179e3b | /Projects/openredalert/src/game/FibHeapEntry.cpp | 898d0eb19a27f42790d9975794573162948214a8 | [] | no_license | crutchwalkfactory/motocakerteam | 1cce9f850d2c84faebfc87d0adbfdd23472d9f08 | 0747624a575fb41db53506379692973e5998f8fe | refs/heads/master | 2021-01-10T12:41:59.321840 | 2010-12-13T18:19:27 | 2010-12-13T18:19:27 | 46,494,539 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,064 | cpp | // FibHeapEntry.cpp
// 1.0
// This file is part of OpenRedAlert.
//
// OpenRedAlert is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 2 of the License.
//
// OpenRedAlert is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with OpenRedAlert. If not, see <http://www.gnu.org/licenses/>.
#include "FibHeapEntry.h"
#include "SDL/SDL_types.h"
#include "TileRef.h"
FibHeapEntry::FibHeapEntry(TileRef* val, Uint32 k)
{
lnkTileRef = val;
key = k;
}
TileRef* FibHeapEntry::getValue()
{
return lnkTileRef;
}
void FibHeapEntry::setKey(Uint32 k)
{
key = k;
}
Uint32& FibHeapEntry::getKey()
{
return key;
}
| [
"[email protected]"
] | [
[
[
1,
43
]
]
] |
dc5fb86b7028db40da5e2a9b05672392696335e6 | 91b964984762870246a2a71cb32187eb9e85d74e | /often_use_res/dataSub1/wordToolTip.inc | 5ac2721478aecd69e0f5489e24a2ffeae1aada59 | [] | no_license | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UHC | C++ | false | false | 834 | inc | "직업" "상대의 직업에 대해서 질문합니다."
"이름" "상대의 이름을 묻습니다."
"근황" "근황을 묻습니다. 기쁜일 또는 고민거리를 얘기할 때도 있습니다.\n대화 중 간혹 돌발적인 퀘스트가 진행되기도 합니다."
"사건" "이런저런 사건들에 대한 얘기를 들을 수 있습니다.\n대화 중 간혹 돌발적인 퀘스트가 진행되기도 합니다."
"작별" "작별 인사를 하고 대화를 끝냅니다."
"아름답다" "상대에게 아름답다는 칭찬의 말을 건넵니다."
"보보쿠" "대장장이 보보쿠에 대한 정보를 얻을 수 있습니다."
"쥬리아" "시티홀 관리자 쥬리아에 대한 정보를 얻을 수 있습니다."
"태엽장치" "마드리갈의 중추신경이라고 할 수 있는 기계 장치입니다." | [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
9
]
]
] |
5b0e5214eed065cc94231afdd44093d228acf238 | e776dbbd4feab1ce37ad62e5608e22a55a541d22 | /luadbg/MainFrm.cpp | e65c4a1b5c240c19fc8debc930ab04577ff82b5e | [] | no_license | EmuxEvans/sailing | 80f2e2b0ae0f821ce6da013c3f67edabc8ca91ec | 6d3a0f02732313f41518839376c5c0067aea4c0f | refs/heads/master | 2016-08-12T23:47:57.509147 | 2011-04-06T03:39:19 | 2011-04-06T03:39:19 | 43,952,647 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,445 | cpp | // MainFrm.cpp : implmentation of the CMainFrame class
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "resource.h"
#include <skates\skates.h>
#include "LuaDebugClient.h"
#include "AboutDlg.h"
#include "DropFileHandler.h"
#include "FileManager.h"
#include "DialogWindow.h"
#include "DebugHostWindow.h"
#include "CommandWindow.h"
#include "MainFrm.h"
#include "SciLexerEdit.h"
#include "LuaEditView.h"
#include "LuaDebugHooker.h"
CMainFrame::CMainFrame() : m_FileManager(&m_view)
{
}
CMainFrame::~CMainFrame()
{
}
BOOL CMainFrame::PreTranslateMessage(MSG* pMsg)
{
if(dockwins::CDockingFrameImpl<CMainFrame>::PreTranslateMessage(pMsg))
return TRUE;
return m_view.PreTranslateMessage(pMsg);
}
BOOL CMainFrame::OnIdle()
{
UIUpdateToolBar();
UISetCheck(ID_VIEW_DEBUGHOST, m_DebugHostWindow.IsVisible());
UISetCheck(ID_VIEW_COMMAND, m_CommandWindow.IsVisible());
m_FileManager.UpdateUI();
return FALSE;
}
BOOL CMainFrame::IsReadyForDrop()
{
return TRUE;
}
BOOL CMainFrame::HandleDroppedFile(LPCTSTR szBuff)
{
LPCTSTR pDot;
pDot = _tcsrchr(szBuff, _T('.'));
if(pDot==NULL || _tcsicmp(pDot+1, _T("lua"))!=0) return TRUE;
m_FileManager.Open(szBuff);
return TRUE;
}
void CMainFrame::EndDropFiles()
{
}
LRESULT CMainFrame::OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
// create command bar window
HWND hWndCmdBar = m_CmdBar.Create(m_hWnd, rcDefault, NULL, ATL_SIMPLE_CMDBAR_PANE_STYLE);
// attach menu
m_CmdBar.AttachMenu(GetMenu());
// load command bar images
m_CmdBar.LoadImages(IDR_MAINFRAME);
// remove old menu
SetMenu(NULL);
HWND hWndToolBar = CreateSimpleToolBarCtrl(m_hWnd, IDR_MAINFRAME, FALSE, ATL_SIMPLE_TOOLBAR_PANE_STYLE);
CreateSimpleReBar(ATL_SIMPLE_REBAR_NOBORDER_STYLE);
AddSimpleReBarBand(hWndCmdBar);
AddSimpleReBarBand(hWndToolBar, NULL, TRUE);
CreateSimpleStatusBar();
m_hWndClient = m_view.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, WS_EX_CLIENTEDGE);
UIAddToolBar(hWndToolBar);
UISetCheck(ID_VIEW_TOOLBAR, 1);
UISetCheck(ID_VIEW_STATUS_BAR, 1);
UISetCheck(ID_VIEW_OUTPUT, 1);
// register object for message filtering and idle updates
CMessageLoop* pLoop = _Module.GetMessageLoop();
ATLASSERT(pLoop != NULL);
pLoop->AddMessageFilter(this);
pLoop->AddIdleHandler(this);
CMenuHandle menuMain = m_CmdBar.GetMenu();
m_view.SetWindowMenu(menuMain.GetSubMenu(WINDOW_MENU_POSITION));
RegisterDropHandler();
InitializeDockingFrame();
DWORD dwStyle=WS_OVERLAPPEDWINDOW | WS_POPUP| WS_CLIPCHILDREN | WS_CLIPSIBLINGS;
CRect rcBar(0, 0, 100, 200);
m_DebugHostWindow.Create(m_hWnd, rcBar, _T("Debug Host"), dwStyle);
DockWindow(m_DebugHostWindow, dockwins::CDockingSide(dockwins::CDockingSide::sBottom),
0/*nBar*/,float(0.5)/*fPctPos*/, 100 /*nWidth*/,200/* nHeight*/);
m_CommandWindow.Create(m_hWnd, rcBar, _T("Command"), dwStyle);
DockWindow(m_CommandWindow, dockwins::CDockingSide(dockwins::CDockingSide::sBottom),
0/*nBar*/,float(0.5)/*fPctPos*/, 100 /*nWidth*/,200/* nHeight*/);
SendMessage(CWM_INITIALIZE, 0, 0);
m_FindDlg.Create(m_hWnd);
m_ReplaceDlg.Create(m_hWnd);
return 0;
}
LRESULT CMainFrame::OnInitialize(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
sstate::CDockWndMgr mgrDockWnds;
mgrDockWnds.Add(sstate::CDockingWindowStateAdapter<CDebugHostWindow>(m_DebugHostWindow));
mgrDockWnds.Add(sstate::CDockingWindowStateAdapter<CCommandWindow>(m_CommandWindow));
m_stateMgr.Initialize(m_hWnd);
m_stateMgr.Add(sstate::CRebarStateAdapter(m_hWndToolBar));
m_stateMgr.Add(sstate::CToggleWindowAdapter(m_hWndStatusBar));
m_stateMgr.Add(mgrDockWnds);
CRegKey key;
if(key.Open(HKEY_CURRENT_USER, _T("SOFTWARE\\Sailing\\LuaEdit"), KEY_READ)==ERROR_SUCCESS)
{
sstate::CStgRegistry reg(key.Detach());
m_stateMgr.Restore(reg);
}
else
m_stateMgr.RestoreDefault();
UpdateLayout();
return 0;
}
LRESULT CMainFrame::OnClose(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
if(CLuaDebugManager::GetDefault()->GetDebugHooker()) {
if(CLuaDebugManager::GetDefault()->GetDebugHooker()->GetLuaDebugClient()->IsStop()) {
CLuaDebugManager::GetDefault()->GetDebugHooker()->GetLuaDebugClient()->Continue();
}
if(CLuaDebugManager::GetDefault()->GetDebugHooker()->GetLuaDebugClient()->IsConnected()) {
CLuaDebugManager::GetDefault()->GetDebugHooker()->GetLuaDebugClient()->Disconnect();
}
}
CRegKey key;
if(key.Open(HKEY_CURRENT_USER, _T("SOFTWARE\\Sailing\\LuaEdit"), KEY_WRITE)==ERROR_SUCCESS || key.Create(HKEY_CURRENT_USER,_T("SOFTWARE\\Sailing\\LuaEdit"))==ERROR_SUCCESS) {
sstate::CStgRegistry reg(key.Detach());
m_stateMgr.Store(reg);
}
bHandled = FALSE;
return 0;
}
LRESULT CMainFrame::OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
// unregister message filtering and idle updates
CMessageLoop* pLoop = _Module.GetMessageLoop();
ATLASSERT(pLoop != NULL);
pLoop->RemoveMessageFilter(this);
pLoop->RemoveIdleHandler(this);
bHandled = FALSE;
return 1;
}
LRESULT CMainFrame::OnFileNew(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
m_FileManager.New();
return 0;
}
LRESULT CMainFrame::OnFileOpen(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
CFileDialog a(TRUE, _T("*.lua"), NULL, OFN_FILEMUSTEXIST, _T("Lua Source File (*.lua)\0*.lua\0"));
if(a.DoModal()!=IDOK) return 0;
HandleDroppedFile(a.m_szFileName);
return 0;
}
LRESULT CMainFrame::OnFileClose(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
if(m_view.GetActivePage()>=0)
m_view.RemovePage(m_view.GetActivePage());
return 0;
}
LRESULT CMainFrame::OnFileSave(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
int nIndex = m_view.GetActivePage();
if(nIndex>=0) {
if(m_FileManager.IsNewFile(nIndex)) {
BOOL bHandled = TRUE;
return OnFileSaveAs(0, 0, NULL, bHandled);
}
m_FileManager.Save(nIndex);
}
return 0;
}
LRESULT CMainFrame::OnFileSaveAs(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
int nIndex = m_view.GetActivePage();
if(nIndex>=0) {
CFileDialog a(FALSE, _T("*.lua"), m_FileManager.GetFileName(nIndex), 0, _T("Lua Source File (*.lua)\0*.lua\0"));
if(a.DoModal()!=IDOK) return 0;
m_FileManager.Save(nIndex, a.m_szFileName);
return 0;
}
return 0;
}
LRESULT CMainFrame::OnFileCloseAll(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
for(int i=m_view.GetPageCount()-1; i>=0; i--) {
m_FileManager.Close(i);
}
return 0;
}
LRESULT CMainFrame::OnFileSaveAll(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
for(int nIndex=m_view.GetPageCount()-1; nIndex>=0; nIndex--) {
if(m_FileManager.IsNewFile(nIndex)) {
CFileDialog a(FALSE, _T("*.lua"), m_FileManager.GetFileName(nIndex), 0, _T("Lua Source File (*.lua)\0*.lua\0"));
if(a.DoModal()!=IDOK) break;
m_FileManager.Save(nIndex, a.m_szFileName);
}
m_FileManager.Save(nIndex);
}
return 0;
}
LRESULT CMainFrame::OnFileExit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
PostMessage(WM_CLOSE);
return 0;
}
LRESULT CMainFrame::OnEditUndo(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
if(m_view.GetActivePage()<0)
return 0;
CLuaEditView* pView;
pView = (CLuaEditView*)m_view.GetPageData(m_view.GetActivePage());
pView->Undo();
return 0;
}
LRESULT CMainFrame::OnEditRedo(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
if(m_view.GetActivePage()<0)
return 0;
CLuaEditView* pView;
pView = (CLuaEditView*)m_view.GetPageData(m_view.GetActivePage());
pView->Redo();
return 0;
}
LRESULT CMainFrame::OnEditCut(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
if(m_view.GetActivePage()<0)
return 0;
CLuaEditView* pView;
pView = (CLuaEditView*)m_view.GetPageData(m_view.GetActivePage());
pView->Cut();
return 0;
}
LRESULT CMainFrame::OnEditCopy(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
if(m_view.GetActivePage()<0)
return 0;
CLuaEditView* pView;
pView = (CLuaEditView*)m_view.GetPageData(m_view.GetActivePage());
pView->Copy();
return 0;
}
LRESULT CMainFrame::OnEditPaste(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
if(m_view.GetActivePage()<0)
return 0;
CLuaEditView* pView;
pView = (CLuaEditView*)m_view.GetPageData(m_view.GetActivePage());
pView->Paste();
return 0;
}
LRESULT CMainFrame::OnEditFind(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
if(m_view.GetActivePage()<0)
return 0;
m_FindDlg.ShowWindow(SW_SHOW);
return 0;
}
LRESULT CMainFrame::OnEditFindNext(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
if(m_view.GetActivePage()<0)
return 0;
return 0;
}
LRESULT CMainFrame::OnEditReplace(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
if(m_view.GetActivePage()<0)
return 0;
m_ReplaceDlg.ShowWindow(SW_SHOW);
return 0;
}
LRESULT CMainFrame::OnEditGoTo(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
if(m_view.GetActivePage()<0)
return 0;
int nLineNumber, nLineMax;
CLuaEditView* pView;
pView = (CLuaEditView*)m_view.GetPageData(m_view.GetActivePage());
nLineMax = (int)pView->GetLineCount();
nLineNumber = (int)pView->GetCurrentLine();
CGoToLineDlg Dlg(nLineMax, nLineNumber);
if(Dlg.DoModal(m_hWnd)!=IDOK) return 0;
pView->GotoLine(Dlg.m_nLineNumber);
return 0;
}
LRESULT CMainFrame::OnBookmarkToggle(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
if(m_view.GetActivePage()<0)
return 0;
CLuaEditView* pView;
pView = (CLuaEditView*)m_view.GetPageData(m_view.GetActivePage());
long lLine = pView->GetCurrentLine();
if(pView->HasBookmark(lLine)) {
pView->DeleteBookmark(lLine);
} else {
pView->AddBookmark(lLine);
}
return 0;
}
LRESULT CMainFrame::OnBookmarkNext(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
if(m_view.GetActivePage()<0)
return 0;
CLuaEditView* pView;
pView = (CLuaEditView*)m_view.GetPageData(m_view.GetActivePage());
pView->FindNextBookmark();
return 0;
}
LRESULT CMainFrame::OnBookmarkPrev(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
if(m_view.GetActivePage()<0)
return 0;
CLuaEditView* pView;
pView = (CLuaEditView*)m_view.GetPageData(m_view.GetActivePage());
pView->FindPreviousBookmark();
return 0;
}
LRESULT CMainFrame::OnViewToolBar(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
static BOOL bVisible = TRUE; // initially visible
bVisible = !bVisible;
CReBarCtrl rebar = m_hWndToolBar;
int nBandIndex = rebar.IdToIndex(ATL_IDW_BAND_FIRST + 1); // toolbar is 2nd added band
rebar.ShowBand(nBandIndex, bVisible);
UISetCheck(ID_VIEW_TOOLBAR, bVisible);
UpdateLayout();
return 0;
}
LRESULT CMainFrame::OnViewStatusBar(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
BOOL bVisible = !::IsWindowVisible(m_hWndStatusBar);
::ShowWindow(m_hWndStatusBar, bVisible ? SW_SHOWNOACTIVATE : SW_HIDE);
UISetCheck(ID_VIEW_STATUS_BAR, bVisible);
UpdateLayout();
return 0;
}
LRESULT CMainFrame::OnDebugAttachHost(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
if(CLuaDebugManager::GetDefault()->GetDebugHooker()) {
MessageBox("Already Attached");
return 0;
}
if(m_AttachHostDlg.DoModal(m_hWnd)!=IDOK) return 0;
if(!CLuaDebugManager::GetDefault()->NewHooker(this)) {
MessageBox("Already Attached");
return 0;
}
if(!CLuaDebugManager::GetDefault()->GetDebugHooker()->Connect(m_AttachHostDlg.m_szAddress, m_AttachHostDlg.m_nCID)) {
MessageBox("Connect Error");
CLuaDebugManager::GetDefault()->DeleteHooker();
return 0;
}
return 0;
}
LRESULT CMainFrame::OnDebugDetachHost(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
if(!CLuaDebugManager::GetDefault()->GetDebugHooker()) {
MessageBox("Not Attach");
return 0;
}
CLuaDebugManager::GetDefault()->GetDebugHooker()->Disconnect();
CLuaDebugManager::GetDefault()->DeleteHooker();
return 0;
}
LRESULT CMainFrame::OnDebugBeginHost(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
return 0;
}
LRESULT CMainFrame::OnDebugHostSetting(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
m_HostSettingDlg.DoModal(m_hWnd);
return 0;
}
LRESULT CMainFrame::OnDebugContinue(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
if(!CLuaDebugManager::GetDefault()->GetDebugHooker()) {
MessageBox("Not Attach");
return 0;
}
if(!CLuaDebugManager::GetDefault()->GetDebugHooker()->GetLuaDebugClient()->IsStop()) {
MessageBox("Not Stop");
return 0;
}
CLuaDebugManager::GetDefault()->GetDebugHooker()->GetLuaDebugClient()->Continue();
m_DebugHostWindow.m_Dlg.Update(NULL, 0);
return 0;
}
LRESULT CMainFrame::OnAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
CAboutDlg dlg;
dlg.DoModal();
return 0;
}
LRESULT CMainFrame::OnWindowActivate(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
int nPage = wID - ID_WINDOW_TABFIRST;
m_view.SetActivePage(nPage);
return 0;
}
LRESULT CMainFrame::OnWindowNext(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
if(m_view.GetActivePage()>=0)
m_view.SetActivePage((m_view.GetActivePage()+1+m_view.GetPageCount()) % m_view.GetPageCount());
return 0;
}
LRESULT CMainFrame::OnWindowPrev(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
if(m_view.GetActivePage()>=0)
m_view.SetActivePage((m_view.GetActivePage()-1+m_view.GetPageCount()) % m_view.GetPageCount());
return 0;
}
| [
"gamemake@74c81372-9d52-0410-afc2-f743258a769a"
] | [
[
[
1,
496
]
]
] |
803295b8588627a84013a99510224b8677a26961 | 073dfce42b384c9438734daa8ee2b575ff100cc9 | /RCF/include/RCF/ConnectionOrientedClientTransport.hpp | b468bf52958bfd7858ada1cfee9076460fdadd14 | [] | no_license | r0ssar00/iTunesSpeechBridge | a489426bbe30ac9bf9c7ca09a0b1acd624c1d9bf | 71a27a52e66f90ade339b2b8a7572b53577e2aaf | refs/heads/master | 2020-12-24T17:45:17.838301 | 2009-08-24T22:04:48 | 2009-08-24T22:04:48 | 285,393 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,261 | hpp |
//******************************************************************************
// RCF - Remote Call Framework
// Copyright (c) 2005 - 2009, Jarl Lindrud. All rights reserved.
// Consult your license for conditions of use.
// Version: 1.1
// Contact: jarl.lindrud <at> gmail.com
//******************************************************************************
#ifndef INCLUDE_RCF_CONNECTIONORIENTEDCLIENTTRANSPORT_HPP
#define INCLUDE_RCF_CONNECTIONORIENTEDCLIENTTRANSPORT_HPP
#include <boost/enable_shared_from_this.hpp>
#include <RCF/AmiThreadPool.hpp>
#include <RCF/AsyncFilter.hpp>
#include <RCF/ByteOrdering.hpp>
#include <RCF/ClientProgress.hpp>
#include <RCF/ClientTransport.hpp>
#include <RCF/Export.hpp>
#include <RCF/RecursionLimiter.hpp>
namespace RCF {
class ConnectionOrientedClientTransport;
class ClientFilterProxy;
class TcpClientTransport;
typedef boost::shared_ptr<TcpClientTransport> TcpClientTransportPtr;
class TcpClientFilterProxy;
class OverlappedAmi;
typedef boost::shared_ptr<OverlappedAmi> OverlappedAmiPtr;
class OverlappedAmi :
public I_OverlappedAmi,
public boost::enable_shared_from_this<OverlappedAmi>
{
public:
OverlappedAmi(ConnectionOrientedClientTransport *pTcpClientTransport) :
mpTransport(pTcpClientTransport)
{
}
~OverlappedAmi()
{
}
void onCompletion(std::size_t numBytes);
void onError(const RCF::Exception & e);
void onTimerExpired(const TimerEntry & timerEntry);
Mutex mMutex;
ConnectionOrientedClientTransport * mpTransport;
OverlappedAmiPtr mThisPtr;
};
void clearSelfReference(OverlappedAmiPtr & overlappedAmiPtr);
class ClientStubCallbackPtr
{
public:
ClientStubCallbackPtr();
void reset(
I_ClientTransportCallback *pClientStub = NULL);
void onConnectCompleted(
bool alreadyConnected = false);
void onSendCompleted();
void onReceiveCompleted();
void onTimerExpired();
void onError(const std::exception &e);
RcfServer * getAsyncDispatcher();
private:
I_ClientTransportCallback * mpClientStub;
std::size_t mCount;
};
class RCF_EXPORT ConnectionOrientedClientTransport :
public I_ClientTransport,
public WithProgressCallback
{
public:
typedef boost::function0<void> CloseFunctor;
typedef boost::function0<void> NotifyCloseFunctor;
ConnectionOrientedClientTransport(const ConnectionOrientedClientTransport &rhs);
ConnectionOrientedClientTransport();
~ConnectionOrientedClientTransport();
void setCloseFunctor(const CloseFunctor &closeFunctor);
void setNotifyCloseFunctor(const NotifyCloseFunctor ¬ifyCloseFunctor);
void close();
void setMaxSendSize(std::size_t maxSendSize);
std::size_t getMaxSendSize();
private:
void read(const ByteBuffer &byteBuffer_, std::size_t bytesRequested);
void write(const std::vector<ByteBuffer> &byteBuffers);
std::size_t timedSend(const std::vector<ByteBuffer> &data);
std::size_t timedReceive(ByteBuffer &byteBuffer, std::size_t bytesRequested);
void setTransportFilters(const std::vector<FilterPtr> &filters);
void getTransportFilters(std::vector<FilterPtr> &filters);
void connectTransportFilters();
void connect(I_ClientTransportCallback &clientStub, unsigned int timeoutMs);
void disconnect(unsigned int timeoutMs);
int timedSend(const char *buffer, std::size_t bufferLen);
int timedReceive(char *buffer, std::size_t bufferLen);
protected:
void onReadCompleted(const ByteBuffer &byteBuffer, int error);
void onWriteCompleted(std::size_t bytes, int error);
bool mOwn;
bool mClosed;
std::size_t mMaxSendSize;
std::size_t mBytesTransferred;
std::size_t mBytesSent;
std::size_t mBytesRead;
std::size_t mBytesTotal;
int mError;
unsigned int mEndTimeMs;
CloseFunctor mCloseFunctor;
NotifyCloseFunctor mNotifyCloseFunctor;
std::vector<FilterPtr> mTransportFilters;
std::vector<ByteBuffer> mByteBuffers;
std::vector<ByteBuffer> mSlicedByteBuffers;
boost::shared_ptr<std::vector<char> > mReadBufferPtr;
boost::shared_ptr<std::vector<char> > mReadBuffer2Ptr;
friend class ClientFilterProxy;
private:
virtual std::size_t implRead(
const ByteBuffer &byteBuffer_,
std::size_t bytesRequested) = 0;
virtual std::size_t implReadAsync(
const ByteBuffer &byteBuffer_,
std::size_t bytesRequested) = 0;
virtual std::size_t implWrite(
const std::vector<ByteBuffer> &byteBuffers) = 0;
virtual std::size_t implWriteAsync(
const std::vector<ByteBuffer> &byteBuffers) = 0;
virtual void implConnect(
I_ClientTransportCallback &clientStub,
unsigned int timeoutMs) = 0;
virtual void implConnectAsync(
I_ClientTransportCallback &clientStub,
unsigned int timeoutMs) = 0;
virtual void implClose() = 0;
public:
enum State {
Connecting,
Reading,
Writing
};
bool mAsync;
bool mRegisteredForAmi;
State mPreState;
State mPostState;
std::size_t mReadBufferPos;
std::size_t mWriteBufferPos;
ClientStubCallbackPtr mClientStubCallbackPtr;
ByteBuffer * mpClientStubReadBuffer;
ByteBuffer mReadBuffer;
std::size_t mBytesToRead;
std::size_t mBytesRequested;
ByteBuffer mByteBuffer;
private:
Mutex mOverlappedPtrMutex;
OverlappedAmiPtr mOverlappedPtr;
public:
OverlappedAmiPtr getOverlappedPtr();
typedef boost::shared_ptr<Lock> LockPtr;
std::pair<LockPtr,OverlappedAmiPtr> detachOverlappedPtr();
TimerEntry mTimerEntry;
friend class TcpClientFilterProxy;
public:
void setAsync(bool async);
void cancel();
TimerEntry setTimer(
boost::uint32_t timeoutMs,
I_ClientTransportCallback *pClientStub);
void killTimer(
const TimerEntry & timerEntry);
void onTimerExpired(
const TimerEntry & timerEntry);
private:
RecursionState<std::size_t, int> mRecursionState;
// TODO: Access control.
public:
void onTransitionCompleted(std::size_t bytesTransferred);
void onCompletion(int bytesTransferred);
void onTimedRecvCompleted(int ret, int err);
void onTimedSendCompleted(int ret, int err);
void onConnectCompleted(int err);
void transition();
void onTransitionCompleted_(std::size_t bytesTransferred);
void issueRead(const ByteBuffer &buffer, std::size_t bytesToRead);
void issueWrite(const std::vector<ByteBuffer> &byteBuffers);
int send(
I_ClientTransportCallback &clientStub,
const std::vector<ByteBuffer> &data,
unsigned int timeoutMs);
int receive(
I_ClientTransportCallback &clientStub,
ByteBuffer &byteBuffer,
unsigned int timeoutMs);
friend class OverlappedAmi;
};
} // namespace RCF
#endif // ! INCLUDE_RCF_CONNECTIONORIENTEDCLIENTTRANSPORT_HPP
| [
"[email protected]"
] | [
[
[
1,
259
]
]
] |
77e97eadc4932433a262860951bfaae42ce5d654 | f8403b6b1005f80d2db7fad9ee208887cdca6aec | /JuceLibraryCode/modules/juce_graphics/native/juce_win32_Fonts.cpp | c1d29a17318602623ac9b2749677f66692242147 | [] | no_license | sonic59/JuceText | 25544cb07e5b414f9d7109c0826a16fc1de2e0d4 | 5ac010ffe59c2025d25bc0f9c02fc829ada9a3d2 | refs/heads/master | 2021-01-15T13:18:11.670907 | 2011-10-29T19:03:25 | 2011-10-29T19:03:25 | 2,507,112 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,249 | 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.
==============================================================================
*/
namespace FontEnumerators
{
int CALLBACK fontEnum2 (ENUMLOGFONTEXW* lpelfe, NEWTEXTMETRICEXW*, int type, LPARAM lParam)
{
if (lpelfe != nullptr && (type & RASTER_FONTTYPE) == 0)
{
const String fontName (lpelfe->elfLogFont.lfFaceName);
((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
}
return 1;
}
int CALLBACK fontEnum1 (ENUMLOGFONTEXW* lpelfe, NEWTEXTMETRICEXW*, int type, LPARAM lParam)
{
if (lpelfe != nullptr && (type & RASTER_FONTTYPE) == 0)
{
LOGFONTW lf = { 0 };
lf.lfWeight = FW_DONTCARE;
lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
lf.lfQuality = DEFAULT_QUALITY;
lf.lfCharSet = DEFAULT_CHARSET;
lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
lf.lfPitchAndFamily = FF_DONTCARE;
const String fontName (lpelfe->elfLogFont.lfFaceName);
fontName.copyToUTF16 (lf.lfFaceName, sizeof (lf.lfFaceName));
HDC dc = CreateCompatibleDC (0);
EnumFontFamiliesEx (dc, &lf,
(FONTENUMPROCW) &fontEnum2,
lParam, 0);
DeleteDC (dc);
}
return 1;
}
}
StringArray Font::findAllTypefaceNames()
{
StringArray results;
HDC dc = CreateCompatibleDC (0);
{
LOGFONTW lf = { 0 };
lf.lfWeight = FW_DONTCARE;
lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
lf.lfQuality = DEFAULT_QUALITY;
lf.lfCharSet = DEFAULT_CHARSET;
lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
lf.lfPitchAndFamily = FF_DONTCARE;
EnumFontFamiliesEx (dc, &lf,
(FONTENUMPROCW) &FontEnumerators::fontEnum1,
(LPARAM) &results, 0);
}
DeleteDC (dc);
results.sort (true);
return results;
}
extern bool juce_IsRunningInWine();
struct DefaultFontNames
{
DefaultFontNames()
{
if (juce_IsRunningInWine())
{
// If we're running in Wine, then use fonts that might be available on Linux..
defaultSans = "Bitstream Vera Sans";
defaultSerif = "Bitstream Vera Serif";
defaultFixed = "Bitstream Vera Sans Mono";
}
else
{
defaultSans = "Verdana";
defaultSerif = "Times";
defaultFixed = "Lucida Console";
defaultFallback = "Tahoma"; // (contains plenty of unicode characters)
}
}
String defaultSans, defaultSerif, defaultFixed, defaultFallback;
};
Typeface::Ptr Font::getDefaultTypefaceForFont (const Font& font)
{
static DefaultFontNames defaultNames;
String faceName (font.getTypefaceName());
if (faceName == Font::getDefaultSansSerifFontName()) faceName = defaultNames.defaultSans;
else if (faceName == Font::getDefaultSerifFontName()) faceName = defaultNames.defaultSerif;
else if (faceName == Font::getDefaultMonospacedFontName()) faceName = defaultNames.defaultFixed;
Font f (font);
f.setTypefaceName (faceName);
return Typeface::createSystemTypefaceFor (f);
}
//==============================================================================
class WindowsTypeface : public Typeface
{
public:
WindowsTypeface (const Font& font)
: Typeface (font.getTypefaceName()),
fontH (0),
previousFontH (0),
dc (CreateCompatibleDC (0)),
ascent (1.0f),
defaultGlyph (-1),
bold (font.isBold()),
italic (font.isItalic())
{
loadFont();
if (GetTextMetrics (dc, &tm))
{
ascent = tm.tmAscent / (float) tm.tmHeight;
defaultGlyph = getGlyphForChar (dc, tm.tmDefaultChar);
createKerningPairs (dc, (float) tm.tmHeight);
}
}
~WindowsTypeface()
{
SelectObject (dc, previousFontH); // Replacing the previous font before deleting the DC avoids a warning in BoundsChecker
DeleteDC (dc);
if (fontH != 0)
DeleteObject (fontH);
}
float getAscent() const { return ascent; }
float getDescent() const { return 1.0f - ascent; }
float getStringWidth (const String& text)
{
const CharPointer_UTF16 utf16 (text.toUTF16());
const size_t numChars = utf16.length();
HeapBlock<int16> results (numChars + 1);
results[numChars] = -1;
float x = 0;
if (GetGlyphIndices (dc, utf16, (int) numChars, reinterpret_cast <WORD*> (results.getData()),
GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR)
{
for (size_t i = 0; i < numChars; ++i)
x += getKerning (dc, results[i], results[i + 1]);
}
return x;
}
void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
{
const CharPointer_UTF16 utf16 (text.toUTF16());
const size_t numChars = utf16.length();
HeapBlock<int16> results (numChars + 1);
results[numChars] = -1;
float x = 0;
if (GetGlyphIndices (dc, utf16, (int) numChars, reinterpret_cast <WORD*> (results.getData()),
GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR)
{
resultGlyphs.ensureStorageAllocated ((int) numChars);
xOffsets.ensureStorageAllocated ((int) numChars + 1);
for (size_t i = 0; i < numChars; ++i)
{
resultGlyphs.add (results[i]);
xOffsets.add (x);
x += getKerning (dc, results[i], results[i + 1]);
}
}
xOffsets.add (x);
}
bool getOutlineForGlyph (int glyphNumber, Path& glyphPath)
{
if (glyphNumber < 0)
glyphNumber = defaultGlyph;
GLYPHMETRICS gm;
// (although GetGlyphOutline returns a DWORD, it may be -1 on failure, so treat it as signed int..)
const int bufSize = (int) GetGlyphOutline (dc, (UINT) glyphNumber, GGO_NATIVE | GGO_GLYPH_INDEX,
&gm, 0, 0, &identityMatrix);
if (bufSize > 0)
{
HeapBlock<char> data (bufSize);
GetGlyphOutline (dc, (UINT) glyphNumber, GGO_NATIVE | GGO_GLYPH_INDEX, &gm,
bufSize, data, &identityMatrix);
const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
const float scaleX = 1.0f / tm.tmHeight;
const float scaleY = -scaleX;
while ((char*) pheader < data + bufSize)
{
glyphPath.startNewSubPath (scaleX * pheader->pfxStart.x.value,
scaleY * pheader->pfxStart.y.value);
const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
const char* const curveEnd = ((const char*) pheader) + pheader->cb;
while ((const char*) curve < curveEnd)
{
if (curve->wType == TT_PRIM_LINE)
{
for (int i = 0; i < curve->cpfx; ++i)
glyphPath.lineTo (scaleX * curve->apfx[i].x.value,
scaleY * curve->apfx[i].y.value);
}
else if (curve->wType == TT_PRIM_QSPLINE)
{
for (int i = 0; i < curve->cpfx - 1; ++i)
{
const float x2 = scaleX * curve->apfx[i].x.value;
const float y2 = scaleY * curve->apfx[i].y.value;
float x3 = scaleX * curve->apfx[i + 1].x.value;
float y3 = scaleY * curve->apfx[i + 1].y.value;
if (i < curve->cpfx - 2)
{
x3 = 0.5f * (x2 + x3);
y3 = 0.5f * (y2 + y3);
}
glyphPath.quadraticTo (x2, y2, x3, y3);
}
}
curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
}
pheader = (const TTPOLYGONHEADER*) curve;
glyphPath.closeSubPath();
}
}
return true;
}
private:
static const MAT2 identityMatrix;
HFONT fontH;
HGDIOBJ previousFontH;
HDC dc;
TEXTMETRIC tm;
float ascent;
int defaultGlyph;
bool bold, italic;
struct KerningPair
{
int glyph1, glyph2;
float kerning;
bool operator== (const KerningPair& other) const noexcept
{
return glyph1 == other.glyph1 && glyph2 == other.glyph2;
}
bool operator< (const KerningPair& other) const noexcept
{
return glyph1 < other.glyph1
|| (glyph1 == other.glyph1 && glyph2 < other.glyph2);
}
};
SortedSet<KerningPair> kerningPairs;
void loadFont()
{
SetMapperFlags (dc, 0);
SetMapMode (dc, MM_TEXT);
LOGFONTW lf = { 0 };
lf.lfCharSet = DEFAULT_CHARSET;
lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
lf.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
lf.lfQuality = PROOF_QUALITY;
lf.lfItalic = (BYTE) (italic ? TRUE : FALSE);
lf.lfWeight = bold ? FW_BOLD : FW_NORMAL;
lf.lfHeight = -256;
name.copyToUTF16 (lf.lfFaceName, sizeof (lf.lfFaceName));
HFONT standardSizedFont = CreateFontIndirect (&lf);
if (standardSizedFont != 0)
{
if ((previousFontH = SelectObject (dc, standardSizedFont)) != 0)
{
fontH = standardSizedFont;
OUTLINETEXTMETRIC otm;
if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
{
lf.lfHeight = -(int) otm.otmEMSquare;
fontH = CreateFontIndirect (&lf);
SelectObject (dc, fontH);
DeleteObject (standardSizedFont);
}
}
}
}
void createKerningPairs (HDC dc, const float height)
{
HeapBlock<KERNINGPAIR> rawKerning;
const DWORD numKPs = GetKerningPairs (dc, 0, 0);
rawKerning.calloc (numKPs);
GetKerningPairs (dc, numKPs, rawKerning);
kerningPairs.ensureStorageAllocated ((int) numKPs);
for (DWORD i = 0; i < numKPs; ++i)
{
KerningPair kp;
kp.glyph1 = getGlyphForChar (dc, rawKerning[i].wFirst);
kp.glyph2 = getGlyphForChar (dc, rawKerning[i].wSecond);
const int standardWidth = getGlyphWidth (dc, kp.glyph1);
kp.kerning = (standardWidth + rawKerning[i].iKernAmount) / height;
kerningPairs.add (kp);
kp.glyph2 = -1; // add another entry for the standard width version..
kp.kerning = standardWidth / height;
kerningPairs.add (kp);
}
}
static int getGlyphForChar (HDC dc, juce_wchar character)
{
const WCHAR charToTest[] = { (WCHAR) character, 0 };
WORD index = 0;
if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) == GDI_ERROR
|| index == 0xffff)
return -1;
return index;
}
static int getGlyphWidth (HDC dc, int glyphNumber)
{
GLYPHMETRICS gm;
gm.gmCellIncX = 0;
GetGlyphOutline (dc, (UINT) glyphNumber, GGO_NATIVE | GGO_GLYPH_INDEX, &gm, 0, 0, &identityMatrix);
return gm.gmCellIncX;
}
float getKerning (HDC dc, const int glyph1, const int glyph2)
{
KerningPair kp;
kp.glyph1 = glyph1;
kp.glyph2 = glyph2;
int index = kerningPairs.indexOf (kp);
if (index < 0)
{
kp.glyph2 = -1;
index = kerningPairs.indexOf (kp);
if (index < 0)
{
kp.glyph2 = -1;
kp.kerning = getGlyphWidth (dc, kp.glyph1) / (float) tm.tmHeight;
kerningPairs.add (kp);
return kp.kerning;
}
}
return kerningPairs.getReference (index).kerning;
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsTypeface);
};
const MAT2 WindowsTypeface::identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
| [
"[email protected]"
] | [
[
[
1,
415
]
]
] |
0b264a328794b4aaf18fc2a13293e2d55c188ea2 | 021e8c48a44a56571c07dd9830d8bf86d68507cb | /build/vtk/vtkPostgreSQLDatabase.h | 2f96f5d20ada225c5f8976d94424f57503de3c94 | [
"BSD-3-Clause"
] | permissive | Electrofire/QdevelopVset | c67ae1b30b0115d5c2045e3ca82199394081b733 | f88344d0d89beeec46f5dc72c20c0fdd9ef4c0b5 | refs/heads/master | 2021-01-18T10:44:01.451029 | 2011-05-01T23:52:15 | 2011-05-01T23:52:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,259 | h | /* -*- Mode: C++; -*- */
/*=========================================================================
Program: Visualization Toolkit
Module: vtkPostgreSQLDatabase.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
// .NAME vtkPostgreSQLDatabase - maintain a connection to a PostgreSQL database
//
// .SECTION Description
//
// PostgreSQL (http://www.postgres.org) is a BSD-licensed SQL database.
// It's large, fast, and can not be easily embedded
// inside other applications. Its databases are stored in files that
// belong to another process.
//
// This class provides a VTK interface to PostgreSQL. You do need to
// download external libraries: we need a copy of PostgreSQL 8
// (currently 8.2 or 8.3) so that we can link against the libpq C
// interface.
//
// .SECTION Thanks
//
// Thanks to David Thompson and Andy Wilson from Sandia National
// Laboratories for implementing this class.
//
// .SECTION See Also
// vtkPostgreSQLQuery
#ifndef __vtkPostgreSQLDatabase_h
#define __vtkPostgreSQLDatabase_h
#include "vtkSQLDatabase.h"
class vtkPostgreSQLQuery;
class vtkStringArray;
class vtkPostgreSQLDatabasePrivate;
struct PQconn;
class VTK_IO_EXPORT vtkPostgreSQLDatabase : public vtkSQLDatabase
{
//BTX
friend class vtkPostgreSQLQuery;
friend class vtkPostgreSQLQueryPrivate;
//ETX
public:
vtkTypeMacro(vtkPostgreSQLDatabase, vtkSQLDatabase);
void PrintSelf(ostream& os, vtkIndent indent);
static vtkPostgreSQLDatabase *New();
// Description:
// Open a new connection to the database. You need to set the
// filename before calling this function. Returns true if the
// database was opened successfully; false otherwise.
bool Open( const char* password = 0 );
// Description:
// Close the connection to the database.
void Close();
// Description:
// Return whether the database has an open connection
bool IsOpen();
// Description:
// Return an empty query on this database.
vtkSQLQuery* GetQueryInstance();
// Description:
// Did the last operation generate an error
virtual bool HasError();
// Description:
// Get the last error text from the database
const char* GetLastErrorText();
// Description:
// String representing database type (e.g. "psql").
vtkGetStringMacro(DatabaseType);
// Description:
// The database server host name.
virtual void SetHostName( const char* );
vtkGetStringMacro(HostName);
// Description:
// The user name for connecting to the database server.
virtual void SetUser( const char* );
vtkGetStringMacro(User);
// Description:
// The user's password for connecting to the database server.
virtual void SetPassword( const char* );
// Description:
// The name of the database to connect to.
virtual void SetDatabaseName( const char* );
vtkGetStringMacro(DatabaseName);
// Description:
// Additional options for the database.
virtual void SetConnectOptions( const char* );
vtkGetStringMacro(ConnectOptions);
// Description:
// The port used for connecting to the database.
virtual void SetServerPort( int );
virtual int GetServerPortMinValue()
{
return 0;
}
virtual int GetServerPortMaxValue()
{
return VTK_INT_MAX;
}
vtkGetMacro(ServerPort, int);
// Description:
// Get a URL referencing the current database connection.
// This is not well-defined if the HostName and DatabaseName
// have not been set. The URL will be of the form
// <code>'psql://'[username[':'password]'@']hostname[':'port]'/'database</code> .
virtual vtkStdString GetURL();
// Description:
// Get the list of tables from the database
vtkStringArray* GetTables();
// Description:
// Get the list of fields for a particular table
vtkStringArray* GetRecord( const char* table );
// Description:
// Return whether a feature is supported by the database.
bool IsSupported( int feature );
// Description:
// Return a list of databases on the server.
vtkStringArray* GetDatabases();
// Description:
// Create a new database, optionally dropping any existing database of the same name.
// Returns true when the database is properly created and false on failure.
bool CreateDatabase( const char* dbName, bool dropExisting = false );
// Description:
// Drop a database if it exists.
// Returns true on success and false on failure.
bool DropDatabase( const char* dbName );
// Description:
// Return the SQL string with the syntax to create a column inside a
// "CREATE TABLE" SQL statement.
// NB: this method implements the PostgreSQL-specific syntax:
// <column name> <column type> <column attributes>
virtual vtkStdString GetColumnSpecification(
vtkSQLDatabaseSchema* schema, int tblHandle, int colHandle );
protected:
vtkPostgreSQLDatabase();
~vtkPostgreSQLDatabase();
// Description:
// Create or refresh the map from Postgres column types to VTK array types.
//
// Postgres defines a table for types so that users may define types.
// This adaptor does not support user-defined types or even all of the
// default types defined by Postgres (some are inherently difficult to
// translate into VTK since Postgres allows columns to have composite types,
// vector-valued types, and extended precision types that vtkVariant does
// not support.
//
// This routine examines the pg_types table to get a map from Postgres column
// type IDs (stored as OIDs) to VTK array types. It is called whenever a new
// database connection is initiated.
void UpdateDataTypeMap();
// Description:
// Overridden to determine connection paramters given the URL.
// This is called by CreateFromURL() to initialize the instance.
// Look at CreateFromURL() for details about the URL format.
virtual bool ParseURL(const char* url);
vtkSetStringMacro(DatabaseType);
vtkSetStringMacro(LastErrorText);
void NullTrailingWhitespace( char* msg );
bool OpenInternal( const char* connectionOptions );
vtkTimeStamp URLMTime;
vtkPostgreSQLDatabasePrivate *Connection;
vtkTimeStamp ConnectionMTime;
char* DatabaseType;
char* HostName;
char* User;
char* Password;
char* DatabaseName;
int ServerPort;
char* ConnectOptions;
char* LastErrorText;
private:
vtkPostgreSQLDatabase( const vtkPostgreSQLDatabase& ); // Not implemented.
void operator = ( const vtkPostgreSQLDatabase& ); // Not implemented.
};
// This is basically the body of the SetStringMacro but with a
// call to update an additional vtkTimeStamp. We inline the implementation
// so that wrapping will work.
#define vtkSetStringPlusMTimeMacro(className,name,timeStamp) \
inline void className::Set##name (const char* _arg) \
{ \
vtkDebugMacro(<< this->GetClassName() << " (" << this << "): setting " << #name " to " << (_arg?_arg:"(null)") ); \
if ( this->name == NULL && _arg == NULL) { return;} \
if ( this->name && _arg && (!strcmp(this->name,_arg))) { return;} \
if (this->name) { delete [] this->name; } \
if (_arg) \
{ \
size_t n = strlen(_arg) + 1; \
char *cp1 = new char[n]; \
const char *cp2 = (_arg); \
this->name = cp1; \
do { *cp1++ = *cp2++; } while ( --n ); \
} \
else \
{ \
this->name = NULL; \
} \
this->Modified(); \
this->timeStamp.Modified(); \
this->Close(); /* Force a re-open on next query */ \
}
vtkSetStringPlusMTimeMacro(vtkPostgreSQLDatabase,HostName,URLMTime);
vtkSetStringPlusMTimeMacro(vtkPostgreSQLDatabase,User,URLMTime);
vtkSetStringPlusMTimeMacro(vtkPostgreSQLDatabase,Password,URLMTime);
vtkSetStringPlusMTimeMacro(vtkPostgreSQLDatabase,DatabaseName,URLMTime);
vtkSetStringPlusMTimeMacro(vtkPostgreSQLDatabase,ConnectOptions,URLMTime);
inline void vtkPostgreSQLDatabase::SetServerPort( int _arg )
{
vtkDebugMacro(<< this->GetClassName() << " (" << this << "): setting ServerPort to " << _arg );
if ( this->ServerPort != ( _arg < 0 ? 0 : ( _arg > VTK_INT_MAX ? VTK_INT_MAX : _arg ) ) )
{
this->ServerPort = ( _arg < 0 ? 0 : ( _arg > VTK_INT_MAX ? VTK_INT_MAX : _arg ) );
this->Modified();
this->URLMTime.Modified();
this->Close(); // Force a re-open on next query
}
}
#endif // __vtkPostgreSQLDatabase_h
| [
"ganondorf@ganondorf-VirtualBox.(none)"
] | [
[
[
1,
265
]
]
] |
c1ecf7cbd9f90cacc18006e7a7d866e5f932ac6d | fcf03ead74f6dc103ec3b07ffe3bce81c820660d | /Messaging/TextMTM/txts/TXTSMAIN.CPP | 7a4d0df4f6f792f645bdec2d6aa326f756741e07 | [] | no_license | huellif/symbian-example | 72097c9aec6d45d555a79a30d576dddc04a65a16 | 56f6c5e67a3d37961408fc51188d46d49bddcfdc | refs/heads/master | 2016-09-06T12:49:32.021854 | 2010-10-14T06:31:20 | 2010-10-14T06:31:20 | 38,062,421 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 239 | cpp | // TXTSMAIN.CPP
//
// Copyright (c) 1999 Symbian Ltd. All rights reserved.
//
#include <e32std.h>
#include "txtspan.h"
GLDEF_C void gPanic(TTxtsPanic aPanic)
{
_LIT(KTXTSPanic,"TXTS");
User::Panic(KTXTSPanic,aPanic);
}
| [
"liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca"
] | [
[
[
1,
13
]
]
] |
e052dd1cbebcb3b58a09bff54ea9acc37983abbb | d99132589576273af2c53da2b2e9376399a7c6b7 | /library/Wire.cpp | d6e3d78e52e14a9eaf6c38e8f700225813f6da6c | [] | no_license | ee-444/trimmed_RoverMission | c71cfa6e69556e513b90ba896185f4748fb4beb0 | 04e41b43d285c8da099a5773a0e009e8332abb39 | refs/heads/master | 2021-01-23T00:15:34.434778 | 2011-05-17T23:53:04 | 2011-05-17T23:53:04 | 1,762,413 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,518 | cpp | /*
TwoWire.cpp - TWI/I2C library for Wiring & Arduino
Copyright (c) 2006 Nicholas Zambetti. All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include "twi.h"
#include "Wire.h"
// Initialize Class Variables //////////////////////////////////////////////////
uint8_t TwoWire::rxBuffer[BUFFER_LENGTH];
uint8_t TwoWire::rxBufferIndex = 0;
uint8_t TwoWire::rxBufferLength = 0;
uint8_t TwoWire::txAddress = 0;
uint8_t TwoWire::txBuffer[BUFFER_LENGTH];
uint8_t TwoWire::txBufferIndex = 0;
uint8_t TwoWire::txBufferLength = 0;
uint8_t TwoWire::transmitting = 0;
void (*TwoWire::user_onRequest)(void);
void (*TwoWire::user_onReceive)(int);
// Constructors ////////////////////////////////////////////////////////////////
TwoWire::TwoWire()
{
}
// Public Methods //////////////////////////////////////////////////////////////
void TwoWire::begin(void)
{
rxBufferIndex = 0;
rxBufferLength = 0;
txBufferIndex = 0;
txBufferLength = 0;
twi_init();
}
void TwoWire::begin(uint8_t address)
{
twi_setAddress(address);
twi_attachSlaveTxEvent(onRequestService);
twi_attachSlaveRxEvent(onReceiveService);
begin();
}
void TwoWire::begin(int address)
{
begin((uint8_t)address);
}
uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity)
{
// clamp to buffer length
if(quantity > BUFFER_LENGTH){
quantity = BUFFER_LENGTH;
}
// perform blocking read into buffer
uint8_t read = twi_readFrom(address, rxBuffer, quantity);
// set rx buffer iterator vars
rxBufferIndex = 0;
rxBufferLength = read;
return read;
}
uint8_t TwoWire::requestFrom(int address, int quantity)
{
return requestFrom((uint8_t)address, (uint8_t)quantity);
}
void TwoWire::beginTransmission(uint8_t address)
{
// indicate that we are transmitting
transmitting = 1;
// set address of targeted slave
txAddress = address;
// reset tx buffer iterator vars
txBufferIndex = 0;
txBufferLength = 0;
}
void TwoWire::beginTransmission(int address)
{
beginTransmission((uint8_t)address);
}
uint8_t TwoWire::endTransmission(void)
{
// transmit buffer (blocking)
int8_t ret = twi_writeTo(txAddress, txBuffer, txBufferLength, 1);
// reset tx buffer iterator vars
txBufferIndex = 0;
txBufferLength = 0;
// indicate that we are done transmitting
transmitting = 0;
return ret;
}
// must be called in:
// slave tx event callback
// or after beginTransmission(address)
void TwoWire::send(uint8_t data)
{
if(transmitting){
// in master transmitter mode
// don't bother if buffer is full
if(txBufferLength >= BUFFER_LENGTH){
return;
}
// put byte in tx buffer
txBuffer[txBufferIndex] = data;
++txBufferIndex;
// update amount in buffer
txBufferLength = txBufferIndex;
}else{
// in slave send mode
// reply to master
twi_transmit(&data, 1);
}
}
// must be called in:
// slave tx event callback
// or after beginTransmission(address)
void TwoWire::send(uint8_t* data, uint8_t quantity)
{
if(transmitting){
// in master transmitter mode
for(uint8_t i = 0; i < quantity; ++i){
send(data[i]);
}
}else{
// in slave send mode
// reply to master
twi_transmit(data, quantity);
}
}
// must be called in:
// slave tx event callback
// or after beginTransmission(address)
void TwoWire::send(char* data)
{
send((uint8_t*)data, strlen(data));
}
// must be called in:
// slave tx event callback
// or after beginTransmission(address)
void TwoWire::send(int data)
{
send((uint8_t)data);
}
// must be called in:
// slave rx event callback
// or after requestFrom(address, numBytes)
uint8_t TwoWire::available(void)
{
return rxBufferLength - rxBufferIndex;
}
// must be called in:
// slave rx event callback
// or after requestFrom(address, numBytes)
uint8_t TwoWire::receive(void)
{
// default to returning null char
// for people using with char strings
uint8_t value = '\0';
// get each successive byte on each call
if(rxBufferIndex < rxBufferLength){
value = rxBuffer[rxBufferIndex];
++rxBufferIndex;
}
return value;
}
// behind the scenes function that is called when data is received
void TwoWire::onReceiveService(uint8_t* inBytes, int numBytes)
{
// don't bother if user hasn't registered a callback
if(!user_onReceive){
return;
}
// don't bother if rx buffer is in use by a master requestFrom() op
// i know this drops data, but it allows for slight stupidity
// meaning, they may not have read all the master requestFrom() data yet
if(rxBufferIndex < rxBufferLength){
return;
}
// copy twi rx buffer into local read buffer
// this enables new reads to happen in parallel
for(uint8_t i = 0; i < numBytes; ++i){
rxBuffer[i] = inBytes[i];
}
// set rx iterator vars
rxBufferIndex = 0;
rxBufferLength = numBytes;
// alert user program
user_onReceive(numBytes);
}
// behind the scenes function that is called when data is requested
void TwoWire::onRequestService(void)
{
// don't bother if user hasn't registered a callback
if(!user_onRequest){
return;
}
// reset tx buffer iterator vars
// !!! this will kill any pending pre-master sendTo() activity
txBufferIndex = 0;
txBufferLength = 0;
// alert user program
user_onRequest();
}
// sets function called on slave write
void TwoWire::onReceive( void (*function)(int) )
{
user_onReceive = function;
}
// sets function called on slave read
void TwoWire::onRequest( void (*function)(void) )
{
user_onRequest = function;
}
| [
"[email protected]"
] | [
[
[
1,
256
]
]
] |
abfaf37d199e8192e172f37f535053d61f3e3f53 | 2982a765bb21c5396587c86ecef8ca5eb100811f | /util/wm5/LibMathematics/Query/Wm5Query3Int64.inl | ac3c76c4714602b21bb42b6f614cbf6f5c4066aa | [] | no_license | evanw/cs224final | 1a68c6be4cf66a82c991c145bcf140d96af847aa | af2af32732535f2f58bf49ecb4615c80f141ea5b | refs/heads/master | 2023-05-30T19:48:26.968407 | 2011-05-10T16:21:37 | 2011-05-10T16:21:37 | 1,653,696 | 27 | 9 | null | null | null | null | UTF-8 | C++ | false | false | 5,321 | inl | // Geometric Tools, LLC
// Copyright (c) 1998-2010
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
//
// File Version: 5.0.0 (2010/01/01)
//----------------------------------------------------------------------------
template <typename Real>
Query3Int64<Real>::Query3Int64 (int iVQuantity, const Vector3<Real>* akVertex)
:
Query3<Real>(iVQuantity,akVertex)
{
}
//----------------------------------------------------------------------------
template <typename Real>
Query::Type Query3Int64<Real>::GetType () const
{
return Query::QT_INT64;
}
//----------------------------------------------------------------------------
template <typename Real>
int Query3Int64<Real>::ToPlane (const Vector3<Real>& test, int v0, int v1,
int v2) const
{
const Vector3<Real>& vec0 = mVertices[v0];
const Vector3<Real>& vec1 = mVertices[v1];
const Vector3<Real>& vec2 = mVertices[v2];
int64_t x0 = (int64_t)test[0] - (int64_t)vec0[0];
int64_t y0 = (int64_t)test[1] - (int64_t)vec0[1];
int64_t z0 = (int64_t)test[2] - (int64_t)vec0[2];
int64_t x1 = (int64_t)vec1[0] - (int64_t)vec0[0];
int64_t y1 = (int64_t)vec1[1] - (int64_t)vec0[1];
int64_t z1 = (int64_t)vec1[2] - (int64_t)vec0[2];
int64_t x2 = (int64_t)vec2[0] - (int64_t)vec0[0];
int64_t y2 = (int64_t)vec2[1] - (int64_t)vec0[1];
int64_t z2 = (int64_t)vec2[2] - (int64_t)vec0[2];
int64_t det = Det3(x0, y0, z0, x1, y1, z1, x2, y2, z2);
return (det > 0 ? +1 : (det < 0 ? -1 : 0));
}
//----------------------------------------------------------------------------
template <typename Real>
int Query3Int64<Real>::ToCircumsphere (const Vector3<Real>& test, int v0,
int v1, int v2, int v3) const
{
const Vector3<Real>& vec0 = mVertices[v0];
const Vector3<Real>& vec1 = mVertices[v1];
const Vector3<Real>& vec2 = mVertices[v2];
const Vector3<Real>& vec3 = mVertices[v3];
int64_t iTest[3] = { (int64_t)test[0], (int64_t)test[1],
(int64_t)test[2] };
int64_t iV0[3] = { (int64_t)vec0[0], (int64_t)vec0[1],
(int64_t)vec0[2] };
int64_t iV1[3] = { (int64_t)vec1[0], (int64_t)vec1[1],
(int64_t)vec1[2] };
int64_t iV2[3] = { (int64_t)vec2[0], (int64_t)vec2[1],
(int64_t)vec2[2] };
int64_t iV3[3] = { (int64_t)vec3[0], (int64_t)vec3[1],
(int64_t)vec3[2] };
int64_t s0x = iV0[0] + iTest[0];
int64_t d0x = iV0[0] - iTest[0];
int64_t s0y = iV0[1] + iTest[1];
int64_t d0y = iV0[1] - iTest[1];
int64_t s0z = iV0[2] + iTest[2];
int64_t d0z = iV0[2] - iTest[2];
int64_t s1x = iV1[0] + iTest[0];
int64_t d1x = iV1[0] - iTest[0];
int64_t s1y = iV1[1] + iTest[1];
int64_t d1y = iV1[1] - iTest[1];
int64_t s1z = iV1[2] + iTest[2];
int64_t d1z = iV1[2] - iTest[2];
int64_t s2x = iV2[0] + iTest[0];
int64_t d2x = iV2[0] - iTest[0];
int64_t s2y = iV2[1] + iTest[1];
int64_t d2y = iV2[1] - iTest[1];
int64_t s2z = iV2[2] + iTest[2];
int64_t d2z = iV2[2] - iTest[2];
int64_t s3x = iV3[0] + iTest[0];
int64_t d3x = iV3[0] - iTest[0];
int64_t s3y = iV3[1] + iTest[1];
int64_t d3y = iV3[1] - iTest[1];
int64_t s3z = iV3[2] + iTest[2];
int64_t d3z = iV3[2] - iTest[2];
int64_t w0 = s0x*d0x + s0y*d0y + s0z*d0z;
int64_t w1 = s1x*d1x + s1y*d1y + s1z*d1z;
int64_t w2 = s2x*d2x + s2y*d2y + s2z*d2z;
int64_t w3 = s3x*d3x + s3y*d3y + s3z*d3z;
int64_t det = Det4(d0x, d0y, d0z, w0, d1x, d1y, d1z, w1, d2x, d2y, d2z,
w2, d3x, d3y, d3z, w3);
return (det > 0 ? 1 : (det < 0 ? -1 : 0));
}
//----------------------------------------------------------------------------
template <typename Real>
int64_t Query3Int64<Real>::Dot (int64_t x0, int64_t y0, int64_t z0,
int64_t x1, int64_t y1, int64_t z1)
{
return x0*x1 + y0*y1 + z0*z1;
}
//----------------------------------------------------------------------------
template <typename Real>
int64_t Query3Int64<Real>::Det3 (int64_t x0, int64_t y0, int64_t z0,
int64_t x1, int64_t y1, int64_t z1, int64_t x2, int64_t y2, int64_t z2)
{
int64_t c00 = y1*z2 - y2*z1;
int64_t c01 = y2*z0 - y0*z2;
int64_t c02 = y0*z1 - y1*z0;
return x0*c00 + x1*c01 + x2*c02;
}
//----------------------------------------------------------------------------
template <typename Real>
int64_t Query3Int64<Real>::Det4 (int64_t x0, int64_t y0,
int64_t z0, int64_t w0, int64_t x1, int64_t y1, int64_t z1,
int64_t w1, int64_t x2, int64_t y2, int64_t z2, int64_t w2,
int64_t x3, int64_t y3, int64_t z3, int64_t w3)
{
int64_t a0 = x0*y1 - x1*y0;
int64_t a1 = x0*y2 - x2*y0;
int64_t a2 = x0*y3 - x3*y0;
int64_t a3 = x1*y2 - x2*y1;
int64_t a4 = x1*y3 - x3*y1;
int64_t a5 = x2*y3 - x3*y2;
int64_t b0 = z0*w1 - z1*w0;
int64_t b1 = z0*w2 - z2*w0;
int64_t b2 = z0*w3 - z3*w0;
int64_t b3 = z1*w2 - z2*w1;
int64_t b4 = z1*w3 - z3*w1;
int64_t b5 = z2*w3 - z3*w2;
return a0*b5 - a1*b4 + a2*b3 + a3*b2 - a4*b1 + a5*b0;
}
//----------------------------------------------------------------------------
| [
"[email protected]"
] | [
[
[
1,
136
]
]
] |
54a8a48c7a7fc99022d78fcb2fddd3cc66a3db92 | 1d2705c9be9ee0f974c224eb794f2f8a9e9a3d50 | /urg_2d_plod/urg_2d_frame.h | 82fdb8238bb4b9443f396e29a8a6fe1f8c01b755 | [] | no_license | llvllrbreeze/alcorapp | dfe2551f36d346d73d998f59d602c5de46ef60f7 | 3ad24edd52c19f0896228f55539aa8bbbb011aac | refs/heads/master | 2021-01-10T07:36:01.058011 | 2008-12-16T12:51:50 | 2008-12-16T12:51:50 | 47,865,136 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,713 | h | /////////////////////////////////////////////////////////////////////////////
// Name: urg_2d_frame.h
// Purpose:
// Author:
// Modified by:
// Created: 10/03/2007 12:59:19
// RCS-ID:
// Copyright:
// Licence:
/////////////////////////////////////////////////////////////////////////////
#ifndef _URG_2D_FRAME_H_
#define _URG_2D_FRAME_H_
#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
#pragma interface "urg_2d_frame.h"
#endif
/*!
* Includes
*/
////@begin includes
#include "wx/frame.h"
////@end includes
/*!
* Forward declarations
*/
////@begin forward declarations
////@end forward declarations
/*!
* Control identifiers
*/
////@begin control identifiers
#define ID_URG_2D_FRAME 10000
#define SYMBOL_URG_2D_FRAME_STYLE wxCAPTION|wxRESIZE_BORDER|wxSYSTEM_MENU|wxCLOSE_BOX
#define SYMBOL_URG_2D_FRAME_TITLE _("urg_2d_frame")
#define SYMBOL_URG_2D_FRAME_IDNAME ID_URG_2D_FRAME
#define SYMBOL_URG_2D_FRAME_SIZE wxSize(400, 300)
#define SYMBOL_URG_2D_FRAME_POSITION wxDefaultPosition
////@end control identifiers
/*!
* Compatibility
*/
#ifndef wxCLOSE_BOX
#define wxCLOSE_BOX 0x1000
#endif
/*!
* urg_2d_frame class declaration
*/
class urg_2d_frame: public wxFrame
{
DECLARE_CLASS( urg_2d_frame )
DECLARE_EVENT_TABLE()
public:
/// Constructors
urg_2d_frame();
urg_2d_frame( wxWindow* parent, wxWindowID id = SYMBOL_URG_2D_FRAME_IDNAME, const wxString& caption = SYMBOL_URG_2D_FRAME_TITLE, const wxPoint& pos = SYMBOL_URG_2D_FRAME_POSITION, const wxSize& size = SYMBOL_URG_2D_FRAME_SIZE, long style = SYMBOL_URG_2D_FRAME_STYLE );
bool Create( wxWindow* parent, wxWindowID id = SYMBOL_URG_2D_FRAME_IDNAME, const wxString& caption = SYMBOL_URG_2D_FRAME_TITLE, const wxPoint& pos = SYMBOL_URG_2D_FRAME_POSITION, const wxSize& size = SYMBOL_URG_2D_FRAME_SIZE, long style = SYMBOL_URG_2D_FRAME_STYLE );
/// Destructor
~urg_2d_frame();
/// Initialises member variables
void Init();
/// Creates the controls and sizers
void CreateControls();
////@begin urg_2d_frame event handler declarations
////@end urg_2d_frame event handler declarations
////@begin urg_2d_frame member function declarations
/// Retrieves bitmap resources
wxBitmap GetBitmapResource( const wxString& name );
/// Retrieves icon resources
wxIcon GetIconResource( const wxString& name );
////@end urg_2d_frame member function declarations
/// Should we show tooltips?
static bool ShowToolTips();
////@begin urg_2d_frame member variables
////@end urg_2d_frame member variables
};
#endif
// _URG_2D_FRAME_H_
| [
"stefano.marra@1ffd000b-a628-0410-9a29-793f135cad17"
] | [
[
[
1,
99
]
]
] |
a36a9554ffcf2376059a2baec85054a1dfd22591 | 6bdb3508ed5a220c0d11193df174d8c215eb1fce | /Codes/Halak/Mouse.h | e2f389f0bae18be7fded66dea566be44743aa129 | [] | no_license | halak/halak-plusplus | d09ba78640c36c42c30343fb10572c37197cfa46 | fea02a5ae52c09ff9da1a491059082a34191cd64 | refs/heads/master | 2020-07-14T09:57:49.519431 | 2011-07-09T14:48:07 | 2011-07-09T14:48:07 | 66,716,624 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 812 | h | #pragma once
#ifndef __HALAK_MOUSE_H__
#define __HALAK_MOUSE_H__
# include <Halak/FWD.h>
# include <Halak/GameComponent.h>
# include <Halak/Point.h>
namespace Halak
{
class Mouse : public GameComponent
{
HKClassFOURCC('M', 'O', 'U', 'S');
public:
Mouse();
Mouse(Window* window);
virtual ~Mouse();
const MouseState& GetState();
void SetPosition(Point value);
Window* GetWindow();
void SetWindow(Window* value);
private:
void OnMouseWheel(int delta);
private:
Window* window;
MouseState* state;
};
}
#endif | [
"[email protected]"
] | [
[
[
1,
35
]
]
] |
cc6f0291347f485f105ce2178d97692ebd11d059 | 880e5a47c23523c8e5ba1602144ea1c48c8c8f9a | /enginesrc/renderer/hardwarepixelbuffer.hpp | be16da6e45ab5bc7116632fc1ac6aa457869aa38 | [] | no_license | kfazi/Engine | 050cb76826d5bb55595ecdce39df8ffb2d5547f8 | 0cedfb3e1a9a80fd49679142be33e17186322290 | refs/heads/master | 2020-05-20T10:02:29.050190 | 2010-02-11T17:45:42 | 2010-02-11T17:45:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 335 | hpp | #ifndef ENGINE_HARDWARE_PIXEL_BUFFER_HPP
#define ENGINE_HARDWARE_PIXEL_BUFFER_HPP
#include "../common.hpp"
#include "../hardwarebuffer.hpp"
namespace engine
{
class CRenderer;
class DLLEXPORTIMPORT CHardwarePixelBuffer
{
friend class CRenderer;
};
}
#endif /* ENGINE_HARDWARE_PIXEL_BUFFER_HPP */
/* EOF */
| [
"[email protected]"
] | [
[
[
1,
21
]
]
] |
971d6f75982d5c4a3beb2e3b64f04988fc392dbd | 6f8721dafe2b841f4eb27237deead56ba6e7a55b | /src/WorldOfAnguis/Graphics/DirectX/Units/Player/DXPlayerView.h | 4d64a1ee35efb4a0215565017d33fdda3449c90a | [] | no_license | worldofanguis/WoA | dea2abf6db52017a181b12e9c0f9989af61cfa2a | 161c7bb4edcee8f941f31b8248a41047d89e264b | refs/heads/master | 2021-01-19T10:25:57.360015 | 2010-02-19T16:05:40 | 2010-02-19T16:05:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,154 | h | /*
* ___ ___ __
* \ \ / / / \
* \ \ / / / \
* \ \ /\ / /___ / /\ \
* \ \/ \/ /| | / ____ \
* \___/\___/ |___|/__/ \__\
* World Of Anguis
*
*/
//#pragma once
#ifndef __PlayerView__
#define __PlayerView__
#include "Common.h"
class DXPlayerView
{
public:
DXPlayerView();
~DXPlayerView();
/* Static functions for setting the requied stuffs (Device & Sprite) */
static void SetDevice(LPDIRECT3DDEVICE9 pDevice) {DXPlayerView::pDevice = pDevice;}
static void SetSprite(LPD3DXSPRITE pSprite) {DXPlayerView::pSprite = pSprite;}
/* Draws the player on the X,Y coords of the screen */
void Draw(int X,int Y,bool FaceRight,bool Jumping);
private:
/* Load the player texture based on the ID (Player<ID>.bmp) */
void LoadTexture(int TextureID);
/* The current animation frame */
int AnimationFrame;
/* Texture for the player */
LPDIRECT3DTEXTURE9 pTexture;
/* Static stuff for drawing (all instances uses the same) */
static LPDIRECT3DDEVICE9 pDevice;
static LPD3DXSPRITE pSprite;
};
#endif | [
"[email protected]"
] | [
[
[
1,
44
]
]
] |
56ffce62248b43fcd8adabe368365d6aa711f33b | accd6e4daa3fc1103c86d245c784182e31681ea4 | /HappyHunter/Core/Mesh.cpp | 29ad7475bc7ce11d35328cc5490e076c0c0dfa2e | [] | no_license | linfuqing/zero3d | d87ad6cf97069aea7861332a9ab8fc02b016d286 | cebb12c37fe0c9047fb5b8fd3c50157638764c24 | refs/heads/master | 2016-09-05T19:37:56.213992 | 2011-08-04T01:37:36 | 2011-08-04T01:37:36 | 34,048,942 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 5,381 | cpp | #include "StdAfx.h"
#include "Mesh.h"
#include "basicutils.h"
using namespace zerO;
const D3DVERTEXELEMENT9 g_MESH_VERTEX_DESCRIPTION[]=
{
{0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0},
{0, 12, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0},
{0, 20, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0},
{0, 32, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TANGENT, 0},
D3DDECL_END()
};
CMesh::CMesh(void) :
CResource(RESOURCE_MESH),
m_pMesh(NULL),
m_pSurfaces(NULL),
m_uNumSurfaces(0)
{
}
CMesh::~CMesh(void)
{
Destroy();
}
void CMesh::SetNormalMap(CTexture* pTexture)
{
for(UINT i = 0; i < m_uNumSurfaces; i ++)
m_pSurfaces[i].SetTexture(pTexture, NORMAL);
}
bool CMesh::CreateSphere(zerO::FLOAT fRadius, zerO::UINT uSlices, zerO::UINT uStacks)
{
Destroy();
HRESULT hr;
hr = D3DXCreateSphere(&DEVICE, fRadius, uSlices, uStacks, &m_pMesh, NULL);
if( FAILED(hr) )
{
DEBUG_WARNING(hr);
return false;
}
DEBUG_NEW(m_pSurfaces, CSurface[1]);
m_uNumSurfaces = 1;
return __GenerateDeclMesh(m_pMesh) && __GetBoundBox(m_pMesh, m_Rectangle);
}
bool CMesh::Load(const PBASICCHAR pcFileName)
{
Destroy();
//加载网格模型
LPD3DXBUFFER pD3DXMtrlBuffer;
HRESULT hr;
hr = D3DXLoadMeshFromX(
pcFileName, D3DXMESH_MANAGED,
&DEVICE, NULL,
&pD3DXMtrlBuffer, NULL, (DWORD*)&m_uNumSurfaces,
&m_pMesh );
if( FAILED(hr) )
{
DEBUG_WARNING(hr);
return false;
}
DEBUG_NEW(m_pSurfaces, CSurface[m_uNumSurfaces]);
//提取材质和纹理文件路径
D3DXMATERIAL* d3dxMaterials = (D3DXMATERIAL*)pD3DXMtrlBuffer->GetBufferPointer();
for( DWORD i = 0; i< m_uNumSurfaces; i ++ )
{
// MatD3D属性里没有环境光的值设置,当它被加载时,需要设置它
d3dxMaterials[i].MatD3D.Ambient = d3dxMaterials[i].MatD3D.Diffuse;
CSurface* pSurface = &m_pSurfaces[i];
pSurface->SetMaterial(d3dxMaterials[i].MatD3D);
if( d3dxMaterials[i].pTextureFilename != NULL )
{
//创建纹理
#ifdef _UNICODE
BASICCHAR szFile[MAX_PATH];
RemovePathFromFileName(d3dxMaterials[i].pTextureFilename, szFile);
BASICSTRING texFile;
GetRealPath(pcFileName, texFile, TEXT("/"), szFile);
pSurface->LoadTexture((PBASICCHAR)texFile.c_str(), 0);
BASICSTRING normalMapFile;
GetRealPath((PBASICCHAR)texFile.c_str(), normalMapFile, TEXT("."), TEXT("-normalmap.tga"), true);
pSurface->LoadTexture((PBASICCHAR)normalMapFile.c_str(), 1) ;
//return false;
#else
if( !pSurface->LoadTexture(d3dxMaterials[i].pTextureFilename, 0) )
return false;
#endif
}
}
DEBUG_RELEASE( pD3DXMtrlBuffer );
__GenerateDeclMesh(m_pMesh) && __GetBoundBox(m_pMesh, m_Rectangle);
return true;
}
bool CMesh::__GenerateDeclMesh(LPD3DXMESH& pMesh)
{
if (pMesh == NULL)
return false;
HRESULT hr;
LPD3DXMESH pMeshSysMem = pMesh;
LPD3DXMESH pMeshSysMem2 = NULL;
hr = pMeshSysMem->CloneMesh(D3DXMESH_MANAGED, g_MESH_VERTEX_DESCRIPTION, &DEVICE, &pMeshSysMem2);
if( FAILED(hr) )
{
DEBUG_WARNING(hr);
return false;
}
//确保顶点包含法线
hr = D3DXComputeNormals(pMeshSysMem2,NULL);
if( FAILED(hr) )
{
DEBUG_WARNING(hr);
return false;
}
//计算切线
hr = D3DXComputeTangent( pMeshSysMem2, 0, 0, 0, true, NULL );
if( FAILED(hr) )
{
DEBUG_WARNING(hr);
return false;
}
/*D3DVERTEXELEMENT9 decl2[]=
{
{0, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0},
{0, 16, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0},
{0, 24, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0},
{0, 36, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TANGENT, 0},
D3DDECL_END()
};*/
hr = pMeshSysMem2->CloneMesh(D3DXMESH_MANAGED, g_MESH_VERTEX_DESCRIPTION, &DEVICE, &pMesh );
if( FAILED(hr) )
{
DEBUG_WARNING(hr);
return false;
}
//释放临时网格模型对象
DEBUG_RELEASE(pMeshSysMem);
DEBUG_RELEASE(pMeshSysMem2);
return true;
}
bool CMesh::__GetBoundBox(const LPD3DXMESH pMesh, CRectangle3D& Rect3d)
{
if (pMesh == NULL)
return false;
UINT uVertexNum = pMesh->GetNumVertices();
LPD3DXMESH pTempMesh;
pMesh->CloneMeshFVF(D3DXMESH_SYSTEMMEM, D3DFVF_XYZ, &DEVICE, &pTempMesh);
LPDIRECT3DVERTEXBUFFER9 pVertexBuffer;
pTempMesh->GetVertexBuffer(&pVertexBuffer);
FLOAT maxX = 0.0f, maxY = 0.0f, maxZ = 0.0f;
FLOAT minX = 0.0f, minY = 0.0f, minZ = 0.0f;
D3DXVECTOR3* pVertices;
pVertexBuffer->Lock(0, 0, (void**)&pVertices, 0);
for(UINT i = 0; i < uVertexNum; i ++)
{
if(pVertices[i].x > maxX)
maxX = pVertices[i].x;
if(pVertices[i].y > maxY)
maxY = pVertices[i].y;
if(pVertices[i].z > maxZ)
maxZ = pVertices[i].z;
if(pVertices[i].x < minX)
minX = pVertices[i].x;
if(pVertices[i].y < minY)
minY = pVertices[i].y;
if(pVertices[i].z < minZ)
minZ = pVertices[i].z;
}
pVertexBuffer->Unlock();
Rect3d.Set(minX, maxX, minY, maxY, minZ, maxZ);
DEBUG_RELEASE(pVertexBuffer);
DEBUG_RELEASE(pTempMesh);
return true;
}
bool CMesh::Destroy()
{
DEBUG_RELEASE(m_pMesh);
DEBUG_DELETE_ARRAY(m_pSurfaces);
m_pMesh = NULL;
m_pSurfaces = NULL;
return true;
} | [
"[email protected]"
] | [
[
[
1,
229
]
]
] |
30b01b6f451fdd4facae5d49d8d9b77b4f76a731 | 18da4b0f8a1f09ff176e77f2c3bc073beffd0525 | /NetCore/NetCoreDLL/ClientContext.cpp | 8d3eb1aa7c3236e9e9160ee94447619242e3bb11 | [] | no_license | myjeffxie/yynetsdk | 7ef95384570df959bf56453b34acfdb45fbf9db7 | 9d6edc080c601ff9caab8edda922bbc604f36654 | refs/heads/master | 2021-12-09T02:40:16.491623 | 2011-06-27T06:56:51 | 2011-06-27T06:56:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 144 | cpp | #include "StdAfx.h"
#include ".\clientcontext.h"
CClientContext::CClientContext(void)
{
}
CClientContext::~CClientContext(void)
{
}
| [
"[email protected]"
] | [
[
[
1,
10
]
]
] |
d0d5d4815f17540a89211791006980d8da3bc47c | 8c54d89af1800c4c06959a3b7b62d04f883a11c0 | /cs752/Original/Raytracer/.svn/text-base/Ray.h.svn-base | 22123bcaaa0dbf8ae27c2f3b588354c69649318f | [] | no_license | dknutsen/dokray | 567c79e7a69c80a97cd73bead151a12ad2d34f23 | 92acd2967542865963462aaf2299ab2427b89f31 | refs/heads/master | 2020-12-24T13:29:01.740250 | 2011-10-23T23:09:49 | 2011-10-23T23:09:49 | 2,639,353 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 740 | /*
Author: Daniel Knutsen
Course: Comp 361, Computer Graphics
Date: 4/28/09
Desc: Ray class
*/
#ifndef Ray_h
#define Ray_h
#include "Vector.h"
#include "Point.h"
class Ray
{
private:
Point o;
Vector dir;
public:
Ray(){
o = Point(0,0,0);
dir = Vector(0,0,0);
}
Ray(const Point& point, const Vector& direction)
{
o = point;
dir = direction;
dir.normalize();
}
Ray(float x, float y, float z, float u, float v, float w)
{
o = Point(x,y,z);
dir = Vector(u,v,w);
}
Point p()const{
return o;
}
Vector d()const{
return dir;
}
Point& p(){
return o;
}
Vector& d(){
return dir;
}
Point pointOn(float t){
return o + t*dir;
}
};
#endif
| [
"[email protected]"
] | [
[
[
1,
57
]
]
] |
|
f0637c7fee3b20d34a2dc34625b3599da09ad0b1 | 6c8c4728e608a4badd88de181910a294be56953a | /RexLogicModule/EntityComponent/EC_Controllable.h | 4a098255bcdfb2ac60ad08d1c245e2062581144f | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | caocao/naali | 29c544e121703221fe9c90b5c20b3480442875ef | 67c5aa85fa357f7aae9869215f840af4b0e58897 | refs/heads/master | 2021-01-21T00:25:27.447991 | 2010-03-22T15:04:19 | 2010-03-22T15:04:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,069 | h | // For conditions of distribution and use, see copyright notice in license.txt
#ifndef incl_RexLogic_EC_Controllable_h
#define incl_RexLogic_EC_Controllable_h
#include "ComponentInterface.h"
#include "RexTypes.h"
#include "InputEvents.h"
#include "RexLogicModuleApi.h"
#include "Declare_EC.h"
#include "ModuleInterface.h"
namespace RexLogic
{
//! Controllable entity component.
/*! Any entity with this component may be controlled by the user.
The entity can be controlled via 'actions'. Each different type
of controllable has their own list of actions, so they work in a
generic fashion.
Controllables have a type. For each different type, a controller
class exists which handles the actual movement of the entity based
on the actions a controllable may perform.
Many actions will probably be common to most or all controllables,
but actions can also be specific to a type of controllable.
F.ex. a tank could have a unique action 'rotate turret'.
For an example of a custom controller for an entity, see
AvatarControllable.
*/
class EC_Controllable : public Foundation::ComponentInterface
{
Q_OBJECT
DECLARE_EC(EC_Controllable);
public:
virtual ~EC_Controllable() {}
//! Add a new action for this controllable
void AddAction(int action)
{
assert(actions_.find(action) == actions_.end() && "Action already added to this controller.");
actions_.insert(action);
}
void RemoveAction(int action)
{
assert(actions_.find(action) != actions_.end() && "Action not present in this controller.");
actions_.erase(action);
}
////! Sets current action for this controllable. Event for the action is send in a delayed fashion.
//void SetCurrentAction(int action)
//{
// assert (action != 0 && "Action ID 0 reserved for internal use.");
// assert(actions_.find(action) != actions_.end() && "Action not supported by this controller.");
// current_action_ = action;
// dirty_ = true;
//}
//! Set unique name for this controllable
void SetType(RexTypes::ControllableType type) { type_ = type; }
//! Returns the type of this controllable
RexTypes::ControllableType GetType() const { return type_; }
private:
typedef std::set<int> ActionSet;
//! list of actions supported by this controller
ActionSet actions_;
//! Currently active action for this controllable
int current_action_;
//! If true, an action is pending and needs to be sent
bool dirty_;
//! Type of this controllable
RexTypes::ControllableType type_;
EC_Controllable(Foundation::ModuleInterface* module) : Foundation::ComponentInterface(module->GetFramework()), current_action_(0), dirty_(false) {}
};
namespace Actions
{
namespace
{
//! A helper function for assigning common actions to a controllable. For an example of how to use, see AvatarControllable.
/*! Returns default mappings from input events to actions which can be used for convinience by controllables.
This function is re-entrant but not threadsafe
\param controllable Controllable component. Not a ComponentPtr to avoid type casts
\return A mapping from input events to controller actions
*/
RexTypes::Actions::ActionInputMap AssignCommonActions(EC_Controllable *controllable)
{
using namespace RexTypes::Actions;
controllable->AddAction(MoveForward);
controllable->AddAction(MoveBackward);
controllable->AddAction(MoveLeft);
controllable->AddAction(MoveRight);
controllable->AddAction(RotateLeft);
controllable->AddAction(RotateRight);
controllable->AddAction(MoveUp);
controllable->AddAction(MoveDown);
controllable->AddAction(RotateUp);
controllable->AddAction(RotateDown);
ActionInputMap input_map;
input_map[Input::Events::MOVE_FORWARD_PRESSED] = MoveForward;
input_map[Input::Events::MOVE_FORWARD_RELEASED] = MoveForward + 1;
input_map[Input::Events::MOVE_BACK_PRESSED] = MoveBackward;
input_map[Input::Events::MOVE_BACK_RELEASED] = MoveBackward + 1;
input_map[Input::Events::MOVE_LEFT_PRESSED] = MoveLeft;
input_map[Input::Events::MOVE_LEFT_RELEASED] = MoveLeft + 1;
input_map[Input::Events::MOVE_RIGHT_PRESSED] = MoveRight;
input_map[Input::Events::MOVE_RIGHT_RELEASED] = MoveRight + 1;
input_map[Input::Events::ROTATE_LEFT_PRESSED] = RotateLeft;
input_map[Input::Events::ROTATE_LEFT_RELEASED] = RotateLeft + 1;
input_map[Input::Events::ROTATE_RIGHT_PRESSED] = RotateRight;
input_map[Input::Events::ROTATE_RIGHT_RELEASED] = RotateRight + 1;
input_map[Input::Events::MOVE_UP_PRESSED] = MoveUp;
input_map[Input::Events::MOVE_UP_RELEASED] = MoveUp + 1;
input_map[Input::Events::MOVE_DOWN_PRESSED] = MoveDown;
input_map[Input::Events::MOVE_DOWN_RELEASED] = MoveDown + 1;
input_map[Input::Events::ROTATE_UP_PRESSED] = RotateUp;
input_map[Input::Events::ROTATE_UP_RELEASED] = RotateUp + 1;
input_map[Input::Events::ROTATE_DOWN_PRESSED] = RotateUp;
input_map[Input::Events::ROTATE_DOWN_RELEASED] = RotateUp + 1;
return input_map;
}
}
}
}
#endif
| [
"cmayhem@5b2332b8-efa3-11de-8684-7d64432d61a3",
"cadaver@5b2332b8-efa3-11de-8684-7d64432d61a3",
"jujjyl@5b2332b8-efa3-11de-8684-7d64432d61a3",
"Stinkfist0@5b2332b8-efa3-11de-8684-7d64432d61a3"
] | [
[
[
1,
8
],
[
12,
34
],
[
37,
42
],
[
44,
48
],
[
50,
115
],
[
117,
145
]
],
[
[
9,
9
],
[
35,
35
]
],
[
[
10,
11
]
],
[
[
36,
36
],
[
43,
43
],
[
49,
49
],
[
116,
116
]
]
] |
a1d63c74fc86741d3c70b48626da88367038a0f6 | 41af2f4856d11c45e860bd4ddbe053d8cf19cbf6 | /utils.cpp | 18dc3d0a6afd40d62a014244c1e824ad7d756475 | [] | no_license | zorbathut/zidrav | 755d7db82ef7f11bbde0cb8d8f9af62f2f6ddaa4 | 3ccc55bbf14b116a0560be2c57be54d5dc008389 | refs/heads/master | 2020-03-11T04:44:01.582743 | 2002-06-29T11:10:32 | 2002-06-29T11:10:32 | 129,783,630 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,029 | cpp | /*
ZIDRAV, file corruption repairer
Copyright (C) 1999 Ben Wilhelm
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <windows.h>
#include "utils.h"
int powerof2( int power ) {
int static powertable[] = { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384,
32768, 65536, 131072, 262144, 524288 };
return powertable[power];
}
void ActivateGenericDD( HWND hwnd ) {
SetWindowLong( hwnd, GWL_USERDATA, (long)GetWindowLong( hwnd, GWL_WNDPROC ) );
SetWindowLong( hwnd, GWL_WNDPROC, (long)GenericDD );
}
int CALLBACK GenericDD( HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam ) {
// Reflect WM_COMMAND messages to parent
switch( message ) {
case WM_COMMAND:
return SendMessage( (HWND)GetWindowLong(hwnd, GWL_HWNDPARENT), message, wParam, lParam);
case WM_DROPFILES:
char filebuf[MAX_PATH];
DragQueryFile( (HDROP)wParam, 0, filebuf, MAX_PATH );
DragFinish( (HDROP)wParam );
CallWindowProc( (WNDPROC)GetWindowLong( hwnd, GWL_USERDATA ), hwnd, WM_SETTEXT, 0, (long)filebuf );
return FALSE;
}
return CallWindowProc( (WNDPROC)GetWindowLong( hwnd, GWL_USERDATA ), hwnd, message, wParam, lParam);
}
void FilenamePlacer( HWND first, HWND second, char origext[], char newext[], char fname[] ) {
int loconf;
int locone;
BOOL fnameprov;
if( !fname ) {
fname = new char[MAX_PATH];
SendMessage( first, WM_GETTEXT, MAX_PATH, (long)fname );
fnameprov = FALSE;
} else {
SendMessage( first, WM_SETTEXT, 0, (long)fname );
fnameprov = TRUE; }
if( newext && second ) {
if( origext ) {
locone = strchr( origext, fname[loconf = strlen(fname) - 1] ) - origext;
locone--; loconf--;
while( locone > -1 && loconf > -1 && fname[loconf] == origext[locone] ) {
locone--; loconf--; }
if( locone == -1 )
fname[ loconf + 1 ] = '\0';
}
strcat( fname, newext );
SendMessage( second, WM_SETTEXT, 0, (long)fname );
}
if( !fnameprov )
delete [] fname;
}
void MakeNeededTree( char *path ) {
char *floater;
char temppath[MAX_PATH];
floater = strchr( path, '\\' );
while( floater = strchr( floater + 1, '\\' ) ) {
strncpy( temppath, path, floater - path );
temppath[ floater - path ] = '\0';
if( GetFileAttributes( temppath ) == 0xFFFFFFFF )
CreateDirectory( temppath, NULL );
}
} | [
"[email protected]"
] | [
[
[
1,
111
]
]
] |
e897b33f60a2c33a49b01ebd861fcff20f72e923 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Common/ModelsC/MG/SM_OIL.CPP | 940af1637145f3f86d067553905b550513062ba0 | [] | no_license | abcweizhuo/Test3 | 0f3379e528a543c0d43aad09489b2444a2e0f86d | 128a4edcf9a93d36a45e5585b70dee75e4502db4 | refs/heads/master | 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 47,381 | cpp | //================== SysCAD - Copyright Kenwalt (Pty) Ltd ===================
// $Nokeywords: $
//===========================================================================
// SysCAD Copyright Kenwalt (Pty) Ltd 1992
#include "stdafx.h"
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include "sc_defs.h"
#define __SM_OILFL_CPP
#include "sp_db.h"
#include "sp_cont.h"
#include "sm_oil.h"
#include "errorlog.h"
//#include "dbgcom.h"
#include "dbgmngr.h"
// #define dbgSM_Oil 0x1
#define dbgSM_Oil 01
#if dbgSM_Oil
static CDbgMngr dbgQPFlash ("SM_Oil", "QPFlash");
static CDbgMngr dbgTPFlash ("SM_Oil", "TPFlash");
static CDbgMngr dbgConvergence("SM_Oil", "Convergence");
static CDbgMngr dbgMemory ("SM_Oil", "Memory");
static CDbgMngr dbgStats ("SM_Oil", "Stats");
static CDbgMngr dbgKConverge ("SM_Oil", "KConverge");
#endif
IMPLEMENT_SPMODEL(SM_Oil, "LHOil", "", TOC_ALL|TOC_GRP_ENERGY|TOC_USER, "Light/Heavy Oil", "");
IMPLEMENT_SPARES(SM_Oil, 100);
#ifdef ForceTests
ACCESS_SPECIE(H2o, "H2O" );
ACCESS_SPECIE(Methane, "MethaneG");
ACCESS_SPECIE(Ethane, "EthaneG");
ACCESS_SPECIE(Propane, "PropaneG");
#endif
// ===========================================================================
flag SM_Oil::fIdealFlashOnly=1;
SM_Oil::SM_Oil(pTagObjClass pClass_, pchar Tag_, pTaggedObject pAttach, TagObjAttachment eAttach) :
SpModel(pClass_, Tag_, pAttach, eAttach)
{
LoadZused = False;
InitRqd = True;
Tsetting=-1.0;
ZLen=0;
Zvap=1.0;
Zliq=1.0;
QPm.Temp=dNAN();
H2OLiq=0.0;
H2OVap=0.0;
QTLast=293;
QPLast=100;
Qflashdone=False;
}
// ---------------------------------------------------------------------------
SM_Oil::~SM_Oil()
{
}
// --------------------------------------------------------------------------
void SM_Oil::BuildDataDefn_Vars(DataDefnBlk & DDB, SPM_View View)
{
SpModel::BuildDataDefn_Vars(DDB, View);
DDB.Bool("IdealKs", "", DC_, "", &fIdealFlashOnly, this, isParm);
}
// --------------------------------------------------------------------------
void SM_Oil::IdealGasKratio(double T, double P)
{
int i;
double ZC,TR,PSAT;
for (i = 0; i < ZLen; i++)
{
ZC = 0.29 - 0.065 * CDB[i].ACent();
TR = T/CDB[i].TCrit();
if (T > CDB[i].TCrit())
{
double RLPSAT = (16.26-73.85*ZC+90.0*ZC*ZC) * (1.0-1.0/TR)-exp(log(10.0)*(-8.68*(TR-1.8+6.2*ZC)*(TR-1.8+6.2*ZC)));
if ((RLPSAT < -LnExpMax))
RLPSAT = -LnExpMax;
if ((RLPSAT > LnExpMax))
RLPSAT = LnExpMax;
PSAT = exp(RLPSAT) * CDB[i].PCrit(); //kcg added *1000
}
else
{
PSAT = exp((4.92 * CDB[i].ACent() + 5.81) * log(TR) - 0.0838 * (4.92 * CDB[i].ACent() + 2.06) * (36.0 /
TR - 35.0 - (TR * TR * TR * TR * TR * TR) + 42.0 *
log(TR))) * CDB[i].PCrit(); //kcg added *1000
}
K[i] = PSAT / P;
}
}
// --------------------------------------------------------------------------
void SM_Oil::SetXYfromK()
{
int i;
double KScl=1.;
double Vf=Range( 1.0e-8, VFrac, 1.0 - 1.0e-8);
//double sx = 0.0;
//double sy = 0.0;
for (int Iter=1;Iter;Iter--)
{
double ZmK=0.0;
double ZdK=0.0;
for (i = 0; i < ZLen; i++)
{
K[i] = Range(1.0e-10, K[i]*KScl, 1.0e10);
X[i] = Z[i] / (1.0 + (Vf * (K[i] - 1.0)));
Y[i] = K[i] * X[i];
ZmK+=Z[i]*K[i];
ZdK+=Z[i]/K[i];
//sx += X[i];
//sy += Y[i];
}
//sx=GTZ(sx);
//sy=GTZ(sy);
double sk = GTZ(K.Sum());
double amk = 0.0;
double gmk = 1.0;
double sz = GTZ(Z.Sum());
double sx = GTZ(X.Sum());
double sy = GTZ(Y.Sum());
for (i = 0; i < ZLen; i++)
{
amk+=K[i];
gmk*=K[i];
}
amk/=ZLen;
gmk=Pow(gmk, 1.0/ZLen);
flag BubblePt=ZmK<1.0;
flag DewPt=ZdK<1.0;
#if dbgSM_Oil
if (dbgKConverge())
dbgpln("SXY %s", BubblePt?"All Liquid" : DewPt ? "All Vapour" : "");
#endif
int xxx=0;
if (fabs(sx-1.0)<0.01)
break;
/**/
for (i = 0; i < ZLen; i++)
{
X[i] /= sx;
Y[i] /= sy;
}
/**/
}
int yyy=0;
}
// --------------------------------------------------------------------------
double VFracSmall = 1.0e-6;
double QPFlashTol = 1.0e-4;
double ConvergeKratiosTol = QPFlashTol*1.0e-3;
double RachRice_SolveTol1 = ConvergeKratiosTol*1.0e-4;
double RachRice_SolveTol2 = 1.0e-10;
double GundersonRootTol = 1.0e-6;
double SM_Oil::GundersonRoot(double A1,double A0,double StartZ)
{
#if SM_OIL_STATS
Cnt.GundRootCall++;
#endif
int Iter = 0;
double ERR,F,DF,ZN,Zv = StartZ,Zv2;
do
{
#if SM_OIL_STATS
Cnt.GundRootIter++;
#endif
Zv2 = Zv*Zv;
F = (Zv * Zv2) - Zv2 + A1 * Zv - A0;
DF = 3.0 * (Zv2) - 2.0 * Zv + A1;
ZN = Zv - (F / DF);
ERR = fabs((ZN - Zv) / ZN);
Zv = ZN;
Iter++;
if( Iter > 45 )
{
LogError("SM_Oil", 0, "gundersonroot is running at more than 45 its");
return(-100.0);
}
}
while (ERR > GundersonRootTol);
return(Zv);
}
// --------------------------------------------------------------------------
// Refer to: Numerical aspects of the mplementation of cubic equations of state
// in flash calculation routines/
// Computers and Chemical Engineering Vol 6, No 3, pp 245-255 1982
void SM_Oil::Gunderson(double &Q,double &R,double &A,double &B,int IPH,double& Z )
{
if( Q > 1.0/3.0 )
{
double F3 = 1.0 / 27.0 - 1.0 / 9.0 + Q / 3.0 - R;
if( F3 > 0.0 )
{
Z = GundersonRoot(Q,R,0.0);
}
else
{
Z = GundersonRoot(Q,R,3.0); // change from program to match gunderson paper
}
}
else
{
if( (R > 1.0/27.0) && (IPH == 1) )
{
Z = GundersonRoot(Q,R,3.0); // change from program to match gunderson paper
}
else
{
double Z1 = (1.0 - sqrt(1.0 - (3.0 * Q))) / 3.0;
double Z2 = (1.0 + sqrt(1.0 - (3.0 * Q))) / 3.0;
double F1 = (Z1 * Z1 * Z1) - (Z1 * Z1) + (Q * Z1) - R;
double F2 = (Z2 * Z2 * Z2) - (Z2 * Z2) + (Q * Z2) - R;
if( IPH == 0 )
{
if( F1 > 0.0 )
{
Z = GundersonRoot(Q,R,0.0);
}
else
{
Z = Z1;
B = B*(1 + F1/R);
Q = A - B - B*B;
R = A * B;
}
}
else
{
if( F2 < 0.0 )
{
Z = GundersonRoot(Q,R,3.0); // change from program to match gunderson paper
}
else
{
Z = Z2;
B = B*(1 + F2/R);
Q = A - B - B*B;
R = A * B;
}
}
}
}
}
// --------------------------------------------------------------------------
double SM_Oil::FindZValue(flag Vapour, double B, double C, double D, CubeRoots Roots, int NRoots, double &AMix, double &BMix)
{
const flag FDebug=0;
flag Imag1 = FALSE;
flag Imag2 = FALSE;
flag WrongRoot = FALSE;
double ZComp=dNAN();
switch (NRoots)
{
case 1:
// there is only one root - first check if it corresponds
// to the required phase, using Gosset's method
{
flag Liq = False;
flag Vap = False;
if (Roots[0] < (BMix / (3.0 * Cb)))
Liq = True;
else
Vap = True;
if (FDebug)
dbgpln("%s, %s Root Found", Liq?"Liquid":" ", Vap ? "Vapour":" ");
if ((Vapour && Liq) || (!Vapour && Vap))
// it doesn't so get a pseudoroot
{
double Z1 = 0.0;
double Z2 = 0.0;
double F1 = 0.0;
double F2 = 0.0;
if (C < (1./3.)) // { have turning points }
{
Z1 = (1. - Sqrt(1. - 3.*C)) / 3.;
Z2 = (1. + Sqrt(1. - 3.*C)) / 3.;
F1 = (Z1 - 1.) * Sqr(Z1) + C * Z1 + D;
F2 = (Z2 - 1.) * Sqr(Z2) + C * Z2 + D;
ZComp = Roots[0];
if (Vapour && (F1 > 0.) && (F2 > 0.))
{
ZComp = Z2;
Imag2 = True;
}
else if (!Vapour && (F1 < 0.) && (F2 < 0.))
{
ZComp = Z1;
Imag1 = True;
};
// retest root found
Liq = False;
Vap = False;
if (ZComp < (BMix / (3.0 * Cb)))
Liq = True;
else
Vap = True;
if (FDebug)
dbgpln("%s, %s Root Found", Liq?"Liquid":" ", Vap ? "Vapour":" ");
if (Vapour && Liq)
{
WrongRoot = True;
Imag1 = False;
ZComp = 1.01 * BMix / (3.0 * Cb);
F1 = (ZComp - 1.) * Sqr (ZComp) + C * ZComp + D;
};
if (!Vapour && Vap)
{
WrongRoot = True;
Imag2 = False;
ZComp = 0.99 * BMix / (3.0 * Cb);
F1 = (ZComp - 1.) * Sqr (ZComp) + C * ZComp + D;
};
}
else
// no turning points
{
if (Vapour && Liq)
ZComp = 1.01 * BMix / (3.0 * Cb);
if (!Vapour && Vap)
ZComp = 0.99 * BMix / (3.0 * Cb);
F1 = (ZComp - 1.) * Sqr (ZComp) + C * ZComp + D;
WrongRoot = True;
};
// modify BMix for imaginary roots
if (WrongRoot) BMix = BMix * (1 - F1/D);
if (Vapour && Imag2) BMix = BMix * (1 - F2/D);
if (!Vapour && Imag1) BMix = BMix * (1 - F1/D);
}
else
ZComp = Roots[0];
break;
};
case 2:
{
if (Vapour)
ZComp = Roots[1];
else
ZComp = Roots[0];
break;
};
case 3:
{
if (Vapour)
ZComp = Roots[2];
else
ZComp = Roots[0];
break;
};
};
return ZComp;
};
// --------------------------------------------------------------------------
double SM_Oil::RachRice_Value(double Vf, double &Deriv, double &LfNew, double &VfNew)
{
int i;
Vf=Range(VFracSmall, Vf, 1.0-VFracSmall);
double Func = 0.0;
Deriv = 0.0;
LfNew=0.0;
if (K.GetLen() < 1)
return 0.0; //kcg new flash in pipe K empty
for( i = 0; i < ZLen; i++ )
{
double t = K[i]-1.0;
double a = (t*Vf + 1.0);
double a2 = a*a;
double MinAValue=MinZValue*1.0e-20;
if( fabs(a ) < MinAValue)
a = MinAValue * Sign(a );
if( fabs(a2) < MinAValue)
a2 = MinAValue * Sign(a2);
Func += ( t * Z[i] ) / (a);
Deriv += -( t * t * Z[i] ) / (a2);
LfNew+=Z[i]/(1.0+Vf*(K[i]-1));
}
VfNew=1.0-LfNew;
return Func;
}
// --------------------------------------------------------------------------
int SM_Oil::RachRice_Solve()
{
int cnt = 0;
int ier = 0;
double F,F1,F2,d1,LfNew, VfNew;
double VFrac_old = VFrac;
#if SM_OIL_STATS
Cnt.RacRicCall++;
#endif
F1 = RachRice_Value(VFracSmall, d1, LfNew, VfNew); // evaluate at zero
if( F1 < 1.0e-10)
{
VFrac = VFracSmall;
//kcg VFrac = VFrac/2.0;
return -1;
}
F2 = RachRice_Value(1.0-VFracSmall, d1, LfNew, VfNew);
if( F2 > 1.0e-6) // CNM 1.0e-6
{
VFrac = 1.0-VFracSmall;
// VFrac = (VFrac + 1.0)/2.0;
return -1;
}
VFrac = Range(0.0, VFrac, 1.0);
for (cnt=1000; cnt; cnt--)
{
#if SM_OIL_STATS
Cnt.RacRicIter++;
#endif
double oldVF = VFrac;
F = RachRice_Value(VFrac, d1, LfNew, VfNew);
double V = VFrac - (F/(d1));
//VFrac = Range(0.000001, (V + VFrac)/2.0, 0.999999);
VFrac = Range(0.0, (V + VFrac)/2.0, 1.0);
if ((fabs(F) < RachRice_SolveTol1) || (fabs(VFrac-oldVF)<RachRice_SolveTol2))
break;
}
if (cnt==0)
LogError("SM_Oil", 0, "RachRice_Solve not Converged");
F = RachRice_Value(VFrac, d1, LfNew, VfNew);
return(0);
}
// --------------------------------------------------------------------------
// RacRic evaluates the Rachford and Rice objective function
double SM_Oil::RacRic()
{
double TempVal = 0.;
for (int i = 0; i < ZLen; i++ )
TempVal = TempVal + Z[i] * (K[i] - 1.) / (1. + VFrac * (K[i] - 1.));
return TempVal;
};
// --------------------------------------------------------------------------
// DRacRic evaluates the first derivative of the Rachford and Rice
// objective function
double SM_Oil::DRacRic ()
{
double TempVal = 0.;
for (int i = 0; i < ZLen; i++ )
TempVal = TempVal - Z[i] * Sqr (K[i] - 1.) / Sqr (1. + VFrac * (K[i] - 1.));
return TempVal;
};
// --------------------------------------------------------------------------
// FindBounds determines the upper and lower bounds for the solution
// of the Rachford and Rice objective function
void SM_Oil::FindBounds(double &Left, double &Right)
{
double SmallestK = 1.0e20;
double LargestK = -1.0e20;
for (int i = 0; i < ZLen; i++ )
{
LargestK = Max(LargestK, K[i]);
SmallestK = Min(SmallestK, K[i]);
//if (K[i] > LargestK )
// LargestK = K[i];
//if (K[i] < SmallestK)
// SmallestK = K[i];
};
Left = 1.0 / (1.0 - LargestK);
Right = 1.0 / (1.0 - SmallestK);
if (SmallestK > 1.)
Right = 1.0e20;
else if (LargestK < 1.)
Left = -1.0e20;
};
// --------------------------------------------------------------------------
// ConvergeVFrac solves the Rachford and Rice objective function ³
// for VFrac using a Newton Raphson technique modified
// to ensure convergence quickly
void SM_Oil::ConvergeVFrac(flag NoGuess)
{
const double FuncErr = 1.0E-4;
const int MaxIter = 50;
double LeftAsym, RightAsym;//, Func, DFunc, D2Func, VFrac1;
//int i;
FindBounds (LeftAsym, RightAsym);
//if (FDebug)
// {
// RTL_Use;
// writeln (DBGFPtr^, 'LeftAsym, RightAsym ', LeftAsym, RightAsym);
// RTL_Free;
// };
if (LeftAsym < -0.9e20)
VFrac = 0.0;
else if (RightAsym > 0.9e20)
VFrac = 1.0;
else
{
if (NoGuess)
VFrac = 0.5 * (LeftAsym + RightAsym);
else if ((VFrac < LeftAsym) || (VFrac > RightAsym))
VFrac = 0.5 * (LeftAsym + RightAsym);
//if (FDebug)
// FOR I = 1 TO NComp DO
// {
// RTL_Use;
// writeln (DBGFPtr^, 'K ', I, K[I]);
// writeln (DBGFPtr^, 'Z ', I, Z[I]);
// RTL_Free;
// };
//double VFrac1 = VFrac;
for (int Iter=MaxIter; Iter; Iter--)
{
//VFrac = VFrac1;
double Func = RacRic ();
if ((fabs(Func) > FuncErr) || (Iter == 0))
{
double DFunc = DRacRic ();
double VFrac1 = VFrac - Func / DFunc;
//if (VFrac1 > RightAsym)
if (VFrac1 > RightAsym)
VFrac1 = 0.5 * (RightAsym + VFrac);
if (VFrac1 < LeftAsym)
VFrac1 = 0.5 * (LeftAsym + VFrac);
//if (Func > RightAsym)
// VFrac1 = 0.5 * (1.0 + VFrac);
//if (Func < LeftAsym)
// VFrac1 = 0.5 * (0.0 + VFrac);
//if (VFrac1 > 1.0)
// VFrac1 = 0.5 * (1.0 + VFrac);
//if (VFrac1 < 0.0)
// VFrac1 = 0.5 * (0.0 + VFrac);
VFrac = Range(0.0, VFrac1, 1.0);
}
else
break;
}
if (Iter==0)
LogError("SM_Oil", 0, "ConvergeVFrac not Converged");
//if (FDebug)
// {
// RTL_Use;
// writeln (DBGFPtr^, ' ', VFrac, Func);
// RTL_Free;
// };
//VFrac = VFrac1;
VFrac=Range(0.0, VFrac, 1.0);
};
};
// --------------------------------------------------------------------------
int SM_Oil::Fugacity (flag Vapour, SpMArray & PHI,double T,double P, CDVector& XorY, double& Zval)
{
int i;//,j;
// Calculate AAM and BBM for the mixture
/*
double AAM = 0.0;
double BBM = 0.0;
for (i = 0; i < ZLen; i++)
{
BBM += B[i] * XorY[i];
for (j = 0; j < ZLen; j++)
{
AAM += ALA[i][j] * XorY[i] * XorY[j];
}
}
// Estimate the Compressability
double BIGA = AAM * P / ( RGas * RGas * T * T );
double BIGB = BBM * P / ( RGas * T);
double Q = BIGA - BIGB - (BIGB*BIGB);
double RR = BIGA * BIGB;
Gunderson(Q,RR,BIGA,BIGB,!LIQ,Zval);
for (j = 0; j < ZLen; j++)
{
double SUMXA = 0;
for (i = 0; i < ZLen; i++)
{
SUMXA = SUMXA + XorY[i] * ALA[j][i];
}
double RLNPHI = 0.0;
if ((((Zval - BIGB) > 0.0) && ((1.0 + BIGB / Zval) > 0.0)))
{
RLNPHI = (B[j] / BBM) * (Zval - 1.0) - log(Zval - BIGB) -
BIGA / BIGB * (2.0 * SUMXA / AAM - B[j] / BBM) * log(1.0 +
(BIGB / Zval));
}
else
{
RLNPHI = 0.0;
//dbgpln("RLNPHI made zero");
}
PHI[j] = RLNPHI;
}
*/
//------------------ACF's version
/*
for (i = 0; i < ZLen; i++)
{
double TCrit = CDB[i].TCrit();
double PCrit = CDB[i].PCrit();
double ACent = CDB[i].ACent();
A[i] = Ca * Sqr(RGas*TCrit) /(PCrit);
S[i] = 0.48 + 1.574 * ACent- 0.176 * Sqr(ACent);
Alpha[i] = Sqr(1.0 + S[i] * (1.0 - Sqrt(T / TCrit)));
//ALA[i][i] = A[i] * Alpha[i];
B[i] = Cb * RGas * CDB[i].TCrit()/CDB[i].PCrit();
}
*/
/*
double AsMix = 0.0;
double BsMix = 0.0;
for (i = 0; i < ZLen; i++)
{
BsMix += B[i] * XorY[i];
AsMix += XorY[i]*CDB[i].TCrit()*Sqrt(Alpha[i]/CDB[i].PCrit());
//AsMix += ALA[i][j] * XorY[i] * XorY[j];
}
double AMix = Ca * Sqr(AsMix) * P / Sqr(T);
double BMix = BsMix * P / (RGas * T);
*/
double AMix = 0.0;
double BMix = 0.0;
for (i = 0; i < ZLen; i++)
{
double TCrit = CDB[i].TCrit();
double PCrit = CDB[i].PCrit();
double ACent = CDB[i].ACent();
S[i] = 0.48 + 1.574 * ACent- 0.176 * Sqr(ACent);
Alpha[i] = Sqr(1.0 + S[i] * (1.0 - Sqrt(T / TCrit)));
AMix += XorY[i] * TCrit*Sqrt(Alpha[i]/PCrit);
BMix += XorY[i] * TCrit/PCrit;
//AsMix += ALA[i][j] * XorY[i] * XorY[j];
}
AMix = Ca * P / Sqr(T) * Sqr(AMix);
BMix = Cb * P / (T) * BMix;
CubeRoots Roots;
int NRoots;
double b = -1;
double c = AMix - BMix - Sqr(BMix);
double d = -AMix * BMix;
NRoots = FindCubeRoots (b, c, d, Roots);
Zval=FindZValue(Vapour, b,c,d, Roots, NRoots, AMix, BMix);
//double BigA = AsMix * P / Sqr(RGas * T);
//double BigB = BsMix * P / (RGas * T);
#if dbgSM_Oil
if (dbgKConverge())
dbgpln("Fug A,B,Z: %14.3g %14.3g %14.3g", AMix, BMix, Zval);
#endif
double SqrtA=0.0;
double B1=0.0;
for (i = 0; i < ZLen; i++)
{
double TCrit = CDB[i].TCrit();
double PCrit = CDB[i].PCrit();
SqrtA+=XorY[i]*Sqrt(Alpha[i]*PCrit);
B1+=XorY[i]*TCrit/PCrit;
}
double LclPhi[MaxSpecies];
for (i = 0; i < ZLen; i++)
{
//double SumXa = 0;
//for (i = 0; i < ZLen; i++)
// SumXa = SumXa + XorY[i] * ALA[i][i];
//SumXa = XorY[i] * ALA[i][i];
double TCrit = CDB[i].TCrit();
double PCrit = CDB[i].PCrit();
double SqrtAj=Sqrt(Alpha[i]/PCrit)*TCrit;
double Bj=TCrit/PCrit;
//Zval=Max(Zval, BMix+1.0e-6);
//ZVal=Max(ZVal, -BMix+1.0e-6);
// if ((((Zval - BMix) > 0.0) && ((1.0 + BMix / Zval) > 0.0)))
if ((((Zval - BMix) > 0.0) && ((1.0 + BMix / Zval) > 0.0)))
LclPhi[i] = (Bj / BMix) * (Zval - 1.0) -
log(Zval - BMix) -
AMix / BMix * (2.0 * SqrtAj/SqrtA - Bj/B1) *
log(1.0 + (BMix / Zval));
else
LclPhi[i] = 0.0;
PHI[i] = LclPhi[i];
}
int ACFs=1;
if (ACFs)
{
// ACF's Version;
double As[MaxSpecies];
double Bs[MaxSpecies];
double Sxa[MaxSpecies];
double AsMix=0.0;
double BsMix=0.0;
for (int i=0; i<ZLen; i++)
{
double TCrit = CDB[i].TCrit();
double PCrit = CDB[i].PCrit();
double ACent = CDB[i].ACent();
As[i]=Ca*Sqr(RGas*TCrit)/PCrit*Alpha[i];
Bs[i]=Cb*RGas*TCrit/PCrit;
}
for (i=0; i<ZLen; i++)
{
Sxa[i]=0.0;
for (int j=0; j<ZLen; j++)
Sxa[i]+=XorY[j]*Sqrt(As[i]*As[j]);
AsMix+=XorY[i]*Sxa[i];
BsMix+=XorY[i]*Bs[i];
}
double AMix=AsMix*P/Sqr(RGas*T);
double BMix=BsMix*P/(RGas*T);
double ALclPhi[MaxSpecies];
for (i=0; i<ZLen; i++)
{
if ((((Zval - BMix) > 0.0) && ((1.0 + BMix / Zval) > 0.0)))
ALclPhi[i] = (Bs[i] / BsMix) * (Zval - 1.0) -
log(Zval - BMix) -
AMix / BMix * (2.0 * Sxa[i]/AsMix - Bs[i]/BsMix) *
log(1.0 + (BMix / Zval));
else
ALclPhi[i] = 0.0;
PHI[i]=ALclPhi[i];
}
int xxx=0;
int yyy=0;
}
/*
double BigA = AsMix * P / Sqr(RGas * T);
double BigB = BsMix * P / (RGas * T);
//dbgpln("P,T,Z: %14.3g %14.3g %14.3g",P,T,Zval);
for (j = 0; j < ZLen; j++)
{
double SumXa = 0;
//for (i = 0; i < ZLen; i++)
// SumXa = SumXa + XorY[i] * ALA[j][i];
SumXa = XorY[i] * ALA[i][i];
double RLnPhi = 0.0;
if ((((Zval - BigB) > 0.0) && ((1.0 + BigB / Zval) > 0.0)))
{
RLnPhi = (B[j] / BsMix) * (Zval - 1.0) - log(Zval - BigB) -
BigA / BigB * (2.0 * SumXa / AsMix - B[j] / BsMix) * log(1.0 +
(BigB / Zval));
}
else
RLnPhi = 0.0;
PHI[j] = RLnPhi;
}
*/
return(0);
}
// --------------------------------------------------------------------------
double SM_Oil::FugacityKratio(double Temp_, double Pres_, double Damp)
{
SpMArray PHIL,PHIV;
#if SM_OIL_STATS
Cnt.FugKCall++;
#endif
//SetXYfromK();
//Temp_=(100.-32.)/1.8+273.16;
//Pres_=(250./14.7)*100.0;
//Y.SetAll(0.0);
//Y[Methane.ci()]=0.75;
//Y[Ethane.ci()]=0.15;
//Y[Propane.ci()]=0.10;
if (Fugacity(False, PHIL, Temp_, Pres_, X, Zliq))
LogError("SM_Oil", 0, "Liquid Fugacity returns error");
if (Fugacity(True, PHIV, Temp_, Pres_, Y, Zvap))
LogError("SM_Oil", 0, "Gas Fugacity returns error");
#if dbgSM_Oil
if (dbgKConverge())
{
int i;
dbgp(" L:");
dbgp(" %10.10s", "");
for (i=0; i<CDB.No() ; i++)
dbgp(" %10.7f", PHIL[i]);
dbgpln("");
dbgp(" V:");
dbgp(" %10.10s", "");
for (i=0; i<CDB.No() ; i++)
dbgp(" %10.7f", PHIV[i]);
dbgpln("");
}
#endif
//Damp=0.0;
double rms = 0.0;
for (int i = 0; i < ZLen; i++)
{
#if SM_OIL_STATS
Cnt.FugKIter++;
#endif
double NewK;
if (0)
NewK = exp(PHIL[i])*X[i]/NZ(exp(PHIV[i])*Y[i]);
else
NewK = exp(Range(-50.0, PHIL[i] - PHIV[i],50.0));
//NewK = exp(Range(-50.0, PHIV[i] - PHIL[i],50.0)); // Just fiddling
rms = Max(fabs(NewK-K[i]),rms);
K[i] = Damp*K[i] +(1.0-Damp)*NewK;
//K[i] = Sqrt(K[i]*NewK);
}
return rms;
}
// --------------------------------------------------------------------------
SM_OilStateSet * SM_Oil::FindBestSet(double Temp_, double Pres_)
{
int is=-1;
double D=SMBigDistance/2.0;
for (int i=0; i<MaxSMOilSets; i++)
{
Sets[i].Age++;
double d=Sets[i].Distance(Temp_, Pres_);
if (d<D)
{
is=i;
D=d;
}
}
if (is>=0)
{
Sets[is].Age=0;
#if dbgSM_Oil
if(dbgMemory())
dbgpln("BestSet %2i D:%12.3e T:%12.3e D:%12.3e", is, D, Sets[is].Ts-Temp_, Sets[is].Ps-Pres_);
#endif
return &Sets[is];
}
return NULL;
}
// --------------------------------------------------------------------------
SM_OilStateSet * SM_Oil::FindOldSet(double Temp_, double Pres_)
{
int is=-1, Age=MaxSMOilSets/2;
double D=0.0;
for (int i=0; i<MaxSMOilSets; i++)
{
if (!Sets[i].Initialised())
return &Sets[i];
double d=Sets[i].Distance(Temp_, Pres_);
if ((d>D) && (Sets[i].Age>Age))
{
is=i;
D=d;
Age=Sets[i].Age;
}
//if (Sets[i].Age>Age)
// {
// is=i;
// Age=Sets[i].Age;
// }
}
if (is>=0)
{
Sets[is].Age=0;
return &Sets[is];
}
return NULL;
}
// --------------------------------------------------------------------------
// Attempt to combine the AFS & MJM approach by KCG -----------------------------
flag SM_Oil::ConvergeKratios(pchar Tag, double Temp_, double Pres_)// , SM_OilStateSet * SS)
{
int cnt = 0;
double deltavf = 1.0e100;
#if SM_OIL_STATS
Cnt.CnvKCall++;
#endif
Temp_ = Range(110.0,Temp_,425.0); // kcg Check Root finder NBNB
Pres_ = Range(1.0,Pres_,1000000.0);
Pres_ = Range(20.0,Pres_,15000.0); // CNM kcg its starts going mog after this
//Pres_ = Range(80.0,Pres_,9000.0); // CNM kcg its starts going mog after this
VFrac = Range(0.0, VFrac, 1.0);
// Initialise the solution
SetConstantTcalcs(Temp_);
InitRqd = 1;
//double Damp;
//int Iter;
//Damp=0.0;
//Iter=0;
//#if dbgSM_Oil
//if(dbgConvergence())
// dbglock();
//#endif
if (fIdealFlashOnly || (K.GetLen() < 1))
{
VFrac=0.93;
IdealGasKratio(Temp_,Pres_);
// CNM This is here to get the solution to started
// Under Some Situations Ks should maybe be reduced
K.Mult(1.2);
#if dbgSM_Oil
if(dbgConvergence())
dbgp("%18.9f %18.9f Ideal ", Temp_, Pres_);
#endif
}
else if (1)
{
SM_OilStateSet * p=FindBestSet(Temp_, Pres_);
if (p)
LoadFrom(*p);
else
{
VFrac=0.93;
IdealGasKratio(Temp_,Pres_);
}
#if dbgSM_Oil
if(dbgConvergence())
if (p)
dbgp("%18.9f %18.9f %14.9f %14.9f ", Temp_, Pres_, p->Ts-Temp_, p->Ps-Pres_);
else
dbgp("%18.9f %18.9f %14s %14s ", Temp_, Pres_, "---", "---");
#endif
}
// Improve VFrac Estimate
RachRice_Solve();
//ConvergeVFrac(False);
if (fIdealFlashOnly)
{
SetXYfromK();
}
else
{
for(int k=100; k ; k--)
{
SetXYfromK();
#if dbgSM_Oil
if (dbgKConverge())
{
int i;
double d1,LfNew,VfNew;
dbgpln(" XX:%10.7f %10.3g", VFrac, RachRice_Value(VFrac, d1, LfNew, VfNew));
dbgp(" ");
dbgp(" %10.10s", "Sigma");
for (i=0; i<CDB.No() ; i++)
dbgp(" %10.10s", CDB[i].SymOrTag());
dbgpln("");
dbgp(" K:");
dbgp(" %10.10s", "");
for (i=0; i<CDB.No() ; i++)
dbgp(" %10.7f", K[i]);
dbgpln("");
dbgp(" Z:");
dbgp(" %10.7f", Z.Sum());
for (i=0; i<CDB.No() ; i++)
dbgp(" %10.7f", Z[i]);
dbgpln("");
dbgp(" X:");
dbgp(" %10.7f", X.Sum());
for (i=0; i<CDB.No() ; i++)
dbgp(" %10.7f", X[i]);
dbgpln("");
dbgp(" Y:");
dbgp(" %10.7f", Y.Sum());
for (i=0; i<CDB.No() ; i++)
dbgp(" %10.7f", Y[i]);
dbgpln("");
}
#endif
double vfr_prv = VFrac;
double DampV = 0.0;
double DampF = 0.0;
// Estimate Ks.
FugacityKratio(Temp_,Pres_,DampF);
double XSum=X.Sum();
int xxx=0;
// Estimate VFrac
RachRice_Solve();
//ConvergeVFrac(False);
if ((fabs(vfr_prv-VFrac) < ConvergeKratiosTol))
break;
VFrac = vfr_prv*DampV + VFrac*(1.0 - DampV);
}
if (k==0)
LogError("SM_Oil", 0, "ConvergeKRatios not Converged");
else
{
SM_OilStateSet * p=FindOldSet(Temp_, Pres_);
if (p)
{
p->LoadFrom(*this);
p->SetTP(Temp_, Pres_);
}
}
}
SetMassAndTemp(Temp_);
// if (SO)
// SO->vs.Save(this);
#if dbgSM_Oil
if(dbgConvergence())
{
double CurE = msHf(som_ALL,Temp_, Pres_,pMArray());
dbgpln("H:%12.4f Vf:%12.8f %s", CurE, VFrac*100.0, Tag);
// dbgunlock();
}
#endif
return True;
}
// --------------------------------------------------------------------------
/*
These routines have be developed from Fortran in Daubert - Chemical Engineering Thermodynamics
The names have been changed to permit two different sets of code to coexist and not to conceal
the source
*/
// --------------------------------------------------------------------------
void SM_Oil::SetConstantTcalcs(double T)
{
int i;//,j;
if( fabs(Tsetting - T) > 0.001 )
{
Tsetting = T;
for (i = 0; i < ZLen; i++)
{
if( CDB[i].TCrit() > 1000.0 || CDB[i].TCrit() < 1.0 )
{
LogWarning("Flashing",0,"Bad Tcrit value in Specie Database for %s",CDB[i].SymOrTag());
}
if( CDB[i].PCrit() > 100000.0 || CDB[i].PCrit() < 1.0 )
{
LogWarning("Flashing",0,"Bad Pcrit value in Specie Database for %s",CDB[i].SymOrTag());
}
if( CDB[i].ACent() > 2.0 || CDB[i].ACent() < -2.0 )
{
LogWarning("Flashing",0,"Bad Acentricity value in Specie Database for %s",CDB[i].SymOrTag());
}
}
for (i = 0; i < ZLen; i++)
{
double TCrit = CDB[i].TCrit();
double PCrit = CDB[i].PCrit();
double ACent = CDB[i].ACent();
A[i] = Ca * Sqr(RGas*TCrit) /(PCrit);
S[i] = 0.48 + 1.574 * ACent- 0.176 * Sqr(ACent);
Alpha[i] = Sqr(1.0 + S[i] * (1.0 - Sqrt(T / TCrit)));
//ALA[i][i] = A[i] * Alpha[i];
B[i] = Cb * RGas * CDB[i].TCrit()/CDB[i].PCrit();
}
/*** To Go Back to handle interaction parms
for(i = 0; i < ZLen; i++)
{
for (j = 0; j < ZLen; j++)
{
// estact to be fleshed page 256 - daubert
//double VCI = (*VC)[(I) - 1] * 1.0e-6;
//double VCJ = (*VC)[(J) - 1] * 1.0e-6;
//ACTION[I][J] = (exp(ln(exp(ln(VCI * VCJ) / 3.0) /
// ((exp(ln(VCI) / 3.0) + exp(ln(VCJ) / 3.0)) / 2.0)) * 3.0));
ALA[i][j] = sqrt(ALA[i][i] * ALA[j][j]) * (1.0 - CDB.BIP[i][j]);
}
}
**/
}
}
// --------------------------------------------------------------------------
/*
double SM_Oil::Enthalpy_Departure(pchar dbgTag,CDVector& C,double Temp_, double Pres_, flag Vapour)
{
double dAsdT = 0.0;
int i,j;
double Zv = Vapour ? Zvap : Zliq;
double HDep = 0.0;
double AAM = 0.0;
double BBM = 0.0;
for (i = 0; i < ZLen; i++)
{
BBM += B[i] * C[i];
for (j = 0; j < ZLen; j++)
{
AAM += ALA[i][j] * C[i] * C[j];
}
}
for (i = 0; i < ZLen; i++)
{
// dasidt[i] = - sqrt(As[i]* * Fc[i] / (Temp_ * CDB[i].TCrit())) * S[i];
double fc = A[i];
f[i] = fc*Alpha[i];
D[i] = -sqrt(f[i])*sqrt(fc)*S[i]/(CDB[i].TCrit()*sqrt(Temp_/CDB[i].TCrit()));
}
dAsdT = 0.0;
for (i = 0; i < CDB.No(); i++)
for (j = 0; j < CDB.No(); j++)
dAsdT = dAsdT + C[i]* C[j]*(1.0 - CDB.BIP(i,j))*(sqrt(f[i]/f[j])*D[j] + sqrt(f[j]/f[i])*D[i]);
dAsdT = dAsdT / 2.0;
HDep = ( - AAM + Temp_ * dAsdT) / BBM * log(1.0 + BBM * Pres_ /(Zv*RGas*Temp_))+RGas*Temp_*(Zv-1.0);
return HDep;
return 0.0;
}
*/
// --------------------------------------------------------------------------
/*
double SM_Oil::msEnthalpyZR(PhMask Phase, double T_, double P_, SpMArray * pMA)
{
return SpModel::msEnthalpyZR(Phase, T_, P_, pMA);
}
// --------------------------------------------------------------------------
double SM_Oil::totCp(PhMask Phase, double T_, double P_, SpMArray * pMA)
{
SpMArray &MA = (pMA==NULL ? MArray() : *pMA);
return msCp(Phase, T_, P_, &MA) * MA.Sum(Phase);
}
// --------------------------------------------------------------------------
double SM_Oil::totEnthalpyZR(PhMask Phase, double T_, double P_, SpMArray * pMA)
{
SpMArray &MA = (pMA==NULL ? MArray() : *pMA);
return msEnthalpyZR(Phase, T_, P_, &MA) * MA.Sum(Phase);
}
// ---------------------------------------------------------------------------
// SpecHeat calculates the specified phase specific heat in J/mol.K
double SM_Oil::msCp(PhMask Phase, double T_, double P_, SpMArray * pMA)
{
return SpModel::msCp(Phase, T_, P_, pMA);
}
*/
// ---------------------------------------------------------------------------
void SM_Oil::LoadZ()
{
LoadZused = True;
if( CDB.No() != ZLen)
{
ValidFlags |= 0x2;
X.SetSize(CDB.No());
Y.SetSize(CDB.No());
Z.SetSize(CDB.No());
K.SetSize(CDB.No(),0.5);
A.SetSize(CDB.No());
B.SetSize(CDB.No());
S.SetSize(CDB.No());
Alpha.SetSize(CDB.No());
ZLen=CDB.No();
}
Z.SetAll(MinZValue);
for (int s=0; s < SDB.No(); s++)
Z[SDB[s].CId()] += SpMoles(s);
Z.Normalise();
}
// ---------------------------------------------------------------------------
// Test Functions
#if SM_OIL_WITHFLASHTEST
flag SM_Oil::DoFlashTest=0;
void SM_Oil::FlashTestGundersonValues()
{
typedef struct { double Ptest;
double Ttest;
double Result;
} Test_Flash;
Test_Flash tf[] =
{
{ 1.0 * 101.0, 100.0, 0.0 } ,
{ 1.0 * 101.0, 180.0, 0.7725 } ,
{ 1.0 * 101.0, 260.0, 0.8864 } ,
{ 1.0 * 101.0, 340.0, 1.0 } ,
{ 8.0 * 101.0, 140.0, 0.0 } ,
{ 8.0 * 101.0, 220.0, 0.7566 } ,
{ 8.0 * 101.0, 300.0, 0.8693 } ,
{ 8.0 * 101.0, 380.0, 1.0 } ,
{ 32.0 * 101.0, 180.0, 0.0 } ,
{ 32.0 * 101.0, 260.0, 0.7251 } ,
{ 32.0 * 101.0, 340.0, 0.8618 } ,
{ 32.0 * 101.0, 400.0, 1.0 } ,
{128.0 * 101.0, 250.0, 0.0 } ,
{128.0 * 101.0, 320.0, 0.6178 } ,
{128.0 * 101.0, 400.0, 1.0 } ,
{160.0 * 101.0, 280.0, 0.0 } ,
{160.0 * 101.0, 320.0, 0.4806 } ,
{160.0 * 101.0, 360.0, 0.7739 } ,
{160.0 * 101.0, 370.0, 0.8934 } ,
{172.0 * 101.0, 300.0, 0.0 } ,
{172.0 * 101.0, 320.0, 0.3500 } ,
{172.0 * 101.0, 340.0, 0.5722 } ,
{172.0 * 101.0, 360.0, 1.0 }
};
LoadZ();
int i;
for( i = 0; i < CDB.No(); i++ )
{
pchar ppp = CDB[i].SymOrTag();
if( CDB[i].SymOrTag() && strcmp(CDB[i].SymOrTag(), "N2" ) == 0 ) Z[i] = 0.0054;
else
if( CDB[i].SymOrTag() && strcmp(CDB[i].SymOrTag(), "MethaneG" ) == 0 ) Z[i] = 0.7280;
else
if( CDB[i].SymOrTag() && strcmp(CDB[i].SymOrTag(), "EthaneG" ) == 0 ) Z[i] = 0.0546;
else
if( CDB[i].SymOrTag() && strcmp(CDB[i].SymOrTag(), "PropaneG" ) == 0 ) Z[i] = 0.0302;
else
if( CDB[i].SymOrTag() && strcmp(CDB[i].SymOrTag(), "NorButaneG" ) == 0 ) Z[i] = 0.0307;
else
if( CDB[i].SymOrTag() && strcmp(CDB[i].SymOrTag(), "NorPentaneG" ) == 0 ) Z[i] = 0.0688;
else
if( CDB[i].SymOrTag() && strcmp(CDB[i].SymOrTag(), "PC6" ) == 0 ) Z[i] = 0.0438;
else
if( CDB[i].SymOrTag() && strcmp(CDB[i].SymOrTag(), "PC8" ) == 0 ) Z[i] = 0.0375;
else
Z[i] = MinZValue;
}
for( i = 0; i < CDB.No(); i++ )
{
dbgpln("Data to converge %12s %12.6f",CDB[i].SymOrTag(),Z[i]);
}
char *s1 = "Temp";
char *s2 = "Pressure";
char *s3 = "GundersonVf";
char *s4 = "Vf";
char *s41 = "VfDiff%";
char *s5 = "Zliquid";
char *s6 = "Zvapour";
for(i = 0 ; i < 23; i++ )
{
//ConvergeKratios("TestFlash",tf[i].Ttest,tf[i].Ptest);
ConvergeKratios("TestFlash",tf[i].Ttest,tf[i].Ptest);
dbgpln(" GundersonTest %15.5f , %15.5f , %15.5f , %15.5f , %15.5f , %15.5f , %15.5f",tf[i].Ttest,tf[i].Ptest,tf[i].Result,VFrac,(tf[i].Result-VFrac)*100.0/GTZ(Max(fabs(tf[i].Result), fabs(VFrac))), Zliq,Zvap);
}
};
// ---------------------------------------------------------------------------
void SM_Oil::FlashTest()
{
double PP1=50.0;
double PP2=15000.0;
double TT1=C_2_K(-150.0);
double TT2=C_2_K(250.0);
double PP,TT;
static int CSVNo=0;
Strng Nm;
Nm.Set("%sFlash%03i.CSV", PrjFiles(),CSVNo++);
dbgp(" ======================== Dump TO CSV %s ======================== ", Nm());
FILE *f=fopen(Nm(), "wt");
if (f)
{
fprintf(f, " ");
if (1)
{
for(TT = TT1; TT <= TT2; TT += 10.0 )
fprintf(f, ",%.5f ",TT);
fprintf(f, "\n");
for(PP = PP1; PP <= PP2; PP += 200.0 )
{
fprintf(f, "%.5f ",PP);
for(TT = TT1; TT <= TT2; TT += 10.0 )
{
ConvergeKratios("TestFlash",TT,PP);
//dbgp(",%.5f(%6.4f) ",VFrac,RachRice_Fv);
fprintf(f, ",%.5f ",VFrac);
}
fprintf(f, "\n");
}
}
else
{
for(PP = PP1; PP <= PP2; PP += 200.0 )
fprintf(f, ",%.5f ",PP);
fprintf(f, "\n");
for(TT = TT1; TT <= TT2; TT += 10.0 )
{
fprintf(f, "%.5f ",TT);
for(PP = PP1; PP <= PP2; PP += 200.0 )
{
ConvergeKratios("TestFlash",TT,PP);
//dbgp(",%.5f(%6.4f) ",VFrac,RachRice_Fv);
fprintf(f, ",%.5f ",VFrac);
}
fprintf(f, "\n");
}
}
fclose(f);
}
}
// --------------------------------------------------------------------------
#endif
// --------------------------------------------------------------------------
void SM_Oil::DbgDump(pchar dbgTag)
{
dbgp("T:%7.2f P:%8.2f H:%8.2f ", Temp(), Press(), SpModel::msHf());
dbgp("F:%8.5f ", VFrac);
dbgp("K:"); for (int i=0; i<CDB.No(); i++) dbgp("%8.5f ", K[i]);
//dbgp("X:"); for (i=0; i<CDB.No(); i++) dbgp("%8.5f ", m.X[i]);
//dbgp("Y:"); for (i=0; i<CDB.No(); i++) dbgp("%8.5f ", m.Y[i]);
//dbgp("Z:"); for (i=0; i<CDB.No(); i++) dbgp("%8.5f ", Z[i]);
dbgpln("%s",dbgTag);
/*
int i;
dbgpln(" Tag = %s",Tag);
dbgpln(" Pressure = %.1fkPa",Pres_);
dbgpln(" Temperature = %.1fK",Temp_);
dbgpln(" Calls to Converge Kratio = %d",kvaluscall);
dbgpln(" Calls to Converge RacRic = %d",racriccall);
dbgpln(" Max Iter in Kvalus = %d",kvalusiter);
dbgpln(" Max Iter in RacRic = %d",racriciter);
dbgpln(" Vapour Fraction = %.5f",VFrac);
dbgpln(" Liquid 'Z' = %.5f",Zliq);
dbgpln(" Vapour 'Z' = %.5f",Zvap);
// dbgpln(" Total Enthalpy = %.5f",Enthalpy);
dbgpln("%15s, %15s, %15s, %15s, %15s, %15s, %15s",
"Species",
"Liquid",
"Vapour",
"X",
"Y",
"Z",
"K");
double l=0.0,v=0.0,x=0.0,y=0.0,z=0.0;
for ( i = 0; i < ZLen; i++ )
{
double liq = (1.0 - VFrac)*Z[i];
double vap = (VFrac )*Z[i];
dbgpln("%15s, %15.5f, %15.5f, %15.5f, %15.5f, %15.5f, %15.5f",CDB[i].SymOrTag(),liq,vap,X[i],Y[i],Z[i],K[i]);
l += liq;
v += vap;
x += X[i];
y += Y[i];
z += Z[i];
}
dbgpln("%15s, %15.5f, %15.5f, %15.5f, %15.5f, %15.5f","Totals",l,v,x,y,z);
*/
};
//--------------------------------------------------------------------------
class QPFnd : public MRootFinderBase
{
public:
SM_Oil &Om;
double P1;
QPFnd(SM_Oil * pM, double P1_, double RqdTol) : MRootFinderBase("QPFnd", RqdTol), Om(*pM)
{ P1=P1_; }
char * ObjTag() { return Om.FullObjTag(); };
double Function(double x)
{
// x is the Temp
Om.ConvergeKratios("QPFnd",x,P1);
//Om.SetMassAndTemp(x);
double H=Om.msHf(som_ALL,x,P1,Om.pMArray());
return H;
};
};
//--------------------------------------------------------------------------
QPF_Modes SM_Oil::QPFlash(pSpModel pVap, double P1, double Duty, flag SaturationLimit, double *pOverDuty)
{ DoBreak(); return QPF_Error;};
QPF_Modes SM_Oil::QPFlash(double P1, double Duty, flag SaturationLimit, double *pOverDuty)
{
LoadZ();
#if SM_OIL_WITHFLASHTEST
if (DoFlashTest)
{
FlashTest();
DoFlashTest=0;
}
#endif
#if SM_OIL_STATS
Cnt.Reset();
#endif
double T0=Temp();
double P0=Press();
#if dbgSM_Oil
if (dbgQPFlash())
dbgp(" QPflash Input Vector T0:%-12.5f P0:%-12.5f P1:%-12.5f %s",T0,P0,P1, FullObjTag());
#endif
#if dbgSM_Oil
if (dbgQPFlash())
dbgpln(" Output Vector T0:%-12.5f P0:%-12.5f P1:%-12.5f",T0,P0,P1);
#endif
// Converge Ks @ Initial conditions
//if (QPm.Init.ValidState())
// LoadFrom(QPm.Init);
ConvergeKratios("InitCond",T0,P0);
//SetMassAndTemp(T0);
double DstE = msHf(som_ALL,T0,P0,pMArray()) + Duty;
double T1=T0, CurE;
//SaveTo(QPm.Init);
// Converge Ks & Temp @ Final conditions such that Enthalpy is conserved
SetPress(P1);
if (Valid(QPm.Temp))
{
T1=QPm.Temp;
QPm.Temp=dNAN();
//if (QPm.Final.ValidState())
// LoadFrom(QPm.Final);
}
ConvergeKratios("CurCond",T1,P1);
//SetMassAndTemp(T1);
CurE = msHf(som_ALL,T1,P1,pMArray());
const double BigTStep=25.0;
const double TStepMult=4.0;
double deltaT = BigTStep/(TStepMult*TStepMult*TStepMult);
double tl, tr, fl, fr;
tl=T1;
tr=T1;
fl=CurE;
fr=CurE;
// look for straddle point
if( DstE > CurE )
{
while( DstE > CurE )
{
tl=T1;
fl=CurE;
T1 = T1 + deltaT;
tr=T1;
ConvergeKratios("FindStraddleUP",T1,P1);
//SetMassAndTemp(T1);
CurE = msHf(som_ALL,T1,P1,pMArray());
fr=CurE;
deltaT=Min(deltaT*TStepMult, BigTStep);
}
}
else
{
while( DstE < CurE && tl>C_2_K(-100.0))
{
tr=T1;
fr=CurE;
T1 = T1 - deltaT;
tl=T1;
ConvergeKratios("FindStraddleDN",T1,P1);
///SetMassAndTemp(T1);
CurE = msHf(som_ALL,T1,P1,pMArray());
fl=CurE;
deltaT=Min(deltaT*TStepMult, BigTStep);
}
}
// solve using Brents algorithm
QPFnd QPF(this, P1, QPFlashTol*fabs(fl-fr));
QPF.SetTarget(DstE);
if (QPF.Start(tl, tr, fl, fr)==RF_OK)
{
if (QPF.Solve_Brent()==RF_OK)
{
QPm.Temp=QPF.Result();
//SaveTo(QPm.Final);
}
else
LogError("SM_Oil", 0, "QPF Not Solved");
}
else
LogError("SM_Oil", 0, "QPF Not Started");
#if dbgSM_Oil && SM_OIL_STATS
if (dbgStats())
Cnt.Write(Temp(), Press());
#endif
return QPF_Sensible;
}
// ---------------------------------------------------------------------------
/**
QPF_Modes SM_Oil::QFlash(double SpaceVolume, double Duty)
{
LoadZ();
return QPF_Sensible;
#if SM_OIL_WITHFLASHTEST
if (DoFlashTest)
{
FlashTest();
DoFlashTest=0;
}
#endif
double T=QTLast;
double P=QPLast, P1;
double H0=SpModel::msHf(), H1;
if(!Qflashdone )
{
T=Temp();
P=Press();
}
dbgpln("=========");
int Dir=0;
double XX=0.8;
P1=P;
while (1)//fabs(T-QTLast)>1.0e-3)
{
//tTemp(T);
while (1)//for (int i=0; i<5; i++)
{
P+=0.01*(P1-P);
//if ()
ConvergeKratios("SM_Oil", T,P);
SetMassAndTemp(T);
P1=Press();
dbgpln(" %8.2f %8.3f %8.3f",T,P,P1);
if (fabs(P-P1)<0.01)
break;
}
H1=SpModel::msHf();
if (fabs(H1-H0)<1.0e-3)
break;
if (Dir!=Sign(H1-H0))
XX=1.0-(1.0-XX)*0.5;
Dir=Sign(H1-H0);
if (H1>H0)
T*=XX;
else
T/=XX;
}
QTLast=T;
QPLast=P;
Qflashdone = True;
return QPF_Sensible;
}
*/
// ---------------------------------------------------------------------------
double SM_Oil::TPFlash(double T1, double P1, double &Duty)
{
LoadZ();
#if SM_OIL_WITHFLASHTEST
if (DoFlashTest)
{
FlashTest();
DoFlashTest=0;
}
#endif
ConvergeKratios(FullObjTag(),T1,P1);
#if dbgSM_Oil
if(dbgTPFlash())
DbgDump(FullObjTag());
#endif
//SetMassAndTemp(T1);
return SpModel::totHf();
}
// ===========================================================================
// Debug
/*
void SM_Oil::WriteDebug (pchar Tag, int Iter, double ErrK, double VFrac_, double Temp_, double Pres_, double Duty_)
{
double XP, YP, ZP;
char xxx[50];
strcpy(xxx," ");
strset(xxx, (Iter>=0) ? '-' : '=');
dbgpln("%s %s %s", xxx,Tag,xxx);
dbgnln();
dbgpln("Temperature : %7.2f K",Temp_);
dbgpln("Pressure : %7.2f kPa",Pres_);
dbgpln("Vapour Fraction :%8.4f",VFrac_);
dbgpln("Duty :%8.1f",Duty_);
if (Iter >=0)
{
dbgpln("Iteration :%3i",Iter);
dbgpln("Error :%14g",ErrK);
}
dbgpln("");
dbgpln(" Feed Vapour Liquid K Component");
for (int I=0; I<CDB.No(); I++)
{
XP = 100 * X[I];
if (XP < 0.0005) XP = 0;
YP = 100 * Y[I];
if (YP < 0.0005) YP = 0;
ZP = 100 * Z[I];
dbgp("%10.2f%10.3f%10.3f",ZP,YP,XP);
if ((K[I] > 1.0E-4) && (K[I] < 1.0E4))
dbgp("%12.5f",K[I]);
else
dbgp("%14g",K[I]);
dbgpln(" %s",CDB[I].Name);
}
dbgpln("%s %s %s", xxx,Tag,xxx);
};
*/
// ===========================================================================
void SM_Oil::SetMassAndTemp(double Temp_)
{
// NB Must enforce mass closure
PhMask Msk=som_Vap|som_Liq;
double Mo_t=Moles(Msk);
for (int c=0; c < CDB.No(); c++)
{
rComponentD Cd=CDB[c];
if (Cd.vi()>=0 && Cd.li()>=0)
{
double m=M[Cd.vi()]+M[Cd.li()];
M[Cd.vi()]=Mo_t*VFrac*Y[c]*SDB[Cd.vi()].MoleWt();
M[Cd.li()]=Max(0.0, m-M[Cd.vi()]);
}
}
//M[H2o.vi()]=H2OVap;
//M[H2o.li()]=H2OLiq;
ClrMStatesOK();
SetTemp(Temp_);
}
// =========================================================================== | [
"[email protected]"
] | [
[
[
1,
1790
]
]
] |
e515b08eede96bb985f73d33f8dc75766fec4f1f | 11da90929ba1488c59d25c57a5fb0899396b3bb2 | /Src/PalmOS/PalmFileWriter.cpp | c3c34782ff2df6b541d71dfc28a21f11109d45ff | [] | no_license | danste/ars-framework | 5e7864630fd8dbf7f498f58cf6f9a62f8e1d95c6 | 90f99d43804d3892432acbe622b15ded6066ea5d | refs/heads/master | 2022-11-11T15:31:02.271791 | 2005-10-17T15:37:36 | 2005-10-17T15:37:36 | 263,623,421 | 0 | 0 | null | 2020-05-13T12:28:22 | 2020-05-13T12:28:21 | null | UTF-8 | C++ | false | false | 473 | cpp |
#include <FileWriter.hpp>
FileWriter::FileWriter() {}
FileWriter::~FileWriter() {}
status_t FileWriter::flush()
{
return file_.flush();
}
status_t FileWriter::writeRaw(const void* begin, uint_t length)
{
assert(isOpen());
return file_.write(begin, length);
}
status_t FileWriter::open(const char_t* name, ulong_t openMode, ulong_t type, ulong_t creator, uint_t cardNo)
{
return file_.open(name, openMode, type, creator, cardNo);
} | [
"andrzejc@10a9aba9-86da-0310-ac04-a2df2cc00fd9",
"kjk@10a9aba9-86da-0310-ac04-a2df2cc00fd9"
] | [
[
[
1,
3
],
[
5,
5
],
[
7,
7
],
[
12,
12
],
[
22,
22
]
],
[
[
4,
4
],
[
6,
6
],
[
8,
11
],
[
13,
21
]
]
] |
abeeb208a3dcc84633668fbfa55619da669e3381 | b24d5382e0575ad5f7c6e5a77ed065d04b77d9fa | /RadiantLaserCross/RLC_GameStateManager.cpp | e46dd90ad522a6f8567a2e081126851c77295fd9 | [] | no_license | Klaim/radiant-laser-cross | f65571018bf612820415e0f672c216caf35de439 | bf26a3a417412c0e1b77267b4a198e514b2c7915 | refs/heads/master | 2021-01-01T18:06:58.019414 | 2010-11-06T14:56:11 | 2010-11-06T14:56:11 | 32,205,098 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,070 | cpp | #include "RLC_GameStateManager.h"
#include "RLC_Game.h"
namespace rlc
{
void GameStateManager::add( GameStatePtr game_state )
{
GC_ASSERT_NOT_NULL( game_state );
GC_ASSERT( ! game_state->name().empty() , "Tried to register a game state with an empty name!" );
if( m_state_index.find( game_state->name() ) != m_state_index.end() )
{
GC_EXCEPTION << "Tried to add a game state with a name already registered : " << game_state->name();
}
// register the state
m_state_index.insert( std::make_pair( game_state->name(), game_state ) );
}
void GameStateManager::switch_to( const std::string& state_name )
{
GC_ASSERT( !state_name.empty() , "Tried to register a game state with an empty name!" );
auto find_it = m_state_index.find( state_name );
if( find_it == m_state_index.end() )
{
GC_EXCEPTION << "Tried to switch to a game state with non registered name : " << state_name;
}
GameStatePtr next_state = find_it->second;
GC_ASSERT_NOT_NULL( next_state );
RLC_LOG << "---------------------------------------------------------";
RLC_LOG << "-- Switching to " << next_state->name() << " state ... -- ";
if( m_current_state != nullptr )
{
//end the current state
RLC_LOG << "Ending state " << m_current_state-> name() << " ...";
m_current_state->end();
RLC_LOG << "Ended state " << m_current_state-> name() << ".";
}
// now set the new state
m_current_state = next_state;
// begin the next state
RLC_LOG << "Beginning state " << m_current_state-> name() << " ...";
m_current_state->begin();
RLC_LOG << "Began state " << m_current_state-> name() << ".";
RLC_LOG << "-- Switching done. -- ";
RLC_LOG << "---------------------------------------------------------";
}
void GameStateManager::update()
{
if( m_current_state != nullptr )
{
m_current_state->update();
}
}
void GameStateManager::render()
{
if( m_current_state != nullptr )
{
m_current_state->render();
}
}
} | [
"[email protected]"
] | [
[
[
1,
82
]
]
] |
686ddb1393f1057291970f6ea3435d255659c10f | 3ec3b97044e4e6a87125470cfa7eef535f26e376 | /timorg-chuzzle_bejeweled_clone/chuzzle_board.h | d4bb2f5da06c9000d2c2756a699cf9f68e47add2 | [] | no_license | strategist922/TINS-Is-not-speedhack-2010 | 6d7a43ebb9ab3b24208b3a22cbcbb7452dae48af | 718b9d037606f0dbd9eb6c0b0e021eeb38c011f9 | refs/heads/master | 2021-01-18T14:14:38.724957 | 2010-10-17T14:04:40 | 2010-10-17T14:04:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 316 | h | #ifndef CHUZZLE_BOARD_H
#define CHUZZLE_BOARD_H
#include "board.h"
class CHUZZLE_BOARD : public BOARD
{
public:
CHUZZLE_BOARD(int w, int h);
private:
// this is run after all the clicking and decision to move are made
virtual void logic(CP_OBJECT_MANAGER<TILE> &removed);
};
#endif
| [
"[email protected]"
] | [
[
[
1,
15
]
]
] |
aafa8e619d7697b6e1ef9224145d84518b0580ea | bfe8eca44c0fca696a0031a98037f19a9938dd26 | /redundancy/foolbear.cpp | a63f64cc1d588397a5acbf959631049ae326cff3 | [] | no_license | 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 | 9,696 | cpp | #include "foolbear.h"
#ifdef WIN32
#include <windows.h>
#include <process.h>
#else
#include <pthread.h>
#endif
int fool_ulaw2linear(unsigned char ulawbyte)
{
static int exp_lut[8] = {0,132,396,924,1980,4092,8316,16764};
int sign, exponent, mantissa, sample;
ulawbyte = ~ulawbyte;
sign = (ulawbyte & 0x80);
exponent = (ulawbyte >> 4) & 0x07;
mantissa = ulawbyte & 0x0F;
sample = exp_lut[exponent] + (mantissa << (exponent + 3));
if ( sign != 0 ) sample = -sample;
return(sample);
}
int fool_getwavefileformat(const char* file, unsigned short* data_encoding,
unsigned long* samples_per_sec, unsigned short* bits_per_sample)
{
struct WAVE_FORMAT
{
WORD wFormatTag; /* format type */
WORD nChannels; /* number of channels (i.e. mono, stereo...) */
DWORD nSamplesPerSec; /* sample rate */
DWORD nAvgBytesPerSec; /* for buffer estimation */
WORD nBlockAlign; /* block size of data */
WORD wBitsPerSample;
// the last 2 fields are not present in PCM format
WORD cbSize;
BYTE extra[80]; /* Possible extra data */
} waveinfo = {0};
/* Beginninng of any WAVE file */
struct WAVE_FILE_HEADER
{
DWORD riff ; /* Must contain 'RIFF' */
DWORD riffsize ; /* size of rest of RIFF chunk (entire file?) */
DWORD wave; /* Must contain 'WAVE' */
} filehdr;
struct CHUNK_HEADER
{
DWORD id ; /* 4-char chunk id */
DWORD size ; /* chunk size */
} chunkhdr ;
FILE *fp = fopen(file, "rb");
if(fp == NULL) return -1;
/* Expect the following structure at the beginning of the file
Position contents
-------- --------
0-3 'RIFF'
4-7 size of the data that follows
8-11 'WAVE'
followed by a sequence of "chunks" containing:
n-n+3 4 char chunk id
n+4 - n+7 size of data
n+8 - n+8+size data
A 'fmt' chunk is manadatory
0-3 'fmt '
4-7 size of the format block (16)
8-23 wave header - see typedef above
24 .. option data for non-PCM formats
A subsequent 'data' chunk is also mandatory
0-3 'data'
4-7 size of the data that follows
8-size+8 data
*/
if(fread (&filehdr, 1, sizeof(filehdr), fp) != sizeof(filehdr)
|| strncmp ((char *)&filehdr.riff, "RIFF", 4) != 0
|| strncmp ((char *)&filehdr.wave, "WAVE", 4) != 0 )
{
fclose(fp);
return -1;
}
BOOL err = FALSE;
for (;;)
{
if (fread (&chunkhdr, 1, sizeof(chunkhdr), fp) != sizeof(chunkhdr))
{
err = TRUE;
break;
}
if (strncmp ((char *)&chunkhdr.id, "fmt ", 4) == 0) break ;
else
{
long size = ((chunkhdr.size +1) & ~1) ; /* round up to even */
if (fseek(fp, size, SEEK_CUR ) !=0)
{
err = TRUE;
break;
}
}
}
if(err)
{
fclose(fp);
return -2;
}
size_t fmtwords = (size_t)((chunkhdr.size+1)/2);
if (chunkhdr.size > sizeof(waveinfo) || fread(&waveinfo, 2, fmtwords, fp) != fmtwords)
{
fclose(fp);
return -3;
}
fclose(fp);
*data_encoding = waveinfo.wFormatTag;
*samples_per_sec = waveinfo.nSamplesPerSec;
*bits_per_sample = waveinfo.wBitsPerSample;
return 0;
}
FOOL_BOOL fool_istiffformatfile(const char* file)
{
/* Beginninng of any TIFF file */
struct TIFF_FILE_HEADER
{
BYTE byte1;
BYTE byte2;
BYTE byte3;
BYTE byte4;
unsigned offset;
} filehdr;
FILE *fp = fopen(file, "rb");
if(fp == NULL) return FOOL_FALSE;
if(fread (&filehdr, 1, sizeof(filehdr), fp) == sizeof(filehdr) &&
(0x49 == filehdr.byte1 || 0x4D == filehdr.byte1) &&
(0x49 == filehdr.byte2 || 0x4D == filehdr.byte2) &&
0x2A == filehdr.byte3 &&
0x00 == filehdr.byte4 &&
filehdr.offset >= 8) {
fclose(fp);
return FOOL_TRUE;
}
fclose(fp);
return FOOL_FALSE;
}
int fool_beginthread(FoolThreadFunc func, void *arg, FOOL_THREAD_T* ptid)
{
FOOL_THREAD_T tid;
#ifdef WIN32
unsigned long thd = _beginthreadex(NULL, 4096, func, arg, 0, (ptid==NULL)?&tid:ptid);
if(0 == thd) return -1;
CloseHandle((HANDLE)thd); //detach
#else
if(0 != pthread_create((ptid==NULL)?&tid:ptid, NULL, func, arg)) return -1;
pthread_detach(ptid == NULL ? tid : *ptid);
#endif
return 0;
}
void fool_wait(int msec)
{
#ifdef WIN32
Sleep(msec);
#else
struct timeval timeout;
if (msec>1000) {
timeout.tv_sec = msec/1000;
timeout.tv_usec = msec%1000 * 1000;
}
else {
timeout.tv_sec = 0;
timeout.tv_usec = msec * 1000;
}
select(0, NULL, NULL, NULL, &timeout);
#endif
}
//define global value "fool_time_base"
struct FOOL_TIME_BASE{
#ifndef WIN32
struct timeval tv; //from 0:0:0 01/01/1970, second+microsencond
#else
unsigned long tick; //from windows begin running, millisecond
#endif
FOOL_TIME_BASE() {
#ifndef WIN32
gettimeofday(&tv, NULL);
#else
tick = GetTickCount();
#endif
}
}fool_time_base;
//get elapsed time(in a ms unit) from beginning
unsigned long fool_getms()
{
#ifndef WIN32
struct timeval tv;
gettimeofday(&tv, NULL);
return (tv.tv_sec-fool_time_base.tv.tv_sec)*1000+(tv.tv_usec-fool_time_base.tv.tv_usec)/1000;
#else
unsigned long tick = GetTickCount();
return tick - fool_time_base.tick;
#endif
}
char *fool_gettimestring(char* buf)
{
if (NULL == buf) return NULL;
int size = strlen(buf);
#ifndef WIN32
struct tm now_t;
struct timeval cur_t;
gettimeofday(&cur_t, NULL);
//now_t = localtime(&cur_t.tv_sec);
localtime_r(&cur_t.tv_sec, &now_t);//NOTE:_REENTRANT in makefile
_snprintf(buf, size-1, "%04d/%02d/%02d %02d:%02d:%02d.%06d",
now->tm_year+1900, now->tm_mon+1, now->tm_mday,
now_t.tm_hour, now_t.tm_min, now_t.tm_sec, cur_t.tv_usec);
#else
SYSTEMTIME now;
GetLocalTime(&now);
_snprintf(buf, size-1, "%04d/%02d/%02d %02d:%02d:%02d.%03d",
now.wYear, now.wMonth, now.wDay,
now.wHour, now.wMinute, now.wSecond, now.wMilliseconds);
#endif
return buf;
}
char *fool_strupr(char *str)
{
#ifndef WIN32
char *p = str;
while(*p) {
if(*p>='a' && *p<='z') *p = *p-'a'+'A';
p++;
}
return str;
#else
return strupr(str);
#endif
}
char *fool_strlwr(char *str)
{
#ifndef WIN32
char *p = str;
while(*p) {
if(*p>='A' && *p<='Z') *p = *p-'A'+'a';
p++;
}
return str;
#else
return strlwr(str);
#endif
}
char *fool_strltrim(char *str)
{
unsigned char *p = (unsigned char*)str; // for chinese text
while(*p && *p <= ' ') p++;
memmove(str,p,strlen((char*)p)+1);
return str;
}
char *fool_strrtrim(char *str)
{
unsigned char *p = (unsigned char*)str+strlen(str)-1;
while((char*)p != (str-1) && *p <= ' ') p--;
*(p+1) = '\0';
return str;
}
char *fool_strtrim(char *str)
{
return fool_strltrim(str), fool_strrtrim(str);
}
char *fool_substr(char *sub, const char *str, int count)
{
int i;
for(i=0; str[i] && i<count; i++) sub[i]=str[i];
sub[i] = '\0';
return sub;
}
char *fool_replacechar(const char* in, char* out, char oldchar, char newchar)
{
int len = 0;
if (NULL == in) sprintf(out, "NULL");
else {
len = strlen(in);
for (int i=0; i<len; i++) {
if (oldchar == in[i]) out[i] = newchar;
else out[i] = in[i];
}
out[len] = '\0';
}
return out;
}
char *fool_get_element_string(char *value, const char *key, const char *cbuf, char delimiter)
{
char *buf = (char*)cbuf;
if(NULL==buf) return NULL;
while(*buf && *buf==delimiter) buf++;
if(0==*buf) return NULL;
char *ep, *dp, ch, NAME[128], KEY[128];
strcpy(KEY,key); strupr(KEY);
while(*buf)
{
ep=strchr(buf,'=');
if(ep)
{
for(dp=ep+1; *dp && *dp!=delimiter; dp++);
*ep='\0'; strcpy(NAME,buf); *ep='=';
fool_strtrim(NAME); strupr(NAME);
if(0==strcmp(KEY,NAME))
{
ch=*dp; *dp='\0';
strcpy(value,ep+1); *dp=ch;
fool_strtrim(value);
return value;
} else buf = *dp?dp+1:dp;
} else { *value='\0'; return NULL; }
}
*value='\0';
return NULL;
}
int fool_get_element_int(int *value, const char *key, const char *cbuf, char delimiter)
{
char tmp[64];
return NULL==fool_get_element_string(tmp,key,cbuf,delimiter)?(*value=0,-1):(*value=atoi(tmp),0);
}
FOOL_BOOL fool_extract_path(const char* fname, char* path)
{
if(fname == NULL || path == NULL) return FOOL_FALSE;
const char *p = fname+strlen(fname);
while(p != fname && *p != '\\') p--;
if(*p != '\\') return FOOL_FALSE;
fool_substr(path, fname, (int)(p-fname));
return FOOL_TRUE;
}
FOOL_BOOL fool_make_path(const char* path)
{
if(NULL == path || 0 == path[0] || 0 == access(path,0)) return FOOL_TRUE;
char ppath[256];
if(FOOL_FALSE == fool_extract_path(path, ppath)) return (0 == _mkdir(path)?FOOL_TRUE:FOOL_FALSE);
else return fool_make_path(ppath) ? (0 == _mkdir(path)?FOOL_TRUE:FOOL_FALSE) : FOOL_FALSE;
} | [
"greatfoolbear@756bb6b0-a119-0410-8338-473b6f1ccd30"
] | [
[
[
1,
371
]
]
] |
5efa3cdfe9597e2516bdd8de4ce049978f740711 | bb8965cede71d539880e29e1b4f1cfaa2d3bf047 | /abanq-2.3-win/src/plugins/styles/kde/kdefx/kstyle.h | f089cca70b9d16aa5bbec1b42ca9eea05cc25bef | [] | no_license | AliYousuf/abanq-port | 5c968c2e46916f6cac47571a99d50ca429ef2ade | e5d31403325506ea8ee40e01daaa8161607f4c59 | refs/heads/master | 2016-09-01T14:40:02.784138 | 2009-03-19T02:54:48 | 2009-03-19T02:54:48 | 51,658,511 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,074 | h | /*
* $Id: kstyle.h,v 1.18 2004/09/13 13:28:29 staniek Exp $
*
* KStyle
* Copyright (C) 2001-2002 Karol Szwed <[email protected]>
*
* QWindowsStyle CC_ListView and style images were kindly donated by TrollTech,
* Copyright (C) 1998-2000 TrollTech AS.
*
* Many thanks to Bradley T. Hughes for the 3 button scrollbar code.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License version 2 as published by the Free Software Foundation.
*
* 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., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifndef __KSTYLE_H
#define __KSTYLE_H
// W A R N I N G
// -------------
// This API is still subject to change.
// I will remove this warning when I feel the API is sufficiently flexible.
#include <qcommonstyle.h>
#include <kdelibs_export.h>
class KPixmap;
struct KStylePrivate;
/**
* Simplifies and extends the QStyle API to make style coding easier.
*
* The KStyle class provides a simple internal menu transparency engine
* which attempts to use XRender for accelerated blending where requested,
* or falls back to fast internal software tinting/blending routines.
* It also simplifies more complex portions of the QStyle API, such as
* the PopupMenuItems, ScrollBars and Sliders by providing extra "primitive
* elements" which are simple to implement by the style writer.
*
* @see QStyle::QStyle
* @see QCommonStyle::QCommonStyle
* @author Karol Szwed ([email protected])
* @version $Id: kstyle.h,v 1.18 2004/09/13 13:28:29 staniek Exp $
*/
class KDEFX_EXPORT KStyle: public QCommonStyle
{
Q_OBJECT
public:
/**
* KStyle Flags:
*
* @li Default - Default style setting, where menu transparency
* and the FilledFrameWorkaround are disabled.
*
* @li AllowMenuTransparency - Enable this flag to use KStyle's
* internal menu transparency engine.
*
* @li FilledFrameWorkaround - Enable this flag to facilitate
* proper repaints of QMenuBars and QToolBars when the style chooses
* to paint the interior of a QFrame. The style primitives in question
* are PE_PanelMenuBar and PE_PanelDockWindow. The HighColor style uses
* this workaround to enable painting of gradients in menubars and
* toolbars.
*/
typedef uint KStyleFlags;
enum KStyleOption {
Default = 0x00000000, //!< All options disabled
AllowMenuTransparency = 0x00000001, //!< Internal transparency enabled
FilledFrameWorkaround = 0x00000002 //!< Filled frames enabled
};
/**
* KStyle ScrollBarType:
*
* Allows the style writer to easily select what type of scrollbar
* should be used without having to duplicate large amounts of source
* code by implementing the complex control CC_ScrollBar.
*
* @li WindowsStyleScrollBar - Two button scrollbar with the previous
* button at the top/left, and the next button at the bottom/right.
*
* @li PlatinumStyleScrollBar - Two button scrollbar with both the
* previous and next buttons at the bottom/right.
*
* @li ThreeButtonScrollBar - %KDE style three button scrollbar with
* two previous buttons, and one next button. The next button is always
* at the bottom/right, whilst the two previous buttons are on either
* end of the scrollbar.
*
* @li NextStyleScrollBar - Similar to the PlatinumStyle scroll bar, but
* with the buttons grouped on the opposite end of the scrollbar.
*
* @see KStyle::KStyle()
*/
enum KStyleScrollBarType {
WindowsStyleScrollBar = 0x00000000, //!< two button, windows style
PlatinumStyleScrollBar = 0x00000001, //!< two button, platinum style
ThreeButtonScrollBar = 0x00000002, //!< three buttons, %KDE style
NextStyleScrollBar = 0x00000004 //!< two button, NeXT style
};
/**
* Constructs a KStyle object.
*
* Select the appropriate KStyle flags and scrollbar type
* for your style. The user's style preferences selected in KControl
* are read by using QSettings and are automatically applied to the style.
* As a fallback, KStyle paints progressbars and tabbars. It inherits from
* QCommonStyle for speed, so don't expect much to be implemented.
*
* It is advisable to use a currently implemented style such as the HighColor
* style as a foundation for any new KStyle, so the limited number of
* drawing fallbacks should not prove problematic.
*
* @param flags the style to be applied
* @param sbtype the scroll bar type
* @see KStyle::KStyleFlags
* @see KStyle::KStyleScrollBarType
* @author Karol Szwed ([email protected])
*/
KStyle( KStyleFlags flags = KStyle::Default,
KStyleScrollBarType sbtype = KStyle::WindowsStyleScrollBar );
/**
* Destructs the KStyle object.
*/
~KStyle();
/**
* Returns the default widget style depending on color depth.
*/
static QString defaultStyle();
/**
* Modifies the scrollbar type used by the style.
*
* This function is only provided for convenience. It allows
* you to make a late decision about what scrollbar type to use for the
* style after performing some processing in your style's constructor.
* In most situations however, setting the scrollbar type via the KStyle
* constructor should suffice.
* @param sbtype the scroll bar type
* @see KStyle::KStyleScrollBarType
*/
void setScrollBarType(KStyleScrollBarType sbtype);
/**
* Returns the KStyle flags used to initialize the style.
*
* This is used solely for the kcmstyle module, and hence is internal.
*/
KStyleFlags styleFlags() const;
// ---------------------------------------------------------------------------
/**
* This virtual function defines the pixmap used to blend between the popup
* menu and the background to create different menu transparency effects.
* For example, you can fill the pixmap "pix" with a gradient based on the
* popup's colorGroup, a texture, or some other fancy painting routine.
* KStyle will then internally blend this pixmap with a snapshot of the
* background behind the popupMenu to create the illusion of transparency.
*
* This virtual is never called if XRender/Software blending is disabled by
* the user in KDE's style control module.
*/
virtual void renderMenuBlendPixmap( KPixmap& pix, const QColorGroup& cg,
const QPopupMenu* popup ) const;
/**
* KStyle Primitive Elements:
*
* The KStyle class extends the Qt's Style API by providing certain
* simplifications for parts of QStyle. To do this, the KStylePrimitive
* elements were defined, which are very similar to Qt's PrimitiveElement.
*
* The first three Handle primitives simplify and extend PE_DockWindowHandle,
* so do not reimplement PE_DockWindowHandle if you want the KStyle handle
* simplifications to be operable. Similarly do not reimplement CC_Slider,
* SC_SliderGroove and SC_SliderHandle when using the KStyle slider
* primitives. KStyle automatically double-buffers slider painting
* when they are drawn via these KStyle primitives to avoid flicker.
*
* @li KPE_DockWindowHandle - This primitive is already implemented in KStyle,
* and paints a bevelled rect with the DockWindow caption text. Re-implement
* this primitive to perform other more fancy effects when drawing the dock window
* handle.
*
* @li KPE_ToolBarHandle - This primitive must be reimplemented. It currently
* only paints a filled rectangle as default behavior. This primitive is used
* to render QToolBar handles.
*
* @li KPE_GeneralHandle - This primitive must be reimplemented. It is used
* to render general handles that are not part of a QToolBar or QDockWindow, such
* as the applet handles used in Kicker. The default implementation paints a filled
* rect of arbitrary color.
*
* @li KPE_SliderGroove - This primitive must be reimplemented. It is used to
* paint the slider groove. The default implementation paints a filled rect of
* arbitrary color.
*
* @li KPE_SliderHandle - This primitive must be reimplemented. It is used to
* paint the slider handle. The default implementation paints a filled rect of
* arbitrary color.
*
* @li KPE_ListViewExpander - This primitive is already implemented in KStyle. It
* is used to draw the Expand/Collapse element in QListViews. To indicate the
* expanded state, the style flags are set to Style_Off, while Style_On implies collapsed.
*
* @li KPE_ListViewBranch - This primitive is already implemented in KStyle. It is
* used to draw the ListView branches where necessary.
*/
enum KStylePrimitive {
KPE_DockWindowHandle,
KPE_ToolBarHandle,
KPE_GeneralHandle,
KPE_SliderGroove,
KPE_SliderHandle,
KPE_ListViewExpander,
KPE_ListViewBranch
};
/**
* This function is identical to Qt's QStyle::drawPrimitive(), except that
* it adds one further parameter, 'widget', that can be used to determine
* the widget state of the KStylePrimitive in question.
*
* @see KStyle::KStylePrimitive
* @see QStyle::drawPrimitive
* @see QStyle::drawComplexControl
*/
virtual void drawKStylePrimitive( KStylePrimitive kpe,
QPainter* p,
const QWidget* widget,
const QRect &r,
const QColorGroup &cg,
SFlags flags = Style_Default,
const QStyleOption& = QStyleOption::Default ) const;
enum KStylePixelMetric {
KPM_MenuItemSeparatorHeight = 0x00000001,
KPM_MenuItemHMargin = 0x00000002,
KPM_MenuItemVMargin = 0x00000004,
KPM_MenuItemHFrame = 0x00000008,
KPM_MenuItemVFrame = 0x00000010,
KPM_MenuItemCheckMarkHMargin = 0x00000020,
KPM_MenuItemArrowHMargin = 0x00000040,
KPM_MenuItemTabSpacing = 0x00000080,
KPM_ListViewBranchThickness = 0x00000100
};
int kPixelMetric( KStylePixelMetric kpm, const QWidget* widget = 0 ) const;
// ---------------------------------------------------------------------------
void polish( QWidget* widget );
void unPolish( QWidget* widget );
void polishPopupMenu( QPopupMenu* );
void drawPrimitive( PrimitiveElement pe,
QPainter* p,
const QRect &r,
const QColorGroup &cg,
SFlags flags = Style_Default,
const QStyleOption& = QStyleOption::Default ) const;
void drawControl( ControlElement element,
QPainter* p,
const QWidget* widget,
const QRect &r,
const QColorGroup &cg,
SFlags flags = Style_Default,
const QStyleOption& = QStyleOption::Default ) const;
void drawComplexControl( ComplexControl control,
QPainter *p,
const QWidget* widget,
const QRect &r,
const QColorGroup &cg,
SFlags flags = Style_Default,
SCFlags controls = SC_All,
SCFlags active = SC_None,
const QStyleOption& = QStyleOption::Default ) const;
SubControl querySubControl( ComplexControl control,
const QWidget* widget,
const QPoint &pos,
const QStyleOption& = QStyleOption::Default ) const;
QRect querySubControlMetrics( ComplexControl control,
const QWidget* widget,
SubControl sc,
const QStyleOption& = QStyleOption::Default ) const;
int pixelMetric( PixelMetric m,
const QWidget* widget = 0 ) const;
QRect subRect( SubRect r,
const QWidget* widget ) const;
QPixmap stylePixmap( StylePixmap stylepixmap,
const QWidget* widget = 0,
const QStyleOption& = QStyleOption::Default ) const;
int styleHint( StyleHint sh,
const QWidget* w = 0,
const QStyleOption &opt = QStyleOption::Default,
QStyleHintReturn* shr = 0 ) const;
protected:
bool eventFilter( QObject* object, QEvent* event );
private:
// Disable copy constructor and = operator
KStyle( const KStyle & );
KStyle& operator=( const KStyle & );
protected:
virtual void virtual_hook( int id, void* data );
private:
KStylePrivate *d;
};
// vim: set noet ts=4 sw=4:
#endif
| [
"project.ufa@9bbcd52c-0291-11de-9d1a-b59b2e1864b6"
] | [
[
[
1,
344
]
]
] |
aa638c96e4e5e3a181ea68591a72be6405bf428b | 00b979f12f13ace4e98e75a9528033636dab021d | /branches/ziis/src/mod/ssl/src/conimpl.cc | 85757453d42056d8f8dc1ca8d20199be31733618 | [] | no_license | BackupTheBerlios/ziahttpd-svn | 812e4278555fdd346b643534d175546bef32afd5 | 8c0b930d3f4a86f0622987776b5220564e89b7c8 | refs/heads/master | 2016-09-09T20:39:16.760554 | 2006-04-13T08:44:28 | 2006-04-13T08:44:28 | 40,819,288 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,897 | cc | //
// conimpl.cc for in
//
// Made by texane
// Login <[email protected]>
//
// Started on Sat Apr 01 11:14:10 2006 texane
// Last update Mon Apr 03 19:05:43 2006 texane
//
#include "include/modimpl.hh"
using namespace std;
static void reset_ssl_data(mod_ssl::_ssl_data_t* p_ssl_data)
{
p_ssl_data->m_bio = 0;
p_ssl_data->m_ssl = 0;
}
void print_ssl_error()
{
cout << ERR_error_string(ERR_get_error(), NULL) << endl;
}
// implement IConnection
short mod_ssl::GetPort()
{
return m_port;
}
const char* mod_ssl::GetHost()
{
return m_host.c_str();
}
void* mod_ssl::Accept(SOCKET id_socket)
{
mod_ssl::_ssl_data_t* p_ssl_data;
int val_accept;
// checks
if (m_ssl_context == 0)
return 0;
p_ssl_data = new mod_ssl::_ssl_data_t;
reset_ssl_data(p_ssl_data);
p_ssl_data->m_bio = BIO_new_socket((int)id_socket, BIO_NOCLOSE);
if (p_ssl_data->m_bio == 0)
return 0;
// create the ssession and set the bio
p_ssl_data->m_ssl = SSL_new(m_ssl_context);
if (p_ssl_data->m_ssl == 0)
return 0;
SSL_set_bio(p_ssl_data->m_ssl, p_ssl_data->m_bio, p_ssl_data->m_bio);
// accept the connection(handshake)
val_accept = SSL_accept(p_ssl_data->m_ssl);
if (val_accept <= 0)
{
print_ssl_error();
BIO_free_all(p_ssl_data->m_bio);
return 0;
}
return (void*)p_ssl_data;
}
int mod_ssl::Recv(SOCKET h_sock, void* p_data, char* p_buf, int ln_buf)
{
int nr_read;
mod_ssl::_ssl_data_t* p_ssl_data;
p_ssl_data = (mod_ssl::_ssl_data_t*)p_data;
if (p_ssl_data == 0)
return -1;
// SSL_set_accept_state(p_ssl_data->m_ssl);
bio_read_again:
nr_read = SSL_read(p_ssl_data->m_ssl, p_buf, ln_buf);
if (nr_read <= 0)
{
if (BIO_should_retry(p_ssl_data->m_bio))
goto bio_read_again;
return -1;
}
return nr_read;
}
int mod_ssl::Send(SOCKET h_sock, void* p_data, const char* p_buf, int ln_buf)
{
int nr_sent;
mod_ssl::_ssl_data_t* p_ssl_data = (mod_ssl::_ssl_data_t*)p_data;
if (p_data == 0)
return -1;
// SSL_set_accept_state(p_ssl_data->m_ssl);
bio_send_again:
nr_sent = SSL_write(p_ssl_data->m_ssl, p_buf, ln_buf);
if (nr_sent <= 0)
{
if (BIO_should_retry(p_ssl_data->m_bio))
goto bio_send_again;
return -1;
}
return nr_sent;
}
void mod_ssl::Close(SOCKET id_socket, void* p_data)
{
int val_shutdown;
_ssl_data_t* p_ssl_data = (_ssl_data_t*)p_data;
if (p_data == 0)
return ;
// send tcp_fin or get client notify
val_shutdown = SSL_shutdown(p_ssl_data->m_ssl);
if (val_shutdown == 0)
{
shutdown(id_socket, 1);
val_shutdown = SSL_shutdown(p_ssl_data->m_ssl);
}
// release internals
if (p_ssl_data->m_bio)
BIO_free_all(p_ssl_data->m_bio);
delete p_ssl_data;
}
| [
"texane@754ce95b-6e01-0410-81d0-8774ba66fe44"
] | [
[
[
1,
141
]
]
] |
26feef1b7570d6c1ef053290ae95da75b3a7e492 | cd387cba6088f351af4869c02b2cabbb678be6ae | /lib/geometry/geometries/linestring.hpp | cba4be4bd207a4ddb9cf4b51e9e986b2f393b62b | [
"BSL-1.0"
] | permissive | pedromartins/mew-dev | e8a9cd10f73fbc9c0c7b5bacddd0e7453edd097e | e6384775b00f76ab13eb046509da21d7f395909b | refs/heads/master | 2016-09-06T14:57:00.937033 | 2009-04-13T15:16:15 | 2009-04-13T15:16:15 | 32,332,332 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,782 | hpp | // Geometry Library
//
// Copyright Barend Gehrels, Geodan Holding B.V. Amsterdam, the Netherlands.
// Copyright Bruno Lalande 2008
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef _GEOMETRY_LINESTRING_HPP
#define _GEOMETRY_LINESTRING_HPP
#include <vector>
#include <boost/concept/assert.hpp>
#include <geometry/concepts/point_concept.hpp>
#include <geometry/geometries/geometry_traits.hpp>
namespace geometry
{
/*!
\brief A linestring (named so by OGC) is a collection (default a vector) of points.
\ingroup Geometry
\par Template parameters:
- \a P point type
- \a V optional container type, for example std::vector, std::list, std::deque
- \a A optional container-allocator-type
(see http://accu.org/index.php/journals/427#ftn.d0e249 )
\par Concepts:
All algorithms work on iterator pairs, based on a container with point types fulfilling
the point concepts. They will take linestring.begin(), linestring.end()
but they will also take std::vector begin()/end(), or other containers.
*/
template<typename P,
template<typename,typename> class V = std::vector,
template<typename> class A = std::allocator>
class linestring : public V<P, A<P> >, public geometry_traits<P>
{
BOOST_CONCEPT_ASSERT((Point<P>));
public :
// Default constructor
linestring()
{}
// Construct from vector
linestring(std::vector<P>& v)
{
for (typename std::vector<P>::const_iterator it = v.begin(); it != v.end(); it++)
{
this->push_back(*it);
}
}
};
} // namespace geometry
#endif //_GEOMETRY_LINESTRING_HPP
| [
"fushunpoon@1fd432d8-e285-11dd-b2d9-215335d0b316"
] | [
[
[
1,
63
]
]
] |
e6183446404f8e9a7eb0d7845e967eaadc7b64a9 | 584d088c264ac58050ed0757b08d032b6c7fc83b | /oldGUI/Gui_Ani.cpp | 102995d76c19797ea0345d417e20a130b29f9051 | [] | no_license | littlewingsoft/lunaproject | a843ca37c04bdc4e1e4e706381043def1789ab39 | 9102a39deaad74b2d73ee0ec3354f37f6f85702f | refs/heads/master | 2020-05-30T15:21:20.515967 | 2011-02-04T18:41:43 | 2011-02-04T18:41:43 | 32,302,109 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 2,200 | cpp |
#include "stdafx.h"
#include "gui_ani.h"
////////////////////////////////////////////////
//
// GUI_ANI 관련 클래스
//
////////////////////////////////////////////////
CGUI_Ani::CGUI_Ani()
{
m_Gui_ClsID= GUI_ANI;
m_LastTime = 0;
m_CurrentFrame = 0;
m_bAni = false;
}
CGUI_Ani::CGUI_Ani(int x, int y, TCHAR* fName )
{
m_Gui_ClsID=GUI_ANI;
g_D3D.LoadAni( fName, m_Img );
if( m_Img.TexID == -1 )
{
#ifdef _HTMLLOG
g_HtmlLog.LogError( _T("%s 를 찾지 못했습니다."), fName );
#endif
assert( m_Img.TexID != -1 );
}
SetBoundRect( x,y, x + m_Img.sprInfo.nWidth , y + m_Img.sprInfo.nHeight); //m_Img.sprInfo.nFrame *
SetDestRect( x,y,x + m_Img.sprInfo.nWidth , y + m_Img.sprInfo.nHeight); //m_Img.sprInfo.nFrame *
SetSrcRect(0,0,m_Img.sprInfo.nWidth, m_Img.sprInfo.nHeight);
m_LastTime = 0;
m_bAni = false;
m_CurrentFrame = 0;
m_Clr = 0xffffffff;
}
void CGUI_Ani::SetAni(bool bAni)
{
m_bAni = bAni;
}
void CGUI_Ani::SetFrame( int Frame )
{
m_CurrentFrame = Frame;
m_CurrentFrame %= m_Img.sprInfo.nFrame;
}
void CGUI_Ani::Process()
{
// 자식을 돌리자
// Process_Child();
}
void CGUI_Ani::Render()
{
if( GETA(m_Clr) == 0x00 ) return;
if( m_bAni )
{
if( timeGetTime() - m_LastTime > m_Img.sprInfo.mspf )
{
m_LastTime = timeGetTime();
m_CurrentFrame++;
if( m_CurrentFrame >= m_Img.sprInfo.nFrame )
m_CurrentFrame = 0;
}
}
RECT srcRect= {
(m_CurrentFrame * m_Img.sprInfo.nWidth)+m_SrcRect.left,
m_SrcRect.top,
(m_CurrentFrame * m_Img.sprInfo.nWidth)+m_SrcRect.right,// (m_CurrentFrame * m_Img.sprInfo.nWidth)+m_Img.sprInfo.nWidth,
m_SrcRect.bottom
};
if( (srcRect.right - srcRect.left) != 0 )
{
if( (srcRect.bottom - srcRect.top) != 0 )
{
RECT tmp={m_DestRect.left,m_DestRect.top, m_DestRect.right,m_DestRect.bottom };
g_D3D.BltSprite( m_Layer, m_Img.TexID, &srcRect, tmp,m_Clr,D3D_ALPHASTATE );//D3D_NORMALSTATE
}
}
// 자식을 그리자
//Render_Child();
}
bool CGUI_Ani::ProcMessage(GUIMSG& pMsg)
{
//if( this->ProcMessage_Child( pMsg ) == true )
// return true;
return false;
}
| [
"jungmoona@2e9c511a-93cf-11dd-bb0a-adccfa6872b9"
] | [
[
[
1,
95
]
]
] |
e3f14d5b3357d7a8eeb40cc993a97019d9f0f047 | e192cc5a9f9dc057cc6e84c755f69f73f6cb1a8b | /LineStripNode.cpp | 4c459c6a4b791943fd94b1a162d4f25b6d852830 | [] | no_license | jnv/fit-swoopers | 2177f91a190fa6c1dcd9cb7a816f1d07711ef9c4 | 4cf2fd2c57ba4c5809524a12d510a56cc614cc23 | refs/heads/master | 2021-01-12T06:02:33.360673 | 2011-12-06T17:59:24 | 2018-12-13T10:14:12 | 77,281,895 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,202 | cpp |
#include "LineStripNode.h"
GLuint LineStripNode::m_vertexBufferObject = 0;
GLuint LineStripNode::m_program = 0;
GLint LineStripNode::m_PVMmatrixLoc = -1;
GLint LineStripNode::m_posLoc = -1;
GLint LineStripNode::m_colLoc = -1;
static const float vertexData[] = {
-0.5, 0, 0.5,
2.75, 0, -0.25,
0.25, 0, -2.75,
3.5, 0, -3.5,
};
/// Init shaders
LineStripNode::LineStripNode(const char * name, SceneNode * parent) :
SceneNode(name, parent)
{
if(m_program == 0)
{
std::vector<GLuint> shaderList;
// Push vertex shader and fragment shader
shaderList.push_back(CreateShader(GL_VERTEX_SHADER, "LineStripNode.vert"));
shaderList.push_back(CreateShader(GL_FRAGMENT_SHADER, "LineStripNode.frag"));
// Create the program with two shaders
m_program = CreateProgram(shaderList);
m_PVMmatrixLoc = glGetUniformLocation(m_program, "PVMmatrix");
m_posLoc = glGetAttribLocation(m_program, "position");
}
if(m_vertexBufferObject == 0)
{
glGenBuffers(1, &m_vertexBufferObject);
glBindBuffer(GL_ARRAY_BUFFER, m_vertexBufferObject);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
}
/// Draw LINE_STRIP
void LineStripNode::draw(SceneParams * scene_params)
{
// inherited draw - draws all children
SceneNode::draw(scene_params);
glm::mat4 matrix = scene_params->projection_mat * scene_params->view_mat * globalMatrix();
glUseProgram(m_program);
glUniformMatrix4fv(m_PVMmatrixLoc, 1, GL_FALSE, glm::value_ptr(matrix));
glBindBuffer(GL_ARRAY_BUFFER, m_vertexBufferObject);
glEnableVertexAttribArray(m_posLoc);
// glEnableVertexAttribArray(m_colLoc);
// vertices of triangles
glVertexAttribPointer(m_posLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
// 8 = 4 + 4 floats per vertex - color
// glVertexAttribPointer(m_colLoc, 4, GL_FLOAT, GL_FALSE, 0, (void*) (4 * sizeof(vertexData) / (8)));
glDrawArrays(GL_LINE_STRIP, 0, sizeof(vertexData) / (3 * sizeof(float))); // 8 = 4+4 floats per vertex
glDisableVertexAttribArray(m_posLoc);
// glDisableVertexAttribArray(m_colLoc);
}
| [
"[email protected]"
] | [
[
[
1,
66
]
]
] |
363872c39833ae37d1167850828fb388cbd3e242 | 2f1f7d0711e054a96f10e849bdac5efcb45c4f39 | /src/main.cpp | 36bd7d6280b144a598b95bb09b3473166a59f765 | [] | no_license | skyformat99/lbtt | ef25d0054ec539d6d77e25e5b0ce8febc4fdc0e8 | 6cf6418a639cc339615c3ecc6e78e1939a9cc1cb | refs/heads/master | 2021-05-27T18:13:03.711188 | 2009-09-12T01:17:41 | 2009-09-12T01:17:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,998 | cpp | #include "tracker.h"
#include "acceptor.h"
#include "thread.h"
#include "worker.h"
#include <v8.h>
#include <iostream>
#include <ev.c>
#include <signal.h>
#include <vector>
#include <getopt.h>
using namespace std;
using namespace v8;
vector<Worker *> workers;
vector<thread<Worker> *> tworkers;
vector<Worker *>::iterator workerit;
void newClient(int cfd) {
Worker *w = *workerit;
w->newClient(cfd);
workerit++;
if(workerit == workers.end())
workerit = workers.begin();
}
bool running;
void stopme(int s){
running = false;
}
int printHelp(){
cout << "-h\thelp" << endl;
cout << "-t\tthreads [def. 5]" << endl;
cout << "-p\tport [def. 8080]" << endl;
cout << "-b\tip [def. 0.0.0.0]" << endl;
cout << "-s\tjavascript file [def. lbtt.js]" << endl;
cout << "-i\tannounce interval [def. 900]" << endl;
cout << "-e\texpire interval [def. 1800]" << endl;
return 0;
}
int main(int argc, char **argv) {
int nthreads = 5;
int socket_timeout = 5;
int port = 8080;
int interval = 900;
int expire = (interval * 2);
string script("lbtt.js");
string bindip("0.0.0.0");
char opt;
while((opt = getopt(argc, argv, "i:e:ht:p:b:s:")) != -1) {
switch(opt){
case 'i':
interval = atoi(optarg);
break;
case 'e':
expire = atoi(optarg);
break;
case 'h':
return printHelp();
case 't':
nthreads = atoi(optarg);
break;
case 'p':
port = atoi(optarg);
break;
case 'b':
bindip = optarg;
break;
case 's':
script = optarg;
break;
}
}
v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
TorrentTracker tracker(script);
tracker.interval = interval;
tracker.expireTimeout = expire * 1000;
//bbye stdin
close(0);
Acceptor binder(bindip.c_str(), port);
binder.setCallback(newClient);
thread<Acceptor> binderthread(binder);
Worker *w;
for (int i = 0; i < nthreads; i++) {
w = new Worker(tracker);
w->timeout = socket_timeout;
thread<Worker> *twork = new thread<Worker>(*w);
workers.push_back(w);
}
workerit = workers.begin();
signal(SIGPIPE, SIG_IGN);
signal(SIGINT, stopme);
running = true;
cout << "started" << endl;
int sleepcount = 0;
while (running) {
if(sleepcount >= 30){
tracker.cleanup();
sleepcount = 0;
}
sleep(1);
sleepcount++;
}
binder.stop();
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
121
]
]
] |
b39ee1a8866e096b2f8268fa94d47e24e7c5e393 | 04fec4cbb69789d44717aace6c8c5490f2cdfa47 | /include/wx/event.h | 00f67158a57ff73fefcd294f64ee90cabfadc151 | [] | 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 | 117,624 | h | /////////////////////////////////////////////////////////////////////////////
// Name: wx/event.h
// Purpose: Event classes
// Author: Julian Smart
// Modified by:
// Created: 01/02/97
// RCS-ID: $Id: event.h 49563 2007-10-31 20:46:21Z VZ $
// Copyright: (c) wxWidgets team
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifndef _WX_EVENT_H__
#define _WX_EVENT_H__
#include "wx/defs.h"
#include "wx/cpp.h"
#include "wx/object.h"
#include "wx/clntdata.h"
#if wxUSE_GUI
#include "wx/gdicmn.h"
#include "wx/cursor.h"
#endif
#include "wx/thread.h"
#include "wx/dynarray.h"
// ----------------------------------------------------------------------------
// forward declarations
// ----------------------------------------------------------------------------
class WXDLLIMPEXP_FWD_BASE wxList;
#if wxUSE_GUI
class WXDLLIMPEXP_FWD_CORE wxDC;
class WXDLLIMPEXP_FWD_CORE wxMenu;
class WXDLLIMPEXP_FWD_CORE wxWindow;
class WXDLLIMPEXP_FWD_CORE wxWindowBase;
#endif // wxUSE_GUI
class WXDLLIMPEXP_BASE wxEvtHandler;
// ----------------------------------------------------------------------------
// Event types
// ----------------------------------------------------------------------------
typedef int wxEventType;
// this is used to make the event table entry type safe, so that for an event
// handler only a function with proper parameter list can be given.
#define wxStaticCastEvent(type, val) wx_static_cast(type, val)
// in previous versions of wxWidgets the event types used to be constants
// which created difficulties with custom/user event types definition
//
// starting from wxWidgets 2.4 the event types are now dynamically assigned
// using wxNewEventType() which solves this problem, however at price of
// several incompatibilities:
//
// a) event table macros declaration changed, it now uses wxEventTableEntry
// ctor instead of initialisation from an agregate - the macro
// DECLARE_EVENT_TABLE_ENTRY may be used to write code which can compile
// with all versions of wxWidgets
//
// b) event types can't be used as switch() cases as they're not really
// constant any more - there is no magic solution here, you just have to
// change the switch()es to if()s
//
// if these are real problems for you, define WXWIN_COMPATIBILITY_EVENT_TYPES
// as 1 to get 100% old behaviour, however you won't be able to use the
// libraries using the new dynamic event type allocation in such case, so avoid
// it if possible.
#ifndef WXWIN_COMPATIBILITY_EVENT_TYPES
#define WXWIN_COMPATIBILITY_EVENT_TYPES 0
#endif
#if WXWIN_COMPATIBILITY_EVENT_TYPES
#define DECLARE_EVENT_TABLE_ENTRY(type, winid, idLast, fn, obj) \
{ type, winid, idLast, fn, obj }
#define BEGIN_DECLARE_EVENT_TYPES() enum {
#define END_DECLARE_EVENT_TYPES() };
#define DECLARE_EVENT_TYPE(name, value) name = wxEVT_FIRST + value,
#define DECLARE_LOCAL_EVENT_TYPE(name, value) name = wxEVT_USER_FIRST + value,
#define DECLARE_EXPORTED_EVENT_TYPE(expdecl, name, value) \
DECLARE_LOCAL_EVENT_TYPE(name, value)
#define DEFINE_EVENT_TYPE(name)
#define DEFINE_LOCAL_EVENT_TYPE(name)
#else // !WXWIN_COMPATIBILITY_EVENT_TYPES
#define DECLARE_EVENT_TABLE_ENTRY(type, winid, idLast, fn, obj) \
wxEventTableEntry(type, winid, idLast, fn, obj)
#define BEGIN_DECLARE_EVENT_TYPES()
#define END_DECLARE_EVENT_TYPES()
#define DECLARE_EXPORTED_EVENT_TYPE(expdecl, name, value) \
extern expdecl const wxEventType name;
#define DECLARE_EVENT_TYPE(name, value) \
DECLARE_EXPORTED_EVENT_TYPE(WXDLLIMPEXP_CORE, name, value)
#define DECLARE_LOCAL_EVENT_TYPE(name, value) \
DECLARE_EXPORTED_EVENT_TYPE(wxEMPTY_PARAMETER_VALUE, name, value)
#define DEFINE_EVENT_TYPE(name) const wxEventType name = wxNewEventType();
#define DEFINE_LOCAL_EVENT_TYPE(name) DEFINE_EVENT_TYPE(name)
// generate a new unique event type
extern WXDLLIMPEXP_BASE wxEventType wxNewEventType();
#endif // WXWIN_COMPATIBILITY_EVENT_TYPES/!WXWIN_COMPATIBILITY_EVENT_TYPES
BEGIN_DECLARE_EVENT_TYPES()
#if WXWIN_COMPATIBILITY_EVENT_TYPES
wxEVT_NULL = 0,
wxEVT_FIRST = 10000,
wxEVT_USER_FIRST = wxEVT_FIRST + 2000,
#else // !WXWIN_COMPATIBILITY_EVENT_TYPES
// it is important to still have these as constants to avoid
// initialization order related problems
DECLARE_EXPORTED_EVENT_TYPE(WXDLLIMPEXP_BASE, wxEVT_NULL, 0)
DECLARE_EXPORTED_EVENT_TYPE(WXDLLIMPEXP_BASE, wxEVT_FIRST, 10000)
DECLARE_EXPORTED_EVENT_TYPE(WXDLLIMPEXP_BASE, wxEVT_USER_FIRST, wxEVT_FIRST + 2000)
#endif // WXWIN_COMPATIBILITY_EVENT_TYPES/!WXWIN_COMPATIBILITY_EVENT_TYPES
DECLARE_EVENT_TYPE(wxEVT_COMMAND_BUTTON_CLICKED, 1)
DECLARE_EVENT_TYPE(wxEVT_COMMAND_CHECKBOX_CLICKED, 2)
DECLARE_EVENT_TYPE(wxEVT_COMMAND_CHOICE_SELECTED, 3)
DECLARE_EVENT_TYPE(wxEVT_COMMAND_LISTBOX_SELECTED, 4)
DECLARE_EVENT_TYPE(wxEVT_COMMAND_LISTBOX_DOUBLECLICKED, 5)
DECLARE_EVENT_TYPE(wxEVT_COMMAND_CHECKLISTBOX_TOGGLED, 6)
// now they are in wx/textctrl.h
#if WXWIN_COMPATIBILITY_EVENT_TYPES
DECLARE_EVENT_TYPE(wxEVT_COMMAND_TEXT_UPDATED, 7)
DECLARE_EVENT_TYPE(wxEVT_COMMAND_TEXT_ENTER, 8)
DECLARE_EVENT_TYPE(wxEVT_COMMAND_TEXT_URL, 13)
DECLARE_EVENT_TYPE(wxEVT_COMMAND_TEXT_MAXLEN, 14)
#endif // WXWIN_COMPATIBILITY_EVENT_TYPES
DECLARE_EVENT_TYPE(wxEVT_COMMAND_MENU_SELECTED, 9)
DECLARE_EVENT_TYPE(wxEVT_COMMAND_SLIDER_UPDATED, 10)
DECLARE_EVENT_TYPE(wxEVT_COMMAND_RADIOBOX_SELECTED, 11)
DECLARE_EVENT_TYPE(wxEVT_COMMAND_RADIOBUTTON_SELECTED, 12)
// wxEVT_COMMAND_SCROLLBAR_UPDATED is now obsolete since we use
// wxEVT_SCROLL... events
DECLARE_EVENT_TYPE(wxEVT_COMMAND_SCROLLBAR_UPDATED, 13)
DECLARE_EVENT_TYPE(wxEVT_COMMAND_VLBOX_SELECTED, 14)
DECLARE_EVENT_TYPE(wxEVT_COMMAND_COMBOBOX_SELECTED, 15)
DECLARE_EVENT_TYPE(wxEVT_COMMAND_TOOL_RCLICKED, 16)
DECLARE_EVENT_TYPE(wxEVT_COMMAND_TOOL_ENTER, 17)
DECLARE_EVENT_TYPE(wxEVT_COMMAND_SPINCTRL_UPDATED, 18)
// Sockets and timers send events, too
DECLARE_EXPORTED_EVENT_TYPE(WXDLLIMPEXP_BASE, wxEVT_SOCKET, 50)
DECLARE_EVENT_TYPE(wxEVT_TIMER , 80)
// Mouse event types
DECLARE_EVENT_TYPE(wxEVT_LEFT_DOWN, 100)
DECLARE_EVENT_TYPE(wxEVT_LEFT_UP, 101)
DECLARE_EVENT_TYPE(wxEVT_MIDDLE_DOWN, 102)
DECLARE_EVENT_TYPE(wxEVT_MIDDLE_UP, 103)
DECLARE_EVENT_TYPE(wxEVT_RIGHT_DOWN, 104)
DECLARE_EVENT_TYPE(wxEVT_RIGHT_UP, 105)
DECLARE_EVENT_TYPE(wxEVT_MOTION, 106)
DECLARE_EVENT_TYPE(wxEVT_ENTER_WINDOW, 107)
DECLARE_EVENT_TYPE(wxEVT_LEAVE_WINDOW, 108)
DECLARE_EVENT_TYPE(wxEVT_LEFT_DCLICK, 109)
DECLARE_EVENT_TYPE(wxEVT_MIDDLE_DCLICK, 110)
DECLARE_EVENT_TYPE(wxEVT_RIGHT_DCLICK, 111)
DECLARE_EVENT_TYPE(wxEVT_SET_FOCUS, 112)
DECLARE_EVENT_TYPE(wxEVT_KILL_FOCUS, 113)
DECLARE_EVENT_TYPE(wxEVT_CHILD_FOCUS, 114)
DECLARE_EVENT_TYPE(wxEVT_MOUSEWHEEL, 115)
// Non-client mouse events
DECLARE_EVENT_TYPE(wxEVT_NC_LEFT_DOWN, 200)
DECLARE_EVENT_TYPE(wxEVT_NC_LEFT_UP, 201)
DECLARE_EVENT_TYPE(wxEVT_NC_MIDDLE_DOWN, 202)
DECLARE_EVENT_TYPE(wxEVT_NC_MIDDLE_UP, 203)
DECLARE_EVENT_TYPE(wxEVT_NC_RIGHT_DOWN, 204)
DECLARE_EVENT_TYPE(wxEVT_NC_RIGHT_UP, 205)
DECLARE_EVENT_TYPE(wxEVT_NC_MOTION, 206)
DECLARE_EVENT_TYPE(wxEVT_NC_ENTER_WINDOW, 207)
DECLARE_EVENT_TYPE(wxEVT_NC_LEAVE_WINDOW, 208)
DECLARE_EVENT_TYPE(wxEVT_NC_LEFT_DCLICK, 209)
DECLARE_EVENT_TYPE(wxEVT_NC_MIDDLE_DCLICK, 210)
DECLARE_EVENT_TYPE(wxEVT_NC_RIGHT_DCLICK, 211)
// Character input event type
DECLARE_EVENT_TYPE(wxEVT_CHAR, 212)
DECLARE_EVENT_TYPE(wxEVT_CHAR_HOOK, 213)
DECLARE_EVENT_TYPE(wxEVT_NAVIGATION_KEY, 214)
DECLARE_EVENT_TYPE(wxEVT_KEY_DOWN, 215)
DECLARE_EVENT_TYPE(wxEVT_KEY_UP, 216)
#if wxUSE_HOTKEY
DECLARE_EVENT_TYPE(wxEVT_HOTKEY, 217)
#endif
// Set cursor event
DECLARE_EVENT_TYPE(wxEVT_SET_CURSOR, 230)
// wxScrollBar and wxSlider event identifiers
DECLARE_EVENT_TYPE(wxEVT_SCROLL_TOP, 300)
DECLARE_EVENT_TYPE(wxEVT_SCROLL_BOTTOM, 301)
DECLARE_EVENT_TYPE(wxEVT_SCROLL_LINEUP, 302)
DECLARE_EVENT_TYPE(wxEVT_SCROLL_LINEDOWN, 303)
DECLARE_EVENT_TYPE(wxEVT_SCROLL_PAGEUP, 304)
DECLARE_EVENT_TYPE(wxEVT_SCROLL_PAGEDOWN, 305)
DECLARE_EVENT_TYPE(wxEVT_SCROLL_THUMBTRACK, 306)
DECLARE_EVENT_TYPE(wxEVT_SCROLL_THUMBRELEASE, 307)
DECLARE_EVENT_TYPE(wxEVT_SCROLL_CHANGED, 308)
// Scroll events from wxWindow
DECLARE_EVENT_TYPE(wxEVT_SCROLLWIN_TOP, 320)
DECLARE_EVENT_TYPE(wxEVT_SCROLLWIN_BOTTOM, 321)
DECLARE_EVENT_TYPE(wxEVT_SCROLLWIN_LINEUP, 322)
DECLARE_EVENT_TYPE(wxEVT_SCROLLWIN_LINEDOWN, 323)
DECLARE_EVENT_TYPE(wxEVT_SCROLLWIN_PAGEUP, 324)
DECLARE_EVENT_TYPE(wxEVT_SCROLLWIN_PAGEDOWN, 325)
DECLARE_EVENT_TYPE(wxEVT_SCROLLWIN_THUMBTRACK, 326)
DECLARE_EVENT_TYPE(wxEVT_SCROLLWIN_THUMBRELEASE, 327)
// System events
DECLARE_EVENT_TYPE(wxEVT_SIZE, 400)
DECLARE_EVENT_TYPE(wxEVT_MOVE, 401)
DECLARE_EVENT_TYPE(wxEVT_CLOSE_WINDOW, 402)
DECLARE_EVENT_TYPE(wxEVT_END_SESSION, 403)
DECLARE_EVENT_TYPE(wxEVT_QUERY_END_SESSION, 404)
DECLARE_EVENT_TYPE(wxEVT_ACTIVATE_APP, 405)
// 406..408 are power events
DECLARE_EVENT_TYPE(wxEVT_ACTIVATE, 409)
DECLARE_EVENT_TYPE(wxEVT_CREATE, 410)
DECLARE_EVENT_TYPE(wxEVT_DESTROY, 411)
DECLARE_EVENT_TYPE(wxEVT_SHOW, 412)
DECLARE_EVENT_TYPE(wxEVT_ICONIZE, 413)
DECLARE_EVENT_TYPE(wxEVT_MAXIMIZE, 414)
DECLARE_EVENT_TYPE(wxEVT_MOUSE_CAPTURE_CHANGED, 415)
DECLARE_EVENT_TYPE(wxEVT_MOUSE_CAPTURE_LOST, 416)
DECLARE_EVENT_TYPE(wxEVT_PAINT, 417)
DECLARE_EVENT_TYPE(wxEVT_ERASE_BACKGROUND, 418)
DECLARE_EVENT_TYPE(wxEVT_NC_PAINT, 419)
DECLARE_EVENT_TYPE(wxEVT_PAINT_ICON, 420)
DECLARE_EVENT_TYPE(wxEVT_MENU_OPEN, 421)
DECLARE_EVENT_TYPE(wxEVT_MENU_CLOSE, 422)
DECLARE_EVENT_TYPE(wxEVT_MENU_HIGHLIGHT, 423)
DECLARE_EVENT_TYPE(wxEVT_CONTEXT_MENU, 424)
DECLARE_EVENT_TYPE(wxEVT_SYS_COLOUR_CHANGED, 425)
DECLARE_EVENT_TYPE(wxEVT_DISPLAY_CHANGED, 426)
DECLARE_EVENT_TYPE(wxEVT_SETTING_CHANGED, 427)
DECLARE_EVENT_TYPE(wxEVT_QUERY_NEW_PALETTE, 428)
DECLARE_EVENT_TYPE(wxEVT_PALETTE_CHANGED, 429)
DECLARE_EVENT_TYPE(wxEVT_JOY_BUTTON_DOWN, 430)
DECLARE_EVENT_TYPE(wxEVT_JOY_BUTTON_UP, 431)
DECLARE_EVENT_TYPE(wxEVT_JOY_MOVE, 432)
DECLARE_EVENT_TYPE(wxEVT_JOY_ZMOVE, 433)
DECLARE_EVENT_TYPE(wxEVT_DROP_FILES, 434)
DECLARE_EVENT_TYPE(wxEVT_DRAW_ITEM, 435)
DECLARE_EVENT_TYPE(wxEVT_MEASURE_ITEM, 436)
DECLARE_EVENT_TYPE(wxEVT_COMPARE_ITEM, 437)
DECLARE_EVENT_TYPE(wxEVT_INIT_DIALOG, 438)
DECLARE_EXPORTED_EVENT_TYPE(WXDLLIMPEXP_BASE, wxEVT_IDLE, 439)
DECLARE_EVENT_TYPE(wxEVT_UPDATE_UI, 440)
DECLARE_EVENT_TYPE(wxEVT_SIZING, 441)
DECLARE_EVENT_TYPE(wxEVT_MOVING, 442)
DECLARE_EVENT_TYPE(wxEVT_HIBERNATE, 443)
// more power events follow -- see wx/power.h
// Clipboard events
DECLARE_EVENT_TYPE(wxEVT_COMMAND_TEXT_COPY, 444)
DECLARE_EVENT_TYPE(wxEVT_COMMAND_TEXT_CUT, 445)
DECLARE_EVENT_TYPE(wxEVT_COMMAND_TEXT_PASTE, 446)
// Generic command events
// Note: a click is a higher-level event than button down/up
DECLARE_EVENT_TYPE(wxEVT_COMMAND_LEFT_CLICK, 500)
DECLARE_EVENT_TYPE(wxEVT_COMMAND_LEFT_DCLICK, 501)
DECLARE_EVENT_TYPE(wxEVT_COMMAND_RIGHT_CLICK, 502)
DECLARE_EVENT_TYPE(wxEVT_COMMAND_RIGHT_DCLICK, 503)
DECLARE_EVENT_TYPE(wxEVT_COMMAND_SET_FOCUS, 504)
DECLARE_EVENT_TYPE(wxEVT_COMMAND_KILL_FOCUS, 505)
DECLARE_EVENT_TYPE(wxEVT_COMMAND_ENTER, 506)
// Help events
DECLARE_EVENT_TYPE(wxEVT_HELP, 1050)
DECLARE_EVENT_TYPE(wxEVT_DETAILED_HELP, 1051)
END_DECLARE_EVENT_TYPES()
// these 2 events are the same
#define wxEVT_COMMAND_TOOL_CLICKED wxEVT_COMMAND_MENU_SELECTED
// ----------------------------------------------------------------------------
// Compatibility
// ----------------------------------------------------------------------------
// this event is also used by wxComboBox and wxSpinCtrl which don't include
// wx/textctrl.h in all ports [yet], so declare it here as well
//
// still, any new code using it should include wx/textctrl.h explicitly
#if !WXWIN_COMPATIBILITY_EVENT_TYPES
extern const wxEventType WXDLLIMPEXP_CORE wxEVT_COMMAND_TEXT_UPDATED;
#endif
// the predefined constants for the number of times we propagate event
// upwards window child-parent chain
enum Propagation_state
{
// don't propagate it at all
wxEVENT_PROPAGATE_NONE = 0,
// propagate it until it is processed
wxEVENT_PROPAGATE_MAX = INT_MAX
};
/*
* wxWidgets events, covering all interesting things that might happen
* (button clicking, resizing, setting text in widgets, etc.).
*
* For each completely new event type, derive a new event class.
* An event CLASS represents a C++ class defining a range of similar event TYPES;
* examples are canvas events, panel item command events.
* An event TYPE is a unique identifier for a particular system event,
* such as a button press or a listbox deselection.
*
*/
class WXDLLIMPEXP_BASE wxEvent : public wxObject
{
private:
wxEvent& operator=(const wxEvent&);
protected:
wxEvent(const wxEvent&); // for implementing Clone()
public:
wxEvent(int winid = 0, wxEventType commandType = wxEVT_NULL );
void SetEventType(wxEventType typ) { m_eventType = typ; }
wxEventType GetEventType() const { return m_eventType; }
wxObject *GetEventObject() const { return m_eventObject; }
void SetEventObject(wxObject *obj) { m_eventObject = obj; }
long GetTimestamp() const { return m_timeStamp; }
void SetTimestamp(long ts = 0) { m_timeStamp = ts; }
int GetId() const { return m_id; }
void SetId(int Id) { m_id = Id; }
// Can instruct event processor that we wish to ignore this event
// (treat as if the event table entry had not been found): this must be done
// to allow the event processing by the base classes (calling event.Skip()
// is the analog of calling the base class version of a virtual function)
void Skip(bool skip = true) { m_skipped = skip; }
bool GetSkipped() const { return m_skipped; }
// this function is used to create a copy of the event polymorphically and
// all derived classes must implement it because otherwise wxPostEvent()
// for them wouldn't work (it needs to do a copy of the event)
virtual wxEvent *Clone() const = 0;
// Implementation only: this test is explicitly anti OO and this function
// exists only for optimization purposes.
bool IsCommandEvent() const { return m_isCommandEvent; }
// Determine if this event should be propagating to the parent window.
bool ShouldPropagate() const
{ return m_propagationLevel != wxEVENT_PROPAGATE_NONE; }
// Stop an event from propagating to its parent window, returns the old
// propagation level value
int StopPropagation()
{
int propagationLevel = m_propagationLevel;
m_propagationLevel = wxEVENT_PROPAGATE_NONE;
return propagationLevel;
}
// Resume the event propagation by restoring the propagation level
// (returned by StopPropagation())
void ResumePropagation(int propagationLevel)
{
m_propagationLevel = propagationLevel;
}
#if WXWIN_COMPATIBILITY_2_4
public:
#else
protected:
#endif
wxObject* m_eventObject;
wxEventType m_eventType;
long m_timeStamp;
int m_id;
public:
// m_callbackUserData is for internal usage only
wxObject* m_callbackUserData;
protected:
// the propagation level: while it is positive, we propagate the event to
// the parent window (if any)
//
// this one doesn't have to be public, we don't have to worry about
// backwards compatibility as it is new
int m_propagationLevel;
#if WXWIN_COMPATIBILITY_2_4
public:
#else
protected:
#endif
bool m_skipped;
bool m_isCommandEvent;
private:
// it needs to access our m_propagationLevel
friend class WXDLLIMPEXP_BASE wxPropagateOnce;
DECLARE_ABSTRACT_CLASS(wxEvent)
};
/*
* Helper class to temporarily change an event not to propagate.
*/
class WXDLLIMPEXP_BASE wxPropagationDisabler
{
public:
wxPropagationDisabler(wxEvent& event) : m_event(event)
{
m_propagationLevelOld = m_event.StopPropagation();
}
~wxPropagationDisabler()
{
m_event.ResumePropagation(m_propagationLevelOld);
}
private:
wxEvent& m_event;
int m_propagationLevelOld;
DECLARE_NO_COPY_CLASS(wxPropagationDisabler)
};
/*
* Another one to temporarily lower propagation level.
*/
class WXDLLIMPEXP_BASE wxPropagateOnce
{
public:
wxPropagateOnce(wxEvent& event) : m_event(event)
{
wxASSERT_MSG( m_event.m_propagationLevel > 0,
_T("shouldn't be used unless ShouldPropagate()!") );
m_event.m_propagationLevel--;
}
~wxPropagateOnce()
{
m_event.m_propagationLevel++;
}
private:
wxEvent& m_event;
DECLARE_NO_COPY_CLASS(wxPropagateOnce)
};
#if wxUSE_GUI
// Item or menu event class
/*
wxEVT_COMMAND_BUTTON_CLICKED
wxEVT_COMMAND_CHECKBOX_CLICKED
wxEVT_COMMAND_CHOICE_SELECTED
wxEVT_COMMAND_LISTBOX_SELECTED
wxEVT_COMMAND_LISTBOX_DOUBLECLICKED
wxEVT_COMMAND_TEXT_UPDATED
wxEVT_COMMAND_TEXT_ENTER
wxEVT_COMMAND_MENU_SELECTED
wxEVT_COMMAND_SLIDER_UPDATED
wxEVT_COMMAND_RADIOBOX_SELECTED
wxEVT_COMMAND_RADIOBUTTON_SELECTED
wxEVT_COMMAND_SCROLLBAR_UPDATED
wxEVT_COMMAND_VLBOX_SELECTED
wxEVT_COMMAND_COMBOBOX_SELECTED
wxEVT_COMMAND_TOGGLEBUTTON_CLICKED
*/
#if WXWIN_COMPATIBILITY_2_4
// Backwards compatibility for wxCommandEvent::m_commandString, will lead to compilation errors in some cases of usage
class WXDLLIMPEXP_CORE wxCommandEvent;
class WXDLLIMPEXP_CORE wxCommandEventStringHelper
{
public:
wxCommandEventStringHelper(wxCommandEvent * evt)
: m_evt(evt)
{ }
void operator=(const wxString &str);
operator wxString();
const wxChar* c_str() const;
private:
wxCommandEvent* m_evt;
};
#endif
class WXDLLIMPEXP_CORE wxCommandEvent : public wxEvent
{
public:
wxCommandEvent(wxEventType commandType = wxEVT_NULL, int winid = 0);
wxCommandEvent(const wxCommandEvent& event)
: wxEvent(event),
#if WXWIN_COMPATIBILITY_2_4
m_commandString(this),
#endif
m_cmdString(event.m_cmdString),
m_commandInt(event.m_commandInt),
m_extraLong(event.m_extraLong),
m_clientData(event.m_clientData),
m_clientObject(event.m_clientObject)
{ }
// Set/Get client data from controls
void SetClientData(void* clientData) { m_clientData = clientData; }
void *GetClientData() const { return m_clientData; }
// Set/Get client object from controls
void SetClientObject(wxClientData* clientObject) { m_clientObject = clientObject; }
wxClientData *GetClientObject() const { return m_clientObject; }
// Get listbox selection if single-choice
int GetSelection() const { return m_commandInt; }
// Set/Get listbox/choice selection string
void SetString(const wxString& s) { m_cmdString = s; }
wxString GetString() const;
// Get checkbox value
bool IsChecked() const { return m_commandInt != 0; }
// true if the listbox event was a selection.
bool IsSelection() const { return (m_extraLong != 0); }
void SetExtraLong(long extraLong) { m_extraLong = extraLong; }
long GetExtraLong() const { return m_extraLong; }
void SetInt(int i) { m_commandInt = i; }
int GetInt() const { return m_commandInt; }
virtual wxEvent *Clone() const { return new wxCommandEvent(*this); }
#if WXWIN_COMPATIBILITY_2_4
public:
wxCommandEventStringHelper m_commandString;
#else
protected:
#endif
wxString m_cmdString; // String event argument
int m_commandInt;
long m_extraLong; // Additional information (e.g. select/deselect)
void* m_clientData; // Arbitrary client data
wxClientData* m_clientObject; // Arbitrary client object
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxCommandEvent)
};
#if WXWIN_COMPATIBILITY_2_4
inline void wxCommandEventStringHelper::operator=(const wxString &str)
{
m_evt->SetString(str);
}
inline wxCommandEventStringHelper::operator wxString()
{
return m_evt->GetString();
}
inline const wxChar* wxCommandEventStringHelper::c_str() const
{
return m_evt->GetString().c_str();
}
#endif
// this class adds a possibility to react (from the user) code to a control
// notification: allow or veto the operation being reported.
class WXDLLIMPEXP_CORE wxNotifyEvent : public wxCommandEvent
{
public:
wxNotifyEvent(wxEventType commandType = wxEVT_NULL, int winid = 0)
: wxCommandEvent(commandType, winid)
{ m_bAllow = true; }
wxNotifyEvent(const wxNotifyEvent& event)
: wxCommandEvent(event)
{ m_bAllow = event.m_bAllow; }
// veto the operation (usually it's allowed by default)
void Veto() { m_bAllow = false; }
// allow the operation if it was disabled by default
void Allow() { m_bAllow = true; }
// for implementation code only: is the operation allowed?
bool IsAllowed() const { return m_bAllow; }
virtual wxEvent *Clone() const { return new wxNotifyEvent(*this); }
private:
bool m_bAllow;
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxNotifyEvent)
};
// Scroll event class, derived form wxCommandEvent. wxScrollEvents are
// sent by wxSlider and wxScrollBar.
/*
wxEVT_SCROLL_TOP
wxEVT_SCROLL_BOTTOM
wxEVT_SCROLL_LINEUP
wxEVT_SCROLL_LINEDOWN
wxEVT_SCROLL_PAGEUP
wxEVT_SCROLL_PAGEDOWN
wxEVT_SCROLL_THUMBTRACK
wxEVT_SCROLL_THUMBRELEASE
wxEVT_SCROLL_CHANGED
*/
class WXDLLIMPEXP_CORE wxScrollEvent : public wxCommandEvent
{
public:
wxScrollEvent(wxEventType commandType = wxEVT_NULL,
int winid = 0, int pos = 0, int orient = 0);
int GetOrientation() const { return (int) m_extraLong; }
int GetPosition() const { return m_commandInt; }
void SetOrientation(int orient) { m_extraLong = (long) orient; }
void SetPosition(int pos) { m_commandInt = pos; }
virtual wxEvent *Clone() const { return new wxScrollEvent(*this); }
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxScrollEvent)
};
// ScrollWin event class, derived fom wxEvent. wxScrollWinEvents
// are sent by wxWindow.
/*
wxEVT_SCROLLWIN_TOP
wxEVT_SCROLLWIN_BOTTOM
wxEVT_SCROLLWIN_LINEUP
wxEVT_SCROLLWIN_LINEDOWN
wxEVT_SCROLLWIN_PAGEUP
wxEVT_SCROLLWIN_PAGEDOWN
wxEVT_SCROLLWIN_THUMBTRACK
wxEVT_SCROLLWIN_THUMBRELEASE
*/
class WXDLLIMPEXP_CORE wxScrollWinEvent : public wxEvent
{
public:
wxScrollWinEvent(wxEventType commandType = wxEVT_NULL,
int pos = 0, int orient = 0);
wxScrollWinEvent(const wxScrollWinEvent & event) : wxEvent(event)
{ m_commandInt = event.m_commandInt;
m_extraLong = event.m_extraLong; }
int GetOrientation() const { return (int) m_extraLong; }
int GetPosition() const { return m_commandInt; }
void SetOrientation(int orient) { m_extraLong = (long) orient; }
void SetPosition(int pos) { m_commandInt = pos; }
virtual wxEvent *Clone() const { return new wxScrollWinEvent(*this); }
#if WXWIN_COMPATIBILITY_2_4
public:
#else
protected:
#endif
int m_commandInt;
long m_extraLong;
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxScrollWinEvent)
};
// Mouse event class
/*
wxEVT_LEFT_DOWN
wxEVT_LEFT_UP
wxEVT_MIDDLE_DOWN
wxEVT_MIDDLE_UP
wxEVT_RIGHT_DOWN
wxEVT_RIGHT_UP
wxEVT_MOTION
wxEVT_ENTER_WINDOW
wxEVT_LEAVE_WINDOW
wxEVT_LEFT_DCLICK
wxEVT_MIDDLE_DCLICK
wxEVT_RIGHT_DCLICK
wxEVT_NC_LEFT_DOWN
wxEVT_NC_LEFT_UP,
wxEVT_NC_MIDDLE_DOWN,
wxEVT_NC_MIDDLE_UP,
wxEVT_NC_RIGHT_DOWN,
wxEVT_NC_RIGHT_UP,
wxEVT_NC_MOTION,
wxEVT_NC_ENTER_WINDOW,
wxEVT_NC_LEAVE_WINDOW,
wxEVT_NC_LEFT_DCLICK,
wxEVT_NC_MIDDLE_DCLICK,
wxEVT_NC_RIGHT_DCLICK,
*/
// the symbolic names for the mouse buttons
enum
{
wxMOUSE_BTN_ANY = -1,
wxMOUSE_BTN_NONE = 0,
wxMOUSE_BTN_LEFT = 1,
wxMOUSE_BTN_MIDDLE = 2,
wxMOUSE_BTN_RIGHT = 3
};
class WXDLLIMPEXP_CORE wxMouseEvent : public wxEvent
{
public:
wxMouseEvent(wxEventType mouseType = wxEVT_NULL);
wxMouseEvent(const wxMouseEvent& event) : wxEvent(event)
{ Assign(event); }
// Was it a button event? (*doesn't* mean: is any button *down*?)
bool IsButton() const { return Button(wxMOUSE_BTN_ANY); }
// Was it a down event from this (or any) button?
bool ButtonDown(int but = wxMOUSE_BTN_ANY) const;
// Was it a dclick event from this (or any) button?
bool ButtonDClick(int but = wxMOUSE_BTN_ANY) const;
// Was it a up event from this (or any) button?
bool ButtonUp(int but = wxMOUSE_BTN_ANY) const;
// Was the given button?
bool Button(int but) const;
// Was the given button in Down state?
bool ButtonIsDown(int but) const;
// Get the button which is changing state (wxMOUSE_BTN_NONE if none)
int GetButton() const;
// Find state of shift/control keys
bool ControlDown() const { return m_controlDown; }
bool MetaDown() const { return m_metaDown; }
bool AltDown() const { return m_altDown; }
bool ShiftDown() const { return m_shiftDown; }
bool CmdDown() const
{
#if defined(__WXMAC__) || defined(__WXCOCOA__)
return MetaDown();
#else
return ControlDown();
#endif
}
// Find which event was just generated
bool LeftDown() const { return (m_eventType == wxEVT_LEFT_DOWN); }
bool MiddleDown() const { return (m_eventType == wxEVT_MIDDLE_DOWN); }
bool RightDown() const { return (m_eventType == wxEVT_RIGHT_DOWN); }
bool LeftUp() const { return (m_eventType == wxEVT_LEFT_UP); }
bool MiddleUp() const { return (m_eventType == wxEVT_MIDDLE_UP); }
bool RightUp() const { return (m_eventType == wxEVT_RIGHT_UP); }
bool LeftDClick() const { return (m_eventType == wxEVT_LEFT_DCLICK); }
bool MiddleDClick() const { return (m_eventType == wxEVT_MIDDLE_DCLICK); }
bool RightDClick() const { return (m_eventType == wxEVT_RIGHT_DCLICK); }
// Find the current state of the mouse buttons (regardless
// of current event type)
bool LeftIsDown() const { return m_leftDown; }
bool MiddleIsDown() const { return m_middleDown; }
bool RightIsDown() const { return m_rightDown; }
// True if a button is down and the mouse is moving
bool Dragging() const
{
return (m_eventType == wxEVT_MOTION) && ButtonIsDown(wxMOUSE_BTN_ANY);
}
// True if the mouse is moving, and no button is down
bool Moving() const
{
return (m_eventType == wxEVT_MOTION) && !ButtonIsDown(wxMOUSE_BTN_ANY);
}
// True if the mouse is just entering the window
bool Entering() const { return (m_eventType == wxEVT_ENTER_WINDOW); }
// True if the mouse is just leaving the window
bool Leaving() const { return (m_eventType == wxEVT_LEAVE_WINDOW); }
// Find the position of the event
void GetPosition(wxCoord *xpos, wxCoord *ypos) const
{
if (xpos)
*xpos = m_x;
if (ypos)
*ypos = m_y;
}
void GetPosition(long *xpos, long *ypos) const
{
if (xpos)
*xpos = (long)m_x;
if (ypos)
*ypos = (long)m_y;
}
// Find the position of the event
wxPoint GetPosition() const { return wxPoint(m_x, m_y); }
// Find the logical position of the event given the DC
wxPoint GetLogicalPosition(const wxDC& dc) const;
// Get X position
wxCoord GetX() const { return m_x; }
// Get Y position
wxCoord GetY() const { return m_y; }
// Get wheel rotation, positive or negative indicates direction of
// rotation. Current devices all send an event when rotation is equal to
// +/-WheelDelta, but this allows for finer resolution devices to be
// created in the future. Because of this you shouldn't assume that one
// event is equal to 1 line or whatever, but you should be able to either
// do partial line scrolling or wait until +/-WheelDelta rotation values
// have been accumulated before scrolling.
int GetWheelRotation() const { return m_wheelRotation; }
// Get wheel delta, normally 120. This is the threshold for action to be
// taken, and one such action (for example, scrolling one increment)
// should occur for each delta.
int GetWheelDelta() const { return m_wheelDelta; }
// Returns the configured number of lines (or whatever) to be scrolled per
// wheel action. Defaults to one.
int GetLinesPerAction() const { return m_linesPerAction; }
// Is the system set to do page scrolling?
bool IsPageScroll() const { return ((unsigned int)m_linesPerAction == UINT_MAX); }
virtual wxEvent *Clone() const { return new wxMouseEvent(*this); }
wxMouseEvent& operator=(const wxMouseEvent& event) { Assign(event); return *this; }
public:
wxCoord m_x, m_y;
bool m_leftDown;
bool m_middleDown;
bool m_rightDown;
bool m_controlDown;
bool m_shiftDown;
bool m_altDown;
bool m_metaDown;
int m_wheelRotation;
int m_wheelDelta;
int m_linesPerAction;
protected:
void Assign(const wxMouseEvent& evt);
private:
DECLARE_DYNAMIC_CLASS(wxMouseEvent)
};
// Cursor set event
/*
wxEVT_SET_CURSOR
*/
class WXDLLIMPEXP_CORE wxSetCursorEvent : public wxEvent
{
public:
wxSetCursorEvent(wxCoord x = 0, wxCoord y = 0)
: wxEvent(0, wxEVT_SET_CURSOR),
m_x(x), m_y(y), m_cursor()
{ }
wxSetCursorEvent(const wxSetCursorEvent & event)
: wxEvent(event),
m_x(event.m_x),
m_y(event.m_y),
m_cursor(event.m_cursor)
{ }
wxCoord GetX() const { return m_x; }
wxCoord GetY() const { return m_y; }
void SetCursor(const wxCursor& cursor) { m_cursor = cursor; }
const wxCursor& GetCursor() const { return m_cursor; }
bool HasCursor() const { return m_cursor.Ok(); }
virtual wxEvent *Clone() const { return new wxSetCursorEvent(*this); }
private:
wxCoord m_x, m_y;
wxCursor m_cursor;
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxSetCursorEvent)
};
// Keyboard input event class
/*
wxEVT_CHAR
wxEVT_CHAR_HOOK
wxEVT_KEY_DOWN
wxEVT_KEY_UP
wxEVT_HOTKEY
*/
class WXDLLIMPEXP_CORE wxKeyEvent : public wxEvent
{
public:
wxKeyEvent(wxEventType keyType = wxEVT_NULL);
wxKeyEvent(const wxKeyEvent& evt);
// can be used check if the key event has exactly the given modifiers:
// "GetModifiers() = wxMOD_CONTROL" is easier to write than "ControlDown()
// && !MetaDown() && !AltDown() && !ShiftDown()"
int GetModifiers() const
{
return (m_controlDown ? wxMOD_CONTROL : 0) |
(m_shiftDown ? wxMOD_SHIFT : 0) |
(m_metaDown ? wxMOD_META : 0) |
(m_altDown ? wxMOD_ALT : 0);
}
// Find state of shift/control keys
bool ControlDown() const { return m_controlDown; }
bool ShiftDown() const { return m_shiftDown; }
bool MetaDown() const { return m_metaDown; }
bool AltDown() const { return m_altDown; }
// "Cmd" is a pseudo key which is Control for PC and Unix platforms but
// Apple ("Command") key under Macs: it makes often sense to use it instead
// of, say, ControlDown() because Cmd key is used for the same thing under
// Mac as Ctrl elsewhere (but Ctrl still exists, just not used for this
// purpose under Mac)
bool CmdDown() const
{
#if defined(__WXMAC__) || defined(__WXCOCOA__)
return MetaDown();
#else
return ControlDown();
#endif
}
// exclude MetaDown() from HasModifiers() because NumLock under X is often
// configured as mod2 modifier, yet the key events even when it is pressed
// should be processed normally, not like Ctrl- or Alt-key
bool HasModifiers() const { return ControlDown() || AltDown(); }
// get the key code: an ASCII7 char or an element of wxKeyCode enum
int GetKeyCode() const { return (int)m_keyCode; }
#if wxUSE_UNICODE
// get the Unicode character corresponding to this key
wxChar GetUnicodeKey() const { return m_uniChar; }
#endif // wxUSE_UNICODE
// get the raw key code (platform-dependent)
wxUint32 GetRawKeyCode() const { return m_rawCode; }
// get the raw key flags (platform-dependent)
wxUint32 GetRawKeyFlags() const { return m_rawFlags; }
// Find the position of the event
void GetPosition(wxCoord *xpos, wxCoord *ypos) const
{
if (xpos) *xpos = m_x;
if (ypos) *ypos = m_y;
}
void GetPosition(long *xpos, long *ypos) const
{
if (xpos) *xpos = (long)m_x;
if (ypos) *ypos = (long)m_y;
}
wxPoint GetPosition() const
{ return wxPoint(m_x, m_y); }
// Get X position
wxCoord GetX() const { return m_x; }
// Get Y position
wxCoord GetY() const { return m_y; }
#if WXWIN_COMPATIBILITY_2_6
// deprecated, Use GetKeyCode instead.
wxDEPRECATED( long KeyCode() const );
#endif // WXWIN_COMPATIBILITY_2_6
virtual wxEvent *Clone() const { return new wxKeyEvent(*this); }
// we do need to copy wxKeyEvent sometimes (in wxTreeCtrl code, for
// example)
wxKeyEvent& operator=(const wxKeyEvent& evt)
{
m_x = evt.m_x;
m_y = evt.m_y;
m_keyCode = evt.m_keyCode;
m_controlDown = evt.m_controlDown;
m_shiftDown = evt.m_shiftDown;
m_altDown = evt.m_altDown;
m_metaDown = evt.m_metaDown;
m_scanCode = evt.m_scanCode;
m_rawCode = evt.m_rawCode;
m_rawFlags = evt.m_rawFlags;
#if wxUSE_UNICODE
m_uniChar = evt.m_uniChar;
#endif
return *this;
}
public:
wxCoord m_x, m_y;
long m_keyCode;
// TODO: replace those with a single m_modifiers bitmask of wxMOD_XXX?
bool m_controlDown;
bool m_shiftDown;
bool m_altDown;
bool m_metaDown;
// FIXME: what is this for? relation to m_rawXXX?
bool m_scanCode;
#if wxUSE_UNICODE
// This contains the full Unicode character
// in a character events in Unicode mode
wxChar m_uniChar;
#endif
// these fields contain the platform-specific information about
// key that was pressed
wxUint32 m_rawCode;
wxUint32 m_rawFlags;
private:
DECLARE_DYNAMIC_CLASS(wxKeyEvent)
};
// Size event class
/*
wxEVT_SIZE
*/
class WXDLLIMPEXP_CORE wxSizeEvent : public wxEvent
{
public:
wxSizeEvent() : wxEvent(0, wxEVT_SIZE)
{ }
wxSizeEvent(const wxSize& sz, int winid = 0)
: wxEvent(winid, wxEVT_SIZE),
m_size(sz)
{ }
wxSizeEvent(const wxSizeEvent & event)
: wxEvent(event),
m_size(event.m_size), m_rect(event.m_rect)
{ }
wxSizeEvent(const wxRect& rect, int id = 0)
: m_size(rect.GetSize()), m_rect(rect)
{ m_eventType = wxEVT_SIZING; m_id = id; }
wxSize GetSize() const { return m_size; }
wxRect GetRect() const { return m_rect; }
void SetRect(const wxRect& rect) { m_rect = rect; }
virtual wxEvent *Clone() const { return new wxSizeEvent(*this); }
public:
// For internal usage only. Will be converted to protected members.
wxSize m_size;
wxRect m_rect; // Used for wxEVT_SIZING
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxSizeEvent)
};
// Move event class
/*
wxEVT_MOVE
*/
class WXDLLIMPEXP_CORE wxMoveEvent : public wxEvent
{
public:
wxMoveEvent()
: wxEvent(0, wxEVT_MOVE)
{ }
wxMoveEvent(const wxPoint& pos, int winid = 0)
: wxEvent(winid, wxEVT_MOVE),
m_pos(pos)
{ }
wxMoveEvent(const wxMoveEvent& event)
: wxEvent(event),
m_pos(event.m_pos)
{ }
wxMoveEvent(const wxRect& rect, int id = 0)
: m_pos(rect.GetPosition()), m_rect(rect)
{ m_eventType = wxEVT_MOVING; m_id = id; }
wxPoint GetPosition() const { return m_pos; }
void SetPosition(const wxPoint& pos) { m_pos = pos; }
wxRect GetRect() const { return m_rect; }
void SetRect(const wxRect& rect) { m_rect = rect; }
virtual wxEvent *Clone() const { return new wxMoveEvent(*this); }
#if WXWIN_COMPATIBILITY_2_4
public:
#else
protected:
#endif
wxPoint m_pos;
wxRect m_rect;
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxMoveEvent)
};
// Paint event class
/*
wxEVT_PAINT
wxEVT_NC_PAINT
wxEVT_PAINT_ICON
*/
#if defined(__WXDEBUG__) && (defined(__WXMSW__) || defined(__WXPM__))
// see comments in src/msw|os2/dcclient.cpp where g_isPainting is defined
extern WXDLLIMPEXP_CORE int g_isPainting;
#endif // debug
class WXDLLIMPEXP_CORE wxPaintEvent : public wxEvent
{
public:
wxPaintEvent(int Id = 0)
: wxEvent(Id, wxEVT_PAINT)
{
#if defined(__WXDEBUG__) && (defined(__WXMSW__) || defined(__WXPM__))
// set the internal flag for the duration of processing of WM_PAINT
g_isPainting++;
#endif // debug
}
// default copy ctor and dtor are normally fine, we only need them to keep
// g_isPainting updated in debug build
#if defined(__WXDEBUG__) && (defined(__WXMSW__) || defined(__WXPM__))
wxPaintEvent(const wxPaintEvent& event)
: wxEvent(event)
{
g_isPainting++;
}
virtual ~wxPaintEvent()
{
g_isPainting--;
}
#endif // debug
virtual wxEvent *Clone() const { return new wxPaintEvent(*this); }
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxPaintEvent)
};
class WXDLLIMPEXP_CORE wxNcPaintEvent : public wxEvent
{
public:
wxNcPaintEvent(int winid = 0)
: wxEvent(winid, wxEVT_NC_PAINT)
{ }
virtual wxEvent *Clone() const { return new wxNcPaintEvent(*this); }
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxNcPaintEvent)
};
// Erase background event class
/*
wxEVT_ERASE_BACKGROUND
*/
class WXDLLIMPEXP_CORE wxEraseEvent : public wxEvent
{
public:
wxEraseEvent(int Id = 0, wxDC *dc = (wxDC *) NULL)
: wxEvent(Id, wxEVT_ERASE_BACKGROUND),
m_dc(dc)
{ }
wxEraseEvent(const wxEraseEvent& event)
: wxEvent(event),
m_dc(event.m_dc)
{ }
wxDC *GetDC() const { return m_dc; }
virtual wxEvent *Clone() const { return new wxEraseEvent(*this); }
#if WXWIN_COMPATIBILITY_2_4
public:
#else
protected:
#endif
wxDC *m_dc;
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxEraseEvent)
};
// Focus event class
/*
wxEVT_SET_FOCUS
wxEVT_KILL_FOCUS
*/
class WXDLLIMPEXP_CORE wxFocusEvent : public wxEvent
{
public:
wxFocusEvent(wxEventType type = wxEVT_NULL, int winid = 0)
: wxEvent(winid, type)
{ m_win = NULL; }
wxFocusEvent(const wxFocusEvent& event)
: wxEvent(event)
{ m_win = event.m_win; }
// The window associated with this event is the window which had focus
// before for SET event and the window which will have focus for the KILL
// one. NB: it may be NULL in both cases!
wxWindow *GetWindow() const { return m_win; }
void SetWindow(wxWindow *win) { m_win = win; }
virtual wxEvent *Clone() const { return new wxFocusEvent(*this); }
private:
wxWindow *m_win;
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxFocusEvent)
};
// wxChildFocusEvent notifies the parent that a child has got the focus: unlike
// wxFocusEvent it is propagated upwards the window chain
class WXDLLIMPEXP_CORE wxChildFocusEvent : public wxCommandEvent
{
public:
wxChildFocusEvent(wxWindow *win = NULL);
wxWindow *GetWindow() const { return (wxWindow *)GetEventObject(); }
virtual wxEvent *Clone() const { return new wxChildFocusEvent(*this); }
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxChildFocusEvent)
};
// Activate event class
/*
wxEVT_ACTIVATE
wxEVT_ACTIVATE_APP
wxEVT_HIBERNATE
*/
class WXDLLIMPEXP_CORE wxActivateEvent : public wxEvent
{
public:
wxActivateEvent(wxEventType type = wxEVT_NULL, bool active = true, int Id = 0)
: wxEvent(Id, type)
{ m_active = active; }
wxActivateEvent(const wxActivateEvent& event)
: wxEvent(event)
{ m_active = event.m_active; }
bool GetActive() const { return m_active; }
virtual wxEvent *Clone() const { return new wxActivateEvent(*this); }
private:
bool m_active;
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxActivateEvent)
};
// InitDialog event class
/*
wxEVT_INIT_DIALOG
*/
class WXDLLIMPEXP_CORE wxInitDialogEvent : public wxEvent
{
public:
wxInitDialogEvent(int Id = 0)
: wxEvent(Id, wxEVT_INIT_DIALOG)
{ }
virtual wxEvent *Clone() const { return new wxInitDialogEvent(*this); }
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxInitDialogEvent)
};
// Miscellaneous menu event class
/*
wxEVT_MENU_OPEN,
wxEVT_MENU_CLOSE,
wxEVT_MENU_HIGHLIGHT,
*/
class WXDLLIMPEXP_CORE wxMenuEvent : public wxEvent
{
public:
wxMenuEvent(wxEventType type = wxEVT_NULL, int winid = 0, wxMenu* menu = NULL)
: wxEvent(winid, type)
{ m_menuId = winid; m_menu = menu; }
wxMenuEvent(const wxMenuEvent & event)
: wxEvent(event)
{ m_menuId = event.m_menuId; m_menu = event.m_menu; }
// only for wxEVT_MENU_HIGHLIGHT
int GetMenuId() const { return m_menuId; }
// only for wxEVT_MENU_OPEN/CLOSE
bool IsPopup() const { return m_menuId == wxID_ANY; }
// only for wxEVT_MENU_OPEN/CLOSE
wxMenu* GetMenu() const { return m_menu; }
virtual wxEvent *Clone() const { return new wxMenuEvent(*this); }
private:
int m_menuId;
wxMenu* m_menu;
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxMenuEvent)
};
// Window close or session close event class
/*
wxEVT_CLOSE_WINDOW,
wxEVT_END_SESSION,
wxEVT_QUERY_END_SESSION
*/
class WXDLLIMPEXP_CORE wxCloseEvent : public wxEvent
{
public:
wxCloseEvent(wxEventType type = wxEVT_NULL, int winid = 0)
: wxEvent(winid, type),
m_loggingOff(true),
m_veto(false), // should be false by default
m_canVeto(true) {}
wxCloseEvent(const wxCloseEvent & event)
: wxEvent(event),
m_loggingOff(event.m_loggingOff),
m_veto(event.m_veto),
m_canVeto(event.m_canVeto) {}
void SetLoggingOff(bool logOff) { m_loggingOff = logOff; }
bool GetLoggingOff() const
{
// m_loggingOff flag is only used by wxEVT_[QUERY_]END_SESSION, it
// doesn't make sense for wxEVT_CLOSE_WINDOW
wxASSERT_MSG( m_eventType != wxEVT_CLOSE_WINDOW,
_T("this flag is for end session events only") );
return m_loggingOff;
}
void Veto(bool veto = true)
{
// GetVeto() will return false anyhow...
wxCHECK_RET( m_canVeto,
wxT("call to Veto() ignored (can't veto this event)") );
m_veto = veto;
}
void SetCanVeto(bool canVeto) { m_canVeto = canVeto; }
bool CanVeto() const { return m_canVeto; }
bool GetVeto() const { return m_canVeto && m_veto; }
virtual wxEvent *Clone() const { return new wxCloseEvent(*this); }
protected:
bool m_loggingOff,
m_veto,
m_canVeto;
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxCloseEvent)
};
/*
wxEVT_SHOW
*/
class WXDLLIMPEXP_CORE wxShowEvent : public wxEvent
{
public:
wxShowEvent(int winid = 0, bool show = false)
: wxEvent(winid, wxEVT_SHOW)
{ m_show = show; }
wxShowEvent(const wxShowEvent & event)
: wxEvent(event)
{ m_show = event.m_show; }
void SetShow(bool show) { m_show = show; }
bool GetShow() const { return m_show; }
virtual wxEvent *Clone() const { return new wxShowEvent(*this); }
protected:
bool m_show;
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxShowEvent)
};
/*
wxEVT_ICONIZE
*/
class WXDLLIMPEXP_CORE wxIconizeEvent : public wxEvent
{
public:
wxIconizeEvent(int winid = 0, bool iconized = true)
: wxEvent(winid, wxEVT_ICONIZE)
{ m_iconized = iconized; }
wxIconizeEvent(const wxIconizeEvent & event)
: wxEvent(event)
{ m_iconized = event.m_iconized; }
// return true if the frame was iconized, false if restored
bool Iconized() const { return m_iconized; }
virtual wxEvent *Clone() const { return new wxIconizeEvent(*this); }
protected:
bool m_iconized;
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxIconizeEvent)
};
/*
wxEVT_MAXIMIZE
*/
class WXDLLIMPEXP_CORE wxMaximizeEvent : public wxEvent
{
public:
wxMaximizeEvent(int winid = 0)
: wxEvent(winid, wxEVT_MAXIMIZE)
{ }
virtual wxEvent *Clone() const { return new wxMaximizeEvent(*this); }
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxMaximizeEvent)
};
// Joystick event class
/*
wxEVT_JOY_BUTTON_DOWN,
wxEVT_JOY_BUTTON_UP,
wxEVT_JOY_MOVE,
wxEVT_JOY_ZMOVE
*/
// Which joystick? Same as Windows ids so no conversion necessary.
enum
{
wxJOYSTICK1,
wxJOYSTICK2
};
// Which button is down?
enum
{
wxJOY_BUTTON_ANY = -1,
wxJOY_BUTTON1 = 1,
wxJOY_BUTTON2 = 2,
wxJOY_BUTTON3 = 4,
wxJOY_BUTTON4 = 8
};
class WXDLLIMPEXP_CORE wxJoystickEvent : public wxEvent
{
#if WXWIN_COMPATIBILITY_2_4
public:
#else
protected:
#endif
wxPoint m_pos;
int m_zPosition;
int m_buttonChange; // Which button changed?
int m_buttonState; // Which buttons are down?
int m_joyStick; // Which joystick?
public:
wxJoystickEvent(wxEventType type = wxEVT_NULL,
int state = 0,
int joystick = wxJOYSTICK1,
int change = 0)
: wxEvent(0, type),
m_pos(),
m_zPosition(0),
m_buttonChange(change),
m_buttonState(state),
m_joyStick(joystick)
{
}
wxJoystickEvent(const wxJoystickEvent & event)
: wxEvent(event),
m_pos(event.m_pos),
m_zPosition(event.m_zPosition),
m_buttonChange(event.m_buttonChange),
m_buttonState(event.m_buttonState),
m_joyStick(event.m_joyStick)
{ }
wxPoint GetPosition() const { return m_pos; }
int GetZPosition() const { return m_zPosition; }
int GetButtonState() const { return m_buttonState; }
int GetButtonChange() const { return m_buttonChange; }
int GetJoystick() const { return m_joyStick; }
void SetJoystick(int stick) { m_joyStick = stick; }
void SetButtonState(int state) { m_buttonState = state; }
void SetButtonChange(int change) { m_buttonChange = change; }
void SetPosition(const wxPoint& pos) { m_pos = pos; }
void SetZPosition(int zPos) { m_zPosition = zPos; }
// Was it a button event? (*doesn't* mean: is any button *down*?)
bool IsButton() const { return ((GetEventType() == wxEVT_JOY_BUTTON_DOWN) ||
(GetEventType() == wxEVT_JOY_BUTTON_UP)); }
// Was it a move event?
bool IsMove() const { return (GetEventType() == wxEVT_JOY_MOVE); }
// Was it a zmove event?
bool IsZMove() const { return (GetEventType() == wxEVT_JOY_ZMOVE); }
// Was it a down event from button 1, 2, 3, 4 or any?
bool ButtonDown(int but = wxJOY_BUTTON_ANY) const
{ return ((GetEventType() == wxEVT_JOY_BUTTON_DOWN) &&
((but == wxJOY_BUTTON_ANY) || (but == m_buttonChange))); }
// Was it a up event from button 1, 2, 3 or any?
bool ButtonUp(int but = wxJOY_BUTTON_ANY) const
{ return ((GetEventType() == wxEVT_JOY_BUTTON_UP) &&
((but == wxJOY_BUTTON_ANY) || (but == m_buttonChange))); }
// Was the given button 1,2,3,4 or any in Down state?
bool ButtonIsDown(int but = wxJOY_BUTTON_ANY) const
{ return (((but == wxJOY_BUTTON_ANY) && (m_buttonState != 0)) ||
((m_buttonState & but) == but)); }
virtual wxEvent *Clone() const { return new wxJoystickEvent(*this); }
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxJoystickEvent)
};
// Drop files event class
/*
wxEVT_DROP_FILES
*/
class WXDLLIMPEXP_CORE wxDropFilesEvent : public wxEvent
{
public:
int m_noFiles;
wxPoint m_pos;
wxString* m_files;
wxDropFilesEvent(wxEventType type = wxEVT_NULL,
int noFiles = 0,
wxString *files = (wxString *) NULL)
: wxEvent(0, type),
m_noFiles(noFiles),
m_pos(),
m_files(files)
{ }
// we need a copy ctor to avoid deleting m_files pointer twice
wxDropFilesEvent(const wxDropFilesEvent& other)
: wxEvent(other),
m_noFiles(other.m_noFiles),
m_pos(other.m_pos),
m_files(NULL)
{
m_files = new wxString[m_noFiles];
for ( int n = 0; n < m_noFiles; n++ )
{
m_files[n] = other.m_files[n];
}
}
virtual ~wxDropFilesEvent()
{
delete [] m_files;
}
wxPoint GetPosition() const { return m_pos; }
int GetNumberOfFiles() const { return m_noFiles; }
wxString *GetFiles() const { return m_files; }
virtual wxEvent *Clone() const { return new wxDropFilesEvent(*this); }
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxDropFilesEvent)
};
// Update UI event
/*
wxEVT_UPDATE_UI
*/
// Whether to always send update events to windows, or
// to only send update events to those with the
// wxWS_EX_PROCESS_UI_UPDATES style.
enum wxUpdateUIMode
{
// Send UI update events to all windows
wxUPDATE_UI_PROCESS_ALL,
// Send UI update events to windows that have
// the wxWS_EX_PROCESS_UI_UPDATES flag specified
wxUPDATE_UI_PROCESS_SPECIFIED
};
class WXDLLIMPEXP_CORE wxUpdateUIEvent : public wxCommandEvent
{
public:
wxUpdateUIEvent(wxWindowID commandId = 0)
: wxCommandEvent(wxEVT_UPDATE_UI, commandId)
{
m_checked =
m_enabled =
m_shown =
m_setEnabled =
m_setShown =
m_setText =
m_setChecked = false;
}
wxUpdateUIEvent(const wxUpdateUIEvent & event)
: wxCommandEvent(event),
m_checked(event.m_checked),
m_enabled(event.m_enabled),
m_shown(event.m_shown),
m_setEnabled(event.m_setEnabled),
m_setShown(event.m_setShown),
m_setText(event.m_setText),
m_setChecked(event.m_setChecked),
m_text(event.m_text)
{ }
bool GetChecked() const { return m_checked; }
bool GetEnabled() const { return m_enabled; }
bool GetShown() const { return m_shown; }
wxString GetText() const { return m_text; }
bool GetSetText() const { return m_setText; }
bool GetSetChecked() const { return m_setChecked; }
bool GetSetEnabled() const { return m_setEnabled; }
bool GetSetShown() const { return m_setShown; }
void Check(bool check) { m_checked = check; m_setChecked = true; }
void Enable(bool enable) { m_enabled = enable; m_setEnabled = true; }
void Show(bool show) { m_shown = show; m_setShown = true; }
void SetText(const wxString& text) { m_text = text; m_setText = true; }
// Sets the interval between updates in milliseconds.
// Set to -1 to disable updates, or to 0 to update as frequently as possible.
static void SetUpdateInterval(long updateInterval) { sm_updateInterval = updateInterval; }
// Returns the current interval between updates in milliseconds
static long GetUpdateInterval() { return sm_updateInterval; }
// Can we update this window?
static bool CanUpdate(wxWindowBase *win);
// Reset the update time to provide a delay until the next
// time we should update
static void ResetUpdateTime();
// Specify how wxWidgets will send update events: to
// all windows, or only to those which specify that they
// will process the events.
static void SetMode(wxUpdateUIMode mode) { sm_updateMode = mode; }
// Returns the UI update mode
static wxUpdateUIMode GetMode() { return sm_updateMode; }
virtual wxEvent *Clone() const { return new wxUpdateUIEvent(*this); }
protected:
bool m_checked;
bool m_enabled;
bool m_shown;
bool m_setEnabled;
bool m_setShown;
bool m_setText;
bool m_setChecked;
wxString m_text;
#if wxUSE_LONGLONG
static wxLongLong sm_lastUpdate;
#endif
static long sm_updateInterval;
static wxUpdateUIMode sm_updateMode;
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxUpdateUIEvent)
};
/*
wxEVT_SYS_COLOUR_CHANGED
*/
// TODO: shouldn't all events record the window ID?
class WXDLLIMPEXP_CORE wxSysColourChangedEvent : public wxEvent
{
public:
wxSysColourChangedEvent()
: wxEvent(0, wxEVT_SYS_COLOUR_CHANGED)
{ }
virtual wxEvent *Clone() const { return new wxSysColourChangedEvent(*this); }
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxSysColourChangedEvent)
};
/*
wxEVT_MOUSE_CAPTURE_CHANGED
The window losing the capture receives this message
(even if it released the capture itself).
*/
class WXDLLIMPEXP_CORE wxMouseCaptureChangedEvent : public wxEvent
{
public:
wxMouseCaptureChangedEvent(wxWindowID winid = 0, wxWindow* gainedCapture = NULL)
: wxEvent(winid, wxEVT_MOUSE_CAPTURE_CHANGED),
m_gainedCapture(gainedCapture)
{ }
wxMouseCaptureChangedEvent(const wxMouseCaptureChangedEvent& event)
: wxEvent(event),
m_gainedCapture(event.m_gainedCapture)
{ }
virtual wxEvent *Clone() const { return new wxMouseCaptureChangedEvent(*this); }
wxWindow* GetCapturedWindow() const { return m_gainedCapture; }
private:
wxWindow* m_gainedCapture;
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxMouseCaptureChangedEvent)
};
/*
wxEVT_MOUSE_CAPTURE_LOST
The window losing the capture receives this message, unless it released it
it itself or unless wxWindow::CaptureMouse was called on another window
(and so capture will be restored when the new capturer releases it).
*/
class WXDLLIMPEXP_CORE wxMouseCaptureLostEvent : public wxEvent
{
public:
wxMouseCaptureLostEvent(wxWindowID winid = 0)
: wxEvent(winid, wxEVT_MOUSE_CAPTURE_LOST)
{}
wxMouseCaptureLostEvent(const wxMouseCaptureLostEvent& event)
: wxEvent(event)
{}
virtual wxEvent *Clone() const { return new wxMouseCaptureLostEvent(*this); }
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxMouseCaptureLostEvent)
};
/*
wxEVT_DISPLAY_CHANGED
*/
class WXDLLIMPEXP_CORE wxDisplayChangedEvent : public wxEvent
{
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxDisplayChangedEvent)
public:
wxDisplayChangedEvent()
: wxEvent(0, wxEVT_DISPLAY_CHANGED)
{ }
virtual wxEvent *Clone() const { return new wxDisplayChangedEvent(*this); }
};
/*
wxEVT_PALETTE_CHANGED
*/
class WXDLLIMPEXP_CORE wxPaletteChangedEvent : public wxEvent
{
public:
wxPaletteChangedEvent(wxWindowID winid = 0)
: wxEvent(winid, wxEVT_PALETTE_CHANGED),
m_changedWindow((wxWindow *) NULL)
{ }
wxPaletteChangedEvent(const wxPaletteChangedEvent& event)
: wxEvent(event),
m_changedWindow(event.m_changedWindow)
{ }
void SetChangedWindow(wxWindow* win) { m_changedWindow = win; }
wxWindow* GetChangedWindow() const { return m_changedWindow; }
virtual wxEvent *Clone() const { return new wxPaletteChangedEvent(*this); }
protected:
wxWindow* m_changedWindow;
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxPaletteChangedEvent)
};
/*
wxEVT_QUERY_NEW_PALETTE
Indicates the window is getting keyboard focus and should re-do its palette.
*/
class WXDLLIMPEXP_CORE wxQueryNewPaletteEvent : public wxEvent
{
public:
wxQueryNewPaletteEvent(wxWindowID winid = 0)
: wxEvent(winid, wxEVT_QUERY_NEW_PALETTE),
m_paletteRealized(false)
{ }
wxQueryNewPaletteEvent(const wxQueryNewPaletteEvent & event)
: wxEvent(event),
m_paletteRealized(event.m_paletteRealized)
{ }
// App sets this if it changes the palette.
void SetPaletteRealized(bool realized) { m_paletteRealized = realized; }
bool GetPaletteRealized() const { return m_paletteRealized; }
virtual wxEvent *Clone() const { return new wxQueryNewPaletteEvent(*this); }
protected:
bool m_paletteRealized;
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxQueryNewPaletteEvent)
};
/*
Event generated by dialog navigation keys
wxEVT_NAVIGATION_KEY
*/
// NB: don't derive from command event to avoid being propagated to the parent
class WXDLLIMPEXP_CORE wxNavigationKeyEvent : public wxEvent
{
public:
wxNavigationKeyEvent()
: wxEvent(0, wxEVT_NAVIGATION_KEY),
m_flags(IsForward | FromTab), // defaults are for TAB
m_focus((wxWindow *)NULL)
{
m_propagationLevel = wxEVENT_PROPAGATE_NONE;
}
wxNavigationKeyEvent(const wxNavigationKeyEvent& event)
: wxEvent(event),
m_flags(event.m_flags),
m_focus(event.m_focus)
{ }
// direction: forward (true) or backward (false)
bool GetDirection() const
{ return (m_flags & IsForward) != 0; }
void SetDirection(bool bForward)
{ if ( bForward ) m_flags |= IsForward; else m_flags &= ~IsForward; }
// it may be a window change event (MDI, notebook pages...) or a control
// change event
bool IsWindowChange() const
{ return (m_flags & WinChange) != 0; }
void SetWindowChange(bool bIs)
{ if ( bIs ) m_flags |= WinChange; else m_flags &= ~WinChange; }
// Set to true under MSW if the event was generated using the tab key.
// This is required for proper navogation over radio buttons
bool IsFromTab() const
{ return (m_flags & FromTab) != 0; }
void SetFromTab(bool bIs)
{ if ( bIs ) m_flags |= FromTab; else m_flags &= ~FromTab; }
// the child which has the focus currently (may be NULL - use
// wxWindow::FindFocus then)
wxWindow* GetCurrentFocus() const { return m_focus; }
void SetCurrentFocus(wxWindow *win) { m_focus = win; }
// Set flags
void SetFlags(long flags) { m_flags = flags; }
virtual wxEvent *Clone() const { return new wxNavigationKeyEvent(*this); }
enum
{
IsBackward = 0x0000,
IsForward = 0x0001,
WinChange = 0x0002,
FromTab = 0x0004
};
long m_flags;
wxWindow *m_focus;
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxNavigationKeyEvent)
};
// Window creation/destruction events: the first is sent as soon as window is
// created (i.e. the underlying GUI object exists), but when the C++ object is
// fully initialized (so virtual functions may be called). The second,
// wxEVT_DESTROY, is sent right before the window is destroyed - again, it's
// still safe to call virtual functions at this moment
/*
wxEVT_CREATE
wxEVT_DESTROY
*/
class WXDLLIMPEXP_CORE wxWindowCreateEvent : public wxCommandEvent
{
public:
wxWindowCreateEvent(wxWindow *win = NULL);
wxWindow *GetWindow() const { return (wxWindow *)GetEventObject(); }
virtual wxEvent *Clone() const { return new wxWindowCreateEvent(*this); }
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxWindowCreateEvent)
};
class WXDLLIMPEXP_CORE wxWindowDestroyEvent : public wxCommandEvent
{
public:
wxWindowDestroyEvent(wxWindow *win = NULL);
wxWindow *GetWindow() const { return (wxWindow *)GetEventObject(); }
virtual wxEvent *Clone() const { return new wxWindowDestroyEvent(*this); }
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxWindowDestroyEvent)
};
// A help event is sent when the user clicks on a window in context-help mode.
/*
wxEVT_HELP
wxEVT_DETAILED_HELP
*/
class WXDLLIMPEXP_CORE wxHelpEvent : public wxCommandEvent
{
public:
// how was this help event generated?
enum Origin
{
Origin_Unknown, // unrecognized event source
Origin_Keyboard, // event generated from F1 key press
Origin_HelpButton // event from [?] button on the title bar (Windows)
};
wxHelpEvent(wxEventType type = wxEVT_NULL,
wxWindowID winid = 0,
const wxPoint& pt = wxDefaultPosition,
Origin origin = Origin_Unknown)
: wxCommandEvent(type, winid),
m_pos(pt),
m_origin(GuessOrigin(origin))
{ }
wxHelpEvent(const wxHelpEvent & event)
: wxCommandEvent(event),
m_pos(event.m_pos),
m_target(event.m_target),
m_link(event.m_link),
m_origin(event.m_origin)
{ }
// Position of event (in screen coordinates)
const wxPoint& GetPosition() const { return m_pos; }
void SetPosition(const wxPoint& pos) { m_pos = pos; }
// Optional link to further help
const wxString& GetLink() const { return m_link; }
void SetLink(const wxString& link) { m_link = link; }
// Optional target to display help in. E.g. a window specification
const wxString& GetTarget() const { return m_target; }
void SetTarget(const wxString& target) { m_target = target; }
virtual wxEvent *Clone() const { return new wxHelpEvent(*this); }
// optional indication of the event source
Origin GetOrigin() const { return m_origin; }
void SetOrigin(Origin origin) { m_origin = origin; }
protected:
wxPoint m_pos;
wxString m_target;
wxString m_link;
Origin m_origin;
// we can try to guess the event origin ourselves, even if none is
// specified in the ctor
static Origin GuessOrigin(Origin origin);
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxHelpEvent)
};
// A Clipboard Text event is sent when a window intercepts text copy/cut/paste
// message, i.e. the user has cut/copied/pasted data from/into a text control
// via ctrl-C/X/V, ctrl/shift-del/insert, a popup menu command, etc.
// NOTE : under windows these events are *NOT* generated automatically
// for a Rich Edit text control.
/*
wxEVT_COMMAND_TEXT_COPY
wxEVT_COMMAND_TEXT_CUT
wxEVT_COMMAND_TEXT_PASTE
*/
class WXDLLIMPEXP_CORE wxClipboardTextEvent : public wxCommandEvent
{
public:
wxClipboardTextEvent(wxEventType type = wxEVT_NULL,
wxWindowID winid = 0)
: wxCommandEvent(type, winid)
{ }
wxClipboardTextEvent(const wxClipboardTextEvent & event)
: wxCommandEvent(event)
{ }
virtual wxEvent *Clone() const { return new wxClipboardTextEvent(*this); }
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxClipboardTextEvent)
};
// A Context event is sent when the user right clicks on a window or
// presses Shift-F10
// NOTE : Under windows this is a repackaged WM_CONTETXMENU message
// Under other systems it may have to be generated from a right click event
/*
wxEVT_CONTEXT_MENU
*/
class WXDLLIMPEXP_CORE wxContextMenuEvent : public wxCommandEvent
{
public:
wxContextMenuEvent(wxEventType type = wxEVT_NULL,
wxWindowID winid = 0,
const wxPoint& pt = wxDefaultPosition)
: wxCommandEvent(type, winid),
m_pos(pt)
{ }
wxContextMenuEvent(const wxContextMenuEvent & event)
: wxCommandEvent(event),
m_pos(event.m_pos)
{ }
// Position of event (in screen coordinates)
const wxPoint& GetPosition() const { return m_pos; }
void SetPosition(const wxPoint& pos) { m_pos = pos; }
virtual wxEvent *Clone() const { return new wxContextMenuEvent(*this); }
protected:
wxPoint m_pos;
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxContextMenuEvent)
};
// Idle event
/*
wxEVT_IDLE
*/
// Whether to always send idle events to windows, or
// to only send update events to those with the
// wxWS_EX_PROCESS_IDLE style.
enum wxIdleMode
{
// Send idle events to all windows
wxIDLE_PROCESS_ALL,
// Send idle events to windows that have
// the wxWS_EX_PROCESS_IDLE flag specified
wxIDLE_PROCESS_SPECIFIED
};
class WXDLLIMPEXP_CORE wxIdleEvent : public wxEvent
{
public:
wxIdleEvent()
: wxEvent(0, wxEVT_IDLE),
m_requestMore(false)
{ }
wxIdleEvent(const wxIdleEvent & event)
: wxEvent(event),
m_requestMore(event.m_requestMore)
{ }
void RequestMore(bool needMore = true) { m_requestMore = needMore; }
bool MoreRequested() const { return m_requestMore; }
virtual wxEvent *Clone() const { return new wxIdleEvent(*this); }
// Specify how wxWidgets will send idle events: to
// all windows, or only to those which specify that they
// will process the events.
static void SetMode(wxIdleMode mode) { sm_idleMode = mode; }
// Returns the idle event mode
static wxIdleMode GetMode() { return sm_idleMode; }
// Can we send an idle event?
static bool CanSend(wxWindow* win);
protected:
bool m_requestMore;
static wxIdleMode sm_idleMode;
private:
DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxIdleEvent)
};
#endif // wxUSE_GUI
/* TODO
wxEVT_MOUSE_CAPTURE_CHANGED,
wxEVT_SETTING_CHANGED, // WM_WININICHANGE (NT) / WM_SETTINGCHANGE (Win95)
// wxEVT_FONT_CHANGED, // WM_FONTCHANGE: roll into wxEVT_SETTING_CHANGED, but remember to propagate
// wxEVT_FONT_CHANGED to all other windows (maybe).
wxEVT_DRAW_ITEM, // Leave these three as virtual functions in wxControl?? Platform-specific.
wxEVT_MEASURE_ITEM,
wxEVT_COMPARE_ITEM
*/
// ============================================================================
// event handler and related classes
// ============================================================================
// for backwards compatibility and to prevent eVC 4 for ARM from crashing with
// internal compiler error when compiling wx, we define wxObjectEventFunction
// as a wxObject method even though it can only be a wxEvtHandler one
typedef void (wxObject::*wxObjectEventFunction)(wxEvent&);
// we can't have ctors nor base struct in backwards compatibility mode or
// otherwise we won't be able to initialize the objects with an agregate, so
// we have to keep both versions
#if WXWIN_COMPATIBILITY_EVENT_TYPES
struct WXDLLIMPEXP_BASE wxEventTableEntry
{
// For some reason, this can't be wxEventType, or VC++ complains.
int m_eventType; // main event type
int m_id; // control/menu/toolbar id
int m_lastId; // used for ranges of ids
wxObjectEventFunction m_fn; // function to call: not wxEventFunction,
// because of dependency problems
wxObject* m_callbackUserData;
};
#else // !WXWIN_COMPATIBILITY_EVENT_TYPES
// struct containing the members common to static and dynamic event tables
// entries
struct WXDLLIMPEXP_BASE wxEventTableEntryBase
{
private:
wxEventTableEntryBase& operator=(const wxEventTableEntryBase& event);
public:
wxEventTableEntryBase(int winid, int idLast,
wxObjectEventFunction fn, wxObject *data)
: m_id(winid),
m_lastId(idLast),
m_fn(fn),
m_callbackUserData(data)
{ }
wxEventTableEntryBase(const wxEventTableEntryBase& event)
: m_id(event.m_id),
m_lastId(event.m_lastId),
m_fn(event.m_fn),
m_callbackUserData(event.m_callbackUserData)
{ }
// the range of ids for this entry: if m_lastId == wxID_ANY, the range
// consists only of m_id, otherwise it is m_id..m_lastId inclusive
int m_id,
m_lastId;
// function to call: not wxEventFunction, because of dependency problems
wxObjectEventFunction m_fn;
// arbitrary user data asosciated with the callback
wxObject* m_callbackUserData;
};
// an entry from a static event table
struct WXDLLIMPEXP_BASE wxEventTableEntry : public wxEventTableEntryBase
{
wxEventTableEntry(const int& evType, int winid, int idLast,
wxObjectEventFunction fn, wxObject *data)
: wxEventTableEntryBase(winid, idLast, fn, data),
m_eventType(evType)
{ }
// the reference to event type: this allows us to not care about the
// (undefined) order in which the event table entries and the event types
// are initialized: initially the value of this reference might be
// invalid, but by the time it is used for the first time, all global
// objects will have been initialized (including the event type constants)
// and so it will have the correct value when it is needed
const int& m_eventType;
private:
wxEventTableEntry& operator=(const wxEventTableEntry&);
};
// an entry used in dynamic event table managed by wxEvtHandler::Connect()
struct WXDLLIMPEXP_BASE wxDynamicEventTableEntry : public wxEventTableEntryBase
{
wxDynamicEventTableEntry(int evType, int winid, int idLast,
wxObjectEventFunction fn, wxObject *data, wxEvtHandler* eventSink)
: wxEventTableEntryBase(winid, idLast, fn, data),
m_eventType(evType),
m_eventSink(eventSink)
{ }
// not a reference here as we can't keep a reference to a temporary int
// created to wrap the constant value typically passed to Connect() - nor
// do we need it
int m_eventType;
// Pointer to object whose function is fn - so we don't assume the
// EventFunction is always a member of the EventHandler receiving the
// message
wxEvtHandler* m_eventSink;
DECLARE_NO_COPY_CLASS(wxDynamicEventTableEntry)
};
#endif // !WXWIN_COMPATIBILITY_EVENT_TYPES
// ----------------------------------------------------------------------------
// wxEventTable: an array of event entries terminated with {0, 0, 0, 0, 0}
// ----------------------------------------------------------------------------
struct WXDLLIMPEXP_BASE wxEventTable
{
const wxEventTable *baseTable; // base event table (next in chain)
const wxEventTableEntry *entries; // bottom of entry array
};
// ----------------------------------------------------------------------------
// wxEventHashTable: a helper of wxEvtHandler to speed up wxEventTable lookups.
// ----------------------------------------------------------------------------
WX_DEFINE_ARRAY_PTR(const wxEventTableEntry*, wxEventTableEntryPointerArray);
class WXDLLIMPEXP_BASE wxEventHashTable
{
private:
// Internal data structs
struct EventTypeTable
{
wxEventType eventType;
wxEventTableEntryPointerArray eventEntryTable;
};
typedef EventTypeTable* EventTypeTablePointer;
public:
// Constructor, needs the event table it needs to hash later on.
// Note: hashing of the event table is not done in the constructor as it
// can be that the event table is not yet full initialize, the hash
// will gets initialized when handling the first event look-up request.
wxEventHashTable(const wxEventTable &table);
// Destructor.
~wxEventHashTable();
// Handle the given event, in other words search the event table hash
// and call self->ProcessEvent() if a match was found.
bool HandleEvent(wxEvent &event, wxEvtHandler *self);
// Clear table
void Clear();
// Clear all tables
static void ClearAll();
// Rebuild all tables
static void ReconstructAll();
protected:
// Init the hash table with the entries of the static event table.
void InitHashTable();
// Helper funtion of InitHashTable() to insert 1 entry into the hash table.
void AddEntry(const wxEventTableEntry &entry);
// Allocate and init with null pointers the base hash table.
void AllocEventTypeTable(size_t size);
// Grow the hash table in size and transfer all items currently
// in the table to the correct location in the new table.
void GrowEventTypeTable();
protected:
const wxEventTable &m_table;
bool m_rebuildHash;
size_t m_size;
EventTypeTablePointer *m_eventTypeTable;
static wxEventHashTable* sm_first;
wxEventHashTable* m_previous;
wxEventHashTable* m_next;
DECLARE_NO_COPY_CLASS(wxEventHashTable)
};
// ----------------------------------------------------------------------------
// wxEvtHandler: the base class for all objects handling wxWidgets events
// ----------------------------------------------------------------------------
class WXDLLIMPEXP_BASE wxEvtHandler : public wxObject
{
public:
wxEvtHandler();
virtual ~wxEvtHandler();
wxEvtHandler *GetNextHandler() const { return m_nextHandler; }
wxEvtHandler *GetPreviousHandler() const { return m_previousHandler; }
void SetNextHandler(wxEvtHandler *handler) { m_nextHandler = handler; }
void SetPreviousHandler(wxEvtHandler *handler) { m_previousHandler = handler; }
void SetEvtHandlerEnabled(bool enabled) { m_enabled = enabled; }
bool GetEvtHandlerEnabled() const { return m_enabled; }
// process an event right now
virtual bool ProcessEvent(wxEvent& event);
// add an event to be processed later
void AddPendingEvent(wxEvent& event);
void ProcessPendingEvents();
#if wxUSE_THREADS
bool ProcessThreadEvent(wxEvent& event);
#endif
// Dynamic association of a member function handler with the event handler,
// winid and event type
void Connect(int winid,
int lastId,
int eventType,
wxObjectEventFunction func,
wxObject *userData = (wxObject *) NULL,
wxEvtHandler *eventSink = (wxEvtHandler *) NULL);
// Convenience function: take just one id
void Connect(int winid,
int eventType,
wxObjectEventFunction func,
wxObject *userData = (wxObject *) NULL,
wxEvtHandler *eventSink = (wxEvtHandler *) NULL)
{ Connect(winid, wxID_ANY, eventType, func, userData, eventSink); }
// Even more convenient: without id (same as using id of wxID_ANY)
void Connect(int eventType,
wxObjectEventFunction func,
wxObject *userData = (wxObject *) NULL,
wxEvtHandler *eventSink = (wxEvtHandler *) NULL)
{ Connect(wxID_ANY, wxID_ANY, eventType, func, userData, eventSink); }
bool Disconnect(int winid,
int lastId,
wxEventType eventType,
wxObjectEventFunction func = NULL,
wxObject *userData = (wxObject *) NULL,
wxEvtHandler *eventSink = (wxEvtHandler *) NULL);
bool Disconnect(int winid = wxID_ANY,
wxEventType eventType = wxEVT_NULL,
wxObjectEventFunction func = NULL,
wxObject *userData = (wxObject *) NULL,
wxEvtHandler *eventSink = (wxEvtHandler *) NULL)
{ return Disconnect(winid, wxID_ANY, eventType, func, userData, eventSink); }
bool Disconnect(wxEventType eventType,
wxObjectEventFunction func,
wxObject *userData = (wxObject *) NULL,
wxEvtHandler *eventSink = (wxEvtHandler *) NULL)
{ return Disconnect(wxID_ANY, eventType, func, userData, eventSink); }
wxList* GetDynamicEventTable() const { return m_dynamicEvents ; }
// User data can be associated with each wxEvtHandler
void SetClientObject( wxClientData *data ) { DoSetClientObject(data); }
wxClientData *GetClientObject() const { return DoGetClientObject(); }
void SetClientData( void *data ) { DoSetClientData(data); }
void *GetClientData() const { return DoGetClientData(); }
// check if the given event table entry matches this event and call the
// handler if it does
//
// return true if the event was processed, false otherwise (no match or the
// handler decided to skip the event)
static bool ProcessEventIfMatches(const wxEventTableEntryBase& tableEntry,
wxEvtHandler *handler,
wxEvent& event);
// implementation from now on
virtual bool SearchEventTable(wxEventTable& table, wxEvent& event);
bool SearchDynamicEventTable( wxEvent& event );
#if wxUSE_THREADS
void ClearEventLocker();
#endif // wxUSE_THREADS
// Avoid problems at exit by cleaning up static hash table gracefully
void ClearEventHashTable() { GetEventHashTable().Clear(); }
private:
static const wxEventTableEntry sm_eventTableEntries[];
protected:
// hooks for wxWindow used by ProcessEvent()
// -----------------------------------------
// This one is called before trying our own event table to allow plugging
// in the validators.
//
// NB: This method is intentionally *not* inside wxUSE_VALIDATORS!
// It is part of wxBase which doesn't use validators and the code
// is compiled out when building wxBase w/o GUI classes, which affects
// binary compatibility and wxBase library can't be used by GUI
// ports.
virtual bool TryValidator(wxEvent& WXUNUSED(event)) { return false; }
// this one is called after failing to find the event handle in our own
// table to give a chance to the other windows to process it
//
// base class implementation passes the event to wxTheApp
virtual bool TryParent(wxEvent& event);
static const wxEventTable sm_eventTable;
virtual const wxEventTable *GetEventTable() const;
static wxEventHashTable sm_eventHashTable;
virtual wxEventHashTable& GetEventHashTable() const;
wxEvtHandler* m_nextHandler;
wxEvtHandler* m_previousHandler;
wxList* m_dynamicEvents;
wxList* m_pendingEvents;
#if wxUSE_THREADS
#if defined (__VISAGECPP__)
const wxCriticalSection& Lock() const { return m_eventsLocker; }
wxCriticalSection& Lock() { return m_eventsLocker; }
wxCriticalSection m_eventsLocker;
# else
const wxCriticalSection& Lock() const { return *m_eventsLocker; }
wxCriticalSection& Lock() { return *m_eventsLocker; }
wxCriticalSection* m_eventsLocker;
# endif
#endif
// Is event handler enabled?
bool m_enabled;
// The user data: either an object which will be deleted by the container
// when it's deleted or some raw pointer which we do nothing with - only
// one type of data can be used with the given window (i.e. you cannot set
// the void data and then associate the container with wxClientData or vice
// versa)
union
{
wxClientData *m_clientObject;
void *m_clientData;
};
// what kind of data do we have?
wxClientDataType m_clientDataType;
// client data accessors
virtual void DoSetClientObject( wxClientData *data );
virtual wxClientData *DoGetClientObject() const;
virtual void DoSetClientData( void *data );
virtual void *DoGetClientData() const;
private:
DECLARE_DYNAMIC_CLASS_NO_COPY(wxEvtHandler)
};
// Post a message to the given eventhandler which will be processed during the
// next event loop iteration
inline void wxPostEvent(wxEvtHandler *dest, wxEvent& event)
{
wxCHECK_RET( dest, wxT("need an object to post event to in wxPostEvent") );
dest->AddPendingEvent(event);
}
typedef void (wxEvtHandler::*wxEventFunction)(wxEvent&);
#define wxEventHandler(func) \
(wxObjectEventFunction)wxStaticCastEvent(wxEventFunction, &func)
#if wxUSE_GUI
typedef void (wxEvtHandler::*wxCommandEventFunction)(wxCommandEvent&);
typedef void (wxEvtHandler::*wxScrollEventFunction)(wxScrollEvent&);
typedef void (wxEvtHandler::*wxScrollWinEventFunction)(wxScrollWinEvent&);
typedef void (wxEvtHandler::*wxSizeEventFunction)(wxSizeEvent&);
typedef void (wxEvtHandler::*wxMoveEventFunction)(wxMoveEvent&);
typedef void (wxEvtHandler::*wxPaintEventFunction)(wxPaintEvent&);
typedef void (wxEvtHandler::*wxNcPaintEventFunction)(wxNcPaintEvent&);
typedef void (wxEvtHandler::*wxEraseEventFunction)(wxEraseEvent&);
typedef void (wxEvtHandler::*wxMouseEventFunction)(wxMouseEvent&);
typedef void (wxEvtHandler::*wxCharEventFunction)(wxKeyEvent&);
typedef void (wxEvtHandler::*wxFocusEventFunction)(wxFocusEvent&);
typedef void (wxEvtHandler::*wxChildFocusEventFunction)(wxChildFocusEvent&);
typedef void (wxEvtHandler::*wxActivateEventFunction)(wxActivateEvent&);
typedef void (wxEvtHandler::*wxMenuEventFunction)(wxMenuEvent&);
typedef void (wxEvtHandler::*wxJoystickEventFunction)(wxJoystickEvent&);
typedef void (wxEvtHandler::*wxDropFilesEventFunction)(wxDropFilesEvent&);
typedef void (wxEvtHandler::*wxInitDialogEventFunction)(wxInitDialogEvent&);
typedef void (wxEvtHandler::*wxSysColourChangedEventFunction)(wxSysColourChangedEvent&);
typedef void (wxEvtHandler::*wxDisplayChangedEventFunction)(wxDisplayChangedEvent&);
typedef void (wxEvtHandler::*wxUpdateUIEventFunction)(wxUpdateUIEvent&);
typedef void (wxEvtHandler::*wxIdleEventFunction)(wxIdleEvent&);
typedef void (wxEvtHandler::*wxCloseEventFunction)(wxCloseEvent&);
typedef void (wxEvtHandler::*wxShowEventFunction)(wxShowEvent&);
typedef void (wxEvtHandler::*wxIconizeEventFunction)(wxIconizeEvent&);
typedef void (wxEvtHandler::*wxMaximizeEventFunction)(wxMaximizeEvent&);
typedef void (wxEvtHandler::*wxNavigationKeyEventFunction)(wxNavigationKeyEvent&);
typedef void (wxEvtHandler::*wxPaletteChangedEventFunction)(wxPaletteChangedEvent&);
typedef void (wxEvtHandler::*wxQueryNewPaletteEventFunction)(wxQueryNewPaletteEvent&);
typedef void (wxEvtHandler::*wxWindowCreateEventFunction)(wxWindowCreateEvent&);
typedef void (wxEvtHandler::*wxWindowDestroyEventFunction)(wxWindowDestroyEvent&);
typedef void (wxEvtHandler::*wxSetCursorEventFunction)(wxSetCursorEvent&);
typedef void (wxEvtHandler::*wxNotifyEventFunction)(wxNotifyEvent&);
typedef void (wxEvtHandler::*wxHelpEventFunction)(wxHelpEvent&);
typedef void (wxEvtHandler::*wxContextMenuEventFunction)(wxContextMenuEvent&);
typedef void (wxEvtHandler::*wxMouseCaptureChangedEventFunction)(wxMouseCaptureChangedEvent&);
typedef void (wxEvtHandler::*wxMouseCaptureLostEventFunction)(wxMouseCaptureLostEvent&);
typedef void (wxEvtHandler::*wxClipboardTextEventFunction)(wxClipboardTextEvent&);
// these typedefs don't have the same name structure as the others, keep for
// backwards compatibility only
#if WXWIN_COMPATIBILITY_2_4
typedef wxSysColourChangedEventFunction wxSysColourChangedFunction;
typedef wxDisplayChangedEventFunction wxDisplayChangedFunction;
#endif // WXWIN_COMPATIBILITY_2_4
#define wxCommandEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxCommandEventFunction, &func)
#define wxScrollEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxScrollEventFunction, &func)
#define wxScrollWinEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxScrollWinEventFunction, &func)
#define wxSizeEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxSizeEventFunction, &func)
#define wxMoveEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxMoveEventFunction, &func)
#define wxPaintEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxPaintEventFunction, &func)
#define wxNcPaintEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxNcPaintEventFunction, &func)
#define wxEraseEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxEraseEventFunction, &func)
#define wxMouseEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxMouseEventFunction, &func)
#define wxCharEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxCharEventFunction, &func)
#define wxKeyEventHandler(func) wxCharEventHandler(func)
#define wxFocusEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxFocusEventFunction, &func)
#define wxChildFocusEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxChildFocusEventFunction, &func)
#define wxActivateEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxActivateEventFunction, &func)
#define wxMenuEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxMenuEventFunction, &func)
#define wxJoystickEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxJoystickEventFunction, &func)
#define wxDropFilesEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxDropFilesEventFunction, &func)
#define wxInitDialogEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxInitDialogEventFunction, &func)
#define wxSysColourChangedEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxSysColourChangedEventFunction, &func)
#define wxDisplayChangedEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxDisplayChangedEventFunction, &func)
#define wxUpdateUIEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxUpdateUIEventFunction, &func)
#define wxIdleEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxIdleEventFunction, &func)
#define wxCloseEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxCloseEventFunction, &func)
#define wxShowEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxShowEventFunction, &func)
#define wxIconizeEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxIconizeEventFunction, &func)
#define wxMaximizeEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxMaximizeEventFunction, &func)
#define wxNavigationKeyEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxNavigationKeyEventFunction, &func)
#define wxPaletteChangedEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxPaletteChangedEventFunction, &func)
#define wxQueryNewPaletteEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxQueryNewPaletteEventFunction, &func)
#define wxWindowCreateEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxWindowCreateEventFunction, &func)
#define wxWindowDestroyEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxWindowDestroyEventFunction, &func)
#define wxSetCursorEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxSetCursorEventFunction, &func)
#define wxNotifyEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxNotifyEventFunction, &func)
#define wxHelpEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxHelpEventFunction, &func)
#define wxContextMenuEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxContextMenuEventFunction, &func)
#define wxMouseCaptureChangedEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxMouseCaptureChangedEventFunction, &func)
#define wxMouseCaptureLostEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxMouseCaptureLostEventFunction, &func)
#define wxClipboardTextEventHandler(func) \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxClipboardTextEventFunction, &func)
#endif // wxUSE_GUI
// N.B. In GNU-WIN32, you *have* to take the address of a member function
// (use &) or the compiler crashes...
#define DECLARE_EVENT_TABLE() \
private: \
static const wxEventTableEntry sm_eventTableEntries[]; \
protected: \
static const wxEventTable sm_eventTable; \
virtual const wxEventTable* GetEventTable() const; \
static wxEventHashTable sm_eventHashTable; \
virtual wxEventHashTable& GetEventHashTable() const;
// N.B.: when building DLL with Borland C++ 5.5 compiler, you must initialize
// sm_eventTable before using it in GetEventTable() or the compiler gives
// E2233 (see http://groups.google.com/groups?selm=397dcc8a%241_2%40dnews)
#define BEGIN_EVENT_TABLE(theClass, baseClass) \
const wxEventTable theClass::sm_eventTable = \
{ &baseClass::sm_eventTable, &theClass::sm_eventTableEntries[0] }; \
const wxEventTable *theClass::GetEventTable() const \
{ return &theClass::sm_eventTable; } \
wxEventHashTable theClass::sm_eventHashTable(theClass::sm_eventTable); \
wxEventHashTable &theClass::GetEventHashTable() const \
{ return theClass::sm_eventHashTable; } \
const wxEventTableEntry theClass::sm_eventTableEntries[] = { \
#define BEGIN_EVENT_TABLE_TEMPLATE1(theClass, baseClass, T1) \
template<typename T1> \
const wxEventTable theClass<T1>::sm_eventTable = \
{ &baseClass::sm_eventTable, &theClass<T1>::sm_eventTableEntries[0] }; \
template<typename T1> \
const wxEventTable *theClass<T1>::GetEventTable() const \
{ return &theClass<T1>::sm_eventTable; } \
template<typename T1> \
wxEventHashTable theClass<T1>::sm_eventHashTable(theClass<T1>::sm_eventTable); \
template<typename T1> \
wxEventHashTable &theClass<T1>::GetEventHashTable() const \
{ return theClass<T1>::sm_eventHashTable; } \
template<typename T1> \
const wxEventTableEntry theClass<T1>::sm_eventTableEntries[] = { \
#define BEGIN_EVENT_TABLE_TEMPLATE2(theClass, baseClass, T1, T2) \
template<typename T1, typename T2> \
const wxEventTable theClass<T1, T2>::sm_eventTable = \
{ &baseClass::sm_eventTable, &theClass<T1, T2>::sm_eventTableEntries[0] }; \
template<typename T1, typename T2> \
const wxEventTable *theClass<T1, T2>::GetEventTable() const \
{ return &theClass<T1, T2>::sm_eventTable; } \
template<typename T1, typename T2> \
wxEventHashTable theClass<T1, T2>::sm_eventHashTable(theClass<T1, T2>::sm_eventTable); \
template<typename T1, typename T2> \
wxEventHashTable &theClass<T1, T2>::GetEventHashTable() const \
{ return theClass<T1, T2>::sm_eventHashTable; } \
template<typename T1, typename T2> \
const wxEventTableEntry theClass<T1, T2>::sm_eventTableEntries[] = { \
#define BEGIN_EVENT_TABLE_TEMPLATE3(theClass, baseClass, T1, T2, T3) \
template<typename T1, typename T2, typename T3> \
const wxEventTable theClass<T1, T2, T3>::sm_eventTable = \
{ &baseClass::sm_eventTable, &theClass<T1, T2, T3>::sm_eventTableEntries[0] }; \
template<typename T1, typename T2, typename T3> \
const wxEventTable *theClass<T1, T2, T3>::GetEventTable() const \
{ return &theClass<T1, T2, T3>::sm_eventTable; } \
template<typename T1, typename T2, typename T3> \
wxEventHashTable theClass<T1, T2, T3>::sm_eventHashTable(theClass<T1, T2, T3>::sm_eventTable); \
template<typename T1, typename T2, typename T3> \
wxEventHashTable &theClass<T1, T2, T3>::GetEventHashTable() const \
{ return theClass<T1, T2, T3>::sm_eventHashTable; } \
template<typename T1, typename T2, typename T3> \
const wxEventTableEntry theClass<T1, T2, T3>::sm_eventTableEntries[] = { \
#define BEGIN_EVENT_TABLE_TEMPLATE4(theClass, baseClass, T1, T2, T3, T4) \
template<typename T1, typename T2, typename T3, typename T4> \
const wxEventTable theClass<T1, T2, T3, T4>::sm_eventTable = \
{ &baseClass::sm_eventTable, &theClass<T1, T2, T3, T4>::sm_eventTableEntries[0] }; \
template<typename T1, typename T2, typename T3, typename T4> \
const wxEventTable *theClass<T1, T2, T3, T4>::GetEventTable() const \
{ return &theClass<T1, T2, T3, T4>::sm_eventTable; } \
template<typename T1, typename T2, typename T3, typename T4> \
wxEventHashTable theClass<T1, T2, T3, T4>::sm_eventHashTable(theClass<T1, T2, T3, T4>::sm_eventTable); \
template<typename T1, typename T2, typename T3, typename T4> \
wxEventHashTable &theClass<T1, T2, T3, T4>::GetEventHashTable() const \
{ return theClass<T1, T2, T3, T4>::sm_eventHashTable; } \
template<typename T1, typename T2, typename T3, typename T4> \
const wxEventTableEntry theClass<T1, T2, T3, T4>::sm_eventTableEntries[] = { \
#define BEGIN_EVENT_TABLE_TEMPLATE5(theClass, baseClass, T1, T2, T3, T4, T5) \
template<typename T1, typename T2, typename T3, typename T4, typename T5> \
const wxEventTable theClass<T1, T2, T3, T4, T5>::sm_eventTable = \
{ &baseClass::sm_eventTable, &theClass<T1, T2, T3, T4, T5>::sm_eventTableEntries[0] }; \
template<typename T1, typename T2, typename T3, typename T4, typename T5> \
const wxEventTable *theClass<T1, T2, T3, T4, T5>::GetEventTable() const \
{ return &theClass<T1, T2, T3, T4, T5>::sm_eventTable; } \
template<typename T1, typename T2, typename T3, typename T4, typename T5> \
wxEventHashTable theClass<T1, T2, T3, T4, T5>::sm_eventHashTable(theClass<T1, T2, T3, T4, T5>::sm_eventTable); \
template<typename T1, typename T2, typename T3, typename T4, typename T5> \
wxEventHashTable &theClass<T1, T2, T3, T4, T5>::GetEventHashTable() const \
{ return theClass<T1, T2, T3, T4, T5>::sm_eventHashTable; } \
template<typename T1, typename T2, typename T3, typename T4, typename T5> \
const wxEventTableEntry theClass<T1, T2, T3, T4, T5>::sm_eventTableEntries[] = { \
#define BEGIN_EVENT_TABLE_TEMPLATE7(theClass, baseClass, T1, T2, T3, T4, T5, T6, T7) \
template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> \
const wxEventTable theClass<T1, T2, T3, T4, T5, T6, T7>::sm_eventTable = \
{ &baseClass::sm_eventTable, &theClass<T1, T2, T3, T4, T5, T6, T7>::sm_eventTableEntries[0] }; \
template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> \
const wxEventTable *theClass<T1, T2, T3, T4, T5, T6, T7>::GetEventTable() const \
{ return &theClass<T1, T2, T3, T4, T5, T6, T7>::sm_eventTable; } \
template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> \
wxEventHashTable theClass<T1, T2, T3, T4, T5, T6, T7>::sm_eventHashTable(theClass<T1, T2, T3, T4, T5, T6, T7>::sm_eventTable); \
template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> \
wxEventHashTable &theClass<T1, T2, T3, T4, T5, T6, T7>::GetEventHashTable() const \
{ return theClass<T1, T2, T3, T4, T5, T6, T7>::sm_eventHashTable; } \
template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> \
const wxEventTableEntry theClass<T1, T2, T3, T4, T5, T6, T7>::sm_eventTableEntries[] = { \
#define BEGIN_EVENT_TABLE_TEMPLATE8(theClass, baseClass, T1, T2, T3, T4, T5, T6, T7, T8) \
template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> \
const wxEventTable theClass<T1, T2, T3, T4, T5, T6, T7, T8>::sm_eventTable = \
{ &baseClass::sm_eventTable, &theClass<T1, T2, T3, T4, T5, T6, T7, T8>::sm_eventTableEntries[0] }; \
template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> \
const wxEventTable *theClass<T1, T2, T3, T4, T5, T6, T7, T8>::GetEventTable() const \
{ return &theClass<T1, T2, T3, T4, T5, T6, T7, T8>::sm_eventTable; } \
template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> \
wxEventHashTable theClass<T1, T2, T3, T4, T5, T6, T7, T8>::sm_eventHashTable(theClass<T1, T2, T3, T4, T5, T6, T7, T8>::sm_eventTable); \
template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> \
wxEventHashTable &theClass<T1, T2, T3, T4, T5, T6, T7, T8>::GetEventHashTable() const \
{ return theClass<T1, T2, T3, T4, T5, T6, T7, T8>::sm_eventHashTable; } \
template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> \
const wxEventTableEntry theClass<T1, T2, T3, T4, T5, T6, T7, T8>::sm_eventTableEntries[] = { \
#define END_EVENT_TABLE() DECLARE_EVENT_TABLE_ENTRY( wxEVT_NULL, 0, 0, 0, 0 ) };
/*
* Event table macros
*/
// helpers for writing shorter code below: declare an event macro taking 2, 1
// or none ids (the missing ids default to wxID_ANY)
//
// macro arguments:
// - evt one of wxEVT_XXX constants
// - id1, id2 ids of the first/last id
// - fn the function (should be cast to the right type)
#define wx__DECLARE_EVT2(evt, id1, id2, fn) \
DECLARE_EVENT_TABLE_ENTRY(evt, id1, id2, fn, NULL),
#define wx__DECLARE_EVT1(evt, id, fn) \
wx__DECLARE_EVT2(evt, id, wxID_ANY, fn)
#define wx__DECLARE_EVT0(evt, fn) \
wx__DECLARE_EVT1(evt, wxID_ANY, fn)
// Generic events
#define EVT_CUSTOM(event, winid, func) \
wx__DECLARE_EVT1(event, winid, wxEventHandler(func))
#define EVT_CUSTOM_RANGE(event, id1, id2, func) \
wx__DECLARE_EVT2(event, id1, id2, wxEventHandler(func))
// EVT_COMMAND
#define EVT_COMMAND(winid, event, func) \
wx__DECLARE_EVT1(event, winid, wxCommandEventHandler(func))
#define EVT_COMMAND_RANGE(id1, id2, event, func) \
wx__DECLARE_EVT2(event, id1, id2, wxCommandEventHandler(func))
#define EVT_NOTIFY(event, winid, func) \
wx__DECLARE_EVT1(event, winid, wxNotifyEventHandler(func))
#define EVT_NOTIFY_RANGE(event, id1, id2, func) \
wx__DECLARE_EVT2(event, id1, id2, wxNotifyEventHandler(func))
// Miscellaneous
#define EVT_SIZE(func) wx__DECLARE_EVT0(wxEVT_SIZE, wxSizeEventHandler(func))
#define EVT_SIZING(func) wx__DECLARE_EVT0(wxEVT_SIZING, wxSizeEventHandler(func))
#define EVT_MOVE(func) wx__DECLARE_EVT0(wxEVT_MOVE, wxMoveEventHandler(func))
#define EVT_MOVING(func) wx__DECLARE_EVT0(wxEVT_MOVING, wxMoveEventHandler(func))
#define EVT_CLOSE(func) wx__DECLARE_EVT0(wxEVT_CLOSE_WINDOW, wxCloseEventHandler(func))
#define EVT_END_SESSION(func) wx__DECLARE_EVT0(wxEVT_END_SESSION, wxCloseEventHandler(func))
#define EVT_QUERY_END_SESSION(func) wx__DECLARE_EVT0(wxEVT_QUERY_END_SESSION, wxCloseEventHandler(func))
#define EVT_PAINT(func) wx__DECLARE_EVT0(wxEVT_PAINT, wxPaintEventHandler(func))
#define EVT_NC_PAINT(func) wx__DECLARE_EVT0(wxEVT_NC_PAINT, wxNcPaintEventHandler(func))
#define EVT_ERASE_BACKGROUND(func) wx__DECLARE_EVT0(wxEVT_ERASE_BACKGROUND, wxEraseEventHandler(func))
#define EVT_CHAR(func) wx__DECLARE_EVT0(wxEVT_CHAR, wxCharEventHandler(func))
#define EVT_KEY_DOWN(func) wx__DECLARE_EVT0(wxEVT_KEY_DOWN, wxKeyEventHandler(func))
#define EVT_KEY_UP(func) wx__DECLARE_EVT0(wxEVT_KEY_UP, wxKeyEventHandler(func))
#if wxUSE_HOTKEY
#define EVT_HOTKEY(winid, func) wx__DECLARE_EVT1(wxEVT_HOTKEY, winid, wxCharEventHandler(func))
#endif
#define EVT_CHAR_HOOK(func) wx__DECLARE_EVT0(wxEVT_CHAR_HOOK, wxCharEventHandler(func))
#define EVT_MENU_OPEN(func) wx__DECLARE_EVT0(wxEVT_MENU_OPEN, wxMenuEventHandler(func))
#define EVT_MENU_CLOSE(func) wx__DECLARE_EVT0(wxEVT_MENU_CLOSE, wxMenuEventHandler(func))
#define EVT_MENU_HIGHLIGHT(winid, func) wx__DECLARE_EVT1(wxEVT_MENU_HIGHLIGHT, winid, wxMenuEventHandler(func))
#define EVT_MENU_HIGHLIGHT_ALL(func) wx__DECLARE_EVT0(wxEVT_MENU_HIGHLIGHT, wxMenuEventHandler(func))
#define EVT_SET_FOCUS(func) wx__DECLARE_EVT0(wxEVT_SET_FOCUS, wxFocusEventHandler(func))
#define EVT_KILL_FOCUS(func) wx__DECLARE_EVT0(wxEVT_KILL_FOCUS, wxFocusEventHandler(func))
#define EVT_CHILD_FOCUS(func) wx__DECLARE_EVT0(wxEVT_CHILD_FOCUS, wxChildFocusEventHandler(func))
#define EVT_ACTIVATE(func) wx__DECLARE_EVT0(wxEVT_ACTIVATE, wxActivateEventHandler(func))
#define EVT_ACTIVATE_APP(func) wx__DECLARE_EVT0(wxEVT_ACTIVATE_APP, wxActivateEventHandler(func))
#define EVT_HIBERNATE(func) wx__DECLARE_EVT0(wxEVT_HIBERNATE, wxActivateEventHandler(func))
#define EVT_END_SESSION(func) wx__DECLARE_EVT0(wxEVT_END_SESSION, wxCloseEventHandler(func))
#define EVT_QUERY_END_SESSION(func) wx__DECLARE_EVT0(wxEVT_QUERY_END_SESSION, wxCloseEventHandler(func))
#define EVT_DROP_FILES(func) wx__DECLARE_EVT0(wxEVT_DROP_FILES, wxDropFilesEventHandler(func))
#define EVT_INIT_DIALOG(func) wx__DECLARE_EVT0(wxEVT_INIT_DIALOG, wxInitDialogEventHandler(func))
#define EVT_SYS_COLOUR_CHANGED(func) wx__DECLARE_EVT0(wxEVT_SYS_COLOUR_CHANGED, wxSysColourChangedEventHandler(func))
#define EVT_DISPLAY_CHANGED(func) wx__DECLARE_EVT0(wxEVT_DISPLAY_CHANGED, wxDisplayChangedEventHandler(func))
#define EVT_SHOW(func) wx__DECLARE_EVT0(wxEVT_SHOW, wxShowEventHandler(func))
#define EVT_MAXIMIZE(func) wx__DECLARE_EVT0(wxEVT_MAXIMIZE, wxMaximizeEventHandler(func))
#define EVT_ICONIZE(func) wx__DECLARE_EVT0(wxEVT_ICONIZE, wxIconizeEventHandler(func))
#define EVT_NAVIGATION_KEY(func) wx__DECLARE_EVT0(wxEVT_NAVIGATION_KEY, wxNavigationKeyEventHandler(func))
#define EVT_PALETTE_CHANGED(func) wx__DECLARE_EVT0(wxEVT_PALETTE_CHANGED, wxPaletteChangedEventHandler(func))
#define EVT_QUERY_NEW_PALETTE(func) wx__DECLARE_EVT0(wxEVT_QUERY_NEW_PALETTE, wxQueryNewPaletteEventHandler(func))
#define EVT_WINDOW_CREATE(func) wx__DECLARE_EVT0(wxEVT_CREATE, wxWindowCreateEventHandler(func))
#define EVT_WINDOW_DESTROY(func) wx__DECLARE_EVT0(wxEVT_DESTROY, wxWindowDestroyEventHandler(func))
#define EVT_SET_CURSOR(func) wx__DECLARE_EVT0(wxEVT_SET_CURSOR, wxSetCursorEventHandler(func))
#define EVT_MOUSE_CAPTURE_CHANGED(func) wx__DECLARE_EVT0(wxEVT_MOUSE_CAPTURE_CHANGED, wxMouseCaptureChangedEventHandler(func))
#define EVT_MOUSE_CAPTURE_LOST(func) wx__DECLARE_EVT0(wxEVT_MOUSE_CAPTURE_LOST, wxMouseCaptureLostEventHandler(func))
// Mouse events
#define EVT_LEFT_DOWN(func) wx__DECLARE_EVT0(wxEVT_LEFT_DOWN, wxMouseEventHandler(func))
#define EVT_LEFT_UP(func) wx__DECLARE_EVT0(wxEVT_LEFT_UP, wxMouseEventHandler(func))
#define EVT_MIDDLE_DOWN(func) wx__DECLARE_EVT0(wxEVT_MIDDLE_DOWN, wxMouseEventHandler(func))
#define EVT_MIDDLE_UP(func) wx__DECLARE_EVT0(wxEVT_MIDDLE_UP, wxMouseEventHandler(func))
#define EVT_RIGHT_DOWN(func) wx__DECLARE_EVT0(wxEVT_RIGHT_DOWN, wxMouseEventHandler(func))
#define EVT_RIGHT_UP(func) wx__DECLARE_EVT0(wxEVT_RIGHT_UP, wxMouseEventHandler(func))
#define EVT_MOTION(func) wx__DECLARE_EVT0(wxEVT_MOTION, wxMouseEventHandler(func))
#define EVT_LEFT_DCLICK(func) wx__DECLARE_EVT0(wxEVT_LEFT_DCLICK, wxMouseEventHandler(func))
#define EVT_MIDDLE_DCLICK(func) wx__DECLARE_EVT0(wxEVT_MIDDLE_DCLICK, wxMouseEventHandler(func))
#define EVT_RIGHT_DCLICK(func) wx__DECLARE_EVT0(wxEVT_RIGHT_DCLICK, wxMouseEventHandler(func))
#define EVT_LEAVE_WINDOW(func) wx__DECLARE_EVT0(wxEVT_LEAVE_WINDOW, wxMouseEventHandler(func))
#define EVT_ENTER_WINDOW(func) wx__DECLARE_EVT0(wxEVT_ENTER_WINDOW, wxMouseEventHandler(func))
#define EVT_MOUSEWHEEL(func) wx__DECLARE_EVT0(wxEVT_MOUSEWHEEL, wxMouseEventHandler(func))
// All mouse events
#define EVT_MOUSE_EVENTS(func) \
EVT_LEFT_DOWN(func) \
EVT_LEFT_UP(func) \
EVT_MIDDLE_DOWN(func) \
EVT_MIDDLE_UP(func) \
EVT_RIGHT_DOWN(func) \
EVT_RIGHT_UP(func) \
EVT_MOTION(func) \
EVT_LEFT_DCLICK(func) \
EVT_MIDDLE_DCLICK(func) \
EVT_RIGHT_DCLICK(func) \
EVT_LEAVE_WINDOW(func) \
EVT_ENTER_WINDOW(func) \
EVT_MOUSEWHEEL(func)
// Scrolling from wxWindow (sent to wxScrolledWindow)
#define EVT_SCROLLWIN_TOP(func) wx__DECLARE_EVT0(wxEVT_SCROLLWIN_TOP, wxScrollWinEventHandler(func))
#define EVT_SCROLLWIN_BOTTOM(func) wx__DECLARE_EVT0(wxEVT_SCROLLWIN_BOTTOM, wxScrollWinEventHandler(func))
#define EVT_SCROLLWIN_LINEUP(func) wx__DECLARE_EVT0(wxEVT_SCROLLWIN_LINEUP, wxScrollWinEventHandler(func))
#define EVT_SCROLLWIN_LINEDOWN(func) wx__DECLARE_EVT0(wxEVT_SCROLLWIN_LINEDOWN, wxScrollWinEventHandler(func))
#define EVT_SCROLLWIN_PAGEUP(func) wx__DECLARE_EVT0(wxEVT_SCROLLWIN_PAGEUP, wxScrollWinEventHandler(func))
#define EVT_SCROLLWIN_PAGEDOWN(func) wx__DECLARE_EVT0(wxEVT_SCROLLWIN_PAGEDOWN, wxScrollWinEventHandler(func))
#define EVT_SCROLLWIN_THUMBTRACK(func) wx__DECLARE_EVT0(wxEVT_SCROLLWIN_THUMBTRACK, wxScrollWinEventHandler(func))
#define EVT_SCROLLWIN_THUMBRELEASE(func) wx__DECLARE_EVT0(wxEVT_SCROLLWIN_THUMBRELEASE, wxScrollWinEventHandler(func))
#define EVT_SCROLLWIN(func) \
EVT_SCROLLWIN_TOP(func) \
EVT_SCROLLWIN_BOTTOM(func) \
EVT_SCROLLWIN_LINEUP(func) \
EVT_SCROLLWIN_LINEDOWN(func) \
EVT_SCROLLWIN_PAGEUP(func) \
EVT_SCROLLWIN_PAGEDOWN(func) \
EVT_SCROLLWIN_THUMBTRACK(func) \
EVT_SCROLLWIN_THUMBRELEASE(func)
// Scrolling from wxSlider and wxScrollBar
#define EVT_SCROLL_TOP(func) wx__DECLARE_EVT0(wxEVT_SCROLL_TOP, wxScrollEventHandler(func))
#define EVT_SCROLL_BOTTOM(func) wx__DECLARE_EVT0(wxEVT_SCROLL_BOTTOM, wxScrollEventHandler(func))
#define EVT_SCROLL_LINEUP(func) wx__DECLARE_EVT0(wxEVT_SCROLL_LINEUP, wxScrollEventHandler(func))
#define EVT_SCROLL_LINEDOWN(func) wx__DECLARE_EVT0(wxEVT_SCROLL_LINEDOWN, wxScrollEventHandler(func))
#define EVT_SCROLL_PAGEUP(func) wx__DECLARE_EVT0(wxEVT_SCROLL_PAGEUP, wxScrollEventHandler(func))
#define EVT_SCROLL_PAGEDOWN(func) wx__DECLARE_EVT0(wxEVT_SCROLL_PAGEDOWN, wxScrollEventHandler(func))
#define EVT_SCROLL_THUMBTRACK(func) wx__DECLARE_EVT0(wxEVT_SCROLL_THUMBTRACK, wxScrollEventHandler(func))
#define EVT_SCROLL_THUMBRELEASE(func) wx__DECLARE_EVT0(wxEVT_SCROLL_THUMBRELEASE, wxScrollEventHandler(func))
#define EVT_SCROLL_CHANGED(func) wx__DECLARE_EVT0(wxEVT_SCROLL_CHANGED, wxScrollEventHandler(func))
#define EVT_SCROLL(func) \
EVT_SCROLL_TOP(func) \
EVT_SCROLL_BOTTOM(func) \
EVT_SCROLL_LINEUP(func) \
EVT_SCROLL_LINEDOWN(func) \
EVT_SCROLL_PAGEUP(func) \
EVT_SCROLL_PAGEDOWN(func) \
EVT_SCROLL_THUMBTRACK(func) \
EVT_SCROLL_THUMBRELEASE(func) \
EVT_SCROLL_CHANGED(func)
// Scrolling from wxSlider and wxScrollBar, with an id
#define EVT_COMMAND_SCROLL_TOP(winid, func) wx__DECLARE_EVT1(wxEVT_SCROLL_TOP, winid, wxScrollEventHandler(func))
#define EVT_COMMAND_SCROLL_BOTTOM(winid, func) wx__DECLARE_EVT1(wxEVT_SCROLL_BOTTOM, winid, wxScrollEventHandler(func))
#define EVT_COMMAND_SCROLL_LINEUP(winid, func) wx__DECLARE_EVT1(wxEVT_SCROLL_LINEUP, winid, wxScrollEventHandler(func))
#define EVT_COMMAND_SCROLL_LINEDOWN(winid, func) wx__DECLARE_EVT1(wxEVT_SCROLL_LINEDOWN, winid, wxScrollEventHandler(func))
#define EVT_COMMAND_SCROLL_PAGEUP(winid, func) wx__DECLARE_EVT1(wxEVT_SCROLL_PAGEUP, winid, wxScrollEventHandler(func))
#define EVT_COMMAND_SCROLL_PAGEDOWN(winid, func) wx__DECLARE_EVT1(wxEVT_SCROLL_PAGEDOWN, winid, wxScrollEventHandler(func))
#define EVT_COMMAND_SCROLL_THUMBTRACK(winid, func) wx__DECLARE_EVT1(wxEVT_SCROLL_THUMBTRACK, winid, wxScrollEventHandler(func))
#define EVT_COMMAND_SCROLL_THUMBRELEASE(winid, func) wx__DECLARE_EVT1(wxEVT_SCROLL_THUMBRELEASE, winid, wxScrollEventHandler(func))
#define EVT_COMMAND_SCROLL_CHANGED(winid, func) wx__DECLARE_EVT1(wxEVT_SCROLL_CHANGED, winid, wxScrollEventHandler(func))
#define EVT_COMMAND_SCROLL(winid, func) \
EVT_COMMAND_SCROLL_TOP(winid, func) \
EVT_COMMAND_SCROLL_BOTTOM(winid, func) \
EVT_COMMAND_SCROLL_LINEUP(winid, func) \
EVT_COMMAND_SCROLL_LINEDOWN(winid, func) \
EVT_COMMAND_SCROLL_PAGEUP(winid, func) \
EVT_COMMAND_SCROLL_PAGEDOWN(winid, func) \
EVT_COMMAND_SCROLL_THUMBTRACK(winid, func) \
EVT_COMMAND_SCROLL_THUMBRELEASE(winid, func) \
EVT_COMMAND_SCROLL_CHANGED(winid, func)
#if WXWIN_COMPATIBILITY_2_6
// compatibility macros for the old name, deprecated in 2.8
#define wxEVT_SCROLL_ENDSCROLL wxEVT_SCROLL_CHANGED
#define EVT_COMMAND_SCROLL_ENDSCROLL EVT_COMMAND_SCROLL_CHANGED
#define EVT_SCROLL_ENDSCROLL EVT_SCROLL_CHANGED
#endif // WXWIN_COMPATIBILITY_2_6
// Convenience macros for commonly-used commands
#define EVT_CHECKBOX(winid, func) wx__DECLARE_EVT1(wxEVT_COMMAND_CHECKBOX_CLICKED, winid, wxCommandEventHandler(func))
#define EVT_CHOICE(winid, func) wx__DECLARE_EVT1(wxEVT_COMMAND_CHOICE_SELECTED, winid, wxCommandEventHandler(func))
#define EVT_LISTBOX(winid, func) wx__DECLARE_EVT1(wxEVT_COMMAND_LISTBOX_SELECTED, winid, wxCommandEventHandler(func))
#define EVT_LISTBOX_DCLICK(winid, func) wx__DECLARE_EVT1(wxEVT_COMMAND_LISTBOX_DOUBLECLICKED, winid, wxCommandEventHandler(func))
#define EVT_MENU(winid, func) wx__DECLARE_EVT1(wxEVT_COMMAND_MENU_SELECTED, winid, wxCommandEventHandler(func))
#define EVT_MENU_RANGE(id1, id2, func) wx__DECLARE_EVT2(wxEVT_COMMAND_MENU_SELECTED, id1, id2, wxCommandEventHandler(func))
#if defined(__SMARTPHONE__)
# define EVT_BUTTON(winid, func) EVT_MENU(winid, func)
#else
# define EVT_BUTTON(winid, func) wx__DECLARE_EVT1(wxEVT_COMMAND_BUTTON_CLICKED, winid, wxCommandEventHandler(func))
#endif
#define EVT_SLIDER(winid, func) wx__DECLARE_EVT1(wxEVT_COMMAND_SLIDER_UPDATED, winid, wxCommandEventHandler(func))
#define EVT_RADIOBOX(winid, func) wx__DECLARE_EVT1(wxEVT_COMMAND_RADIOBOX_SELECTED, winid, wxCommandEventHandler(func))
#define EVT_RADIOBUTTON(winid, func) wx__DECLARE_EVT1(wxEVT_COMMAND_RADIOBUTTON_SELECTED, winid, wxCommandEventHandler(func))
// EVT_SCROLLBAR is now obsolete since we use EVT_COMMAND_SCROLL... events
#define EVT_SCROLLBAR(winid, func) wx__DECLARE_EVT1(wxEVT_COMMAND_SCROLLBAR_UPDATED, winid, wxCommandEventHandler(func))
#define EVT_VLBOX(winid, func) wx__DECLARE_EVT1(wxEVT_COMMAND_VLBOX_SELECTED, winid, wxCommandEventHandler(func))
#define EVT_COMBOBOX(winid, func) wx__DECLARE_EVT1(wxEVT_COMMAND_COMBOBOX_SELECTED, winid, wxCommandEventHandler(func))
#define EVT_TOOL(winid, func) wx__DECLARE_EVT1(wxEVT_COMMAND_TOOL_CLICKED, winid, wxCommandEventHandler(func))
#define EVT_TOOL_RANGE(id1, id2, func) wx__DECLARE_EVT2(wxEVT_COMMAND_TOOL_CLICKED, id1, id2, wxCommandEventHandler(func))
#define EVT_TOOL_RCLICKED(winid, func) wx__DECLARE_EVT1(wxEVT_COMMAND_TOOL_RCLICKED, winid, wxCommandEventHandler(func))
#define EVT_TOOL_RCLICKED_RANGE(id1, id2, func) wx__DECLARE_EVT2(wxEVT_COMMAND_TOOL_RCLICKED, id1, id2, wxCommandEventHandler(func))
#define EVT_TOOL_ENTER(winid, func) wx__DECLARE_EVT1(wxEVT_COMMAND_TOOL_ENTER, winid, wxCommandEventHandler(func))
#define EVT_CHECKLISTBOX(winid, func) wx__DECLARE_EVT1(wxEVT_COMMAND_CHECKLISTBOX_TOGGLED, winid, wxCommandEventHandler(func))
// Generic command events
#define EVT_COMMAND_LEFT_CLICK(winid, func) wx__DECLARE_EVT1(wxEVT_COMMAND_LEFT_CLICK, winid, wxCommandEventHandler(func))
#define EVT_COMMAND_LEFT_DCLICK(winid, func) wx__DECLARE_EVT1(wxEVT_COMMAND_LEFT_DCLICK, winid, wxCommandEventHandler(func))
#define EVT_COMMAND_RIGHT_CLICK(winid, func) wx__DECLARE_EVT1(wxEVT_COMMAND_RIGHT_CLICK, winid, wxCommandEventHandler(func))
#define EVT_COMMAND_RIGHT_DCLICK(winid, func) wx__DECLARE_EVT1(wxEVT_COMMAND_RIGHT_DCLICK, winid, wxCommandEventHandler(func))
#define EVT_COMMAND_SET_FOCUS(winid, func) wx__DECLARE_EVT1(wxEVT_COMMAND_SET_FOCUS, winid, wxCommandEventHandler(func))
#define EVT_COMMAND_KILL_FOCUS(winid, func) wx__DECLARE_EVT1(wxEVT_COMMAND_KILL_FOCUS, winid, wxCommandEventHandler(func))
#define EVT_COMMAND_ENTER(winid, func) wx__DECLARE_EVT1(wxEVT_COMMAND_ENTER, winid, wxCommandEventHandler(func))
// Joystick events
#define EVT_JOY_BUTTON_DOWN(func) wx__DECLARE_EVT0(wxEVT_JOY_BUTTON_DOWN, wxJoystickEventHandler(func))
#define EVT_JOY_BUTTON_UP(func) wx__DECLARE_EVT0(wxEVT_JOY_BUTTON_UP, wxJoystickEventHandler(func))
#define EVT_JOY_MOVE(func) wx__DECLARE_EVT0(wxEVT_JOY_MOVE, wxJoystickEventHandler(func))
#define EVT_JOY_ZMOVE(func) wx__DECLARE_EVT0(wxEVT_JOY_ZMOVE, wxJoystickEventHandler(func))
// These are obsolete, see _BUTTON_ events
#if WXWIN_COMPATIBILITY_2_4
#define EVT_JOY_DOWN(func) EVT_JOY_BUTTON_DOWN(func)
#define EVT_JOY_UP(func) EVT_JOY_BUTTON_UP(func)
#endif // WXWIN_COMPATIBILITY_2_4
// All joystick events
#define EVT_JOYSTICK_EVENTS(func) \
EVT_JOY_BUTTON_DOWN(func) \
EVT_JOY_BUTTON_UP(func) \
EVT_JOY_MOVE(func) \
EVT_JOY_ZMOVE(func)
// Idle event
#define EVT_IDLE(func) wx__DECLARE_EVT0(wxEVT_IDLE, wxIdleEventHandler(func))
// Update UI event
#define EVT_UPDATE_UI(winid, func) wx__DECLARE_EVT1(wxEVT_UPDATE_UI, winid, wxUpdateUIEventHandler(func))
#define EVT_UPDATE_UI_RANGE(id1, id2, func) wx__DECLARE_EVT2(wxEVT_UPDATE_UI, id1, id2, wxUpdateUIEventHandler(func))
// Help events
#define EVT_HELP(winid, func) wx__DECLARE_EVT1(wxEVT_HELP, winid, wxHelpEventHandler(func))
#define EVT_HELP_RANGE(id1, id2, func) wx__DECLARE_EVT2(wxEVT_HELP, id1, id2, wxHelpEventHandler(func))
#define EVT_DETAILED_HELP(winid, func) wx__DECLARE_EVT1(wxEVT_DETAILED_HELP, winid, wxHelpEventHandler(func))
#define EVT_DETAILED_HELP_RANGE(id1, id2, func) wx__DECLARE_EVT2(wxEVT_DETAILED_HELP, id1, id2, wxHelpEventHandler(func))
// Context Menu Events
#define EVT_CONTEXT_MENU(func) wx__DECLARE_EVT0(wxEVT_CONTEXT_MENU, wxContextMenuEventHandler(func))
#define EVT_COMMAND_CONTEXT_MENU(winid, func) wx__DECLARE_EVT1(wxEVT_CONTEXT_MENU, winid, wxContextMenuEventHandler(func))
// Clipboard text Events
#define EVT_TEXT_CUT(winid, func) wx__DECLARE_EVT1(wxEVT_COMMAND_TEXT_CUT, winid, wxClipboardTextEventHandler(func))
#define EVT_TEXT_COPY(winid, func) wx__DECLARE_EVT1(wxEVT_COMMAND_TEXT_COPY, winid, wxClipboardTextEventHandler(func))
#define EVT_TEXT_PASTE(winid, func) wx__DECLARE_EVT1(wxEVT_COMMAND_TEXT_PASTE, winid, wxClipboardTextEventHandler(func))
// ----------------------------------------------------------------------------
// Global data
// ----------------------------------------------------------------------------
// for pending event processing - notice that there is intentionally no
// WXDLLEXPORT here
extern WXDLLIMPEXP_BASE wxList *wxPendingEvents;
#if wxUSE_THREADS
extern WXDLLIMPEXP_BASE wxCriticalSection *wxPendingEventsLocker;
#endif
// ----------------------------------------------------------------------------
// Helper functions
// ----------------------------------------------------------------------------
#if wxUSE_GUI
// Find a window with the focus, that is also a descendant of the given window.
// This is used to determine the window to initially send commands to.
WXDLLIMPEXP_CORE wxWindow* wxFindFocusDescendant(wxWindow* ancestor);
#endif // wxUSE_GUI
#endif // _WX_EVENT_H__
| [
"[email protected]"
] | [
[
[
1,
3116
]
]
] |
bc785a6ee30f304db88543bafbec199c5da588ca | 7aa5cd977756e067e96d48585db1ec4a35c4c962 | /antilander/Level.cpp | e3775ebe69e92729dc41f3af0c622ca399dd6bfb | [] | no_license | zzyzxr99/antilander | 15faf715fe9248286d375e9f8e8af08260df7fa4 | c1c9b05d0d869c251e19f9c31e6c223f63104e54 | refs/heads/master | 2021-01-19T14:10:00.561194 | 2008-08-02T17:18:27 | 2008-08-02T17:18:27 | 34,579,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,899 | cpp | // Level.cpp
#include "Constants.h"
#include "Structs.h"
#include "Level.h"
#include <vector>
#include <fstream>
#include <iostream>
#include <ostream>
#include <string>
using namespace std;
//static variables
Level::Level( )
{
mNumLndrLvl = kDefaultLandersPerLevel;
mNumLndrScr = kDefaultLandersPerScreen;
mLndrPersist = false;
mLndrDescRate = kBaseDescendRate;
mNumMissile = kStartAmmo;
mMissileSpd = kMissileStartSpeed;
mGunMoves = false;
mGunMoveRnd = false;
mEndGamePadOcc = kLanderPadGoal;
mGunReload = kReloadTime;
mExpRad = kExplosionMaxRadiusDefault;
mExpRate = kExplosionExpandRateDefault;
mFrat = false;
mNumBomb = kDefaultStartBomb;
mBombMxSpd = kBombMaxSpeed;
mBombAcc = kGravity;
mBombRad = kBombRadius;
mBombReloadTime = kBombReloadTime;
Point pt;
pt.x = 10.0F;
pt.y = 90.0F;
mPadPt.push_back(pt);
pt.x = 100.0F;
pt.y = 180.0F;
mPadPt.push_back(pt);
pt.x = 200.0F;
pt.y = 270.0F;
mPadPt.push_back(pt);
pt.x = 320.0F;
pt.y = 360.0F;
mPadPt.push_back(pt);
pt.x = 440.0F;
pt.y = 270.0F;
mPadPt.push_back(pt);
pt.x = 540.0F;
pt.y = 180.0F;
mPadPt.push_back(pt);
pt.x = 629.0F;
pt.y = 90.0F;
mPadPt.push_back(pt);
mNumPad = mPadPt.size( );
vector<Point>::iterator Iter;
for ( Iter = mPadPt.begin( ); Iter != mPadPt.end( ); Iter++)
{
pt.x = Iter->x-10;
pt.y = Iter->y;
mTerPt.push_back(pt);
pt.x += 20;
mTerPt.push_back(pt);
}
mNumTerPt = mTerPt.size( );
mGunStartPad = mNumPad/2;
}
Level::~Level( )
{ }
USINT Level::GetNumLndrLvl( )
{
return mNumLndrLvl;
}
USINT Level::GetNumLndrScr( )
{
return mNumLndrScr;
}
bool Level::GetLndrPersist( )
{
return mLndrPersist;
}
float Level::GetLndrDescRate( )
{
return mLndrDescRate;
}
USINT Level::GetNumPad( )
{
return mNumPad;
}
vector<Point>* Level::GetPadpt( )
{
return &mPadPt;
}
USINT Level::GetNumTerPt( )
{
return mNumTerPt;
}
vector<Point>* Level::GetTerPt()
{
return &mTerPt;
}
USINT Level::GetNumMissile( )
{
return mNumMissile;
}
float Level::GetMissileSpd( )
{
return mMissileSpd;
}
USINT Level::GetGunStartPad( )
{
return mGunStartPad;
}
bool Level::GetGunMoves( )
{
return mGunMoves;
}
bool Level::GetGunMoveRnd( )
{
return mGunMoveRnd;
}
USINT Level::GetEndGamePadOcc( )
{
return mEndGamePadOcc;
}
float Level::GetGunReload( )
{
return mGunReload;
}
float Level::GetExpRad( )
{
return mExpRad;
}
float Level::GetExplRate( )
{
return mExpRate;
}
bool Level::GetFrat( )
{
return mFrat;
}
USINT Level::GetNumBomb( )
{
return mNumBomb;
}
float Level::GetBombMxSpd( )
{
return mBombMxSpd;
}
float Level::GetBombAcc( )
{
return mBombAcc;
}
float Level::GetBombRad( )
{
return mBombRad;
}
float Level::GetBombReloadTime( )
{
return mBombReloadTime;
}
void Level::SetNumLndrLvl( USINT landers )
{
mNumLndrLvl = landers;
}
void Level::SetNumLndrScr( USINT landers )
{
mNumLndrScr = landers;
}
void Level::SetLndrPersist( bool persist )
{
mLndrPersist = persist;
}
void Level::SetLndrDescRate( float rate )
{
mLndrDescRate = rate;
}
void Level::SetNumPad( USINT pads )
{
mNumPad = pads;
}
void Level::SetNumTerPt( USINT points )
{
mNumTerPt = points;
}
void Level::SetNumMissile( USINT missiles )
{
mNumMissile = missiles;
}
void Level::SetMissileSpd( float speed )
{
mMissileSpd = speed;
}
void Level::SetGunStartPad( USINT pad )
{
mGunStartPad = pad;
}
void Level::SetGunMoves( bool moves )
{
mGunMoves = moves;
}
void Level::SetGunMoveRnd( bool moveRnd )
{
mGunMoveRnd = moveRnd;
}
void Level::SetEndGamePadOcc( USINT pads )
{
mEndGamePadOcc = pads;
}
void Level::SetGunReload( float reloadTime )
{
mGunReload = reloadTime;
}
void Level::SetExpRad( float radius )
{
mExpRad = radius;
}
void Level::SetExpRate( float rate )
{
mExpRate = rate;
}
void Level::SetFrat( bool frat )
{
mFrat = frat;
}
void Level::SetNumBomb( USINT num )
{
mNumBomb = num;
}
void Level::SetBombMxSpd( float spd )
{
mBombMxSpd = spd;
}
void Level::SetBombAcc( float acc )
{
mBombAcc = acc;
}
void Level::SetBombRad( float rad )
{
mBombRad = rad;
}
void Level::SetBombReloadTime( float t )
{
mBombReloadTime = t;
}
void Level::ClearLevel( )
{
mNumLndrLvl = kDefaultLandersPerLevel;
mNumLndrScr = kDefaultLandersPerScreen;
mLndrPersist = false;
mLndrDescRate = kBaseDescendRate;
mNumMissile = kStartAmmo;
mMissileSpd = kMissileStartSpeed;
mGunMoves = false;
mGunMoveRnd = false;
mEndGamePadOcc = kLanderPadGoal;
mGunReload = kReloadTime;
mExpRad = kExplosionMaxRadiusDefault;
mExpRate = kExplosionExpandRateDefault;
mFrat = false;
mNumBomb = kDefaultStartBomb;
mBombMxSpd = kBombMaxSpeed;
mBombAcc = kGravity;
mBombRad = kBombRadius;
mNumTerPt = 0;
mNumPad = 0;
mTerPt.clear();
mPadPt.clear();
}
bool Level::LoadLevel( string LevString )
{
LevString = "data\\" + LevString;
ifstream infile(LevString.c_str());
if ( !infile )
{
return false;
}
mTerPt.clear();
mPadPt.clear();
vector<Point>::iterator iterTer = mTerPt.begin();
vector<Point>::iterator iterPad = mPadPt.begin();
int ctr = 0;
string str[100];
string p;
char* index[] = {"mTerPt","mPadPt","mGunStartPad","mEndGamePadOcc","mNumLndrLvl","mNumLndrScr","mNumBomb","mNumMissile","mBombMxSpd",
"mBombAcc","mBombRad","mLndrDescRate","mGunReload","mExpRad","mExpRate","mMissileSpd","mLndrPersist","mFrat","mGunMoves",
"mGunMoveRnd","mBombReloadTime","LAST"}; //index of strings to compare
Point pt;
while (!infile.eof())
{
getline(infile, str[ctr]);
ctr++;
}
//ctr = amount of lines
for (int j = 0; j < ctr; j++)
{
if(!str[j].compare(index[0])) //if current line is TERRAINPTS
{
for (int l = j+1; str[l].compare(index[1]); l++)
{
p = str[l].substr( 0,
str[l].find(",") );
pt.x = (float)atof(p.c_str( ));
p = str[l].substr( str[l].find(" ")+1,
str[l].length( ) );
pt.y = (float)atof(p.c_str( ));
mTerPt.push_back(pt);
cout << pt.x << " " << pt.y << endl;
}
mNumTerPt = mTerPt.size();
}
else if(!str[j].compare(index[1]))
{
for (int l = j+1, k = 0; str[l].compare(index[2]); l++, k++)
{
p = str[l].substr( 0,
str[l].find(",") );
pt.x = (float)atof(p.c_str( ));
p = str[l].substr( str[l].find(" ")+1,
str[l].length( ) );
pt.y = (float)atof(p.c_str( ));
mPadPt.push_back(pt);
}
mNumPad = mPadPt.size();
}
else if(!str[j].compare(index[2]))
{
SetGunStartPad((USINT)(atoi(str[j+1].c_str())));
}
else if(!str[j].compare(index[3]))
{
SetEndGamePadOcc((USINT)(atoi(str[j+1].c_str())));
}
else if(!str[j].compare(index[4]))
{
SetNumLndrLvl((USINT)(atoi(str[j+1].c_str())));
}
else if(!str[j].compare(index[5]))
{
SetNumLndrScr((USINT)(atoi(str[j+1].c_str())));
}
else if(!str[j].compare(index[6]))
{
SetNumBomb((USINT)(atoi(str[j+1].c_str())));
}
else if(!str[j].compare(index[7]))
{
SetNumMissile((USINT)(atoi(str[j+1].c_str())));
}
else if(!str[j].compare(index[8]))
{
SetBombMxSpd((float)(atof(str[j+1].c_str())));
}
else if(!str[j].compare(index[9]))
{
SetBombAcc((float)(atof(str[j+1].c_str())));
}
else if(!str[j].compare(index[10]))
{
SetBombRad((float)(atof(str[j+1].c_str())));
}
else if(!str[j].compare(index[11]))
{
SetLndrDescRate((float)(atof(str[j+1].c_str())));
}
else if(!str[j].compare(index[12]))
{
SetGunReload((float)(atof(str[j+1].c_str())));
}
else if(!str[j].compare(index[13]))
{
SetExpRad((float)(atof(str[j+1].c_str())));
}
else if(!str[j].compare(index[14]))
{
SetExpRate((float)(atof(str[j+1].c_str())));
}
else if(!str[j].compare(index[15]))
{
SetMissileSpd((float)(atof(str[j+1].c_str())));
}
else if(!str[j].compare(index[16]))
{
if ( atoi(str[j+1].c_str( )) > 0 )
{
SetLndrPersist(true);
}
else
{
SetLndrPersist(false);
}
}
else if(!str[j].compare(index[17]))
{
if (atoi(str[j+1].c_str( )) > 0 )
{
SetFrat(true);
}
else
{
SetFrat(false);
}
}
else if(!str[j].compare(index[18]))
{
if ( atoi(str[j+1].c_str( )) > 0 )
{
SetGunMoves(true);
}
else
{
SetGunMoves(false);
}
}
else if(!str[j].compare(index[19]))
{
if ( atoi(str[j+1].c_str( )) > 0 )
{
SetGunMoveRnd(true);
}
else
{
SetGunMoveRnd(false);
}
}
else if(!str[j].compare(index[20]))
{
SetBombReloadTime((float)(atof(str[j+1].c_str())));
}
}
infile.close( );
return true;
}
void Level::SaveLevel( string LevString )
{
LevString = "data\\" + LevString;
ofstream outfile(LevString.c_str());
outfile << "mTerPt" << endl;
for(int i = 0; i < mNumTerPt; i++)
{
outfile << mTerPt[i].x << ", " << mTerPt[i].y << endl;
}
outfile << "mPadPt" << endl;
for(int i = 0; i < mNumPad; i++)
{
outfile << mPadPt[i].x << ", " << mPadPt[i].y << endl;
}
outfile << "mGunStartPad" << endl; outfile << mGunStartPad << endl;
outfile << "mEndGamePadOcc" << endl; outfile << mEndGamePadOcc << endl;
outfile << "mNumLndrLvl" << endl; outfile << mNumLndrLvl << endl;
outfile << "mNumLndrScr" << endl; outfile << mNumLndrScr << endl;
outfile << "mNumBomb" << endl; outfile << mNumBomb << endl;
outfile << "mNumMissile" << endl; outfile << mNumMissile << endl;
outfile << "mBombMxSpd" << endl; outfile << mBombMxSpd << endl;
outfile << "mBombAcc" << endl; outfile << mBombAcc << endl;
outfile << "mBombRad" << endl; outfile << mBombRad << endl;
outfile << "mLndrDescRate" << endl; outfile << mLndrDescRate << endl;
outfile << "mGunReload" << endl; outfile << mGunReload << endl;
outfile << "mExpRad" << endl; outfile << mExpRad << endl;
outfile << "mExpRate" << endl; outfile << mExpRate << endl;
outfile << "mMissileSpd" << endl; outfile << mMissileSpd << endl;
outfile << "mLndrPersist" << endl; outfile << mLndrPersist << endl;
outfile << "mFrat" << endl; outfile << mFrat << endl;
outfile << "mGunMoves" << endl; outfile << mGunMoves << endl;
outfile << "mGunMoveRnd" << endl; outfile << mGunMoveRnd << endl;
//////////////////////////////////////////////////////////////////////////////
outfile << "mBombReloadTime" << endl; outfile << mBombReloadTime << endl;
outfile << "LAST" << endl;
}
//void Level::EJRTestSaveLevel(string filename)
//{
// // Open output file stream to destination filename ios::out means to write
// ofstream outf(filename.c_str(),ios::out);
//
// // Write out level header
// outf << "Level 1" << endl;
// // Write out number of terrain points
// outf << mNumTerPt << endl;
//
// // close and save file
// outf.close();
//}
//
//void Level::EJRTestLoadLevel(string filename)
//{
// // open file as input file stream, ios::in read
// ifstream inf(filename.c_str(),ios::in);
// // if ifstream is NULL will fail
// if (inf != NULL) // File exists
// {
// // read first line of ifstream inf into strLevel
// string strLevel="";
// getline(inf,strLevel);
// cout << strLevel << endl;; // output to console
//
// // read next line and convert it to an integer to put into terrain points
// string strNumTerrain="";
// getline(inf,strNumTerrain);
// int numterr= atoi(strNumTerrain.c_str()); // atoi is asc to integer -
//
// cout << "Number of points=" << numterr <<endl; // outp to console for test
// }
// inf.close();
//}
void Level::AddPoint(Point p)
{
mTerPt.push_back (p);
mNumTerPt= mTerPt.size();
}
void Level::AddPad(Point p)
{
mTerPt.push_back (p);
mNumTerPt= mTerPt.size();
}
void Level::MakePadPtsFromTerrainPts()
{
mPadPt.clear();
for (int n= 0; n < mNumTerPt-1; n++)
{
Point p1, p2, p3;
p1 = mTerPt[n];
p2 = mTerPt[n+1];
if (p1.y == p2.y)
{
p3.x = (p1.x + p2.x)/2;
p3.y = p1.y;
mPadPt.push_back(p3);
}
}
mNumPad= mPadPt.size();
}
void Level::Clone( Level* srcLvl )
{
mNumLndrLvl = srcLvl->GetNumLndrLvl( );
mNumLndrScr = srcLvl->GetNumLndrScr( );
mLndrPersist = srcLvl->GetLndrPersist( );
mLndrDescRate = srcLvl->GetLndrDescRate( );
mNumMissile = srcLvl->GetNumMissile( );
mMissileSpd = srcLvl->GetMissileSpd( );
mGunStartPad = srcLvl->GetGunStartPad( );
mGunMoves = srcLvl->GetGunMoves( );
mGunMoveRnd = srcLvl->GetGunMoveRnd( );
mEndGamePadOcc = srcLvl->GetEndGamePadOcc( );
mGunReload = srcLvl->GetGunReload( );
mExpRad = srcLvl->GetExpRad( );
mExpRate = srcLvl->GetExplRate( );
mFrat = srcLvl->GetFrat( );
mNumBomb = srcLvl->GetNumBomb( );
mBombMxSpd = srcLvl->GetBombMxSpd( );
mBombAcc = srcLvl->GetBombAcc( );
mBombRad = srcLvl->GetBombRad( );
mBombReloadTime = srcLvl->GetBombReloadTime( );
mPadPt.clear( );
vector<Point>::iterator Iter;
for ( Iter = srcLvl->GetPadpt( )->begin( );
Iter != srcLvl->GetPadpt( )->end( ); Iter++ )
{
mPadPt.push_back(*Iter);
}
mNumPad = mPadPt.size( );
mTerPt.clear( );
for ( Iter = srcLvl->GetTerPt( )->begin( );
Iter != srcLvl->GetTerPt( )->end( ); Iter++ )
{
mTerPt.push_back(*Iter);
}
mNumTerPt = mTerPt.size( );
}
Level* Level::GetPtr( )
{
return this;
} | [
"dynamo.dwl@12e01eeb-bf4d-0410-af2a-23d671325bb1",
"[email protected]@12e01eeb-bf4d-0410-af2a-23d671325bb1",
"eric.riel@12e01eeb-bf4d-0410-af2a-23d671325bb1",
"arctorus@12e01eeb-bf4d-0410-af2a-23d671325bb1",
"katsuhitsu@12e01eeb-bf4d-0410-af2a-23d671325bb1",
"[email protected]@12e01eeb-bf4d-0410-af2a-23d671325bb1"
] | [
[
[
1,
5
],
[
10,
11
],
[
14,
72
],
[
74,
77
],
[
79,
92
],
[
94,
102
],
[
104,
112
],
[
114,
122
],
[
124,
137
],
[
139,
162
],
[
164,
187
],
[
189,
191
],
[
193,
206
],
[
208,
211
],
[
213,
216
],
[
218,
226
],
[
228,
241
],
[
243,
266
],
[
268,
290
],
[
301,
301
],
[
315,
322
],
[
329,
329
],
[
346,
351
],
[
361,
366
],
[
429,
436
],
[
440,
447
],
[
451,
458
],
[
462,
469
],
[
477,
480
],
[
482,
483
],
[
584,
629
]
],
[
[
6,
7
],
[
12,
13
],
[
73,
73
],
[
78,
78
],
[
93,
93
],
[
103,
103
],
[
113,
113
],
[
123,
123
],
[
138,
138
],
[
163,
163
],
[
188,
188
],
[
192,
192
],
[
207,
207
],
[
212,
212
],
[
217,
217
],
[
227,
227
],
[
242,
242
],
[
267,
267
],
[
323,
328
],
[
330,
345
],
[
352,
360
],
[
367,
428
],
[
437,
439
],
[
448,
450
],
[
459,
461
],
[
470,
476
],
[
481,
481
],
[
484,
515
]
],
[
[
8,
9
],
[
553,
553
]
],
[
[
291,
300
],
[
302,
314
],
[
516,
517
],
[
554,
558
],
[
566,
581
],
[
583,
583
]
],
[
[
518,
552
]
],
[
[
559,
565
],
[
582,
582
]
]
] |
b8925d01d5aad8d05cc880385fc56be6cac1cdac | 8b506bf34b36af04fa970f2749e0c8033f1a9d7a | /Code/Win32/dx/dxTransformer.cpp | 7a5679edaaa89d10b5fd8fb484738df666770496 | [] | no_license | gunstar/Prototype | a5155e25d7d54a1991425e7be85bfc7da42c634f | a4448b5f6d18048ecaedf26c71e2b107e021ea6e | refs/heads/master | 2021-01-10T21:42:24.221750 | 2011-11-06T10:16:26 | 2011-11-06T10:16:26 | 2,708,481 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 450 | cpp | #include "dxTransformer.h"
/*******************************************************************/
dxTransformer::dxTransformer(IDirect3DDevice9* device)
{
Device = device;
}
void dxTransformer::setMatrix(const enMatrix& mat)
{
D3DXMATRIX world
(
mat.X.X, mat.X.Y, mat.X.Z, 0,
mat.Y.X, mat.Y.Y, mat.Y.Z, 0,
mat.Z.X, mat.Z.Y, mat.Z.Z, 0,
mat.P.X, mat.P.Y, mat.P.Z, 1
);
Device->SetTransform(D3DTS_WORLD, &world);
}
| [
"[email protected]"
] | [
[
[
1,
21
]
]
] |
91f94d26b1d8d2eeb5de7b07d7e8ac8eac44d3ed | 17dbb168ccbceabdd07510d9f038133f7dc34514 | /expression_template/vector.cpp | 8ff1bb99f195cea9944107387a5d8eec0e9ef915 | [] | no_license | ohtaman/reinvention_of_the_wheel | 40f80005ae9fff6cf41f41bb7076048e25e9634d | 9bddcf1ee12b88cd97f1e101323f8549eefa6e4e | refs/heads/master | 2016-09-10T11:06:56.018128 | 2010-07-25T13:09:44 | 2010-07-25T13:09:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,502 | cpp | namespace YUI
{
template<typename T, typename L, typename R, typename OP>
class VectorExpr;
template<typename T, int DIM>
class Vector{
private:
T value[DIM];
public:
Vector()
{
}
Vector(const Vector<T, DIM> &rhs)
{
for (int i = 0; i < DIM; ++i) {
this->value[i] = rhs[i];
}
}
Vector(const T *value)
{
for (int i = 0; i < DIM; ++i) {
this->value[i] = value[i];
}
}
template<typename L, typename R, typename OP>
Vector(const VectorExpr<T, L, R, OP> &rhs);
virtual ~Vector()
{
}
T &operator[](int i)
{
return value[i];
}
const T &operator[](int i) const
{
return value[i];
}
Vector<T, DIM> &operator=(const Vector<T, DIM> &rhs)
{
if (this != &rhs) {
for (int i = 0; i < DIM; ++i) {
(*this)[i] = rhs[i];
}
}
return *this;
}
template<typename R>
Vector &operator=(const R &rhs)
{
for (int i = 0; i < DIM; ++i) {
value[i] = rhs[i];
}
return *this;
}
};
template<typename T, typename L, typename R, typename OP>
class VectorExpr{
const L &lhs_;
const R &rhs_;
public:
VectorExpr(const L &lhs, const R &rhs)
:lhs_(lhs), rhs_(rhs)
{
}
inline T operator[](int i) const
{
return OP::eval(lhs_[i], rhs_[i]);
}
};
template<typename T>
class Plus{
public:
static inline T eval(const T &lhs, const T &rhs)
{
return lhs + rhs;
}
};
template<typename T, int DIM, typename R>
VectorExpr<T, Vector<T, DIM>, R, Plus<T> > operator+(const Vector<T, DIM> &lhs, const R &rhs)
{
return VectorExpr<T, Vector<T, DIM>, R, Plus<T> >(lhs, rhs);
}
template<typename T, int DIM, typename L>
VectorExpr<T, L, Vector<T, DIM>, Plus<T> > operator+(const L &lhs, const Vector<T, DIM> &rhs)
{
return VectorExpr<T, L, Vector<T, DIM>, Plus<T> >(lhs, rhs);
}
template<typename T, int DIM>
VectorExpr<T, Vector<T, DIM>, Vector<T, DIM>, Plus<T> > operator+(const Vector<T, DIM> &lhs, const Vector<T, DIM> &rhs)
{
return VectorExpr<T, Vector<T, DIM>, Vector<T, DIM>, Plus<T> >(lhs, rhs);
}
/* inner product */
template<typename T, int DIM, typename R>
T operator*(const Vector<T, DIM> &lhs, const R &rhs)
{
T result = lhs[0]*rhs[0];
for (int i = 1; i < DIM; ++i) {
result += lhs[i]*rhs[i];
}
return result;
}
template<typename T, int DIM, typename L>
T operator*(const L &lhs, const Vector<T, DIM> &rhs)
{
T result = lhs[0]*rhs[0];
for (int i = 1; i < DIM; ++i) {
result += lhs[i]*rhs[i];
}
return result;
}
template<typename T, typename T2, int DIM>
T operator*(const Vector<T, DIM> &lhs, const Vector<T2, DIM> &rhs)
{
T result = lhs[0]*rhs[0];
for (int i = 1; i < DIM; ++i) {
result += lhs[i]*rhs[i];
}
return result;
}
template<typename T, int DIM>
template<typename L, typename R, typename OP>
Vector<T, DIM>::Vector<T, DIM>(const VectorExpr<T, L, R, OP> &rhs)
{
for (int i = 0; i < DIM; ++i) {
value[i] = rhs[i];
}
}
} /* namespace YUI */
#include <iostream>
using namespace std;
using YUI;
int main()
{
cout << "som started" << endl;
Vector<int, 10> vec1((int[]){0,1,2,3,4,5,6,7,8,9});
cout << vec1[3] << endl;
Vector<int , 10> vec2;
vec2 = vec1+vec1;
cout << (vec1 + vec2)[3] << endl;
Vector<int, 10> vec3;
vec3 = vec2 + (vec1 + vec2);
cout << vec3[3] << endl;
Vector<int, 15> vec4;
cout << vec3*vec2 << endl;
cout << vec3*(vec2 + vec1) << endl;
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
190
]
]
] |
0804ae79a22bacfe09df6d53a85aae07263cdde8 | 7a4dfb986f5bd5fbee2186fcf37a0a0a74ef6033 | /SubtitleGrabber/StringConversion.h | 0a1a0d0db5ffc99978e1acba2fafd7aa1166c36f | [] | no_license | zsjoska/subtitle-grabber | cad96727e73d6d3ec58eb3ad5eb1dfbac0c646bd | 8de1a741b2b7fdd2e7899738839516e729d23430 | refs/heads/master | 2016-09-06T19:14:26.133224 | 2007-05-30T09:20:55 | 2007-05-30T09:20:55 | 32,320,106 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 305 | h | #pragma once
LPCSTR ConvertFromWide(UINT nCodePage, LPCWSTR strText, int & nCount);
CString ConvertToCString(UINT nCodePage, LPCSTR strText, int nCount);
CString GetStringError(HRESULT hr);
class CStringConversion
{
public:
CStringConversion(void);
public:
~CStringConversion(void);
};
| [
"zsjoska@a99920ad-ab31-0410-9f62-6da89933afc0"
] | [
[
[
1,
14
]
]
] |
7c2edbf0676bb4d322044792cac36cc7f0a5287c | ec4c161b2baf919424d8d21cd0780cf8065e3f69 | /Velo/Source/Embedded Controller/arduino/cSensor.cpp | 1c0f356e7c2448e852caf0db638d0b5278b98534 | [] | no_license | jhays200/EV-Tracking | b215d2a915987fe7113a05599bda53f254248cfa | 06674e6f0f04fc2d0be1b1d37124a9a8e0144467 | refs/heads/master | 2016-09-05T18:41:21.650852 | 2011-06-04T01:50:25 | 2011-06-04T01:50:25 | 1,673,213 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 502 | cpp | ///////////////////////////////////////////////////////////
// cSensor.cpp
// Implementation of the Class cSensor
// Created on: 05-May-2010 3:28:51 AM
// Original author: shawn.mcginnis
///////////////////////////////////////////////////////////
#include "cSensor.h"
#include "cKernel.h"
cSensor::cSensor(){
}
cSensor::~cSensor(){
}
DateTime cSensor::GetLastUpdate(){
return LastUpdate;
}
void cSensor::SetLastUpdate(DateTime newVal)
{
LastUpdate = newVal;
} | [
"[email protected]"
] | [
[
[
1,
27
]
]
] |
c05b909727360448f124a447477f7a77fc3ad878 | d609fb08e21c8583e5ad1453df04a70573fdd531 | /trunk/OpenXP/模板组件/src/HHtmlCtrl.cpp | c4ec52176f00ee79e0b2f79d89d5dac832c985fe | [] | no_license | svn2github/openxp | d68b991301eaddb7582b8a5efd30bc40e87f2ac3 | 56db08136bcf6be6c4f199f4ac2a0850cd9c7327 | refs/heads/master | 2021-01-19T10:29:42.455818 | 2011-09-17T10:27:15 | 2011-09-17T10:27:15 | 21,675,919 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 3,459 | cpp | #include "stdAfx.h"
#include "../include/HHtmlCtrl.h"
#include <urlmon.h>
WCHAR* ToWChar(char *str)
{
static WCHAR buffer[1024];
wcsset(buffer,0);
MultiByteToWideChar(CP_ACP,0,str,(int)strlen(str),buffer,1024);
return buffer;
}
void DefaultOpenURL(CString sURL)
{
HKEY hkRoot,hSubKey; //定义注册表根关键字及子关键字
char ValueName[256];
unsigned char DataValue[256];
unsigned long cbValueName=256;
unsigned long cbDataValue=256;
char ShellChar[256]; //定义命令行
DWORD dwType;
//打开注册表根关键字
if(RegOpenKey(HKEY_CLASSES_ROOT,NULL,&hkRoot)==ERROR_SUCCESS)
{
//打开子关键字
if(RegOpenKeyEx(hkRoot,
"htmlfile\\shell\\open\\command",
0,
KEY_ALL_ACCESS,
&hSubKey)==ERROR_SUCCESS)
{
//读取注册表,获取默认浏览器的命令行
RegEnumValue(hSubKey,
0,
ValueName,
&cbValueName,
NULL,
&dwType,
DataValue,
&cbDataValue);
// 调用参数(主页地址)赋值
strcpy(ShellChar,(char *)DataValue);
strcat(ShellChar,sURL);
// 启动浏览器
WinExec(ShellChar,SW_SHOW);
}
else
{
//关闭注册表
RegCloseKey(hSubKey);
RegCloseKey(hkRoot);
}
}
}
BOOL DialogOpenURL(LPWSTR url)
{
//装载动态连
HINSTANCE hinstMSHTML = LoadLibrary("MSHTML.DLL");
//此地址名称可直接用html文件名代替
LPWSTR lpUrl=url;
if(hinstMSHTML)//装载动态连接库成功
{
SHOWHTMLDIALOGFN *pfnShowHTMLDialog;
pfnShowHTMLDialog = (SHOWHTMLDIALOGFN*) GetProcAddress(hinstMSHTML, "ShowHTMLDialog");
if(pfnShowHTMLDialog)
{
IMoniker *moniker=NULL;
//
if( FAILED(CreateURLMoniker( NULL, (LPWSTR)lpUrl, &moniker ) ))
{
FreeLibrary(hinstMSHTML);
return FALSE;
}
//调用ShowHTMLDialog函数显示URL上的HTML文件
pfnShowHTMLDialog(NULL, moniker, NULL, NULL, NULL);
if(moniker != NULL)
moniker->Release();
//显示成功,返回TRUE
return TRUE;
}
else //GetProcessAddress失败
return FALSE;
FreeLibrary(hinstMSHTML);
}
else //装载动态连接库失败
return FALSE;
}
IMPLEMENT_DYNAMIC(HHtmlCtrl, CHtmlView)
BEGIN_MESSAGE_MAP(HHtmlCtrl, CHtmlView)
ON_WM_MOUSEACTIVATE()
ON_WM_DESTROY()
END_MESSAGE_MAP()
BOOL HHtmlCtrl::CreateFromStatic( UINT nID, CWnd* pParent )
{
CStatic wndStatic;
if (!wndStatic.SubclassDlgItem(nID, pParent))
return FALSE;
CRect rc;
wndStatic.GetWindowRect(&rc);
pParent->ScreenToClient(&rc);
wndStatic.DestroyWindow();
return Create(NULL,NULL,(WS_CHILD|WS_VISIBLE),rc,pParent,nID,NULL);
}
void HHtmlCtrl::OpenURL( LPCTSTR lpszURL,UINT nOpenType )
{
if (nOpenType == (UINT)HTML_OPEN_VIEW)
{
Navigate(lpszURL);
}
else if (nOpenType == (UINT)HTML_OPEN_DEFAULT)
{
DefaultOpenURL(lpszURL);
}
else if (nOpenType == (UINT)HTML_OPEN_DIALOG)
{
char *pchTemp = const_cast<char*>(lpszURL);
DialogOpenURL(ToWChar(pchTemp));
}
}
void HHtmlCtrl::OnDestroy()
{
CHtmlView::OnDestroy();
}
int HHtmlCtrl::OnMouseActivate(CWnd* pDesktopWnd, UINT nHitTest, UINT msg)
{
return CHtmlView::OnMouseActivate(pDesktopWnd, nHitTest, msg);
}
HHtmlCtrl::HHtmlCtrl()
{
}
HHtmlCtrl::~HHtmlCtrl()
{
}
void HHtmlCtrl::PostNcDestroy()
{
} | [
"[email protected]@f92b348d-55a1-4afa-8193-148a6675784b"
] | [
[
[
1,
157
]
]
] |
36560d637e9a65cc21845da4f26f70eec5884538 | 075043812c30c1914e012b52c60bc3be2cfe49cc | /src/SDLGUIlib/Widget.h | 5bd47bb17029e19c05a2c9244820bc42ca2859d5 | [] | no_license | Luke-Vulpa/Shoko-Rocket | 8a916d70bf777032e945c711716123f692004829 | 6f727a2cf2f072db11493b739cc3736aec40d4cb | refs/heads/master | 2020-12-28T12:03:14.055572 | 2010-02-28T11:58:26 | 2010-02-28T11:58:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,590 | h | #pragma once
#include "vmath.h"
#include <vector>
#include <boost/signal.hpp>
#include <boost/bind.hpp>
#include "Event.h"
#include "TextAlignment.h"
#include "BlittableRect.h"
#include "Tiling.h"
#include <sdl.h>
//Widgets should not be used on the stack - they are tracked automatically!
using std::vector;
class Widget
{
protected:
Vector2i position_;
Vector2i size_;
vector<Widget*> children_;
vector<Widget*> pending_children_;
vector<Widget*> pending_removal_children_;
Widget* parent_;
Widget* left_link_;
Widget* right_link_;
Widget* up_link_;
Widget* down_link_;
Widget* left_inner_link_;
Widget* right_inner_link_;
Widget* up_inner_link_;
Widget* down_inner_link_;
BlittableRect* blit_rect_;
BlittableRect* back_rect_;
int z_order_;
bool deletion_due_;
static Widget* widget_with_focus_;
static Widget* widget_with_highlight_;
static Widget* widget_with_depression_;
static Widget* widget_with_drag_;
static Widget* widget_with_modal_;
static Widget* widget_with_edit_;
static DragEventArgs drag_event_args_;
static Vector2i drag_start_position_;
static vector<Widget*> root_; // The widgets that aren't children
static vector<Widget*> all_; // All the widgets
static vector<Widget*> pending_root_; //Pending version are widgets added by a callback
static vector<Widget*> pending_all_;
static bool event_lock_;
bool invalidated_;
bool rejects_focus_;
bool hides_highlight_; //For item browser widget to prevent background turning blue
bool allow_drag_;
bool depressed_;
bool visible_;
bool ignore_dest_transparency_;
bool allow_edit_;
WidgetText widget_text_;
std::string tag_; //Stores some related name or useful data
static float screen_fade_;
static BlittableRect* screen_fade_rect_;
static BlittableRect* edit_cursor_rect_;
static double sum_time_;
void InsertPending();
void DeleteInternal();
static void RemoveEventLock();
public:
/* Typedefs etc */
typedef boost::signal<void (Widget*)> WidgetEvent;
typedef boost::signal<void (Widget*, MouseEventArgs)> MouseEvent;
typedef boost::signal<void (Widget*, KeyPressEventArgs)> KeyEvent;
typedef boost::signal<void (Widget*, DragEventArgs*)> DragEvent;
typedef boost::signal<void (Widget*, BlittableRect*)> DrawEvent;
/* Constructors */
Widget(void);
Widget(std::string _filename);
Widget(BlittableRect* _blittable);
Widget(VerticalTile _tiles, int _height);
Widget(HorizontalTile _tiles, int _width);
virtual ~Widget(void);
void Delete();
static Widget* GetWidgetWithFocus(){return widget_with_focus_;}
/* Getters and setters */
Vector2i GetPosition(){return position_;}
Vector2i GetGlobalPosition();
void SetPosition(Vector2i _position);
Vector2i GetSize(){return size_;}
void SetSize(Vector2i _size);
void SetZOrder(int _z_order){z_order_ = _z_order;}
int GetZOrder(){return z_order_;}
void SetTag(std::string _tag){tag_ = _tag;}
std::string GetTag(){return tag_;}
/* Children members */
vector<Widget*>& GetChildren();
void AddChild(Widget* _widget);
void RemoveChild(Widget* _widget);
void ClearChildren();
/* Parent members */
void SetParent(Widget* _widget){parent_ = _widget;}
Widget* GetParent(){return parent_;}
/* Signals */
WidgetEvent OnClick;
WidgetEvent OnFocusedClick;
MouseEvent OnMouseClick;
MouseEvent OnMouseMove;
WidgetEvent OnGainFocus;
WidgetEvent OnLostFocus;
KeyEvent OnKeyUp;
DrawEvent OnDraw;
/* Static signals */
static KeyEvent OnGlobalKeyUp;
DragEvent OnDragStart; //Allows filling of drag data - drag_type must be non zero
DragEvent OnDragReset;
DragEvent OnDragEnter;
DragEvent OnDragLand;
/* Event handling */
void HandleEvent(Event _event);
/* Keyboard links */
void LinkLeft(Widget* _link){left_link_ = _link;}
void LinkRight(Widget* _link){right_link_ = _link;}
void LinkUp(Widget* _link){up_link_ = _link;}
void LinkDown(Widget* _link){down_link_ = _link;}
Widget* GetLeftLink(){return left_link_;}
Widget* GetRightLink(){return right_link_;}
Widget* GetUpLink(){return up_link_;}
Widget* GetDownLink(){return down_link_;}
void LinkInnerLeft(Widget* _link){left_inner_link_ = _link;}
void LinkInnerRight(Widget* _link){right_inner_link_ = _link;}
void LinkInnerUp(Widget* _link){up_inner_link_ = _link;}
void LinkInnerDown(Widget* _link){down_inner_link_ = _link;}
Widget* GetLeftParentLink();
Widget* GetRightParentLink();
Widget* GetUpParentLink();
Widget* GetDownParentLink();
/* Visibility */
bool GetVisibility(){return visible_;}
void SetVisibility(bool _visibility){visible_ = _visibility;}
/* Focus */
bool HasFocus(){return widget_with_focus_ == this;}
void SetFocus();
static void ClearFocus();
void SetRejectsFocus(bool _focus){rejects_focus_ = _focus;}
bool GetRejectsFocus(){return rejects_focus_;}
/* Highlight */
bool HasHighlight(){return widget_with_highlight_ == this;}
void SetHidesHighlight(bool _hides_highlight){hides_highlight_ = _hides_highlight;}
void SetHighlight();
/* Click depression */
bool HasDepressed(){return depressed_;}
void SetDepresssed(bool _depressed);
/* Drag and drop */
bool GetAllowDrag(){return allow_drag_;}
void SetAllowDrag(bool _allow_drag){allow_drag_ = _allow_drag;}
static Widget* GetDraggedWidget(){return widget_with_drag_;}
/* Drawing and redrawing */
void Redraw();
void Invalidate();
void SetText(std::string _text, TextAlignment::Enum _alignment);
void SetTextWrap(bool _wrap);
BlittableRect* GetBackRect(){return back_rect_;}
/* Root handling and drawing */
static void ClearRoot();
static vector<Widget*> GetRoot(){return root_;}
static void RenderRoot(BlittableRect* _screen);
static void DistributeSDLEvents(SDL_Event* event);
static void Tick(float _dt){sum_time_ += _dt;}
/* Modal widget */
static Widget* GetModalWidget(){return widget_with_modal_;}
static void SetModalWidget(Widget* _widget);
bool HasModal(){return widget_with_modal_ == this;}
bool HasOrInheritsModal();
void SetModal(bool _modal);
/* Text edit */
static Widget* GetEdittingWidget(){return widget_with_edit_;}
bool GetEditable(){return allow_edit_;}
void SetEditable(bool _editable){allow_edit_ = _editable;}
bool HasEditting();
void SetEditting(bool _editting);
std::string GetText(){return widget_text_.GetText();}
/* Screen fading */
static void SetFade(float _fade_amount);
static float GetFade(){return screen_fade_;}
};
| [
"[email protected]"
] | [
[
[
1,
212
]
]
] |
8cfdf33f5732dc047db8ee38b86407b3487c1862 | 25f1d3e7bbb6f445174e75fed29a1028546d3562 | /2DTransView.cpp | 23dce376e3204b81a18541298fcdea02c6909393 | [] | no_license | psgsgpsg/windr2-project | 288694c5d4bb8f28e67c392a2b15220d4b02f9af | 4f4f92734860cba028399bda6ab4ea7d46f63ca1 | refs/heads/master | 2021-01-22T23:26:48.972710 | 2010-06-16T08:31:34 | 2010-06-16T08:31:34 | 39,536,718 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,786 | cpp | // 2DTransView.cpp : CMy2DTransView 클래스의 구현
#include "stdafx.h"
#include "2DTrans.h"
#include "MainFrm.h"
#include "2DTransDoc.h"
#include "2DTransView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
using namespace std;
// 좌표축을 그리기 위한 펜의 속성 및 색상 설정 (전역)
CPen Circle( PS_SOLID, 3, RGB( 255, 0, 0 ) );
CPen CoorLine( PS_DASH, 1, RGB( 0, 0, 0 ) );
// CMy2DTransView
IMPLEMENT_DYNCREATE(CMy2DTransView, CView)
BEGIN_MESSAGE_MAP(CMy2DTransView, CView)
// 표준 메뉴 명령입니다.
ON_COMMAND(ID_FILE_OPEN, &CMy2DTransView::OnFileOpen)
ON_COMMAND(ID_FILE_NEW, &CMy2DTransView::OnFileNew)
ON_COMMAND(ID_FILE_PRINT, &CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, &CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, &CMy2DTransView::OnFilePrintPreview)
// 마우스 명령에 따른 메시지 맵
ON_WM_RBUTTONUP()
ON_WM_MOUSEMOVE()
ON_WM_MOUSEWHEEL()
ON_WM_LBUTTONDOWN()
ON_WM_LBUTTONUP()
// 메뉴 코맨드 메시지 맵
// 이동 범주 메뉴 메시지
ON_COMMAND(ID_DIR_DOWN, &CMy2DTransView::OnDirDown)
ON_COMMAND(ID_DIR_LEFT, &CMy2DTransView::OnDirLeft)
ON_COMMAND(ID_DIR_LUP, &CMy2DTransView::OnDirLup)
ON_COMMAND(ID_DIR_LDOWN, &CMy2DTransView::OnDirLdown)
ON_COMMAND(ID_DIR_RDOWN, &CMy2DTransView::OnDirRdown)
ON_COMMAND(ID_DIR_RIGHT, &CMy2DTransView::OnDirRight)
ON_COMMAND(ID_DIR_RUP, &CMy2DTransView::OnDirRup)
ON_COMMAND(ID_DIR_UP, &CMy2DTransView::OnDirUp)
// 회전 및 크기 변경 메뉴 메시지
ON_COMMAND(ID_ROT_LEFT, &CMy2DTransView::OnRotateLeft)
ON_COMMAND(ID_ROT_RIGHT, &CMy2DTransView::OnRotateRight)
ON_COMMAND(ID_SCALE_MAGNIFY, &CMy2DTransView::OnScaleMagnify)
ON_COMMAND(ID_SCALE_ORIGINAL, &CMy2DTransView::recalcScale)
ON_COMMAND(ID_SCALE_SHRINK, &CMy2DTransView::OnScaleShrink)
END_MESSAGE_MAP()
// CMy2DTransView 생성/소멸
CMy2DTransView::CMy2DTransView()
{
// 여기에 생성 코드를 추가합니다.
nElements = 0;
DirSize = 10;
Scale = 1.0;
moveX = 0.0;
moveY = 0.0;
delScale = 0.1;
rotAngle = 10.0;
rotCenterX = 0.0;
rotCenterY = 0.0;
totalRot = 0.0;
// jbrBack.CreateSolidBrush(crBack); // 지정된 색으로 브러시 생성.
// crBack = RGB(255, 255, 255); // 배경 색을 흰색으로 설정.
}
CMy2DTransView::~CMy2DTransView()
{
}
BOOL CMy2DTransView::PreCreateWindow(CREATESTRUCT& cs)
{
// CREATESTRUCT cs를 수정하여 여기에서
// Window 클래스 또는 스타일을 수정합니다.
return CView::PreCreateWindow(cs);
}
// CMy2DTransView 그리기
void CMy2DTransView::OnDraw(CDC* pDC)
{
// 2DTransDoc 클래스의 구현에 문제를 확인하는 부분으로
// 이 부분은 특별한 문제가 없을 경우 삭제해도 무방함
// 예외처리가 필요한 경우에는 반드시 이 부분이 존재해야 함
// CMy2DTransDoc* pDoc = GetDocument();
// ASSERT_VALID(pDoc);
// if (!pDoc) return;
GetClientRect(rcClient); // client 영역 설정
//pDC->FillRect(rcClient, &jbrBack); // 브러시로 클라이언트 영역을 채움.
//pDC->SetBkColor(crBack); // 지정된 바탕화면 색으로 덮음.
/* 점 데이터의 최대 최소값을 읽어들여 스케일링을 하는 부분
1. 마우스 조작이 가해진 경우 GetCapture()로 플래그를 읽어 들여 동작 여부를 확인함
2. 도형 요소의 수가 0일 경우에는 동작하지 않음 */
// nElements가 0이 아닐 경우에만
if (nElements != 0) {
WIDTH = rcClient.Width(); // 클라이언트 영역의 폭을 읽어옴
HEIGHT = rcClient.Height(); // 클라이언트 영역의 높이를 읽어옴
cen_x = (int)(WIDTH/2); // 클라이언트 영역의 중앙점 x 좌표
cen_y = (int)(HEIGHT/2); // 클라이언트 영역의 중앙점 y 좌표
/* 읽어들인 데이터로부터 중심점을 계산 */
wsx = (MaxX - MinX) / 2;
wsy = (MaxY - MinY) / 2;
CenX = MinX + wsx;
CenY = MinY + wsy;
// 스케일을 계산함. 작은쪽을 취해준다 min(x, y)를 사용함
// 마우스 휠 조작으로 스케일이 변경된 경우에는 계산하지 않음
if ( !isScaleRatioCustomized ) {
Scale = (double)(0.9 * min( WIDTH/(wsx*2), HEIGHT/(wsy*2) ));
}
/* 계산한 중심점을 스케일에 맞추어 변환하고, 클라이언트 영역의 중심점과의 차이를 저장 */
CenX = cen_x - Scale * ( CenX - MinX );
CenY = cen_y - ( HEIGHT - ( Scale * ( CenY - MinY) ) );
/* 데이터의 원점을 스케일에 맞추어 변환하고, 클라이언트 영역의 중심점과의 차이를 저장 */
originX = ( Scale * -MinX ) + CenX + moveX;
originY = ( HEIGHT + (Scale * MinY) ) + CenY + moveY;
/* 회전 중심점을 화면 좌표로 재계산하여 저장 */
rotCenterX_view = Scale * (rotCenterX - MinX) + CenX + moveX;
rotCenterY_view = HEIGHT - (Scale * (rotCenterY - MinY)) + CenY + moveY;
/* 좌표축을 화면에 뿌려줌 */
DrawAxes();
// 계산된 스케일로 점 데이터를 다시 계산
if ( GetCapture() != this ) { // 특정 조작의 경우, SetCapture를 통해 아래 연산을 하지 않도록 할 수 있음
int k = 0;
for(vector<DisplayList>::iterator j = tempList.begin(); j != tempList.end(); ++j) {
for(unsigned int i = 0; i < j->GetNodes(); ++i) {
// viewport mapping을 수행
j->setXPos( i, Scale * ( DList[k].getXPos(i) - MinX ) + CenX + moveX);
j->setYPos( i, (HEIGHT - ( Scale * ( DList[k].getYPos(i) - MinY ) )) + CenY + moveY);
}
// 회전 변환을 수행
j->rot(totalRot, rotCenterX_view, rotCenterY_view);
++k;
}
}
// 계산된 tempList 데이터를 화면에 그려줌
DrawLines();
}
}
// CMy2DTransView 인쇄
void CMy2DTransView::OnFilePrintPreview()
{
AFXPrintPreview(this);
}
BOOL CMy2DTransView::OnPreparePrinting(CPrintInfo* pInfo)
{
// 기본적인 준비
return DoPreparePrinting(pInfo);
}
void CMy2DTransView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: 인쇄하기 전에 추가 초기화 작업을 추가합니다.
}
void CMy2DTransView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: 인쇄 후 정리 작업을 추가합니다.
}
void CMy2DTransView::OnRButtonUp(UINT nFlags, CPoint point)
{
ClientToScreen(&point);
OnContextMenu(this, point);
}
void CMy2DTransView::OnContextMenu(CWnd* pWnd, CPoint point)
{
theApp.GetContextMenuManager()->ShowPopupMenu(IDR_POPUP_EDIT, point.x, point.y, this, FALSE);
}
void CMy2DTransView::AddToRecentFileList(LPCTSTR lpszPathName) // 최근 파일 열기 목록에 추가하는 명령입니다.
{
dynamic_cast<CMy2DTransApp*>(AfxGetApp())->AddToRecentFileList(lpszPathName);
}
CMainFrame* CMy2DTransView::GetMainFrm() // 주 윈도우 주소창의 주소를 반환합니다.
{
return ( dynamic_cast<CMainFrame*>(AfxGetApp()->GetMainWnd()) );
}
// CMy2DTransView 진단
#ifdef _DEBUG
void CMy2DTransView::AssertValid() const
{
CView::AssertValid();
}
void CMy2DTransView::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
CMy2DTransDoc* CMy2DTransView::GetDocument() const // 디버그되지 않은 버전은 인라인으로 지정됩니다.
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CMy2DTransDoc)));
return (CMy2DTransDoc*)m_pDocument;
}
#endif //_DEBUG
// CMy2DTransView 메시지 처리기
// 1. 파일을 열 경우 메세지 처리
void CMy2DTransView::OnFileOpen() {
TCHAR szFilter[] = _T("DAT File (.dat)|*.dat|OUT File (.out)|*.out|All File (.*)|*.*||");
CFileDialog m_FileOpenDialog(TRUE, NULL, NULL, OFN_HIDEREADONLY | OFN_EXPLORER, szFilter);
m_FileOpenDialog.m_ofn.lpstrTitle = _T("데이터 파일 열기"); // 파일 열기 대화 상자의 제목을 설정
// 현재 프로그램 실행 경로를 기본 경로로 설정
TCHAR currentPath[250];
GetCurrentDirectory(255, currentPath);
m_FileOpenDialog.m_ofn.lpstrInitialDir = (LPCTSTR)currentPath;
if( m_FileOpenDialog.DoModal() == IDOK ) {
if( !FileRead( m_FileOpenDialog.GetPathName() ) ) {
AfxMessageBox( _T("파일 읽기가 제대로 수행되지 않았습니다.") );
return;
}// 파일 열기 함수 호출
}
if( m_FileOpenDialog.GetFileName() == _T("\0") ) {
AfxMessageBox( _T("파일을 선택하지 않으셨습니다") );
}
}
bool CMy2DTransView::FileRead(CString FileName) {
TCHAR str[100] = {L'\0'};
bool isColorSelected; // 색이 지정되었는지 여부를 확인하는 변수
MinX = 1.0E6; MinY = 1.0E6;
MaxX = 1.0E-6; MaxY = 1.0E-6;
double x = 0., y = 0.;
int red, green, blue;
unsigned int nNodes;
DisplayList tmp; // 임시 리스트
// DList 원소의 갯수가 0이 아닐 경우 모든 원소를 삭제하도록 해야함
if( !DList.empty() ) { DList.clear(); }
if( !tempList.empty() ) { tempList.clear(); }
// 마우스 움직임 변량값을 초기화
moveX = 0;
moveY = 0;
// 전체 회전값 초기화
totalRot = 0.0;
// 플래그 초기화 수행
isScaleRatioCustomized = false;
// 파일 포인터를 설정/
FILE *fp;
// 파일에 대한 읽기 모드가 실패할 경우 메세지 출력
if ( _tfopen_s(&fp, (LPCTSTR)FileName, _T("r")) != NULL) {
AfxMessageBox(_T("선택한 파일을 읽기 모드로 열수 없습니다.\n다른 프로그램에서 사용중이지 않은지 확인하시기 바랍니다."));
return false;
}
// 파일 구조를 parsing 하는 부분
while (_fgetts(str, 100, fp) != NULL) {
// 첫줄에 "COLOR"가 있다면 R, G, B값을 읽어들임
if (str[0] == 'C') {
_stscanf_s ( _tcschr(str, '/')+1, _T("%d %d %d"), &red, &green, &blue );
// R, G, B 색상은 모두 0-255사이의 값이어야 하므로
if ( red < 0 || red > 255 || green <0 || green > 255 || blue < 0 || blue > 255 ) {
// 오류 메시지 출력
AfxMessageBox( _T("색상 데이터는 0~255 사이어야 합니다.\n데이터 파일이 잘못되지 않았는지 확인하십시오.") );
return false;
} else
{
// 정상적으로 지정된 경우 색상을 저장
tmp.SetRGB(red, green, blue);
isColorSelected = true; // 색이 지정되었음을 지정함
}
}
else if (str[0] == 'P') {
// 만약 COLOR가 없다면 기본색인 흑색이 할당된다
if (!isColorSelected) {
tmp.SetRGB(0, 0, 0);
}
// "POLYGON /" 이후에는 노드의 갯수가 대입된다
_stscanf_s (_tcschr(str, '/')+1, _T("%d"), &nNodes);
// 노드의 갯수는 최소 2개이상이어야 하므로
if ( nNodes < 2) {
// 오류 메시지 출력
AfxMessageBox(_T("노드 갯수는 최소한 2개 이상이어야 합니다.\n데이터 파일이 잘못되지 않았는지 확인하십시오."));
return false;
} else {
// 2개 이상으로 지정된 경우 vector 컨테이너의 공간을 미리 할당함
tmp.setNodes(nNodes);
}
// 점 데이터를 읽어들이는 부분
for (unsigned int i = 0; i < nNodes; ++i) {
_ftscanf_s(fp, _T("%lf %lf"), &x, &y);
tmp.setXPos(i, x);
tmp.setYPos(i, y);
if (x < MinX) MinX = x;
if (y < MinY) MinY = y;
if (x > MaxX) MaxX = x;
if (y > MaxY) MaxY = y;
}
DList.push_back(tmp); // tmp를 DList의 마지막 원소로 삽입
tmp.reset(); // tmp를 초기화 함
isColorSelected = false; // 색 지정 여부 플래그를 초기화 함
}
}
// 최종 element의 갯수는 DList의 사이즈임 (size_type을 int로 캐스팅)
nElements = (int)DList.size();
// tempList에 읽어들인 원본 데이터 DList를 복사
// 미리 공간을 확보
tempList.assign(DList.begin(), DList.end());
// 파일을 닫음
fclose(fp);
// MRU 목록에 해당 파일을 추가하거나 랭크를 상위로 올림
AddToRecentFileList( (LPCTSTR)FileName );
// 읽어들인 데이터로부터 document의 내용을 반영
GetMainFrm()->RedrawWindow();
status.Format( _T("%s - 2DTrans"), FileName );
GetMainFrm()->SetWindowText( status ); // 윈도우 제목창을 다시 설정함
// 파일 읽기 성공 여부 반환
return true;
}
// 좌표축을 그리는 동작 구현 부분
void CMy2DTransView::DrawAxes() {
CClientDC dc(this);
// 데이터의 원점에 해당되는 곳에 원을 그려주고, 십자 표시를 그려줌
// 원은 회전 중심점을 의미함
dc.SelectObject(&Circle);
dc.Ellipse( (int)round(rotCenterX_view) - 2, (int)round(rotCenterY_view) - 2,
(int)round(rotCenterX_view) + 2, (int)round(rotCenterY_view) + 2 );
dc.SelectObject(&CoorLine);
dc.MoveTo( -5, (int)round(originY) );
dc.LineTo( WIDTH + 5, (int)round(originY) );
dc.MoveTo( (int)round(originX), -5 );
dc.LineTo( (int)round(originX), HEIGHT + 5);
// x, y 좌표임을 알려주는 문자를 표시
dc.TextOutW( WIDTH - 10, (int)round(originY) + 10, L"x");
dc.TextOutW( (int)round(originX) + 10, 10, L"y");
}
// 데이터를 그리는 동작 구현 부분
void CMy2DTransView::DrawLines() {
// nElements가 0이 아닐 경우에만
if (nElements != 0) {
CClientDC dc(this);
for(vector<DisplayList>::iterator iterPos = tempList.begin(); iterPos != tempList.end(); ++iterPos) {
// 펜의 속성 및 색상 설정
CPen NewPen( PS_SOLID, 1, RGB( iterPos->getR(), iterPos->getG(), iterPos->getB() ) );
dc.SelectObject(&NewPen);
// i번째 element의 점 데이터를 이용해서 선을 그림
for(unsigned int i = 0; i < iterPos->GetNodes() - 1; i++) {
dc.MoveTo( (int)round(iterPos->getXPos(i)) , (int)round(iterPos->getYPos(i)) );
dc.LineTo( (int)round(iterPos->getXPos(i+1)), (int)round(iterPos->getYPos(i+1)) );
}
// 마지막 노드와 처음 노드를 잇는 부분
// 노드 갯수가 2개인 경우에는 이 동작이 필요하지 않음
if (iterPos->GetNodes() != 2) {
dc.MoveTo( (int)round(iterPos->getXPos(iterPos->GetNodes() - 1)), (int)round(iterPos->getYPos(iterPos->GetNodes() - 1)) );
dc.LineTo( (int)round(iterPos->getXPos(0)) , (int)round(iterPos->getYPos(0)) );
}
}
}
}
// 새 파일을 만들 경우
void CMy2DTransView::OnFileNew() {
CClientDC dc(this); // 클라이언트 영역의 dc를 읽어옴
CString str;
str.Format( _T("제목 없음 - 2DTrans") );
nElements = 0; // Element 갯수를 0으로 리셋하여 draw 방지
tempList.clear(); // DisplayList 데이터를 모두 초기화함
DList.clear();
Scale = 0.0; // Scale을 0.0으로 리셋하고
moveX = 0.0; moveY = 0.0; // 이동 변량 변수 모두 리셋
isScaleRatioCustomized = false; // 스케일 변경 여부 리셋
totalRot = 0.0; // 전체 회전 각도 리셋
GetMainFrm()->m_wndStatusBar.GetElement(0)->SetText( _T("준비됨") ); // 상태 표시줄의 메시지를 초기화
GetMainFrm()->SetWindowText( str ); // 제목 표시줄을 초기화
GetMainFrm()->RedrawWindow(); // 내용을 다시 그리도록 함 (OnDraw 호출)
}
BOOL CMy2DTransView::OnMouseWheel(UINT nFlags, short zDelta, CPoint point)
{
// tempList의 사이즈가 0이 아닐 경우에만
if ( tempList.size() > 0 ) {
// Control 키와 함께 누르지 않은 경우에는, 종료
if( (nFlags & MK_CONTROL) != MK_CONTROL ) {
return CView::OnMouseWheel(nFlags, zDelta, point);
}
// 마우스 조작이 가해졌음을 플래그에 설정
isScaleRatioCustomized = true;
// 휠이 위 아래로 움직이는지 여부에 따라 스케일 수치를 변경함
if ( zDelta > 0 ) {
Scale += delScale;
if ( Scale > 100 ) {
Scale = 100;
}
}
else {
Scale -= delScale;
if (Scale < 1E-6) {
Scale = 1E-6;
}
}
status.Format(_T("X 좌표 : %ld / Y 좌표 : %ld / 현재 배율 : %8.6lf"), point.x, point.y, Scale);
GetMainFrm()->m_wndStatusBar.GetElement(0)->SetText(status);
GetMainFrm()->m_wndStatusBar.RecalcLayout();
GetMainFrm()->m_wndStatusBar.RedrawWindow();
// view에 내용을 반영
GetMainFrm()->RedrawWindow();
}
return CView::OnMouseWheel(nFlags, zDelta, point);
}
void CMy2DTransView::OnMouseMove(UINT nFlags, CPoint point) {
// 마우스 이동시 상태 표시줄에 좌표를 출력합니다.
// 만약 드래그를 한다면 점을 이동합니다.
CPoint realPos(0, 0);
if( GetCapture() == this ) {
// tempList의 사이즈가 0이 아닐 경우에만
if ( tempList.size() > 0 ) {
realPos += (point - anchor);
anchor = point;
// 계산된 좌표만큼 형상을 이동시킨다.
if ( nElements != 0) {
for( vector<DisplayList>::iterator j = tempList.begin(); j != tempList.end(); ++j) {
j->Translate( (double)realPos.x, (double)realPos.y );
}
}
// 마우스로 이동한 변량을 변수에 계속 더한다.
moveX += (double)realPos.x;
moveY += (double)realPos.y;
// view에 내용을 반영
GetMainFrm()->RedrawWindow();
}
}
// 위치를 변수에 저장
curPoint = point;
// 상태 표시줄 업데이트
status.Format(_T("X 좌표 : %ld / Y 좌표 : %ld / 현재 배율 : %8.6lf"), point.x, point.y, Scale);
GetMainFrm()->m_wndStatusBar.GetElement(0)->SetText(status);
GetMainFrm()->m_wndStatusBar.RecalcLayout();
GetMainFrm()->m_wndStatusBar.RedrawWindow();
}
void CMy2DTransView::OnLButtonDown(UINT nFlags, CPoint point)
{
// 마우스 클릭 상태 플래그 설정
SetCapture();
// 클릭한 위치를 저장해둠
anchor = point;
CView::OnLButtonDown(nFlags, point);
}
void CMy2DTransView::OnLButtonUp(UINT nFlags, CPoint point)
{
// 마우스 클릭 상태 플래그 해제
ReleaseCapture();
CView::OnLButtonUp(nFlags, point);
}
void CMy2DTransView::OnDirUp() // 상단으로 형상을 이동하는 함수
{
// tempList의 사이즈가 0이 아닐 경우에만
if ( tempList.size() > 0 ) {
// 모든 DisplayList의 좌표를 Size만큼 위로 이동시킴 (방향이 반대이므로 y를 감소시킴)
for( vector<DisplayList>::iterator i = tempList.begin(); i != tempList.end(); ++i ) {
i->Translate( 0.0, -DirSize );
}
// 이동 변량을 더해준다.
moveY -= DirSize;
SetCapture();
GetMainFrm()->RedrawWindow();
ReleaseCapture();
}
}
void CMy2DTransView::OnDirDown() // 하단으로 형상을 이동하는 함수
{
// tempList의 사이즈가 0이 아닐 경우에만
if ( tempList.size() > 0 ) {
// 모든 DisplayList의 좌표를 Size만큼 아래로 이동시킴 (방향이 반대이므로 y를 증가시킴)
for( vector<DisplayList>::iterator i = tempList.begin(); i != tempList.end(); ++i ) {
i->Translate( 0.0, DirSize );
}
// 이동 변량을 더해준다.
moveY += DirSize;
SetCapture();
GetMainFrm()->RedrawWindow();
ReleaseCapture();
}
}
void CMy2DTransView::OnDirLeft() // 좌측으로 형상을 이동하는 함수
{
// tempList의 사이즈가 0이 아닐 경우에만
if ( tempList.size() > 0 ) {
// 모든 DisplayList의 좌표를 Size만큼 좌로로 이동시킴 (x를 감소시킴)
for( vector<DisplayList>::iterator i = tempList.begin(); i != tempList.end(); ++i ) {
i->Translate( -DirSize, 0.0 );
}
// 이동 변량을 더해준다.
moveX -= DirSize;
SetCapture();
GetMainFrm()->RedrawWindow();
ReleaseCapture();
}
}
void CMy2DTransView::OnDirRight() // 우측으로 형상을 이동하는 함수
{
// tempList의 사이즈가 0이 아닐 경우에만
if ( tempList.size() > 0 ) {
// 모든 DisplayList의 좌표를 Size만큼 우측으로 이동시킴 (x를 증가)
for( vector<DisplayList>::iterator i = tempList.begin(); i != tempList.end(); ++i ) {
i->Translate( DirSize, 0.0 );
}
// 이동 변량을 더해준다.
moveX += DirSize;
SetCapture();
GetMainFrm()->RedrawWindow();
ReleaseCapture();
}
}
void CMy2DTransView::OnDirLup() // 좌측 상단으로 형상을 이동하는 함수
{
// tempList의 사이즈가 0이 아닐 경우에만
if ( tempList.size() > 0 ) {
// 모든 DisplayList의 좌표를 Size만큼 좌측위로 이동 (x를 감소, y를 감소)
for( vector<DisplayList>::iterator i = tempList.begin(); i != tempList.end(); ++i ) {
i->Translate( -DirSize, -DirSize );
}
// 이동 변량을 더해준다.
moveX -= DirSize;
moveY -= DirSize;
SetCapture();
GetMainFrm()->RedrawWindow();
ReleaseCapture();
}
}
void CMy2DTransView::OnDirLdown() // 좌측 하단으로 형상을 이동하는 함수
{
// tempList의 사이즈가 0이 아닐 경우에만
if ( tempList.size() > 0 ) {
// 모든 DisplayList의 좌표를 Size만큼 좌측 아래로 이동 (x를 감소, y를 증가)
for( vector<DisplayList>::iterator i = tempList.begin(); i != tempList.end(); ++i ) {
i->Translate( -DirSize, DirSize );
}
// 이동 변량을 더해준다.
moveX -= DirSize;
moveY += DirSize;
SetCapture();
GetMainFrm()->RedrawWindow();
ReleaseCapture();
}
}
void CMy2DTransView::OnDirRdown() // 우측 하단으로 형상을 이동하는 함수
{
// tempList의 사이즈가 0이 아닐 경우에만
if ( tempList.size() > 0 ) {
// 모든 DisplayList의 좌표를 Size만큼 우측 아래로 이동시킴 (x를 증가, y를 증가)
for( vector<DisplayList>::iterator i = tempList.begin(); i != tempList.end(); ++i ) {
i->Translate( DirSize, DirSize );
}
// 이동 변량을 더해준다.
moveX += DirSize;
moveY += DirSize;
SetCapture();
GetMainFrm()->RedrawWindow();
ReleaseCapture();
}
}
void CMy2DTransView::OnDirRup() // 우측 상단으로 형상을 이동하는 함수
{
// tempList의 사이즈가 0이 아닐 경우에만
if ( tempList.size() > 0 ) {
// 모든 DisplayList의 좌표를 Size만큼 우측 위로 이동시킴 (x를 증가, y를 감소)
for( vector<DisplayList>::iterator i = tempList.begin(); i != tempList.end(); ++i ) {
i->Translate( DirSize, -DirSize );
}
// 이동 변량을 더해준다.
moveX += DirSize;
moveY -= DirSize;
SetCapture();
GetMainFrm()->RedrawWindow();
ReleaseCapture();
}
}
void CMy2DTransView::OnRotateLeft() // 모든 DisplayList의 좌표를 정해진 각도만큼 반시계방향으로 회전시킴
{
// tempList의 사이즈가 0이 아닐 경우에만
//if ( tempList.size() > 0 ) {
// // 모든 DisplayList의 좌표를 회전하여 표현함
// for( vector<DisplayList>::iterator i = tempList.begin(); i != tempList.end(); ++i ) {
// i->rot(-rotAngle, rotCenterX_view, rotCenterY_view);
// }
//}
// 전체 회전 각도를 감소 시킴
totalRot -= rotAngle;
//SetCapture();
GetMainFrm()->RedrawWindow();
//ReleaseCapture();
}
void CMy2DTransView::OnRotateRight() // 모든 DisplayList의 좌표를 정해진 각도만큼 시계방향으로 회전시킴
{
// tempList의 사이즈가 0이 아닐 경우에만
//if ( tempList.size() > 0 ) {
// // 모든 DisplayList의 좌표를 Size만큼 우측 위로 이동시킴 (x를 증가, y를 감소)
// for( vector<DisplayList>::iterator i = tempList.begin(); i != tempList.end(); ++i ) {
// i->rot(rotAngle, rotCenterX_view, rotCenterY_view);
// }
//}
// 전체 회전 각도를 증가시킴
totalRot += rotAngle;
//SetCapture();
GetMainFrm()->RedrawWindow();
//ReleaseCapture();
}
void CMy2DTransView::OnScaleMagnify() // 확대 버튼을 누를 경우 메시지 처리
{
// 프로그램이 자동 계산한 스케일을 사용하지 않도록 플래그 설정
isScaleRatioCustomized = true;
// 스케일을 증가시킴
Scale += delScale;
// Capture 설정을 하고 redraw
GetMainFrm()->RedrawWindow();
// Status Bar에 현재 Scale을 반영
status.Format(_T("X 좌표 : %ld / Y 좌표 : %ld / 현재 배율 : %8.6lf"), curPoint.x, curPoint.y, Scale);
GetMainFrm()->m_wndStatusBar.GetElement(0)->SetText(status);
GetMainFrm()->m_wndStatusBar.RecalcLayout();
GetMainFrm()->m_wndStatusBar.RedrawWindow();
}
// 원래 스케일대로 계산하기. 스케일을 재계산하고, 다시 그립니다.
void CMy2DTransView::recalcScale() {
// 스케일 변경 플래그를 해제
isScaleRatioCustomized = false;
// 다시 그리기
GetMainFrm()->RedrawWindow();
// Status Bar에 현재 Scale을 반영
status.Format(_T("X 좌표 : %ld / Y 좌표 : %ld / 현재 배율 : %8.6lf"), curPoint.x, curPoint.y, Scale);
GetMainFrm()->m_wndStatusBar.GetElement(0)->SetText(status);
GetMainFrm()->m_wndStatusBar.RecalcLayout();
GetMainFrm()->m_wndStatusBar.RedrawWindow();
}
void CMy2DTransView::OnScaleShrink() // 축소 버튼을 누를 경우 메시지 처리
{
// 프로그램이 자동 계산한 스케일을 사용하지 않도록 플래그 설정
isScaleRatioCustomized = true;
// 스케일을 감소시킴
Scale -= delScale;
// Capture 설정을 하고 redraw
GetMainFrm()->RedrawWindow();
// Status Bar에 현재 Scale을 반영
status.Format(_T("X 좌표 : %ld / Y 좌표 : %ld / 현재 배율 : %8.6lf"), curPoint.x, curPoint.y, Scale);
GetMainFrm()->m_wndStatusBar.GetElement(0)->SetText(status);
GetMainFrm()->m_wndStatusBar.RecalcLayout();
GetMainFrm()->m_wndStatusBar.RedrawWindow();
}
size_t CMy2DTransView::round( double d ) // 반올림을 수행하는 함수
{
return (size_t)floor( d + 0.5 );
}
| [
"happyday19c@f92c9028-33b8-4ca2-afdf-7b78eec7ef35",
"Happyday19c@f92c9028-33b8-4ca2-afdf-7b78eec7ef35"
] | [
[
[
1,
12
],
[
19,
23
],
[
26,
36
],
[
40,
46
],
[
55,
59
],
[
61,
61
],
[
72,
81
],
[
84,
91
],
[
98,
98
],
[
102,
102
],
[
106,
108
],
[
111,
120
],
[
124,
124
],
[
133,
133
],
[
141,
141
],
[
144,
145
],
[
150,
150
],
[
154,
154
],
[
158,
190
],
[
192,
193
],
[
196,
196
],
[
201,
201
],
[
203,
228
],
[
235,
236
],
[
241,
247
],
[
249,
249
],
[
251,
253
],
[
257,
258
],
[
268,
268
],
[
273,
277
],
[
279,
280
],
[
282,
285
],
[
298,
300
],
[
303,
305
],
[
317,
318
],
[
320,
320
],
[
323,
328
],
[
332,
337
],
[
342,
344
],
[
348,
348
],
[
355,
356
],
[
379,
385
],
[
388,
389
],
[
393,
394
],
[
400,
407
],
[
410,
411
],
[
413,
414
],
[
423,
426
],
[
432,
432
],
[
462,
466
],
[
482,
482
],
[
490,
492
],
[
497,
497
],
[
501,
504
],
[
506,
507
],
[
509,
510
],
[
512,
515
],
[
517,
521
],
[
523,
523
],
[
538,
539
],
[
541,
541
],
[
548,
548
],
[
557,
557
],
[
559,
559
],
[
574,
575
],
[
593,
593
],
[
595,
595
],
[
602,
602
],
[
612,
612
],
[
614,
614
],
[
621,
621
],
[
631,
631
],
[
633,
633
],
[
640,
640
],
[
650,
650
],
[
652,
652
],
[
659,
659
],
[
669,
669
],
[
671,
671
],
[
686,
687
],
[
723,
723
]
],
[
[
13,
18
],
[
24,
25
],
[
37,
39
],
[
47,
54
],
[
60,
60
],
[
62,
71
],
[
82,
83
],
[
92,
97
],
[
99,
101
],
[
103,
105
],
[
109,
110
],
[
121,
123
],
[
125,
132
],
[
134,
140
],
[
142,
143
],
[
146,
149
],
[
151,
153
],
[
155,
157
],
[
191,
191
],
[
194,
195
],
[
197,
200
],
[
202,
202
],
[
229,
234
],
[
237,
240
],
[
248,
248
],
[
250,
250
],
[
254,
256
],
[
259,
267
],
[
269,
272
],
[
278,
278
],
[
281,
281
],
[
286,
297
],
[
301,
302
],
[
306,
316
],
[
319,
319
],
[
321,
322
],
[
329,
331
],
[
338,
341
],
[
345,
347
],
[
349,
354
],
[
357,
378
],
[
386,
387
],
[
390,
392
],
[
395,
399
],
[
408,
409
],
[
412,
412
],
[
415,
422
],
[
427,
431
],
[
433,
461
],
[
467,
481
],
[
483,
489
],
[
493,
496
],
[
498,
500
],
[
505,
505
],
[
508,
508
],
[
511,
511
],
[
516,
516
],
[
522,
522
],
[
524,
537
],
[
540,
540
],
[
542,
547
],
[
549,
556
],
[
558,
558
],
[
560,
573
],
[
576,
592
],
[
594,
594
],
[
596,
601
],
[
603,
611
],
[
613,
613
],
[
615,
620
],
[
622,
630
],
[
632,
632
],
[
634,
639
],
[
641,
649
],
[
651,
651
],
[
653,
658
],
[
660,
668
],
[
670,
670
],
[
672,
685
],
[
688,
722
],
[
724,
760
]
]
] |
932fc0b749c451fa1156667e26b8765c1465c110 | 6e563096253fe45a51956dde69e96c73c5ed3c18 | /dhnetsdk/Demo/NetSDKDemoDlg.cpp | df6c221b8fae8583c2a2b839bcb499cc4369eab0 | [] | 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 | 128,654 | cpp | // NetSDKDemoDlg.cpp : implementation file
#include "stdafx.h"
#include "NetSDKDemo.h"
#include "NetSDKDemoDlg.h"
#include "splitinfodlg.h"
#include "adddevicedlg.h"
#include "searchrecord.h"
#include "systemconfig.h"
#include "extptzctrl.h"
#include "ptzmenu.h"
#include "transcom.h"
#include "recordctrldlg.h"
#include "deviceworkstate.h"
#include "alarmctrldlg.h"
#include "cyclemonitor.h"
//#include "systemcfg.h"
#include "direct.h"
#include "playbackbytime.h"
#include "downloadbytime.h"
#include "NetUpgrade.h"
#include "DDNS_QueryIP.h"
#include "DiskControl.h"
#include "usermanage.h"
#include "configmaindlg.h"
#include "PreviewParmsDlg.h"
#include "automaintenance.h"
#include "../netsdk/assistant.h"
#include "../netsdk/netsdk.h"
/*
/////////////////////////////////////////
//console
////////////////////////////////////////
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
#include <iostream>
#include <fstream>
*/
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// #pragma data_seg("sharesec")
// __declspec (allocate("sharesec")) HWND g_share_hWnd = NULL;
// #pragma comment(linker,"/SECTION:sharesec,RWS")
#define ALARMLOG 0x1099
#define UPDATATREE 0x2000
BOOL g_bUpdataTree = FALSE;
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
inline void dbg_print_ex(int level, const char *msg, ...)
{
char buf[256];
va_list ap;
va_start(ap, msg); // use variable arg list
vsprintf(buf, msg, ap);
va_end( ap );
}
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
virtual BOOL OnInitDialog();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CNetSDKDemoDlg dialog
CNetSDKDemoDlg::CNetSDKDemoDlg(CWnd* pParent /*=NULL*/)
: CDialog(CNetSDKDemoDlg::IDD, pParent)
{
m_connectwaittime = 3000;
m_myBrush.CreateSolidBrush(RGB(255,255,255));
//{{AFX_DATA_INIT(CNetSDKDemoDlg)
m_play_frame = 0;
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = 0;//AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CNetSDKDemoDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CNetSDKDemoDlg)
DDX_Control(pDX, IDC_TREE_DEVICELIST, m_devicelist);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CNetSDKDemoDlg, CDialog)
//{{AFX_MSG_MAP(CNetSDKDemoDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_WM_CLOSE()
ON_WM_TIMER()
ON_WM_CTLCOLOR()
ON_NOTIFY(NM_DBLCLK, IDC_TREE_DEVICELIST, OnDblclkTreeDevicelist)
ON_WM_SIZE()
ON_WM_DESTROY()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////初始化回调相关的函数////////////////////////////////////////////////
//设备断开时回调函数,可以用来处理断开后设备列表的更新及设备的删除操作
void CALLBACK DisConnectFunc(LONG lLoginID, char *pchDVRIP, LONG nDVRPort, DWORD dwUser)
{
if(dwUser == 0)
{
return;
}
CNetSDKDemoDlg *dlg = (CNetSDKDemoDlg *)dwUser;
dlg->DeviceDisConnect(lLoginID, pchDVRIP,nDVRPort);
}
//设备断开处理
void CNetSDKDemoDlg::DeviceDisConnect(LONG lLoginID, char *sDVRIP,LONG nDVRPort)
{
CDevMgr::GetDevMgr().ModifyNode(lLoginID, FALSE);
g_bUpdataTree = TRUE;
return;
DeviceNode node;
int r = CDevMgr::GetDevMgr().GetDev(lLoginID, node);
if (r < 0)
{
return ;
}
/*
DeviceNode *nDev=(DeviceNode *)FindDeviceInfo(lLoginID, sDVRIP,nDVRPort);
if(nDev == NULL)
{
return;
}
*/
CString nStr;
nStr.Format("%s ",node.IP);
nStr = nStr + ConvertString(MSG_DEVICE_DISCONNECT);
ProcessDeleteDevice(&node, true, true);
UpdateDeviceList();
UpdateCurScreenInfo();
MessageBox(nStr);
UpdateScreen(m_normalBtnPannel.GetSplit());
// Invalidate(true);
}
void CALLBACK HaveReconnFunc(LONG lLoginID, char *pchDVRIP, LONG nDVRPort, DWORD dwUser)
{
if(dwUser == 0)
{
return;
}
CNetSDKDemoDlg *dlg = (CNetSDKDemoDlg *)dwUser;
dlg->DeviceReConnect(lLoginID, pchDVRIP,nDVRPort);
}
void CNetSDKDemoDlg::DeviceReConnect(LONG lLoginID, char *sDVRIP,LONG nDVRPort)
{
CDevMgr::GetDevMgr().ModifyNode(lLoginID, TRUE);
UpdateDeviceList();
return;
}
//消息回调处理函数,是对整个sdk应用的回调
BOOL CALLBACK MessCallBack(LONG lCommand, LONG lLoginID, char *pBuf, DWORD dwBufLen,
char *pchDVRIP, LONG nDVRPort, DWORD dwUser)
{
if(!dwUser) return FALSE;
CNetSDKDemoDlg *dlg = (CNetSDKDemoDlg *)dwUser;
return dlg ->ReceiveMessage(lLoginID, lCommand, pchDVRIP, nDVRPort,pBuf, dwBufLen);
}
//接收到设备消息的处理,目前只定义了报警消息回调
BOOL CNetSDKDemoDlg::ReceiveMessage(LONG lLoginID, LONG lCommand, char *pchDVRIP, LONG nDVRPort,
char *pBuf, DWORD dwBufLen)
{
// EnterCriticalSection(&g_csAlarm);
// CCSLock lk(g_cs);
/*
if (!m_bShowStatus)
{
return false;
}*/
int nRet = CDevMgr::GetDevMgr().SetAlarmInfo(lLoginID, lCommand, pchDVRIP, nDVRPort,
pBuf, dwBufLen);
return nRet<0?FALSE:TRUE;
/*
DeviceNode node;
int r = CDevMgr::GetDevMgr().GetDev(lLoginID, node);
if (r < 0)
{
LeaveCriticalSection(&g_csAlarm);
return false;
}
DeviceNode *nDev = &node;
DeviceNode *nDev = (DeviceNode *)FindDeviceInfo(lLoginID, pchDVRIP,nDVRPort );
if(nDev == NULL)
{
goto e_exit;
}
switch(lCommand) {
case COMM_ALARM:
{
NET_CLIENT_STATE *ClientState = (NET_CLIENT_STATE *)pBuf;
if(ClientState == NULL)
{
return FALSE;
}
printf("alarm infomation:\n");
CString str;
for(int i=0; i<ClientState->channelcount; i++)
{
CString strTemp;
strTemp.Format("%d ", ClientState->record[i]);
str += strTemp;
}
printf("alarm: Recording Status-- %s\n", str.GetBuffer(0));
for(i=0; i<ClientState->alarminputcount; i++)
{
CString strTemp;
strTemp.Format("%d ", ClientState->alarm[i]);
str += strTemp;
}
printf("alarm: Extern Alarm-- %s\n", str.GetBuffer(0));
for(i=0; i<ClientState->channelcount; i++)
{
CString strTemp;
strTemp.Format("%d ", ClientState->motiondection[i]);
str += strTemp;
}
printf("alarm: Motion Detect-- %s\n", str.GetBuffer(0));
for(i=0; i<ClientState->channelcount; i++)
{
CString strTemp;
strTemp.Format("%d ", ClientState->videolost[i]);
str += strTemp;
}
printf("alarm: Video Lost-- %s\n", str.GetBuffer(0));
}
UpdateDeviceState(nDev, pBuf, dwBufLen);
//m_ClientStateDlg.UpdateState(nDev,pBuf, dwBufLen);
if(!m_ClientStateDlg.m_isNoMoreShow)
{
m_ClientStateDlg.ShowWindow(SW_SHOW);
}
break;
default :
goto e_exit;
}
// LeaveCriticalSection(&g_csAlarm);
return true;
e_exit:
// LeaveCriticalSection(&g_csAlarm);
return false;
*/
/*
DeviceNode *nDev = (DeviceNode *)FindDeviceInfo(lLoginID, pchDVRIP,nDVRPort );
if(nDev == NULL)
{
m_bShowStatus = FALSE;
return false;
}
switch(lCommand) {
case COMM_ALARM:
UpdateDeviceState(nDev, pBuf, dwBufLen);
m_ClientStateDlg.UpdateState(nDev,pBuf, dwBufLen);
if(!m_ClientStateDlg.m_isNoMoreShow)
{
m_ClientStateDlg.ShowWindow(SW_SHOW);
}
break;
default :
m_bShowStatus = FALSE;
return false;
}
m_bShowStatus = FALSE;
return true;*/
}
//自定义画板回调,可以用来显示通道信息
void CALLBACK ChannelAutoDraw(LONG lLoginID, LONG lPlayHandle, HDC hDC, DWORD dwUser)
{
if(!dwUser) return;
CNetSDKDemoDlg *dlg = (CNetSDKDemoDlg *)dwUser;
dlg->AddDisplayInfo(lLoginID, lPlayHandle, hDC);
}
//叠加字符或图片
void CNetSDKDemoDlg::AddDisplayInfo(LONG lLoginID, LONG lPlayHandle, HDC hDC)
{
DeviceNode *pDev;
CString str;
//取得窗口号
int i = GetHandleSplit(lPlayHandle);
if(i < 0)
{
return;
}
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(i, &siNode);
if (!ret)
{
return;
}
switch(siNode.Type)
{
case SPLIT_TYPE_MONITOR:
{
SplitMonitorParam *mParam = (SplitMonitorParam *)siNode.Param;
if (mParam)
{
pDev = mParam->pDevice;
str.Format(" %s[%s] %02d", pDev->Name,pDev->IP, mParam->iChannel + 1);
str = ConvertString(MSG_DEMODLG_MONITOR) + str;
// for(int j = 0; j < pDev->State.channelcount; j++)
// {
// if(pDev->State.motion[mParam->iChannel])
if(pDev->State.cState.motiondection[mParam->iChannel])
{
CString almstr;
almstr.Format(ConvertString("! ALARM !"));
SetTextColor(hDC, RGB(255,0,0));
CRect rect;
//m_playWnd[i].GetClientRect(&rect);
CWnd* pWnd = m_screenPannel.GetPage(i);
if (!pWnd)
{
MessageBox(ConvertString("unexpected error!!"));
}
pWnd->GetClientRect(&rect);
if (pWnd && ::IsWindow(pWnd->GetSafeHwnd()))
{
TextOut(hDC, rect.right / 3, rect.bottom / 2, almstr.GetBuffer(0), almstr.GetLength());
}
// break;
}
// }
}
}
break;
case SPLIT_TYPE_MULTIPLAY:
pDev = (DeviceNode *)siNode.Param;
str.Format(" %s[%s]", pDev->Name, pDev->IP);
str = ConvertString(MSG_DEMODLG_PREVIEW) + str;
break;
case SPLIT_TYPE_NETPLAY:
{
SplitNetPlayParam *nParam = (SplitNetPlayParam *)siNode.Param;
pDev = nParam->pFileInfo->pDevice;
str.Format(" %s[%s]%02d", pDev->Name, pDev->IP,
nParam->pFileInfo->fileinfo.ch + 1);
str = ConvertString(MSG_DEMODLG_PLAYBACKCHL) + str;
}
break;
case SPLIT_TYPE_PBBYTIME:
{
break;
}
case SPLIT_TYPE_CYCLEMONITOR:
{
SplitCycleParam *cParam = (SplitCycleParam *)siNode.Param;
CycleChannelInfo *cci = 0;
POSITION pos = cParam->pChannelList->GetHeadPosition();
for (int counter = 0; counter <= cParam->iCurPosition; counter++)
{
cci = (CycleChannelInfo *)cParam->pChannelList->GetNext(pos);
}
pDev = (DeviceNode *)cci->dwDeviceID;
str.Format(" %s[%s](%02d)", pDev->Name, pDev->IP, cci->iChannel + 1);
str = ConvertString(MSG_DEMODLG_CYCLEMONITOR) + str;
break;
}
default :
return;
}
SetBkMode(hDC, TRANSPARENT);
SetTextColor(hDC, RGB(255,255,0));
TextOut(hDC, 0, 0, str.GetBuffer(0), str.GetLength());
}
// CNetSDKDemoDlg message handlers
BOOL CNetSDKDemoDlg::OnInitDialog()
{
// RedirectIOToConsole();
// if(g_share_hWnd)
// {
// AfxMessageBox(_T("Only one process allowed"));
// CWnd* pWnd = CWnd::FromHandle(g_share_hWnd);
// if(pWnd)
// {
// if (pWnd->IsIconic())
// {
// pWnd->ShowWindow(SW_RESTORE);
// }
// pWnd->SetForegroundWindow();
// }
// exit(0);
// }
// else
// {
// g_share_hWnd = m_hWnd;
// }
CDialog::OnInitDialog();
g_SetWndStaticText(this);
Getversion();
char tmpDir[1000];
_getcwd(tmpDir, 1000);
g_strWorkDir.Format("%s", tmpDir);
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
//初始化网络sdk,所有调用的开始
BOOL ret = CLIENT_Init(DisConnectFunc, (DWORD)this);
if (!ret)
{
LastError();
}
//设置断线重连
CLIENT_SetAutoReconnect(HaveReconnFunc, (DWORD)this);
//设置信息回调函数,默认接收所有设备信息
CLIENT_SetDVRMessCallBack(MessCallBack, (DWORD)this);
//初始化各子窗口
m_selectPannel.Create(IDD_PANNEL_SELECT, this);
//m_screenPannel.Create(IDD_PANNEL_SCREEN, this);
m_screenPannel.Create(
NULL,
NULL,
WS_CHILD|WS_VISIBLE,
CRect(0,0,0,0),
this,
1981);
m_saveDataPannel.Create(IDD_PANNEL_SAVEDATA, this);
m_colorPannel.Create(IDD_PANNEL_COLOR, this);
m_playctrlPannel.Create(IDD_PANNEL_PLAYCTRL, this);
m_normalBtnPannel.Create(IDD_PANNEL_NORMAL_BTN, this);
m_advanceBtnPannel.Create(IDD_PANNEL_ADVANCE_BTN, this);
m_ptzPannel.Create(IDD_PANNEL_PTZ, this);
m_runtimeMsgPannel.Create(IDD_PANNEL_RUNTIME_MSG, this);
UpdatePannelPosition();
m_selectPannel.ShowWindow(SW_SHOW);
m_screenPannel.ShowWindow(SW_SHOW);
m_saveDataPannel.ShowWindow(SW_HIDE);
m_colorPannel.ShowWindow(SW_HIDE);
m_playctrlPannel.ShowWindow(SW_HIDE);
m_devicelist.ShowWindow(SW_SHOW);
m_advanceBtnPannel.ShowWindow(SW_HIDE);
m_ptzPannel.ShowWindow(SW_HIDE);
m_runtimeMsgPannel.ShowWindow(SW_SHOW);
//初始化画面分割模式选择项
m_normalBtnPannel.InitSplit(CUR_SPLIT);
m_normalBtnPannel.ShowWindow(SW_SHOW);
m_curScreen = 0;
m_screenPannel.SetShowPlayWin(SPLIT4, m_curScreen);
//设置连接等待时间
CLIENT_SetConnectTime(m_connectwaittime, 3);
LastError();
CLIENT_RigisterDrawFun(ChannelAutoDraw, (DWORD)this);
LastError();
// for (int j = 0; j < CUR_MAXCHAN; j++)
// {
// m_playWnd[j].Create(IDD_CHILD_PLAYWND, &m_screenPannel);//can't input this point,may be input
// m_playWnd[j].SetWinID(j);
// }
// m_originParent = 0;
// m_bFullSCRN = FALSE;
//初始化关闭声音
m_curSoundSplit = -1;
//创建状态页面和系统配置页面
m_ClientStateDlg.Create(IDD_CLIENT_STATE);
m_ClientStateDlg.CenterWindow();
m_ClientStateDlg.m_isNoMoreShow = TRUE;
m_ClientStateDlg.UpdateData(false);
//初始化云台控制状态
m_bPTZCtrl = FALSE;
//刷新界面信息
UpdateScreen(CUR_SPLIT+1);
UpdateCurScreenInfo();
/*Begin: Add by yehao(10857) For Task.NO.11071 2006-12-23*/
m_broadcastDevList.clear();
m_bRecord = FALSE;
memset((void *)&m_talkhandle, 0, sizeof(TalkHandleInfo));
m_uRecordCount = 0;
/*End: yehao(10857) Task.NO.11071 */
//目前还没实现的功能
// GetDlgItem(IDC_UPDATECPROCESS)->EnableWindow(false);
// GetDlgItem(IDC_SETIFRAME)->EnableWindow(false);
// GetDlgItem(IDC_DEVICE_WORKSTATE)->EnableWindow(false);
//设置系统秒定时器,用于刷新码流统计和进度条并更新客户端信息
// m_bShowStatus = FALSE;
// SetTimer(TIMER_KBPS, 1111,NULL);
//download test
m_dbByTime.Create(IDD_DOWNLOADBYTIME, this);
//specified alarm test
ZeroMemory(&m_lastAlarm, sizeof(DEV_STATE));
CString strAlmLogPath = g_strWorkDir + "\\AlarmLog_comm.txt";
m_almLogFile_Comm = fopen(strAlmLogPath, "wr");
strAlmLogPath = g_strWorkDir + "\\AlarmLog_shelter.txt";
m_almLogFile_Shelter = fopen(strAlmLogPath, "wr");
strAlmLogPath = g_strWorkDir + "\\AlarmLog_diskFull.txt";
m_almLogFile_dFull = fopen(strAlmLogPath, "wr");
strAlmLogPath = g_strWorkDir + "\\AlarmLog_diskError.txt";
m_almLogFile_dError = fopen(strAlmLogPath, "wr");
strAlmLogPath = g_strWorkDir + "\\AlarmLog_soundAlarm.txt";
m_almLogFile_SoundDec = fopen(strAlmLogPath, "wr");
if (m_almLogFile_Comm && m_almLogFile_Shelter && m_almLogFile_dFull
&& m_almLogFile_dError && m_almLogFile_SoundDec)
{
SetTimer(ALARMLOG, 1000, NULL);
}
SetTimer(UPDATATREE, 1000, NULL);
//listen device test
m_lListenDevice = 0;
m_lListenChannel = 0;
memset(&m_mylsdata, 0 , sizeof(m_mylsdata));
return TRUE;
}
void CNetSDKDemoDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CNetSDKDemoDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CNetSDKDemoDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
////////////////////////////////内部使用小接口函数///////////////////////////////////////////////////
//根据登录ID获取设备信息指针
void *CNetSDKDemoDlg::FindDeviceInfo(LONG lLoginID, char *sDVRIP,LONG nDVRPort)
{
/*
POSITION nPos;
DeviceNode *pInfo;
nPos = g_ptrdevicelist->GetHeadPosition();
for(int i = 0; i < g_ptrdevicelist->GetCount(); i ++ )
{
pInfo = (DeviceNode *)g_ptrdevicelist->GetNext(nPos);
if(pInfo->LoginID == lLoginID)
{
return pInfo;
}
}
*/
return NULL;
}
//获取当前设备列表中选择的设备信息指针
void *CNetSDKDemoDlg::GetCurDeviceInfo()
{
HTREEITEM node;
DWORD nData;
node = m_devicelist.GetSelectedItem();
if(!node)
{
MessageBox(ConvertString(MSG_DEMODLG_CHECKSEL));
return NULL;
}
nData = m_devicelist.GetItemData(node);
if(nData < 16) //通道选项,取得父项
{
node = m_devicelist.GetParentItem(node);
}
return (void *)m_devicelist.GetItemData(node); //父项记录的数据为设备的信息指针值
}
//根据句柄获取播放窗口序号,其中句柄可以是监视通道Id,播放Id,预览id等
int CNetSDKDemoDlg::GetHandleSplit(LONG lPlayHandle)
{
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
for(int i = 0; i < MAX_CHANNUM; i++)
{
if (!GetSplitInfo_Main(i, &siNode))
{
return -1;
}
if(siNode.Type != SPLIT_TYPE_NULL)
{
if(siNode.iHandle == (DWORD)lPlayHandle)
{
return i;
}
}
}
return -1;
}
//获取当前画面分割模式的指定画面的起始画面序号
int CNetSDKDemoDlg::GetCurSplitStart(int nScreen, int nSplit)
{
return -1;
/*
//设置到对应画面的单画面
int nScreenStart = 0;
if(nScreen >= nSplit * nSplit)
{
nScreenStart = m_curScreen/(nSplit * nSplit)*(nSplit * nSplit);
}
//当当前画面选择通道序号大于16时更改选择通道
//例如当前画面序号时10时,显示9画面,则显示7~16通道;
if((nScreenStart + nSplit * nSplit) >= CUR_MAXCHAN)
{
nScreenStart = CUR_MAXCHAN - nSplit * nSplit;
}
return nScreenStart;
*/
}
//检测当前画面状态并关闭当前状态
BOOL CNetSDKDemoDlg::CheckCurSplitAndClose()
{
ProcessCloseScreen(m_curScreen);
UpdateCurScreenInfo();
return TRUE;
}
//检测当前选择通道是否在某个轮循列表中
BOOL CNetSDKDemoDlg::IsCycling(DWORD deviceID, int channelNo)
{
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
for (int i = 0; i < MAX_CHANNUM; i++)
{
BOOL ret = GetSplitInfo_Main(i, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split information"));
return TRUE;
}
if (siNode.Type == SPLIT_TYPE_CYCLEMONITOR)
{
POSITION pos = ((SplitCycleParam *)siNode.Param)->pChannelList->GetHeadPosition();
for (int j = 0; j < ((SplitCycleParam *)siNode.Param)->pChannelList->GetCount(); j++)
{
CycleChannelInfo *tempnode;
tempnode = (CycleChannelInfo *)((SplitCycleParam *)siNode.Param)->pChannelList->GetNext(pos);
if ((tempnode->dwDeviceID == deviceID) && (tempnode->iChannel == channelNo))
{
return TRUE;
}
}
}
}
return FALSE;
}
void CNetSDKDemoDlg::DeleteCycleParam(int nScreen)
{
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(nScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
return;
}
int count;
count = ((SplitCycleParam *)siNode.Param)->pChannelList->GetCount();
for (int i = 0; i < count; i++)
{
delete (CycleChannelInfo *)((SplitCycleParam *)siNode.Param)->pChannelList->GetTail();
((SplitCycleParam *)siNode.Param)->pChannelList->RemoveTail();
}
delete ((SplitCycleParam *)siNode.Param)->pChannelList;
delete (SplitCycleParam *)siNode.Param;
siNode.Type = SPLIT_TYPE_NULL;
siNode.Param = NULL;
ret = SetSplitInfo_Main(nScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while setting split info"));
}
CPlayWnd *plWnd = (CPlayWnd *)m_screenPannel.GetPage(nScreen);
if (plWnd)
{
plWnd->PostMessage(VIDEO_REPAINT);
}
}
//关闭画面的显示状态
BOOL CNetSDKDemoDlg::ProcessCloseScreen(int scrNo, BOOL bDis)
{
BOOL ret = TRUE;
// EnterCriticalSection(&g_cs);
// CCSLock lck(g_cs);
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
ret = GetSplitInfo_Main(scrNo, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
return FALSE;
}
switch(siNode.Type)
{
case SPLIT_TYPE_MONITOR:
{
// ret = CLIENT_StopRealPlay(siNode.iHandle);
ret = CLIENT_StopRealPlayEx(siNode.iHandle);
if (!ret)
{
LastError();
if (!bDis)
{
MessageBox(ConvertString(MSG_CYCLE_STOPMONITORERROR));
}
}
delete (SplitMonitorParam *)siNode.Param;
siNode.Param = NULL;
siNode.Type = SPLIT_TYPE_NULL;
ret = SetSplitInfo_Main(scrNo, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
}
CPlayWnd *plWnd = (CPlayWnd *)m_screenPannel.GetPage(scrNo);
if (plWnd)
{
plWnd->PostMessage(VIDEO_REPAINT);
}
break;
}
case SPLIT_TYPE_MULTIPLAY:
{
// ret = CLIENT_StopMultiPlay(siNode.iHandle);
ret = CLIENT_StopRealPlayEx(siNode.iHandle);
if (!ret)
{
LastError();
if (!bDis)
{
MessageBox(ConvertString(MSG_CYCLE_STOPMULTIPLAYERROR));
}
}
siNode.Param = NULL;
siNode.Type = SPLIT_TYPE_NULL;
ret = SetSplitInfo_Main(scrNo, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
}
m_advanceBtnPannel.EnableTalk(TRUE);
CPlayWnd *plWnd = (CPlayWnd *)m_screenPannel.GetPage(scrNo);
if (plWnd)
{
plWnd->PostMessage(VIDEO_REPAINT);
}
break;
}
case SPLIT_TYPE_NETPLAY:
case SPLIT_TYPE_PBBYTIME:
{
int nRet = PlayStop(scrNo, bDis);
if (nRet < 0)
{
ret = FALSE;
}
else
{
ret = TRUE;
}
break;
}
case SPLIT_TYPE_CYCLEMONITOR:
{
//仅用于“关闭”指令,删除与断开设备有另外的代码。
KillTimer(scrNo);
// EnterCriticalSection(&g_csCycle);
ret = CLIENT_StopRealPlay(siNode.iHandle);
if (!ret)
{
LastError();
MessageBox(ConvertString(MSG_CYCLE_STOPCYCLEERROR));
}
if (siNode.Param)
{
DeleteCycleParam(scrNo);
}
// LeaveCriticalSection(&g_csCycle);
break;
}
default:
break;
}
// LeaveCriticalSection(&g_cs);
return ret;
}
int UpdateDeviceListCallback(const DeviceNode& node, DWORD dwUser)
{
CNetSDKDemoDlg* pThis = (CNetSDKDemoDlg*)dwUser;
if (!pThis)
{
return 1;
}
return pThis->UpdateDeviceListCallback_Imp(node);
}
int CNetSDKDemoDlg::UpdateDeviceListCallback_Imp(const DeviceNode& node)
{
CString strDev, strCh;
HTREEITEM hnode, hnode1;
CString strDevType;
switch(node.Info.byDVRType)
{
case NET_DVR_MPEG4_SX2:
strDevType.Format("LB");
break;
case NET_DVR_MEPG4_ST2:
strDevType.Format("GB");
break;
case NET_DVR_MEPG4_SH2:
strDevType.Format("HB");
break;
case NET_DVR_ATM:
strDevType.Format("ATM");
break;
case NET_DVR_NONREALTIME:
strDevType.Format("NRT");
break;
case NET_DVR_MPEG4_NVSII:
strDevType.Format("NVS");
break;
case NET_NB_SERIAL:
strDevType.Format("NB");
break;
case NET_LN_SERIAL:
strDevType.Format("LN");
break;
case NET_BAV_SERIAL:
strDevType.Format("BAV");
break;
case NET_SDIP_SERIAL:
strDevType.Format("SDIP");
break;
case NET_IPC_SERIAL:
strDevType.Format("IPC");
break;
case NET_NVS_B:
strDevType.Format("NVS B");
break;
case NET_NVS_C:
strDevType.Format("NVS H");
break;
case NET_NVS_S:
strDevType.Format("NVS S");
break;
case NET_NVS_E:
strDevType.Format("NVS E");
break;
case NET_DVR_NEW_PROTOCOL:
strDevType.Format("DVR");
break;
case NET_NVD_SERIAL:
strDevType.Format("NVD");
break;
case NET_DVR_N5:
strDevType.Format("N5");
break;
case NET_DVR_MIX_DVR:
strDevType.Format("HDVR");
break;
case NET_SVR_SERIAL:
strDevType.Format("SVR");
break;
case NET_SVR_BS:
strDevType.Format("SVR-BS");
break;
case NET_NVR_SERIAL:
strDevType.Format("NVR");
break;
default:
strDevType.Format("??");
}
strDev.Format(" %s (%s)<%s>",node.Name, node.IP, strDevType.GetBuffer(0));
if (node.bIsOnline)
{
strDev = strDev + ConvertString("(on-line)");
}
else
{
strDev = strDev +ConvertString("(off-line)");
}
hnode = m_devicelist.InsertItem(strDev,0,0,TVI_ROOT);
//设备项直接将设备信息指针作为列表Id
m_devicelist.SetItemData(hnode,(DWORD)&node);
for(int j = 0; j < node.Info.byChanNum; j++)
{
strCh.Format(ConvertString("channel %02d"),j+1);
hnode1 = m_devicelist.InsertItem(strCh,0,0,hnode);
//通道项将通道序号作为列表ID
m_devicelist.SetItemData(hnode1,j);
}
return 0;
}
////////////////////////////////刷新显示相关的接口函数//////////////////////////////////////////
//刷新设备列表显示,直接根据g_ptrdevicelist重新刷新显示
void CNetSDKDemoDlg::UpdateDeviceList()
{
/*
DeviceNode *nDev;
HTREEITEM node, node1;
CString strDev, strCh;
POSITION nPos;
*/
m_devicelist.DeleteAllItems();
CDevMgr::GetDevMgr().For_EachDev(UpdateDeviceListCallback, (DWORD)this);
if (m_devicelist.GetCount() > 0)
{
m_devicelist.SetFocus();
}
/*
nPos = g_ptrdevicelist->GetHeadPosition();
for(int i = 0; i < g_ptrdevicelist->GetCount(); i ++ )
{
nDev = (DeviceNode *)g_ptrdevicelist->GetNext(nPos);
strDev.Format(" %s (%s)<%s>",nDev->Name, nDev->IP, nDev->UserNanme);
node = m_devicelist.InsertItem(strDev,0,0,TVI_ROOT);
//设备项直接将设备信息指针作为列表Id
m_devicelist.SetItemData(node,(DWORD)nDev);
for(int j = 0; j < nDev->Info.byChanNum; j++)
{
strCh.Format("channel %02d",j+1);
node1 = m_devicelist.InsertItem(strCh,0,0,node);
//通道项将通道序号作为列表ID
m_devicelist.SetItemData(node1,j);
}
}
*/
}
//画面分割刷新显示
void CNetSDKDemoDlg::UpdateScreen(int nSplit)
{
//m_screenPannel.SetShowPlayWin(nSplit, 0);
/*
int k;
int spWide, spHight; //分割大小
CRect nRect;
CRect subRect;
// Invalidate();
m_screenPannel.GetClientRect(&nRect);
if (!m_bFullSCRN)
{
m_screenPannel.ClientToScreen(&nRect);
ScreenToClient(&nRect);
}
//处理为可以对任何画面显示在各种画面
int nScreenStart = GetCurSplitStart(m_curScreen,nSplit);
//隐藏所有画面
for(k = 0 ; k < CUR_MAXCHAN; k++)
{
m_playWnd[k].ShowWindow(SW_HIDE);
}
//确定每个分割项大小
spWide = nRect.Width()/nSplit;
spHight = nRect.Height()/nSplit;
//确定各分割项位置,并显示//CListBox
int offsplit;
for(int i = 0; i < nSplit; i++)
{
for(int j = 0; j < nSplit; j ++)
{
subRect.left = nRect.left + j * spWide+1;
subRect.top = nRect.top + i * spHight+1;
subRect.right = subRect.left + spWide - 1;
subRect.bottom = subRect.top + spHight - 1;
offsplit = nScreenStart + i * nSplit + j;
// m_playWnd[offsplit].ShowWindow(SW_HIDE);
m_playWnd[offsplit].MoveWindow(&subRect,false);
// m_playWnd[offsplit].ShowWindow(SW_NORMAL);
//当是当前选择分割项时,叠加显示外框
if(offsplit == m_curScreen)
{
CRect rect;
rect.left = subRect.left + 1;
rect.top = subRect.top + 1;
rect.right = subRect.right + 1;
rect.bottom = subRect.bottom + 1;
GetDlgItem(IDC_CURWIN)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_CURWIN)->MoveWindow(&rect,false);
GetDlgItem(IDC_CURWIN)->ShowWindow(SW_NORMAL);
}
}
}
//显示有效的分割画面
for(k = nScreenStart ; k < nScreenStart + nSplit * nSplit ; k++)
{
m_playWnd[k].ShowWindow(SW_SHOW);
}
*/
}
//刷新当前显示画面的相关信息
void CNetSDKDemoDlg::UpdateCurScreenInfo()
{
//判断是否打开了语音对讲
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
/* BOOL bTalkOpen = FALSE;
for (int i = 0; i < MAX_CHANNUM; i++)
{
BOOL ret = GetSplitInfo_Main(i, &siNode);
if (!ret)
{
MessageBox("error while getting split info");
return;
}
if (siNode.Type == SPLIT_TYPE_MONITOR)
{
if (((SplitMonitorParam *)(siNode.Param))->isTalkOpen)
{
bTalkOpen = TRUE;
break;
}
}
}
m_normalBtnPannel.EnableMultiplay(!bTalkOpen);
*/
//更新保存数据项和音频项
BOOL ret = GetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
return;
}
m_saveDataPannel.SetCheckReal(siNode.isSaveData);
m_saveDataPannel.SetCheckRaw(siNode.SavecbFileRaw ? 1 : 0);
m_saveDataPannel.SetCheckStd(siNode.SavecbFileStd ? 1 : 0);
m_saveDataPannel.SetCheckYuv(siNode.SavecbFileYUV ? 1 : 0);
m_saveDataPannel.SetCheckPcm(siNode.SavecbFilePcm ? 1 : 0);
m_advanceBtnPannel.SetCheckSound(m_curSoundSplit == m_curScreen ? 1 : 0);
//更新视频参数项
UpdateVideoCtrl(VIDEO_TOTAL);
/*
if (siNode.Type == SPLIT_TYPE_MONITOR &&
((SplitMonitorParam *)siNode.Param)->isTalkOpen)
{
m_advanceBtnPannel.SetCheckTalk(1);
}
else
{
m_advanceBtnPannel.SetCheckTalk(0);
}
*/
}
//刷新视频参数控制区,nMode 0~3对应单项刷新
void CNetSDKDemoDlg::UpdateVideoCtrl(int nMode)
{
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
return;
}
BYTE bVideo[4];
memset(bVideo,0, 4);
if(siNode.Type == SPLIT_TYPE_MONITOR)
{
memcpy(bVideo, siNode.nVideoParam.bParam, 4);
BOOL nRet = CLIENT_ClientSetVideoEffect(siNode.iHandle,
bVideo[0], bVideo[1], bVideo[2], bVideo[3]);
if (!nRet)
{
LastError();
}
}
if (nMode == VIDEO_TOTAL)
{
for (int i = 0; i < VIDEO_TOTAL; i++)
{
m_colorPannel.UpdateVideoDisplay(i, bVideo[i]);
}
}
else
{
m_colorPannel.UpdateVideoDisplay(nMode, bVideo[nMode]);
}
}
/////////////for one////////////////
DWORD GetMonthDays(const DWORD& dwYear, const DWORD& dwMonth)
{
DWORD dwMDays = 0;
switch(dwMonth)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
dwMDays = 31;
break;
case 2:
{
if (((dwYear%4==0)&& dwYear%100) || (dwYear%400==0))
{
dwMDays = 29;
}
else
{
dwMDays = 28;
}
}
break;
case 4:
case 6:
case 9:
case 11:
dwMDays = 30;
break;
default:
break;
}
return dwMDays;
}
/*
* can't surpport year offset time
*/
NET_TIME GetSeekTimeByOffsetTime(const NET_TIME& bgtime, unsigned int offsettime)
{
NET_TIME tmseek;
memset(&tmseek, 0x00, sizeof(NET_TIME));
DWORD dwNext = 0;
//second
tmseek.dwSecond = (bgtime.dwSecond+offsettime)%60;
dwNext = (bgtime.dwSecond+offsettime)/60;
//minute
tmseek.dwMinute = (dwNext+bgtime.dwMinute)%60;
dwNext = (dwNext+bgtime.dwMinute)/60;
//hour
tmseek.dwHour = (dwNext+bgtime.dwHour)%24;
dwNext = (dwNext+bgtime.dwHour)/24;
DWORD dwMDays = GetMonthDays(bgtime.dwYear, bgtime.dwMonth);
//day
tmseek.dwDay = (dwNext+bgtime.dwDay)%dwMDays;
dwNext = (dwNext+bgtime.dwDay)/dwMDays;
//month
tmseek.dwMonth = (dwNext+bgtime.dwMonth)%12;
dwNext = (dwNext+bgtime.dwMonth)/12;
tmseek.dwYear = dwNext+bgtime.dwYear;
return tmseek;
}
/*
* can't surpport year offset time
*/
DWORD GetOffsetTime(const NET_TIME& st, const NET_TIME& et)
{
DWORD dwRet = -1;
if (et.dwYear != st.dwYear)
{
return dwRet;
}
DWORD dwDays = 0;
for(int i=st.dwMonth+1; i < et.dwMonth; ++i)
{
dwDays += GetMonthDays(st.dwYear, i);
}
if (et.dwMonth == st.dwMonth)
{
dwDays +=et.dwDay - st.dwDay;
}
else
{
dwDays += et.dwDay;
dwDays += GetMonthDays(st.dwYear, st.dwMonth) - st.dwDay;
}
dwRet = dwDays*24*60*60 + ((int)et.dwHour - (int)st.dwHour)*60*60 +
((int)et.dwMinute - (int)st.dwMinute)*60 + (int)et.dwSecond - (int)st.dwSecond;
return dwRet;
}
/////////////for one////////////////
//播放进度条拖动的处理
BOOL CNetSDKDemoDlg::SeekPlayPositon(int nPos)
//void CNetSDKDemoDlg::OnReleasedcapturePlayPosition(NMHDR* pNMHDR, LRESULT* pResult)
{
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
return FALSE;
}
ret = FALSE;
if(siNode.Type == SPLIT_TYPE_NETPLAY)
{
SplitNetPlayParam * pbParam = (SplitNetPlayParam *)siNode.Param;
if (pbParam->iStatus == STATUS_PAUSE)
{
return FALSE;
}
pbParam->iPlayPos = nPos;
DWORD total = pbParam->pFileInfo->fileinfo.size;
ret = CLIENT_SeekPlayBack(siNode.iHandle, 0xFFFFFFFF, nPos * total /100);
if (!ret)
{
LastError();
}
}
else if (siNode.Type == SPLIT_TYPE_PBBYTIME)
{
SplitPBByTimeParam * pbParam = (SplitPBByTimeParam *)siNode.Param;
if (pbParam->iStatus == STATUS_PAUSE)
{
return FALSE;
}
pbParam->npos = nPos;
//DWORD time = g_IntervalTime(&pbParam->starttime, &pbParam->endtime);
DWORD time = GetOffsetTime(pbParam->starttime, pbParam->endtime);
BOOL ret = CLIENT_SeekPlayBack(siNode.iHandle, nPos * time /100, 0xFFFFFFFF);
if (!ret)
{
LastError();
}
}
return ret;
// *pResult = 0;
}
////////////////////////////////////////////功能操作//////////////////////////////////////////////
//增加设备连接项
void CNetSDKDemoDlg::AddDevice()
{
AddDeviceDlg dlg;
if(dlg.DoModal() == IDOK)
{
UpdateDeviceList(); //刷新设备列表显示
}
// TODO: Add your control notification handler code here
}
//实时数据回调,用于计算码流统计和保存数据
void CALLBACK RealDataCallBack(LONG lRealHandle, DWORD dwDataType, BYTE *pBuffer, DWORD dwBufSize, DWORD dwUser)
{
if(dwUser == 0)
{
return;
}
CNetSDKDemoDlg *dlg = (CNetSDKDemoDlg *)dwUser;
dlg ->ReceiveRealData(lRealHandle,dwDataType, pBuffer, dwBufSize);
}
//回放数据回调函数,demo里将数据保存成文件
int CALLBACK PBDataCallBack(LONG lRealHandle, DWORD dwDataType, BYTE *pBuffer, DWORD dwBufSize, DWORD dwUser)
{
if(dwUser == 0)
{
return -1;
}
CNetSDKDemoDlg *dlg = (CNetSDKDemoDlg *)dwUser;
dlg ->ReceiveRealData(lRealHandle,dwDataType, pBuffer, dwBufSize);
return 1;
}
void CALLBACK RealDataCallBackEx(LONG lRealHandle, DWORD dwDataType, BYTE *pBuffer,DWORD dwBufSize, LONG lParam, DWORD dwUser)
{
if(dwUser == 0)
{
return;
}
CNetSDKDemoDlg *dlg = (CNetSDKDemoDlg *)dwUser;
dlg->ReceiveRealData(lRealHandle,dwDataType, pBuffer, dwBufSize);
}
//根据设备列表取得设备Id,根据通道选择通道号
void CNetSDKDemoDlg::OpenChannel()
{
HTREEITEM node_dev, tmpnode;
DWORD nItem;
CString strCh;
DeviceNode *pInfo;
tmpnode = m_devicelist.GetSelectedItem();
if(!tmpnode)
{
MessageBox(ConvertString(MSG_DEMODLG_CHECKSEL));
return;
}
RealPlayType subtype;
int subidx = m_normalBtnPannel.GetSubType();
switch(subidx)
{
case 0:
subtype = RType_Realplay_0;
break;
case 1:
subtype = RType_Realplay_1;
break;
case 2:
subtype = RType_Realplay_2;
break;
case 3:
subtype = RType_Realplay_3;
break;
default:
subtype = RType_Realplay_0;
}
nItem = m_devicelist.GetItemData(tmpnode);
if(nItem < 16) //是通道项
{
node_dev = m_devicelist.GetParentItem(tmpnode);
pInfo = (DeviceNode *)m_devicelist.GetItemData(node_dev);
OpenSingleChannel(pInfo, nItem, m_curScreen, subtype);
}
else //设备项
{
OpenAllChannel((DeviceNode *)nItem, subtype);
}
}
void CNetSDKDemoDlg::OpenSingleChannel(DeviceNode *pInfo, int nCh, int screenNo, RealPlayType subtype)
{
//查询是否被列入轮循列表
if (IsCycling((DWORD)pInfo, nCh))
{
MessageBox(ConvertString(MSG_DEMODLG_ERROR_CYCLING));
return;
}
//关闭当前窗口的播放
ProcessCloseScreen(screenNo);
CWnd* pWnd = m_screenPannel.GetPage(screenNo);
if (!pWnd)
{
return ;
}
LONG nID = pInfo->LoginID;
LONG nChannelID;
// nChannelID = CLIENT_RealPlay(nID, nCh, GetDlgItem(IDC_SCREEN1 + m_curScreen )->m_hWnd);
// nChannelID = CLIENT_RealPlay(nID, nCh, NULL);
nChannelID = CLIENT_RealPlayEx(nID, nCh, pWnd->m_hWnd/*m_playWnd[screenNo].m_hWnd*/, subtype);
CLIENT_MakeKeyFrame(nID, nCh, subtype);
if(!nChannelID)
{
LastError();
MessageBox(ConvertString(MSG_DEMODLG_OPENCHLFAILED));
return;
}
// CLIENT_AdjustFluency(nChannelID, 7);
//获取视频参数
BYTE bVideo[4];
BOOL nRet = CLIENT_ClientGetVideoEffect(nChannelID, &bVideo[0],&bVideo[1],&bVideo[2],&bVideo[3]);
if (!nRet)
{
LastError();
}
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(screenNo, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
}
siNode.Type = SPLIT_TYPE_MONITOR;
siNode.nVideoParam.dwParam = *(DWORD *)bVideo;
siNode.iHandle = nChannelID;
SplitMonitorParam *mparam = new SplitMonitorParam;
mparam->pDevice = pInfo;
mparam->iChannel = nCh;
siNode.Param = mparam;
ret = SetSplitInfo_Main(screenNo, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while setting split info"));
}
//更新保存数据状态
if(siNode.isSaveData)
{
CString strName ;
strName.Format("savech%d.dav", nCh);
BOOL ret = CLIENT_SaveRealData(nChannelID, strName.GetBuffer(0));
if(!ret)
{
LastError();
MessageBox(ConvertString(MSG_DEMODLG_SAVEDATAFAILED));
}
}
UpdateCurScreenInfo();
//更新音频
if(m_curSoundSplit == screenNo)
{
BOOL nRet = CLIENT_OpenSound(nChannelID);
if (!nRet)
{
LastError();
}
}
//设置数据回调
// BOOL cbRec = CLIENT_SetRealDataCallBack(nChannelID, RealDataCallBack, (DWORD)this);
BOOL cbRec = CLIENT_SetRealDataCallBackEx(nChannelID, RealDataCallBackEx, (DWORD)this, 0x0000000f);
if (!cbRec)
{
LastError();
}
// BOOL bRet = CLIENT_YWPTZControl(nID,0, PTZ_UP_CONTROL, 2, 2,0, false);
// int iii = 0;
}
//接收播放进度状态处理
void CNetSDKDemoDlg::ReceivePlayPos(LONG lPlayHandle, DWORD dwTotalSize, DWORD dwDownLoadSize)
{
//取得窗口号
int nScreen = GetHandleSplit(lPlayHandle);
if(nScreen < 0)
{
return;
}
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(nScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
}
//更新播放进度值
if (siNode.Type == SPLIT_TYPE_NETPLAY)
{
SplitNetPlayParam *nParam = (SplitNetPlayParam *)siNode.Param;
if (nParam && dwTotalSize > 0)
{
nParam->iPlayPos = dwDownLoadSize * 100 / dwTotalSize;
if (nParam->iPlayPos > 100)
{
int xyz = 0;
}
if(((int)dwDownLoadSize == -1))
{
PlayStop(nScreen);
//m_playWnd[nScreen].ShowWindow(SW_HIDE);
//m_playWnd[nScreen].ShowWindow(SW_SHOW);
}
}
}
else if (siNode.Type == SPLIT_TYPE_PBBYTIME)
{
SplitPBByTimeParam *pbParam = (SplitPBByTimeParam *)siNode.Param;
if (pbParam && dwTotalSize > 0)
{
pbParam->npos = dwDownLoadSize * 100 / dwTotalSize;
if(((int)dwDownLoadSize == -1) || (pbParam->npos >= 100))
{
PlayStop(nScreen);
}
}
}
}
//播放进度状态回调
void CALLBACK PlayCallBack(LONG lPlayHandle, DWORD dwTotalSize, DWORD dwDownLoadSize, DWORD dwUser)
{
if(dwUser == 0)
{
return;
}
CNetSDKDemoDlg *dlg = (CNetSDKDemoDlg *)dwUser;
dlg->ReceivePlayPos(lPlayHandle, dwTotalSize, dwDownLoadSize);
}
//录像查询
void CNetSDKDemoDlg::SearchRecord()
{
CSearchRecord dlg;
if(dlg.DoModal() == IDOK) //打开回放时
{
if (!dlg.m_playfile)
{
return;
}
if(!CheckCurSplitAndClose())
{
return;
}
PlayRecordFile(dlg.m_playfile, m_curScreen);
/*
if (!dlg.m_playList)
{
return;
}
else
{
for (int i = 0; i < dlg.m_playCount; i++)
{
PlayRecordFile(&dlg.m_playList[i], i);
}
}
*/
}
}
void CNetSDKDemoDlg::PlayRecordFile(FileInfoNode* playfile, int scrNo)
{
CWnd *plWnd = m_screenPannel.GetPage(scrNo);
if (!plWnd)
{
MessageBox(ConvertString("unexpected error!!!!"));
return;
}
// playfile->fileinfo.ch = 0;
// memset(&playfile->fileinfo.endtime, 0, sizeof(NET_TIME));
// memset(&playfile->fileinfo.starttime, 0, sizeof(NET_TIME));
// memset(playfile->fileinfo.filename, 0, 128);
// playfile->fileinfo.size = 0;
LONG lPlayHandle = CLIENT_PlayBackByRecordFile/*Ex*/(playfile->pDevice->LoginID, &playfile->fileinfo,
plWnd->m_hWnd/*m_playWnd[m_curScreen].m_hWnd*/, PlayCallBack, (DWORD)this/*, PBDataCallBack, (DWORD)this*/);
// LONG lPlayHandle = CLIENT_PlayBackByRecordFile/*Ex*/(playfile->pDevice->LoginID, &playfile->fileinfo,
// plWnd->m_hWnd/*m_playWnd[m_curScreen].m_hWnd*/, PlayCallBack, (DWORD)this/*, PBDataCallBack, (DWORD)this*/);
if(!lPlayHandle)
{
LastError();
MessageBox(ConvertString(MSG_DEMODLG_PLAYFAILED));
return;
}
else
{ //如果其它通道没有打开音频,则打开音频
if (m_curSoundSplit < 0)
{
if (FALSE == CLIENT_OpenSound(lPlayHandle))
{
LastError();
MessageBox(ConvertString(MSG_OPENSOUNDFAILED));
m_advanceBtnPannel.SetCheckSound(0);
}
else
{
m_advanceBtnPannel.SetCheckSound(1);
m_curSoundSplit = scrNo;
}
}
}
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(scrNo, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
}
siNode.Type = SPLIT_TYPE_NETPLAY;
siNode.iHandle = lPlayHandle;
SplitNetPlayParam *nParam = new SplitNetPlayParam;
nParam->pFileInfo = new FileInfoNode;
memcpy(nParam->pFileInfo, playfile, sizeof(FileInfoNode));
nParam->iPlayPos = 0;
nParam->iStatus = STATUS_PLAY;
siNode.Param = nParam;
ret = SetSplitInfo_Main(scrNo, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
}
m_playctrlPannel.StartPlay();
UpdateCurScreenInfo();
}
//停止播放当前播放画面
BOOL CNetSDKDemoDlg::PlayCtrl_Stop()
{
int nRet = PlayStop(m_curScreen);
if (nRet < 0)
{
return FALSE;
}
else
{
// m_playWnd[curScreen].ShowWindow(SW_HIDE);
// m_playWnd[curScreen].ShowWindow(SW_NORMAL);
}
return TRUE;
}
//快放
BOOL CNetSDKDemoDlg::PlayCtrl_Fast()
{/*
for (int i = 0; i<16; i++)
{
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(i, &siNode);
if (!ret)
{
MessageBox("error while getting split info");
return FALSE;
}
if(siNode.Type == SPLIT_TYPE_NETPLAY)
{
SplitNetPlayParam *pParam = (SplitNetPlayParam *)siNode.Param;
if(pParam->iStatus == STATUS_PAUSE)
{
goto e_exit;
}
if(pParam->iStatus == STATUS_STEP)
{
ret = CLIENT_StepPlayBack(siNode.iHandle, TRUE);
if (!ret)
{
LastError();
goto e_exit;
}
pParam->iStatus = STATUS_STOP;
}
if (m_curSoundSplit == i)
{
if (FALSE == CLIENT_CloseSound())
{
LastError();
MessageBox(MSG_CLOSESOUNDFAILED);
goto e_exit;
}
m_advanceBtnPannel.SetCheckSound(0);
m_curSoundSplit = -1;
}
ret = CLIENT_FastPlayBack(siNode.iHandle);
if(!ret)
{
LastError();
MessageBox(MSG_DEMODLG_PLAYCTRLFAILED);
}
pParam->iStatus = STATUS_PLAY;
}
else if (siNode.Type == SPLIT_TYPE_PBBYTIME)
{
SplitPBByTimeParam *pbParam = (SplitPBByTimeParam *)siNode.Param;
if(pbParam->iStatus == STATUS_PAUSE)
{
goto e_exit;
}
if(pbParam->iStatus == STATUS_STEP)
{
ret = CLIENT_StepPlayBack(siNode.iHandle, TRUE);
if (!ret)
{
LastError();
}
else
{
pbParam->iStatus = STATUS_STOP;
}
}
if (m_curSoundSplit == i)
{
if (FALSE == CLIENT_CloseSound())
{
LastError();
MessageBox(MSG_CLOSESOUNDFAILED);
goto e_exit;
}
m_advanceBtnPannel.SetCheckSound(0);
m_curSoundSplit = -1;
}
ret = CLIENT_FastPlayBack(siNode.iHandle);
if(!ret)
{
LastError();
MessageBox(MSG_DEMODLG_PLAYCTRLFAILED);
goto e_exit;
}
pbParam->iStatus = STATUS_PLAY;
}
else
{
// MessageBox(MSG_DEMODLG_NOTPLAYING);
// goto e_exit;
}
}
*/
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
return FALSE;
}
if(siNode.Type == SPLIT_TYPE_NETPLAY)
{
SplitNetPlayParam *pParam = (SplitNetPlayParam *)siNode.Param;
if(pParam->iStatus == STATUS_PAUSE)
{
goto e_exit;
}
if(pParam->iStatus == STATUS_STEP)
{
ret = CLIENT_StepPlayBack(siNode.iHandle, TRUE);
if (!ret)
{
LastError();
goto e_exit;
}
pParam->iStatus = STATUS_STOP;
}
if (m_curSoundSplit == m_curScreen)
{
if (FALSE == CLIENT_CloseSound())
{
LastError();
MessageBox(ConvertString(MSG_CLOSESOUNDFAILED));
goto e_exit;
}
m_advanceBtnPannel.SetCheckSound(0);
m_curSoundSplit = -1;
}
ret = CLIENT_FastPlayBack(siNode.iHandle);
if(!ret)
{
LastError();
MessageBox(ConvertString(MSG_DEMODLG_PLAYCTRLFAILED));
}
pParam->iStatus = STATUS_PLAY;
}
else if (siNode.Type == SPLIT_TYPE_PBBYTIME)
{
SplitPBByTimeParam *pbParam = (SplitPBByTimeParam *)siNode.Param;
if(pbParam->iStatus == STATUS_PAUSE)
{
goto e_exit;
}
if(pbParam->iStatus == STATUS_STEP)
{
ret = CLIENT_StepPlayBack(siNode.iHandle, TRUE);
if (!ret)
{
LastError();
}
else
{
pbParam->iStatus = STATUS_STOP;
}
}
if (m_curSoundSplit == m_curScreen)
{
if (FALSE == CLIENT_CloseSound())
{
LastError();
MessageBox(ConvertString(MSG_CLOSESOUNDFAILED));
goto e_exit;
}
m_advanceBtnPannel.SetCheckSound(0);
m_curSoundSplit = -1;
}
ret = CLIENT_FastPlayBack(siNode.iHandle);
if(!ret)
{
LastError();
MessageBox(ConvertString(MSG_DEMODLG_PLAYCTRLFAILED));
goto e_exit;
}
pbParam->iStatus = STATUS_PLAY;
}
else
{
MessageBox(ConvertString(MSG_DEMODLG_NOTPLAYING));
goto e_exit;
}
return TRUE;
e_exit:
return FALSE;
}
//慢放
BOOL CNetSDKDemoDlg::PlayCtrl_Slow()
{
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
return FALSE;
}
if(siNode.Type == SPLIT_TYPE_NETPLAY)
{
SplitNetPlayParam *pParam = (SplitNetPlayParam *)siNode.Param;
if(pParam->iStatus == STATUS_PAUSE)
{
goto e_exit;
}
if(pParam->iStatus == STATUS_STEP)
{
ret = CLIENT_StepPlayBack(siNode.iHandle, TRUE);
if (!ret)
{
LastError();
goto e_exit;
}
pParam->iStatus = STATUS_STOP;
}
ret = CLIENT_SlowPlayBack(siNode.iHandle);
if(!ret)
{
LastError();
MessageBox(ConvertString(MSG_DEMODLG_PLAYCTRLFAILED));
goto e_exit;
}
pParam->iStatus = STATUS_PLAY;
}
else if (siNode.Type == SPLIT_TYPE_PBBYTIME)
{
SplitPBByTimeParam *pbParam = (SplitPBByTimeParam *)siNode.Param;
if(pbParam->iStatus == STATUS_PAUSE)
{
goto e_exit;
}
if(pbParam->iStatus == STATUS_STEP)
{
ret = CLIENT_StepPlayBack(siNode.iHandle, TRUE);
if (!ret)
{
LastError();
goto e_exit;
}
pbParam->iStatus = STATUS_STOP;
}
ret = CLIENT_SlowPlayBack(siNode.iHandle);
if(!ret)
{
LastError();
MessageBox(ConvertString(MSG_DEMODLG_PLAYCTRLFAILED));
goto e_exit;
}
pbParam->iStatus = STATUS_PLAY;
}
else
{
MessageBox(ConvertString(MSG_DEMODLG_NOTPLAYING));
goto e_exit;
}
return TRUE;
e_exit:
return FALSE;
}
//单帧播放
BOOL CNetSDKDemoDlg::PlayCtrl_Step()
{
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
return FALSE;
}
if(siNode.Type == SPLIT_TYPE_NETPLAY)
{
SplitNetPlayParam *pParam = (SplitNetPlayParam *)siNode.Param;
if(pParam->iStatus == STATUS_PAUSE)
{
goto e_exit;
}
ret = CLIENT_StepPlayBack(siNode.iHandle, FALSE);
if(!ret)
{
LastError();
MessageBox(ConvertString(MSG_DEMODLG_PLAYCTRLFAILED));
goto e_exit;
}
pParam->iStatus = STATUS_STEP;
}
else if (siNode.Type == SPLIT_TYPE_PBBYTIME)
{
SplitPBByTimeParam *pbParam = (SplitPBByTimeParam *)siNode.Param;
if(pbParam->iStatus == STATUS_PAUSE)
{
MessageBox(ConvertString("paused"));
goto e_exit;
}
ret = CLIENT_StepPlayBack(siNode.iHandle, FALSE);
if(!ret)
{
LastError();
MessageBox(ConvertString(MSG_DEMODLG_PLAYCTRLFAILED));
goto e_exit;
}
pbParam->iStatus = STATUS_STEP;
}
else
{
MessageBox(ConvertString(MSG_DEMODLG_NOTPLAYING));
goto e_exit;
}
return TRUE;
e_exit:
return FALSE;
}
BOOL CNetSDKDemoDlg::PlayCtrl_Frame(int frame)
{
// KillTimer(TIMER_KBPS);
if(!UpdateData(true))
{
return FALSE;
}
if ((frame < 0) || (frame > 120))
{
MessageBox(ConvertString(MSG_SCHRECORD_ILLEGALFRAME));
return FALSE;
}
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
return FALSE;
}
ret = FALSE;
if(siNode.Type == SPLIT_TYPE_NETPLAY)
{
SplitNetPlayParam *pParam = (SplitNetPlayParam *)siNode.Param;
if(pParam->iStatus == STATUS_PAUSE)
{
goto out;
}
if(pParam->iStatus == STATUS_STEP)
{
ret = CLIENT_StepPlayBack(siNode.iHandle, TRUE);
if (!ret)
{
LastError();
goto out;
}
pParam->iStatus = STATUS_STOP;
}
if (m_curSoundSplit == m_curScreen)
{
if (FALSE == CLIENT_CloseSound())
{
LastError();
MessageBox(ConvertString(MSG_CLOSESOUNDFAILED));
goto out;
}
m_advanceBtnPannel.SetCheckSound(0);
m_curSoundSplit = -1;
}
ret = CLIENT_SetFramePlayBack(siNode.iHandle, frame);
if(!ret)
{
LastError();
MessageBox(ConvertString(MSG_DEMODLG_PLAYCTRLFAILED));
goto out;
}
}
else if(siNode.Type == SPLIT_TYPE_PBBYTIME)
{
SplitPBByTimeParam *pbParam = (SplitPBByTimeParam *)siNode.Param;
if(pbParam->iStatus == STATUS_PAUSE)
{
goto out;
}
if(pbParam->iStatus == STATUS_STEP)
{
ret = CLIENT_StepPlayBack(siNode.iHandle, TRUE);
if (!ret)
{
LastError();
goto out;
}
pbParam->iStatus = STATUS_STOP;
}
if (m_curSoundSplit == m_curScreen)
{
if (FALSE == CLIENT_CloseSound())
{
LastError();
MessageBox(ConvertString(MSG_CLOSESOUNDFAILED));
goto out;
}
m_advanceBtnPannel.SetCheckSound(0);
m_curSoundSplit = -1;
}
ret = CLIENT_SetFramePlayBack(siNode.iHandle, frame);
if(!ret)
{
LastError();
MessageBox(ConvertString(MSG_DEMODLG_PLAYCTRLFAILED));
goto out;
}
}
else
{
MessageBox(ConvertString(MSG_DEMODLG_NOTPLAYING));
goto out;
}
out:
// SetTimer(TIMER_KBPS, 1111,NULL);
return ret;
}
//播放/暂停切换
BOOL CNetSDKDemoDlg::PlayCtrl_Play()
{
BOOL isPause = false;
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
return FALSE;
}
ret = FALSE;
if(siNode.Type == SPLIT_TYPE_NETPLAY)
{
SplitNetPlayParam *pParam = (SplitNetPlayParam *)siNode.Param;
if(pParam->iStatus == STATUS_STEP)
{
ret = CLIENT_StepPlayBack(siNode.iHandle, TRUE);
if (!ret)
{
LastError();
goto out;
}
pParam->iStatus = STATUS_STOP;
}
if(pParam->iStatus != STATUS_PAUSE)
{
isPause = true;
}
ret = CLIENT_PausePlayBack(siNode.iHandle, isPause);
if(!ret)
{
LastError();
MessageBox(ConvertString(MSG_DEMODLG_PLAYCTRLFAILED));
}
else
{
if(pParam->iStatus == STATUS_PAUSE)
{
pParam->iStatus = STATUS_PLAY;
}
else
{
pParam->iStatus = STATUS_PAUSE;
}
}
}
else if(siNode.Type == SPLIT_TYPE_PBBYTIME)
{
SplitPBByTimeParam *pbParam = (SplitPBByTimeParam *)siNode.Param;
if(pbParam->iStatus == STATUS_STEP)
{
ret = CLIENT_StepPlayBack(siNode.iHandle, TRUE);
if (!ret)
{
LastError();
goto out;
}
pbParam->iStatus = STATUS_STOP;
}
if(pbParam->iStatus != STATUS_PAUSE)
{
isPause = true;
}
ret = CLIENT_PausePlayBack(siNode.iHandle, isPause);
if(!ret)
{
LastError();
MessageBox(ConvertString(MSG_DEMODLG_PLAYCTRLFAILED));
}
else
{
if(pbParam->iStatus == STATUS_PAUSE)
{
pbParam->iStatus = STATUS_PLAY;
}
else
{
pbParam->iStatus = STATUS_PAUSE;
}
}
}
else
{
MessageBox(ConvertString(MSG_DEMODLG_NOTPLAYING));
}
out:
return ret;
}
int CNetSDKDemoDlg::PlayStop(int iScreen, BOOL bDis)
{
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(iScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
goto e_clear;
}
CPlayWnd *plWnd;
if(siNode.Type == SPLIT_TYPE_NETPLAY)
{
SplitNetPlayParam *pParam = (SplitNetPlayParam *)siNode.Param;
//如果处于单帧播放状态,需先恢复
if(pParam->iStatus == STATUS_STEP)
{
ret = CLIENT_StepPlayBack(siNode.iHandle, TRUE);
if (!ret)
{
LastError();
goto e_clear;
}
}
m_playctrlPannel.StopPlay();
ret = CLIENT_StopPlayBack(siNode.iHandle);
if (!ret)
{
LastError();
if (!bDis)
{
MessageBox(ConvertString(MSG_DEMODLG_STOPPLAYFAILED));
goto e_clear;
}
}
FileInfoNode *pFile = ((SplitNetPlayParam *)siNode.Param)->pFileInfo;
delete pFile;
delete (SplitNetPlayParam *)siNode.Param;
siNode.Param = NULL;
siNode.Type = SPLIT_TYPE_NULL;
ret = SetSplitInfo_Main(iScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while setting split info"));
}
if (m_curSoundSplit == iScreen)
{
//m_advanceBtnPannel.SetCheckSound(0);
m_curSoundSplit = -1;
}
}
else if (siNode.Type == SPLIT_TYPE_PBBYTIME)
{
SplitPBByTimeParam *pbParam = (SplitPBByTimeParam *)siNode.Param;
//如果处于单帧播放状态,需先恢复
if(pbParam->iStatus == STATUS_STEP)
{
ret = CLIENT_StepPlayBack(siNode.iHandle, TRUE);
if (!ret)
{
LastError();
goto e_clear;
}
}
m_playctrlPannel.StopPlay();
ret = CLIENT_StopPlayBack(siNode.iHandle);
if (!ret)
{
LastError();
if (!bDis)
{
MessageBox(ConvertString(MSG_DEMODLG_STOPPLAYFAILED));
goto e_clear;
}
}
delete (SplitPBByTimeParam *)siNode.Param;
//add by zhaojs 2006-12-06
siNode.Param = NULL;
siNode.Type = SPLIT_TYPE_NULL;
ret = SetSplitInfo_Main(iScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while setting split info"));
}
if (m_curSoundSplit == iScreen)
{
//m_advanceBtnPannel.SetCheckSound(0);
m_curSoundSplit = -1;
}
}
else
{
MessageBox(ConvertString(MSG_DEMODLG_NOTPLAYING));
goto e_clear;
}
// repaint the play window
plWnd = (CPlayWnd *)m_screenPannel.GetPage(iScreen);
if (plWnd)
{
plWnd->PostMessage(VIDEO_REPAINT);
}
return 0;
e_clear:
return -1;
}
//对当前监视通道进行抓图,对播放通道是否能抓图有待验证
void CNetSDKDemoDlg::CaptureScreen()
{
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
return;
}
CString strName = "pct.bmp";
//支持多种图像的抓图
if(siNode.Type == SPLIT_TYPE_NULL)
{
MessageBox(ConvertString(MSG_DEMODLG_CANTCAPTURE));
return;
}
//抓图保存文件名的输入
CFileDialog dlg(FALSE,"*.bmp","pct.bmp",OFN_OVERWRITEPROMPT|OFN_HIDEREADONLY,
"All File(*.bmp)|*.*||",this);
if(dlg.DoModal() == IDOK)
{
strName = dlg.GetPathName();
}
ret = CLIENT_CapturePicture(siNode.iHandle, strName.GetBuffer(0));
if(!ret)
{
LastError();
MessageBox(ConvertString(MSG_DEMODLG_CAPTUREFAILED));
}
}
//强制I帧
void CNetSDKDemoDlg::SetIframe()
{
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
return;
}
if(siNode.Type != SPLIT_TYPE_MONITOR)
{
MessageBox(ConvertString(MSG_DEMODLG_CANTFORCE_I));
return;
}
SplitMonitorParam *mParam = (SplitMonitorParam *)siNode.Param;
ret = CLIENT_MakeKeyFrame(mParam->pDevice->LoginID, mParam->iChannel);
if(!ret)
{
LastError();
MessageBox(ConvertString(MSG_DEMODLG_FAILEDFORCE_I));
}
}
//是否打开声音
BOOL CNetSDKDemoDlg::OpenSound(BOOL bOpen)
{
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
return FALSE;
}
if(bOpen)
{
if (m_curSoundSplit >= 0 &&
(siNode.Type == SPLIT_TYPE_MONITOR ||
siNode.Type == SPLIT_TYPE_NETPLAY ||
siNode.Type == SPLIT_TYPE_PBBYTIME))
{
if (FALSE == CLIENT_CloseSound())
{
LastError();
MessageBox(ConvertString(MSG_CLOSESOUNDFAILED));
return FALSE;
}
}
m_curSoundSplit = m_curScreen;
if (siNode.Type == SPLIT_TYPE_MONITOR ||
siNode.Type == SPLIT_TYPE_NETPLAY ||
siNode.Type == SPLIT_TYPE_PBBYTIME)
{
if (FALSE == CLIENT_OpenSound(siNode.iHandle))
{
LastError();
MessageBox(ConvertString(MSG_OPENSOUNDFAILED));
return FALSE;
}
}
}
else
{
if (siNode.Type == SPLIT_TYPE_MONITOR ||
siNode.Type == SPLIT_TYPE_NETPLAY ||
siNode.Type == SPLIT_TYPE_PBBYTIME)
{
if (FALSE == CLIENT_CloseSound())
{
LastError();
MessageBox(ConvertString(MSG_CLOSESOUNDFAILED));
return FALSE;
}
}
m_curSoundSplit = -1;
}
return TRUE;
}
//是否保存实时数据数据
void CNetSDKDemoDlg::SaveRealdata(int nCheck)
{
CPlayWnd *plWnd = (CPlayWnd *)m_screenPannel.GetPage(m_curScreen);
if (!plWnd)
{
MessageBox(ConvertString("we have a big error here!"));
return;
}
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
return;
}
CString strName = "save.dav";
if(nCheck > 0)
{
siNode.isSaveData = 1;
if (siNode.Type == SPLIT_TYPE_MONITOR || siNode.Type == SPLIT_TYPE_MULTIPLAY)
{
//文件名的输入
CFileDialog dlg(FALSE,"*.dav","save.dav",OFN_OVERWRITEPROMPT|OFN_HIDEREADONLY,
"All File(*.dav)|*.*||",this);
if(dlg.DoModal() == IDOK)
{
strName = dlg.GetPathName();
}
else
{
return;
}
BOOL ret = CLIENT_SaveRealData(siNode.iHandle, strName.GetBuffer(0));
if(!ret)
{
LastError();
MessageBox (ConvertString(MSG_DEMODLG_SAVEDATAFAILED));
}
else
{
plWnd->SetSplitCBFlag_Real(1);
}
}
}
else
{
siNode.isSaveData = 0;
if(siNode.Type == SPLIT_TYPE_MONITOR || siNode.Type == SPLIT_TYPE_MULTIPLAY)
{
BOOL stop = CLIENT_StopSaveRealData(siNode.iHandle);
if (stop)
{
plWnd->SetSplitCBFlag_Real(0);
MessageBox(ConvertString(MSG_DEMODLG_REALSAVE_STOPPED));
}
else
{
LastError();
MessageBox(ConvertString("stop save file failed"));
}
}
}
}
//用来打开显示画面分割各显示区域的信息
void CNetSDKDemoDlg::ShowFluxInfo()
{
CSplitInfoDlg dlg;
m_runtimeMsgPannel.EnableShowFlux(FALSE);
dlg.DoModal();
m_runtimeMsgPannel.EnableShowFlux(TRUE);
}
/*
//刷新画面分割模式
void CNetSDKDemoDlg::OnSelchangeSplittesel()
{
UpdateScreen();
}
*/
//关闭监视图像
void CNetSDKDemoDlg::CloseScreen()
{
BOOL ret = ProcessCloseScreen(m_curScreen);
//m_playWnd[m_curScreen].ShowWindow(SW_HIDE);
//m_playWnd[m_curScreen].ShowWindow(SW_NORMAL);
UpdateCurScreenInfo();
}
void CNetSDKDemoDlg::PtzControl(int type, BOOL stop, int param)
{
BOOL ret;
SplitMonitorParam *nParam ;
BOOL upRet;
LONG lHandle;
int iChannel;
if (stop)
{
if (!m_bPTZCtrl)
{
goto exitPTZCtrl;
}
}
switch(type) {
//在主页面的控制
case PTZ_UP_CONTROL : //上
case PTZ_DOWN_CONTROL: //下
case PTZ_LEFT_CONTROL: //左
case PTZ_RIGHT_CONTROL: //右
case PTZ_ZOOM_ADD_CONTROL: //变倍
case PTZ_ZOOM_DEC_CONTROL:
case PTZ_FOCUS_ADD_CONTROL: //调焦
case PTZ_FOCUS_DEC_CONTROL:
case PTZ_APERTURE_ADD_CONTROL: //光圈
case PTZ_APERTURE_DEC_CONTROL:
case EXTPTZ_LEFTTOP :
case EXTPTZ_RIGHTTOP :
case EXTPTZ_LEFTDOWN :
case EXTPTZ_RIGHTDOWN:
upRet = UpdateData(true);
if (!upRet)
{
goto exitPTZCtrl;
}
break;
case PTZ_POINT_MOVE_CONTROL : //转至
case PTZ_POINT_SET_CONTROL : //设置
case PTZ_POINT_DEL_CONTROL : //删除
case PTZ_POINT_LOOP_CONTROL : //点间轮循
case PTZ_LAMP_CONTROL: //灯
default:
MessageBox(ConvertString(MSG_DEMODLG_PTZCMDFAILED));
goto exitPTZCtrl;
}
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
ret = GetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
return;
}
if(siNode.Type != SPLIT_TYPE_MONITOR)
{
goto exitPTZCtrl;
}
nParam = (SplitMonitorParam *)siNode.Param;
lHandle = nParam->pDevice->LoginID;
iChannel = nParam->iChannel;
if(type >= EXTPTZ_LEFTTOP)
{
ret = CLIENT_YWPTZControl(lHandle,iChannel, type, (BYTE)param, (BYTE)param,0, stop);
if (!ret)
{
LastError();
}
m_bPTZCtrl = !stop;
}
else
{
// ret = CLIENT_YWPTZControl(iHandle,iChannel, type, 0, (BYTE)nData,0, stop);
ret = CLIENT_PTZControl(lHandle,iChannel, type, param, stop);
if (!ret)
{
LastError();
}
m_bPTZCtrl = !stop;
}
if(!ret)
{
MessageBox(ConvertString(MSG_DEMODLG_PTZCTRLFAILED));
goto exitPTZCtrl;
}
return;
exitPTZCtrl:
m_bPTZCtrl = FALSE;
return;
}
/*
//处理点击到当前分割区域时的显示,并确定刷新当前显示画面
void CNetSDKDemoDlg::OnLButtonDown(UINT nFlags, CPoint point)
{
CRect nRect, subRect;
int nSplit, spWide, spHight, i, j;
//m_mywindows 的客户区域位置
GetDlgItem(IDC_MYWINDOW)->GetClientRect(&nRect);
GetDlgItem(IDC_MYWINDOW)->ClientToScreen(&nRect);
ScreenToClient(&nRect);
//当不在显示的区域时直接返回
if(point.x < nRect.left || point.x > nRect.right)
{
return;
}
if(point.y < nRect.top || point.y > nRect.bottom)
{
return;
}
nSplit = m_splittesel.GetCurSel() + 1; //分割画面类型确定分割行列数
spWide = nRect.Width()/nSplit;
spHight = nRect.Height()/nSplit;
//确定当前画面序号和当前区域
j = (point.x - nRect.left)/spWide;
i = (point.y - nRect.top)/spHight;
m_curScreen = i * nSplit + j + GetCurSplitStart(m_curScreen, nSplit);
subRect.left = nRect.left + j * spWide;
subRect.top = nRect.top + i * spHight;
subRect.right = subRect.left + spWide;
subRect.bottom = subRect.top + spHight;
//当前画面更新显示
// GetDlgItem(IDC_CURWIN)->ShowWindow(SW_HIDE);
// GetDlgItem(IDC_CURWIN)->MoveWindow(&subRect,false);
// GetDlgItem(IDC_CURWIN)->ShowWindow(SW_NORMAL);
UpdateCurScreenInfo();
}
*/
/*
//双击切换到单画面
void CNetSDKDemoDlg::OnLButtonDblClk(UINT nFlags, CPoint point)
{
CRect nRect, subRect;
int nSplit, spWide, spHight, i, j;
if(m_splittesel.GetCurSel() == SPLIT1)
{
m_splittesel.SetCurSel(m_previousSplit);
UpdataScreen();
return;
}
//m_mywindows 的客户区域位置
GetDlgItem(IDC_MYWINDOW)->GetClientRect(&nRect);
GetDlgItem(IDC_MYWINDOW)->ClientToScreen(&nRect);
ScreenToClient(&nRect);
//当不在显示的区域时直接返回
if(point.x < nRect.left || point.x > nRect.right)
{
return;
}
if(point.y < nRect.top || point.y > nRect.bottom)
{
return;
}
nSplit = m_splittesel.GetCurSel() + 1; //
spWide = nRect.Width()/nSplit;
spHight = nRect.Height()/nSplit;
j = (point.x - nRect.left)/spWide;
i = (point.y - nRect.top)/spHight;
//设置到对应画面的单画面
m_curScreen = i * nSplit + j + GetCurSplitStart(m_curScreen, nSplit);
m_previousSplit = m_splittesel.GetCurSel();
m_splittesel.SetCurSel(SPLIT1);
//刷新显示
UpdataScreen();
UpdateCurScreenInfo();
CDialog::OnLButtonDblClk(nFlags, point);
}
*/
int CloseAllDevCallback(const DeviceNode& node, DWORD dwUser)
{
CNetSDKDemoDlg* pThis = (CNetSDKDemoDlg*)dwUser;
if (!pThis)
{
return 1;
}
pThis->ProcessDeleteDevice(const_cast<DeviceNode*>(&node), false, true);
return 0;
}
//窗口关闭时的处理,主要是需要释放动态内存
void CNetSDKDemoDlg::OnClose()
{
int i;
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
//关闭打开的回调数据保存文件
for(i = 0; i < 16 ; i++)
{
BOOL ret = GetSplitInfo_Main(i, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
}
if(siNode.SavecbFileRaw)
{
fclose(siNode.SavecbFileRaw);
}
if(siNode.SavecbFileStd)
{
fclose(siNode.SavecbFileStd);
}
if(siNode.SavecbFilePcm)
{
fclose(siNode.SavecbFilePcm);
}
if(siNode.SavecbFileYUV)
{
fclose(siNode.SavecbFileYUV);
}
ProcessCloseScreen(i);
}
//删除设备列表
CDevMgr::GetDevMgr().For_EachDev(CloseAllDevCallback, (DWORD)this);
//listen device test
if (m_lListenChannel)
{
BOOL b = CLIENT_StopRealPlayEx(m_lListenChannel);
}
if (m_lListenDevice)
{
BOOL b = CLIENT_Logout(m_lListenDevice);
}
CLIENT_Cleanup(); //关闭网络sdk
LastError();
//关闭网络sdk
TCHAR* pPath = g_GetIniPath();
if(NULL != pPath)
{
delete []pPath;
}
CDialog::OnClose();
}
void CNetSDKDemoDlg::ProcessDeleteDevice(DeviceNode *pDevice, BOOL bDelList, BOOL bDis)
{
int i;
FileInfoNode *pInfo;
if(!pDevice)
{
return;
}
/*Begin: Add by yehao(10857) For Task.NO.11071 2006-12-26*/
{
list<DeviceNode *>::iterator it = m_broadcastDevList.begin();
for (; it != m_broadcastDevList.end(); it++)
{
if (LONG(pDevice) == LONG(*it))
{
CLIENT_AudioBroadcastDelDev(pDevice->LoginID);
m_broadcastDevList.erase(it);
break;
}
}
}
if (m_talkhandle.pDevice && pDevice->LoginID == m_talkhandle.pDevice->LoginID)
{
this->OpenTalk(FALSE);
}
/*End: yehao(10857) Task.NO.11071 */
//检查是否正在刷新该设备的报警信息
DeviceNode *alarmDev = m_ClientStateDlg.GetDevice();
if (alarmDev && alarmDev->LoginID == pDevice->LoginID)
{
m_ClientStateDlg.StopRefresh();
m_ClientStateDlg.SetDevice(0);
}
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
DeviceNode *pDev = pDevice;
//关闭该设备的监视通道和播放通道
for(i = 0; i < 16; i++)
{
BOOL ret = GetSplitInfo_Main(i, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
}
switch(siNode.Type)
{
case SPLIT_TYPE_MONITOR:
if (pDev->LoginID == ((SplitMonitorParam *)siNode.Param)->pDevice->LoginID)
{
ProcessCloseScreen(i, bDis);
}
break;
case SPLIT_TYPE_MULTIPLAY:
if (pDev->LoginID == ((DeviceNode *)siNode.Param)->LoginID)
{
ProcessCloseScreen(i, bDis);
}
break;
case SPLIT_TYPE_NETPLAY:
if (pDev->LoginID == ((SplitNetPlayParam *)siNode.Param)->pFileInfo->pDevice->LoginID)
{
ProcessCloseScreen(i, bDis);
}
break;
case SPLIT_TYPE_PBBYTIME:
if (pDev->LoginID == ((SplitPBByTimeParam *)siNode.Param)->pDevice->LoginID)
{
ProcessCloseScreen(i, bDis);
}
break;
case SPLIT_TYPE_CYCLEMONITOR:
{
// EnterCriticalSection(&g_csCycle);
// CCSLock lck(g_cs);
KillTimer(i);
if (!siNode.Param)
{
break;
}
POSITION pos1, pos2;
pos1 = ((SplitCycleParam *)siNode.Param)->pChannelList->GetHeadPosition();
int count = ((SplitCycleParam *)siNode.Param)->pChannelList->GetCount();
for (int j = 0; j < count; j++)
{
pos2 = pos1;
void *temp = ((SplitCycleParam *)siNode.Param)->pChannelList->GetNext(pos1);
//比较轮循列表中节点的设备名
if ((DWORD)pDev == ((CycleChannelInfo *)temp)->dwDeviceID)
{
//是否刚好是正在播放的节点
if (j == ((SplitCycleParam *)siNode.Param)->iCurPosition)
{
BOOL ret = TRUE;
if (0 != siNode.iHandle)
{
ret = CLIENT_StopRealPlay(siNode.iHandle);
}
if(ret)
{
delete (CycleChannelInfo *)((SplitCycleParam *)siNode.Param)->pChannelList->GetAt(pos2);
((SplitCycleParam *)siNode.Param)->pChannelList->RemoveAt(pos2);
((SplitCycleParam *)siNode.Param)->iChannelCount--;
siNode.iHandle = 0;
ret = SetSplitInfo_Main(i, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while setting split info"));
}
//如果列表已空,则结束轮循
if (((SplitCycleParam *)siNode.Param)->iChannelCount <= 0)
{
DeleteCycleParam(i);
siNode.Param = NULL;
break;
}
}
else
{
if (siNode.Param)
{
if (!bDis)
{
MessageBox(ConvertString(MSG_CYCLE_CLOSECHANNELFAILED));
}
DeleteCycleParam(i);
siNode.Param = NULL;
}
break;
}
}
//不是当前播放节点,直接删除
else
{
delete (CycleChannelInfo *)((SplitCycleParam *)siNode.Param)->pChannelList->GetAt(pos2);
((SplitCycleParam *)siNode.Param)->pChannelList->RemoveAt(pos2);
((SplitCycleParam *)siNode.Param)->iChannelCount--;
if (((SplitCycleParam *)siNode.Param)->iChannelCount <= 0)
{
DeleteCycleParam(i);
siNode.Param = NULL;
break;
}
}
//当前位置放回前一个,以便timer计时到了播放正确的下一个
if (((SplitCycleParam *)siNode.Param)->iCurPosition != 0)
{
((SplitCycleParam *)siNode.Param)->iCurPosition--;
}
else
{
((SplitCycleParam *)siNode.Param)->iCurPosition = ((SplitCycleParam *)siNode.Param)->iChannelCount - 1;
}
}
}
//如果列表中还有其它设备的通道,半秒后执行切换
if (siNode.Param)
{
SetTimer(i, 500, NULL);
}
// LeaveCriticalSection(&g_csCycle);
}
break;
default:
break;
}
}
//删除查询文件列表中该设备的文件项
POSITION nPos1 = g_ptrfilelist->GetHeadPosition();
POSITION nPos2;
int filecount = g_ptrfilelist->GetCount();
for(i = 0; i < filecount; i++)
{
nPos2 = nPos1;
pInfo = (FileInfoNode *)g_ptrfilelist->GetNext(nPos1);
if(pInfo && pInfo->pDevice == pDev)
{
g_ptrfilelist->RemoveAt(nPos2);
delete pInfo;
}
}
CLIENT_Logout(pDev->LoginID);
// LastError();
if(bDelList)
{
/*
POSITION nPos = g_ptrdevicelist->Find(nDev);
g_ptrdevicelist->RemoveAt(nPos);
delete nDev;
*/
CDevMgr::GetDevMgr().DelNode(pDev->LoginID);
}
}
//断开当前选择的设备
void CNetSDKDemoDlg::DeleteDevice()
{
DeviceNode *nDev=(DeviceNode *)GetCurDeviceInfo();
if(nDev == NULL)
{
return;
}
ProcessDeleteDevice(nDev, TRUE);
UpdateDeviceList();
UpdateCurScreenInfo();
UpdateScreen(m_normalBtnPannel.GetSplit());
// Invalidate(true);
}
//拖动亮度控制条
void CNetSDKDemoDlg::CtrlColor_Bright(int pos)
{
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
return;
}
if(siNode.Type == SPLIT_TYPE_MONITOR)
{
siNode.nVideoParam.bParam[0] = pos;
ret = SetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while setting split info"));
return;
}
}
UpdateVideoCtrl(VIDEO_BRIGHT);
}
//拖动对比度控制条
void CNetSDKDemoDlg::CtrlColor_Contrast(int pos)
{
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
return;
}
if(siNode.Type == SPLIT_TYPE_MONITOR)
{
siNode.nVideoParam.bParam[1] = pos;
ret = SetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while setting split info"));
return;
}
}
UpdateVideoCtrl(VIDEO_CONTRAST);
}
//拖动色度控制条
void CNetSDKDemoDlg::CtrlColor_Hue(int pos)
{
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
return;
}
if(siNode.Type == SPLIT_TYPE_MONITOR)
{
siNode.nVideoParam.bParam[2] = pos;
ret = SetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while setting split info"));
return;
}
}
UpdateVideoCtrl(VIDEO_HUE);
}
//拖动饱和度控制条
void CNetSDKDemoDlg::CtrlColor_Saturation(int pos)
{
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
return;
}
if(siNode.Type == SPLIT_TYPE_MONITOR)
{
siNode.nVideoParam.bParam[3] = pos;
ret = SetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while setting split info"));
return;
}
}
UpdateVideoCtrl(VIDEO_SATURATION);
}
//更新设备状态
void CNetSDKDemoDlg::UpdateDeviceState(void *pDevice, char *pBuf, DWORD dwBufLen)
{/*
DeviceNode *pDev = (DeviceNode *)pDevice;
NET_CLIENT_STATE *ClientState = (NET_CLIENT_STATE *)pBuf;
if(ClientState == NULL)
{
return;
}
//设备列表中信息刷新
pDev->State.channelcount = ClientState->channelcount;
pDev->State.alarminputcount = ClientState->alarminputcount;
memcpy(pDev->State.diskerror, ClientState->diskerror, 32);
//录像状态
if(pDev->State.record == NULL)
{
pDev->State.record = new BYTE[pDev->State.channelcount];
}
memcpy(pDev->State.record,ClientState->record,pDev->State.channelcount );
//报警状态
if(pDev->State.alarm == NULL)
{
pDev->State.alarm = new BYTE[pDev->State.alarminputcount];
}
memcpy(pDev->State.alarm,ClientState->alarm,pDev->State.alarminputcount );
//动态检测报警
if(pDev->State.motiondection == NULL)
{
pDev->State.motiondection = new BYTE[pDev->State.channelcount];
}
memcpy(pDev->State.motiondection,ClientState->motiondection,pDev->State.channelcount );
//视频丢失报警
if(pDev->State.videolost == NULL)
{
pDev->State.videolost = new BYTE[pDev->State.channelcount];
}
memcpy(pDev->State.videolost,ClientState->videolost,pDev->State.channelcount );
*/
}
//接收到实时数后需要做的处理
void CNetSDKDemoDlg::ReceiveRealData(LONG lRealHandle, DWORD dwDataType, BYTE *pBuffer, DWORD dwBufSize)
{
// char ougmsg[100];
// sprintf(ougmsg, "Receive real data--type:%d, length:%d\n", dwDataType, dwBufSize);
// OutputDebugString(ougmsg);
//取得窗口号
int nScreen = GetHandleSplit(lRealHandle);
if(nScreen < 0)
{
return;
}
//码流统计
// g_splitinfo[nScreen].nKBPS += dwBufSize;
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(nScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
return;
}
//保存实时数据
switch(dwDataType) {
case 0:
if(siNode.SavecbFileRaw)
{
fwrite(pBuffer, 1, dwBufSize, siNode.SavecbFileRaw);
}
break;
case 1:
if(siNode.SavecbFileStd)
{
fwrite(pBuffer, 1, dwBufSize, siNode.SavecbFileStd);
}
break;
case 2:
if(siNode.SavecbFileYUV)
{
fwrite(pBuffer, 1, dwBufSize, siNode.SavecbFileYUV);
}
break;
case 3: //音频
if(siNode.SavecbFilePcm)
{
fwrite(pBuffer, 1, dwBufSize, siNode.SavecbFilePcm);
}
break;
default: break;
}
}
//显示设备列表中当前选项的详细信息
void CNetSDKDemoDlg::DeviceState()
{
DeviceNode *pDev = (DeviceNode *)GetCurDeviceInfo();
if (pDev)
{
m_ClientStateDlg.SetDevice(pDev);
m_ClientStateDlg.StartRefresh();
m_ClientStateDlg.ShowWindow(SW_SHOW);
}
}
//打开网络预览
void CNetSDKDemoDlg::OpenMultiplay()
{
DeviceNode *pDev = (DeviceNode *)GetCurDeviceInfo();
if(pDev == NULL)
{
return;
}
CPreviewParmsDlg dlg;
int iRet = dlg.DoModal();
int channelid = 0;
RealPlayType rType;
if (IDOK == iRet)
{
channelid = dlg.m_channelId;
rType = RealPlayType(RType_Multiplay_1+dlg.m_iPreviewType);
}
else
{
return;
}
if(/*m_advanceBtnPannel.IsTalkOpen() ||*/ !CheckCurSplitAndClose())
{
return;
}
CWnd *plWnd = m_screenPannel.GetPage(m_curScreen);
if (!plWnd)
{
MessageBox(ConvertString("!error!"));
}
// LONG nPlayID = CLIENT_MultiPlay(pDev->LoginID, plWnd->m_hWnd);
//LONG nPlayID = CLIENT_RealPlayEx(pDev->LoginID, -1, plWnd->m_hWnd/*m_playWnd[m_curScreen].m_hWnd*/, RType_Multiplay);
LONG nPlayID = CLIENT_RealPlayEx(pDev->LoginID, channelid, plWnd->m_hWnd, rType);
if(!nPlayID)
{
LastError();
AfxMessageBox(ConvertString(MSG_DEMODLG_NOPREVIEW));
return;
}
else
{
//禁止语音对讲
m_advanceBtnPannel.EnableTalk(FALSE);
}
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
}
siNode.Type = SPLIT_TYPE_MULTIPLAY;
siNode.iHandle = nPlayID;
siNode.Param = pDev;
ret = SetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
}
UpdateCurScreenInfo();
BOOL cbRec = CLIENT_SetRealDataCallBackEx(nPlayID, RealDataCallBackEx, (DWORD)this, 0x0000000F);
if (!cbRec)
{
LastError();
}
}
void CNetSDKDemoDlg::Sysconfig()
{
DeviceNode *pDev = (DeviceNode *)GetCurDeviceInfo();
if(pDev == NULL)
{
return;
}
MessageBox(ConvertString("Please use the Parameter Config Demo in Sort Application folder , this part of code is stopped maintenance"), ConvertString("prompt"));
return;
CConfigMainDlg dlg;
dlg.SetDevice(pDev);
dlg.DoModal();
/*
DeviceNode *nDev;
In_DeviceInfo m_di;
CSystemConfig nSyscfgdlg;
nDev = (DeviceNode *)GetCurDeviceInfo();
if(nDev == NULL)
{
return;
}
memset(m_di.cDeviceIP ,0, 15);
*(LONG *)m_di.cDeviceIP = nDev->LoginID;
memcpy(m_di.cDeviceName , nDev->Name, 20);
m_di.unAlarmInNum = nDev->Info.byAlarmInPortNum;
m_di.unAlarmOutNum = nDev->Info.byAlarmOutPortNum;
m_di.unChannelNum = nDev->Info.byChanNum;
m_di.unTypeIndex = 1;
m_di.unVideoCodeType = 8;
m_di.unNetType = 1;
nSyscfgdlg.setDeviceId(nDev->LoginID);
nSyscfgdlg.ShowDefModal(m_di);
*/
}
void CNetSDKDemoDlg::Ywptzctrl()
{
CPtzMenu dlg;
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
return;
}
if(siNode.Type != SPLIT_TYPE_MONITOR)
{
MessageBox(ConvertString(MSG_DEMODLG_NOTOPENNED));
return;
}
SplitMonitorParam *nParam = (SplitMonitorParam *)siNode.Param;
LONG iHandle = nParam->pDevice->LoginID;
int iChannel = nParam->iChannel;
dlg.SetPtzParam(iHandle, iChannel);
dlg.DoModal();
}
void CNetSDKDemoDlg::Extptzctrl()
{
CExtPtzCtrl dlg;
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
return;
}
if(siNode.Type != SPLIT_TYPE_MONITOR)
{
MessageBox(ConvertString(MSG_DEMODLG_NOTOPENNED));
return;
}
SplitMonitorParam *nParam = (SplitMonitorParam *)siNode.Param;
LONG iHandle = nParam->pDevice->LoginID;
int iChannel = nParam->iChannel;
dlg.SetExtPtzParam(iHandle, iChannel);
dlg.DoModal();
}
//打开透明串口页面
void CNetSDKDemoDlg::Transcom()
{
CTransCom dlg;
DeviceNode *nDev = (DeviceNode *)GetCurDeviceInfo();
if(nDev == NULL)
{
return;
}
dlg.SetDeviceId(nDev->LoginID);
dlg.DoModal();
}
void CNetSDKDemoDlg::UpdateDevice()
{
DeviceNode *nDev = (DeviceNode *)GetCurDeviceInfo();
if(nDev == NULL)
{
return;
}
CNetUpgrade dlg;
dlg.SetDevice(nDev);
dlg.DoModal();
}
//录像控制
void CNetSDKDemoDlg::Recordstate()
{
DeviceNode *nDev = (DeviceNode *)GetCurDeviceInfo();
if(nDev == NULL)
{
return;
}
CRecordCtrlDlg dlg;
dlg.SetDeviceId(nDev->LoginID);
dlg.DoModal();
}
//Io控制
void CNetSDKDemoDlg::AlarmIOctrl()
{
DeviceNode *nDev = (DeviceNode *)GetCurDeviceInfo();
if(nDev == NULL)
{
return;
}
CAlarmCtrlDlg dlg;
dlg.SetDeviceId(nDev->LoginID);
dlg.DoModal();
}
//设备状态
/*
void CNetSDKDemoDlg::OnDeviceWorkstate()
{
DeviceNode *nDev = (DeviceNode *)GetCurDeviceInfo();
if(nDev == NULL)
{
return;
}
CDeviceWorkState dlg;
dlg.SetDeviceId(nDev->LoginID);
dlg.DoModal();
*/
// CLIENT_StopUpgrade(0);
/*
BOOL nRet = CLIENT_SetVolume(g_splitinfo[0].iHandle, 50);
if(!nRet)
{
LastError();
}
}
*/
//语音对讲功能
/* Modified by yehao(10857) 2006-12-20*/
BOOL CNetSDKDemoDlg::OpenTalk(BOOL bOpen)
{
/*Begin: yehao(10857) 2006-12-20*/
HTREEITEM node_dev, tmpnode;
DWORD nItem;
DeviceNode *pInfo = NULL;
tmpnode = m_devicelist.GetSelectedItem();
if(!tmpnode)
{
MessageBox(ConvertString(MSG_DEMODLG_CHECKSEL));
return FALSE;
}
nItem = m_devicelist.GetItemData(tmpnode);
if(nItem < 16) //是通道项
{
node_dev = m_devicelist.GetParentItem(tmpnode);
pInfo = (DeviceNode *)m_devicelist.GetItemData(node_dev);
}
else //设备项
{
pInfo = (DeviceNode *)nItem;
}
if (bOpen)
{
m_talkhandle.pDevice = pInfo;
m_talkhandle.lHandle = CLIENT_StartTalkEx(pInfo->LoginID, CNetSDKDemoDlg::AudioDataCallBack, (DWORD)this);
if (NULL == m_talkhandle.lHandle)
{
m_advanceBtnPannel.SetCheckTalk(0);
m_talkhandle.pDevice = NULL;
return FALSE;
}
/*
int aaa = 0;
int bbb = 0;
BOOL b = CLIENT_QueryDevState(pInfo->LoginID, DEVSTATE_TALK_ECTYPE, (char*)&aaa, sizeof(int), &bbb);
if (!b)
{
bbb = 4;
}
*/
m_normalBtnPannel.EnableMultiplay(FALSE);
RecordStart();
}
else
{
RecordStop();
BOOL bRet = CLIENT_StopTalkEx(m_talkhandle.lHandle);
if (!bRet)
{
MessageBox(ConvertString("Stop talk error"));
}
m_advanceBtnPannel.SetCheckTalk(0);
m_talkhandle.pDevice = NULL;
m_normalBtnPannel.EnableMultiplay(TRUE);
}
/*End: yehao(10857) */
/*
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox("error while getting split info");
return FALSE;
}
if(siNode.Type != SPLIT_TYPE_MONITOR)
{
m_advanceBtnPannel.SetCheckTalk(0);
MessageBox(MSG_DEMODLG_NOTMONITOR);
return FALSE;
}
ret = FALSE;
if(bOpen)
{
ret = CLIENT_StartTalk(siNode.iHandle);
if(!ret)
{
LastError();
m_advanceBtnPannel.SetCheckTalk(0);
MessageBox(MSG_DEMODLG_OPENTALKFAILED);
return FALSE;
}
else
{
((SplitMonitorParam *)siNode.Param)->isTalkOpen = TRUE;
m_normalBtnPannel.EnableMultiplay(FALSE);
}
}
else
{
ret = CLIENT_StopTalk(siNode.iHandle);
if(!ret)
{
LastError();
m_advanceBtnPannel.SetCheckTalk(1);
MessageBox(MSG_DEMODLG_CLOSETALKFAILED);
return FALSE;
}
else
{
((SplitMonitorParam *)siNode.Param)->isTalkOpen = FALSE;
m_normalBtnPannel.EnableMultiplay(TRUE);
}
}
*/
return TRUE;
}
/*Begin: Add by yehao(10857) 2006-12-20*/
LONG CNetSDKDemoDlg::GetTalkHandle()
{
return m_talkhandle.lHandle;
}
BOOL CNetSDKDemoDlg::RecordStart()
{
BOOL bRet = FALSE;
if (0 == m_uRecordCount)
{
bRet = CLIENT_RecordStart();
}
else
{
bRet = TRUE;
}
if (TRUE == bRet)
{
m_uRecordCount++;
}
// char buf[100] = {0};
// sprintf(buf, "record start num is %d \n", m_uRecordCount);
// OutputDebugString(buf);
return bRet;
}
BOOL CNetSDKDemoDlg::RecordStop()
{
BOOL bRet = FALSE;
if (m_uRecordCount > 0)
{
bRet = TRUE;
m_uRecordCount--;
}
if (0 == m_uRecordCount)
{
bRet = CLIENT_RecordStop();
if (FALSE == bRet)
{
m_uRecordCount++;
}
}
// char buf[100] = {0};
// sprintf(buf, "record stop num is %d \n", m_uRecordCount);
// OutputDebugString(buf);
return bRet;
}
void CNetSDKDemoDlg::AudioDataCallBack(LONG lTalkHandle, char *pDataBuf, DWORD dwBufSize, BYTE byAudioFlag, DWORD dwUser)
{
CNetSDKDemoDlg *pdlg = (CNetSDKDemoDlg *)dwUser;
if (lTalkHandle != pdlg->GetTalkHandle())
{
return;
}
static int num = 0;
char buf[100] = {0};
LONG lRet = -1;
switch (byAudioFlag)
{
case 0:
lRet = CLIENT_TalkSendData(lTalkHandle, pDataBuf, dwBufSize);
sprintf(buf, ConvertString("current num is %d \n"), num);
num++;
// OutputDebugString(buf);
if (lRet != dwBufSize)
{
}
break;
case 1:
CLIENT_AudioDec(pDataBuf, dwBufSize);
break;
default:
break;
}
}
/*End: yehao(10857) */
//是否保存回调原始数据
void CNetSDKDemoDlg::SavecbdataRaw(int nCheck)
{
CPlayWnd *plWnd = (CPlayWnd *)m_screenPannel.GetPage(m_curScreen);
if (!plWnd)
{
MessageBox(ConvertString("we have a big error here!"));
return;
}
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
return;
}
CString strName ;
if(nCheck > 0)
{
strName.Format("cbdata %d.bin",m_curScreen);
CFileDialog dlg(FALSE,"*.bin",strName.GetBuffer(0),OFN_OVERWRITEPROMPT|OFN_HIDEREADONLY,
"All File(*.bin)|*.*||",this);
if(dlg.DoModal() == IDOK)
{
strName = dlg.GetPathName();
FILE *file = fopen(strName.GetBuffer(0),"wb");
if(!file)
{
MessageBox(ConvertString(MSG_DEMODLG_OPENFILEFAILED));
m_saveDataPannel.SetCheckRaw(0);
}
plWnd->SetSplitCBFile_Raw(file);
#ifdef STREAMPARSER
m_spFile = file;
#endif
}
else
{
return;
}
}
else
{
if(siNode.SavecbFileRaw)
{
fclose(siNode.SavecbFileRaw);
plWnd->SetSplitCBFile_Raw(NULL);
}
}
}
void CNetSDKDemoDlg::SavecbdataStd(int nCheck)
{
CPlayWnd *plWnd = (CPlayWnd *)m_screenPannel.GetPage(m_curScreen);
if (!plWnd)
{
MessageBox(ConvertString("we have a big error here!"));
return;
}
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
return;
}
CString strName ;
if(nCheck > 0)
{
strName.Format("cbdata %d.dav",m_curScreen);
CFileDialog dlg(FALSE,"*.dav",strName.GetBuffer(0),OFN_OVERWRITEPROMPT|OFN_HIDEREADONLY,
"All File(*.dav)|*.*||",this);
if(dlg.DoModal() == IDOK)
{
strName = dlg.GetPathName();
FILE *file = fopen(strName.GetBuffer(0),"wb");
if(!file)
{
MessageBox(ConvertString(MSG_DEMODLG_OPENFILEFAILED));
m_saveDataPannel.SetCheckStd(0);
}
plWnd->SetSplitCBFile_Std(file);
}
else
{
return;
}
}
else
{
if(siNode.SavecbFileStd)
{
fclose(siNode.SavecbFileStd);
plWnd->SetSplitCBFile_Std(NULL);
}
}
}
void CNetSDKDemoDlg::Savecbdatapcm(int nCheck)
{
CPlayWnd *plWnd = (CPlayWnd *)m_screenPannel.GetPage(m_curScreen);
if (!plWnd)
{
MessageBox(ConvertString("we have a big error here!"));
return;
}
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
return;
}
CString strName ;
if(nCheck > 0)
{
strName.Format("cbdata %d.pcm",m_curScreen);
CFileDialog dlg(FALSE,"*.pcm",strName.GetBuffer(0),OFN_OVERWRITEPROMPT|OFN_HIDEREADONLY,
"All File(*.pcm)|*.*||",this);
if(dlg.DoModal() == IDOK)
{
strName = dlg.GetPathName();
FILE *file = fopen(strName.GetBuffer(0),"wb");
if(!file)
{
MessageBox(ConvertString(MSG_DEMODLG_OPENFILEFAILED));
m_saveDataPannel.SetCheckPcm(0);
}
plWnd->SetSplitCBFile_Pcm(file);
}
else
{
return;
}
}
else
{
if(siNode.SavecbFilePcm)
{
fclose(siNode.SavecbFilePcm);
plWnd->SetSplitCBFile_Pcm(NULL);
}
}
}
void CNetSDKDemoDlg::Savecbdatayuv(int nCheck)
{
CPlayWnd *plWnd = (CPlayWnd *)m_screenPannel.GetPage(m_curScreen);
if (!plWnd)
{
MessageBox(ConvertString("we have a big error here!"));
return;
}
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
return;
}
CString strName ;
if(nCheck > 0)
{
strName.Format("cbdata %d.yuv",m_curScreen);
CFileDialog dlg(FALSE,"*.yuv",strName.GetBuffer(0),OFN_OVERWRITEPROMPT|OFN_HIDEREADONLY,
"All File(*.yuv)|*.*||",this);
if(dlg.DoModal() == IDOK)
{
strName = dlg.GetPathName();
FILE *file = fopen(strName.GetBuffer(0),"wb");
if(!file)
{
MessageBox(ConvertString(MSG_DEMODLG_OPENFILEFAILED));
m_saveDataPannel.SetCheckYuv(0);
}
plWnd->SetSplitCBFile_Yuv(file);
}
else
{
return;
}
}
else
{
if(siNode.SavecbFileYUV)
{
fclose(siNode.SavecbFileYUV);
plWnd->SetSplitCBFile_Yuv(NULL);
}
}
}
BOOL CAboutDlg::OnInitDialog()
{
CDialog::OnInitDialog();
g_SetWndStaticText(this);
return TRUE;
}
void CNetSDKDemoDlg::CycleMonitor()
{
CCycleMonitor dlg;
if (dlg.DoModal() == IDOK)
{
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
// EnterCriticalSection(&g_csCycle);
//刷新画面,如果有画面被关闭了可以正常显示
CPlayWnd *plWnd;
for (int curWin = 0; curWin < MAX_CHANNUM; curWin++)
{
plWnd = (CPlayWnd *)m_screenPannel.GetPage(curWin);
if (plWnd)
{
plWnd->PostMessage(VIDEO_REPAINT);
}
plWnd->PostMessage(VIDEO_REPAINT);
}
for (int screenNo = 0; screenNo < MAX_CHANNUM; screenNo++)
{
KillTimer(screenNo);
BOOL ret = GetSplitInfo_Main(screenNo, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
return;
}
//判断是否轮循类型
if (siNode.Type == SPLIT_TYPE_CYCLEMONITOR)
{
POSITION pos = ((SplitCycleParam *)siNode.Param)->pChannelList->GetHeadPosition();
CycleChannelInfo *tempnode = (CycleChannelInfo *)((SplitCycleParam *)siNode.Param)->pChannelList->GetNext(pos);
DeviceNode *pDev = (DeviceNode *)tempnode->dwDeviceID;
((SplitCycleParam *)siNode.Param)->pDevice = pDev;
LONG nID = pDev->LoginID;
int nCh = tempnode->iChannel;
CWnd *plWnd = m_screenPannel.GetPage(screenNo);
if (!plWnd)
{
MessageBox(ConvertString("!!error!!"));
return;
}
//用户选择1个通道,相当于打开1个监视通道
//test,无论通道多少,一视同仁
if (FALSE/*((SplitCycleParam *)siNode.Param)->iChannelCount == 1*/)
{
LONG nChannelID = CLIENT_RealPlay(nID, nCh, plWnd->m_hWnd/*m_playWnd[screenNo].m_hWnd*/);
if(!nChannelID)
{
LastError();
KillTimer(screenNo);
MessageBox(ConvertString(MSG_CYCLE_OPENCHANNELFAILED));
if (siNode.Param)
{
DeleteCycleParam(screenNo);
}
continue;
}
//设置轮循位置为第一个
((SplitCycleParam *)siNode.Param)->iCurPosition = 0;
//获取视频参数
byte bVideo[4];
BOOL nRet = CLIENT_ClientGetVideoEffect(nChannelID, &bVideo[0],&bVideo[1],&bVideo[2],&bVideo[3]);
if (!nRet)
{
LastError();
}
siNode.nVideoParam.dwParam = *(DWORD *)bVideo;
((CPlayWnd *)plWnd)->SetSplitHandle(nChannelID);
continue;
}
//用户选择了2个或2个以上通道,开始轮循
else
{
LONG nChannelID = CLIENT_RealPlay(nID, nCh, plWnd->m_hWnd/*m_playWnd[screenNo].m_hWnd*/);
if(!nChannelID)
{
LastError();
KillTimer(screenNo);
MessageBox(ConvertString(MSG_CYCLE_OPENCHANNELFAILED));
if (siNode.Param)
{
DeleteCycleParam(screenNo);
}
continue;
}
//设置轮循位置为第一个
((SplitCycleParam *)siNode.Param)->iCurPosition = 0;
//获取视频参数
byte bVideo[4];
BOOL nRet = CLIENT_ClientGetVideoEffect(nChannelID, &bVideo[0],&bVideo[1],&bVideo[2],&bVideo[3]);
if (!nRet)
{
LastError();
}
siNode.nVideoParam.dwParam = *(DWORD *)bVideo;
((CPlayWnd *)plWnd)->SetSplitHandle(nChannelID);
//设置轮循计时器,将秒转换为毫秒
UINT interval = ((SplitCycleParam *)siNode.Param)->iInterval;
SetTimer((UINT)screenNo, interval * 1000, NULL);
UpdateCurScreenInfo();
}
}
}//end of for (int screenNo = 0; screenNo < MAX_CHANNUM; screenNo++)
//LeaveCriticalSection(&g_csCycle);
}
}
int WriteAlarmLogFunc(const AlarmNode& node, DWORD dwUser)
{
CNetSDKDemoDlg* pThis = (CNetSDKDemoDlg*)dwUser;
if (!pThis)
{
return 1;
}
return pThis->WriteAlarmLogFunc_Imp(node);
}
int CNetSDKDemoDlg::WriteAlarmLogFunc_Imp(const AlarmNode& node)
{
if (!m_almLogFile_Comm || !m_almLogFile_Shelter || !m_almLogFile_dFull
|| !m_almLogFile_dError || !m_almLogFile_SoundDec)
{
return 1;
}
CString strNewLog = "";
CString strAlmTime;
strAlmTime.Format(ConvertString("upgrade time:%d-%d-%d,%d:%d:%d\n"),
node.timeStamp.GetYear(), node.timeStamp.GetMonth(), node.timeStamp.GetDay(),
node.timeStamp.GetHour(), node.timeStamp.GetMinute(), node.timeStamp.GetSecond());
strNewLog += strAlmTime;
// CString strAlmType;
CString strAlmContent = (ConvertString("information:\n"));
CString strTemp;
BOOL isAlarm = FALSE; //确定是否有新的报警
switch(node.alarmType)
{
case COMM_ALARM:
// case ALARM_ALARM_EX:
// case MOTION_ALARM_EX:
// case VIDEOLOST_ALARM_EX:
{
//strAlmType.Format("报警类型:常规\n");
//alarm input
for(int i = 0; i < 16; i++)
{
// if (node.state.alarmout[i] != m_lastAlarm.alarmout[i])
if (node.state.cState.alarm[i] != m_lastAlarm.cState.alarm[i])
{
// if (m_lastAlarm.alarmout[i]) //alarm i is gone
if (m_lastAlarm.cState.alarm[i]) //alarm i is gone
{
strTemp.Format(ConvertString("Alarm end, alarm: channel No.:%d\n"), i+1);
}
else //new alarm
{
strTemp.Format(ConvertString("Alarm start, alram: channel No.:%d\n"), i+1);
}
isAlarm = TRUE;
strAlmContent += strTemp;
}
}
if (m_almLogFile_Comm && isAlarm)
{
strNewLog += strAlmContent + "\n";
fwrite(strNewLog.GetBuffer(0), strNewLog.GetLength(), 1, m_almLogFile_Comm);
fflush(m_almLogFile_Comm);
}
//motion detect
if (isAlarm)
{
strNewLog = "";
}
CString strAlmContent = "";
isAlarm = FALSE;
for (i = 0; i < 16; i++)
{
// if (node.state.motion[i] != m_lastAlarm.motion[i])
if (node.state.cState.motiondection[i] != m_lastAlarm.cState.motiondection[i])
{
// if (m_lastAlarm.motion[i]) //alarm i is gone
if (m_lastAlarm.cState.motiondection[i]) //alarm i is gone
{
strTemp.Format(ConvertString("Alarm end, motion alarm: channel No.:%d\n"), i+1);
}
else //new alarm
{
strTemp.Format(ConvertString("Alarm start, motion alarm: channel No.:%d\n"), i+1);
}
isAlarm = TRUE;
strAlmContent += strTemp;
}
}
if (m_almLogFile_Comm && isAlarm)
{
strNewLog += strAlmContent + "\n";
fwrite(strNewLog.GetBuffer(0), strNewLog.GetLength(), 1, m_almLogFile_Comm);
fflush(m_almLogFile_Comm);
}
//video lost
if (isAlarm)
{
strNewLog = "";
}
strAlmContent = "";
isAlarm = FALSE;
for (i = 0; i < 16; i++)
{
// if (node.state.videolost[i] != m_lastAlarm.videolost[i])
if (node.state.cState.videolost[i] != m_lastAlarm.cState.videolost[i])
{
// if (m_lastAlarm.videolost[i]) //alarm i is gone
if (m_lastAlarm.cState.videolost[i]) //alarm i is gone
{
strTemp.Format(ConvertString("Alarm end, video lost alarm: channel No.:%d\n"), i+1);
}
else //new alarm
{
strTemp.Format(ConvertString("Alarm start, video lost alarm: channel No.:%d\n"), i+1);
}
isAlarm = TRUE;
strAlmContent += strTemp;
}
}
if (m_almLogFile_Comm && isAlarm)
{
strNewLog += strAlmContent + "\n";
fwrite(strNewLog.GetBuffer(0), strNewLog.GetLength(), 1, m_almLogFile_Comm);
fflush(m_almLogFile_Comm);
}
}
break;
case SHELTER_ALARM:
// case SHELTER_ALARM_EX:
{
// strAlmType.Format("报警类型:遮挡\n");
for (int i = 0; i < 16; i++)
{
if (node.state.shelter[i] != m_lastAlarm.shelter[i])
{
if (m_lastAlarm.shelter[i]) //alarm i is gone
{
strTemp.Format(ConvertString("Alarm end, shelter alarm: channel No.:%d\n"), i+1);
}
else //new alarm
{
strTemp.Format(ConvertString("Alarm start, shelter alarm: channel No.:%d\n"), i+1);
}
isAlarm = TRUE;
strAlmContent += strTemp;
}
}
if (m_almLogFile_Shelter && isAlarm)
{
strNewLog += strAlmContent + "\n";
fwrite(strNewLog.GetBuffer(0), strNewLog.GetLength(), 1, m_almLogFile_Shelter);
fflush(m_almLogFile_Shelter);
}
}
break;
case DISK_FULL_ALARM:
// case DISKFULL_ALARM_EX:
{
// strAlmType.Format("报警类型:硬盘满\n");
// if (node.state.dFull != m_lastAlarm.dFull)
{
// if (node.state.diskfull) //disk full
if (node.state.dFull) //disk full
{
strTemp.Format(ConvertString("Alarm, Disk full\n"));
isAlarm = TRUE;
strAlmContent += strTemp;
}
else //disk full alarm is gone
{
// strTemp.Format("报警消失!硬盘满\n");
}
}
if (m_almLogFile_dFull && isAlarm)
{
strNewLog += strAlmContent + "\n";
fwrite(strNewLog.GetBuffer(0), strNewLog.GetLength(), 1, m_almLogFile_dFull);
fflush(m_almLogFile_dFull);
}
}
break;
case DISK_ERROR_ALARM:
// case DISKERROR_ALARM_EX:
{
// strAlmType.Format("报警类型:坏硬盘\n");
for (int i = 0; i < 32; i++)
{
DWORD dwDE = node.state.dError ^ m_lastAlarm.dError;
// if (node.state.diskerror[i] != m_lastAlarm.diskerror[i])
if (dwDE & (0x01<<i))
{
if (m_lastAlarm.dError & (0x01<<i)) //disk error alarm is gone
{
strTemp.Format(ConvertString("Alarm end, Disk error alarm %d\n"), i+1);
}
else
{
strTemp.Format(ConvertString("Alarm start, Disk error alarm %d\n"), i+1);
}
isAlarm = TRUE;
strAlmContent += strTemp;
}
}
if (m_almLogFile_dError && isAlarm)
{
strNewLog += strAlmContent + "\n";
fwrite(strNewLog.GetBuffer(0), strNewLog.GetLength(), 1, m_almLogFile_dError);
fflush(m_almLogFile_dError);
}
}
break;
case SOUND_DETECT_ALARM:
// case SOUND_DETECT_ALARM_EX:
{
// strAlmType.Format("报警类型:音频检测\n");
for (int i = 0; i < 16; i++)
{
if (node.state.soundalarm[i] != m_lastAlarm.soundalarm[i])
{
if (m_lastAlarm.soundalarm[i]) //alarm i is gone
{
strTemp.Format(ConvertString("Alarm end, sound detect alarm: channel No.:%d\n"), i+1);
}
else //new alarm
{
strTemp.Format(ConvertString("Alarm start, sound detect alarm:channel No.:%d\n"), i+1);
}
isAlarm = TRUE;
strAlmContent += strTemp;
}
}
if (m_almLogFile_SoundDec && isAlarm)
{
strNewLog += strAlmContent + "\n";
fwrite(strNewLog.GetBuffer(0), strNewLog.GetLength(), 1, m_almLogFile_SoundDec);
fflush(m_almLogFile_SoundDec);
}
}
break;
default:
return 1;
}
memcpy(&m_lastAlarm, &node.state, sizeof(DEV_STATE));
return 0;
}
void CNetSDKDemoDlg::OnTimer(UINT nIDEvent)
{
//刷新播放放进度条
CDialog::OnTimer(nIDEvent);
if (nIDEvent >= 0 && nIDEvent <= CUR_MAXCHAN)
{
NextCycleMonitor(nIDEvent);
}
else if (nIDEvent == ALARMLOG)
{
CDevMgr::GetDevMgr().For_EachAlmNode(WriteAlarmLogFunc, (DWORD)this);
/* //listen devide test
if (m_mylsdata.state == 1)
{
NET_DEVICEINFO info = {0};
// int error;
BOOL b = CLIENT_ResponseDevReg(m_mylsdata.serial, m_mylsdata.ip, m_mylsdata.port, true);
if (b)
{
// m_lListenDevice = CLIENT_LoginEx(m_mylsdata.ip, m_mylsdata.port, "admin", "admin", 2, m_mylsdata.serial, &info, &error);
// if (!m_lListenDevice)
// {
// MessageBox("login failed!");
// }
}
if (m_lListenDevice)
{//test disconnect
// MessageBox("1!");
// m_lListenChannel = CLIENT_RealPlayEx(m_lListenDevice, 0, m_screenPannel.GetPage(0)->m_hWnd);
// if (!m_lListenDevice)
// {
// MessageBox("open channel failed!");
// }
// MessageBox("1");
}
}
*/
}
else if (nIDEvent == UPDATATREE)
{
if (g_bUpdataTree)
{
g_bUpdataTree = FALSE;
UpdateDeviceList();
}
}
}
void CNetSDKDemoDlg::Getversion()
{
CString strCptn;
GetWindowText(strCptn);
LONG lVer = CLIENT_GetSDKVersion();
byte bVer[4] = {0};
// bVer[0] = (byte)lVer;
bVer[1] = (byte)(lVer>>8);
bVer[2] = (byte)(lVer>>16);
bVer[3] = (byte)(lVer>>24);
CString strVer;
strVer.Format("%d.%d.%d", bVer[3], bVer[2], bVer[1]);
strVer = ConvertString(MSG_VERSION) + strVer;
strCptn += strVer;
SetWindowText(strCptn);
/*
MessageBox(strVer);
*/
}
/*Begin: Add by yehao(10857) For Task.NO.11071 2006-12-23*/
void CNetSDKDemoDlg::OpenAudioBroadcastDlg()
{
DeviceNode *ptmpDevNode = NULL;
HTREEITEM tmphandle = m_devicelist.GetRootItem();
int num = 0;
m_audioBroadcastDlg.m_AllDevList.clear();
m_audioBroadcastDlg.m_BroadcastDevList.clear();
while (tmphandle)
{
ptmpDevNode = (DeviceNode *)m_devicelist.GetItemData(tmphandle);
m_audioBroadcastDlg.m_AllDevList.push_back(ptmpDevNode);
tmphandle = m_devicelist.GetNextItem(tmphandle, TVGN_NEXT);
}
list<DeviceNode *>::iterator it = m_broadcastDevList.begin();
for (; it != m_broadcastDevList.end(); it++)
{
list<DeviceNode *>::iterator itt = m_audioBroadcastDlg.m_AllDevList.begin();
for (; itt != m_audioBroadcastDlg.m_AllDevList.end(); itt++)
{
if (LONG(*it) == LONG(*itt))
{
m_audioBroadcastDlg.m_BroadcastDevList.push_back((*it));
m_audioBroadcastDlg.m_AllDevList.erase(itt);
break;
}
}
}
m_audioBroadcastDlg.m_bRecord = m_bRecord;
int iRet = m_audioBroadcastDlg.DoModal();
if (IDOK == iRet)
{
if (m_bRecord != m_audioBroadcastDlg.m_bRecord)
{
m_bRecord = m_audioBroadcastDlg.m_bRecord;
if (m_bRecord)
{
RecordStart();
}
else
{
RecordStop();
}
}
BOOL find = FALSE;
{
list<DeviceNode *>::iterator it = m_broadcastDevList.begin();
for (; it != m_broadcastDevList.end(); it++)
{
find = FALSE;
list<DeviceNode *>::iterator itt = m_audioBroadcastDlg.m_BroadcastDevList.begin();
for (; itt != m_audioBroadcastDlg.m_BroadcastDevList.end(); itt++)
{
if (LONG(*it) == LONG(*itt))
{
find = TRUE;
break;
}
}
if (FALSE == find)
{
CLIENT_AudioBroadcastDelDev((*it)->LoginID);
}
}
}
{
list<DeviceNode *>::iterator it = m_audioBroadcastDlg.m_BroadcastDevList.begin();
for (; it != m_audioBroadcastDlg.m_BroadcastDevList.end(); it++)
{
find = FALSE;
list<DeviceNode *>::iterator itt = m_broadcastDevList.begin();
for (; itt != m_broadcastDevList.end(); itt++)
{
if (LONG(*it) == LONG(*itt))
{
find = TRUE;
break;
}
}
if (FALSE == find)
{
CLIENT_AudioBroadcastAddDev((*it)->LoginID);
}
}
}
{
m_broadcastDevList.clear();
list<DeviceNode *>::iterator it = m_audioBroadcastDlg.m_BroadcastDevList.begin();
for (; it != m_audioBroadcastDlg.m_BroadcastDevList.end(); it++)
{
m_broadcastDevList.push_back(*it);
}
}
}
else
{
}
return;
}
/*End: yehao(10857) Task.NO.11071 */
HBRUSH CNetSDKDemoDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
if (pWnd->GetDlgCtrlID() == IDC_TREE_DEVICELIST)
{
return m_myBrush;
}
return hbr;
}
void CNetSDKDemoDlg::Sysconfig2()
{
DeviceNode *pDev;
In_DeviceInfo m_di;
CSystemConfig nSyscfgdlg;
pDev = (DeviceNode *)GetCurDeviceInfo();
if(pDev == NULL)
{
return;
}
// memset(m_di.cDeviceIP ,0, 15);
m_di.lDeviceID = pDev->LoginID;
memcpy(m_di.cDeviceName , pDev->Name, 20);
m_di.unAlarmInNum = pDev->Info.byAlarmInPortNum;
m_di.unAlarmOutNum = pDev->Info.byAlarmOutPortNum;
m_di.unChannelNum = pDev->Info.byChanNum;
m_di.unTypeIndex = (pDev->Info.byDVRType == NET_DVR_MPEG4_NVSII) ? 2 : 1;
m_di.unVideoCodeType = 8;
m_di.unNetType = 1;
nSyscfgdlg.setDeviceId(pDev->LoginID);
nSyscfgdlg.ShowDefModal(m_di);
}
void CNetSDKDemoDlg::Playbackbytime()
{
CPlayBackByTime dlg;
showBTwindow:
if (dlg.DoModal() == IDOK)
{
if(!CheckCurSplitAndClose())
{
MessageBox(ConvertString("Error: Cannot close current screen!"));
return;
}
PlayBackByTimeInfo *tmpinfo = dlg.GetPlayBackInfo();
NET_RECORDFILE_INFO ri;
ZeroMemory(&ri, sizeof(ri));
ri.starttime = tmpinfo->starttime;
ri.endtime = tmpinfo->endtime;
/* LONG lPlayID = CLIENT_PlayBackByRecordFile(tmpinfo->pDevice->LoginID, &ri,
GetDlgItem(IDC_SCREEN1 + m_curScreen )->m_hWnd, 0,0);
*/
// LONG lPlayID = CLIENT_PlayBackByTime(tmpinfo->pDevice->LoginID, tmpinfo->nChannel,
// &tmpinfo->starttime, &tmpinfo->endtime, GetDlgItem(IDC_SCREEN1 + m_curScreen )->m_hWnd, PlayCallBack, (DWORD)this);
CWnd *plWnd = m_screenPannel.GetPage(m_curScreen);
if (!plWnd)
{
MessageBox(ConvertString("!!error!!"));
return;
}
LONG lPlayID = CLIENT_PlayBackByTimeEx(tmpinfo->pDevice->LoginID, tmpinfo->nChannel,
&tmpinfo->starttime, &tmpinfo->endtime, plWnd->m_hWnd/*m_playWnd[m_curScreen].m_hWnd*/,
PlayCallBack, (DWORD)this,PBDataCallBack, (DWORD)this);
if(!lPlayID)
{
LastError();
MessageBox(ConvertString(MSG_DEMODLG_PLAYFAILED));
goto showBTwindow;
}
else
{ //如果其它通道没有打开音频,则打开音频
if (m_curSoundSplit < 0)
{
if (FALSE == CLIENT_OpenSound(lPlayID))
{
LastError();
MessageBox(ConvertString(MSG_OPENSOUNDFAILED));
m_advanceBtnPannel.SetCheckSound(0);
}
else
{
m_advanceBtnPannel.SetCheckSound(1);
m_curSoundSplit = m_curScreen;
}
}
}
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
}
siNode.Type = SPLIT_TYPE_PBBYTIME;
siNode.iHandle = lPlayID;
SplitPBByTimeParam *nparam = new SplitPBByTimeParam;
nparam->pDevice = tmpinfo->pDevice;
nparam->nChannel = tmpinfo->nChannel;
nparam->starttime = tmpinfo->starttime;
nparam->endtime = tmpinfo->endtime;
siNode.Param = nparam;
ret = SetSplitInfo_Main(m_curScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while setting split info"));
}
//时间播放的进度条目前不做
// m_play_position.EnableWindow(FALSE);
m_playctrlPannel.StartPlay();
UpdateCurScreenInfo();
}
}
void CNetSDKDemoDlg::Downloadbytime()
{
m_dbByTime.CenterWindow();
m_dbByTime.ShowWindow(SW_SHOW);
}
void CNetSDKDemoDlg::RebootDevice()
{
DeviceNode *nDev = (DeviceNode *)GetCurDeviceInfo();
if (NULL == nDev)
{
return;
}
BOOL bRet = CLIENT_RebootDev(nDev->LoginID);
if (!bRet)
{
LastError();
MessageBox(ConvertString(MSG_DEMODLG_REBOOTFAILED));
}
else
{
MessageBox(ConvertString(MSG_DEMODLG_REBOOTDONE));
}
}
void CNetSDKDemoDlg::ShutdownDevice()
{
DeviceNode *nDev = (DeviceNode *)GetCurDeviceInfo();
if (NULL == nDev)
{
return;
}
BOOL bRet = CLIENT_ShutDownDev(nDev->LoginID);
if (!bRet)
{
LastError();
MessageBox(ConvertString(MSG_DEMODLG_SHUTDOWNFAILED));
}
else
{
MessageBox(ConvertString(MSG_DEMODLG_SHUTDOWNDONE));
}
}
void CNetSDKDemoDlg::DDNS_QueryIP()
{
CDDNS_QueryIP dlg;
dlg.DoModal();
}
void CNetSDKDemoDlg::OnDblclkTreeDevicelist(NMHDR* pNMHDR, LRESULT* pResult)
{
OpenChannel();
*pResult = 0;
}
void CNetSDKDemoDlg::OpenAllChannel(DeviceNode *pInfo, RealPlayType subtype)
{
LONG nChannelID = 0;
ProcessCloseAllChannel(pInfo);
LONG nID = pInfo->LoginID;
int chNum = pInfo->Info.byChanNum;
int ScreenNum = CUR_MAXCHAN;//本SDK现在所能显示的最大画面数
int FreeScreen = 0;
DWORD freeFlag = 0;
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
if(chNum > CUR_MAXCHAN)//设备返回通道数>SDK显示通道数
{
for(int ii = 0 ; ii < CUR_MAXCHAN ; ii++)
{
if (ProcessCloseScreen(ii))
{
freeFlag |= (0x00000001 << ii);
}
}
FreeScreen = CUR_MAXCHAN;
UpdateCurScreenInfo();
}
else
{
for(int ii = 0 ; ii< CUR_MAXCHAN; ii++)
{
BOOL ret = GetSplitInfo_Main(ii, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
}
if(SPLIT_TYPE_NULL == siNode.Type)
{
freeFlag |= (0x00000001 << ii);
FreeScreen ++;
}
}
if((chNum > FreeScreen))//空余画面数<设备返回通道数
{
int killNum = chNum - FreeScreen;
for (int ii = 0 ; ii < CUR_MAXCHAN; ii ++)
{
if(killNum && !(freeFlag & (0x00000001 << ii)))
{
if (ProcessCloseScreen(ii))
{
freeFlag |= (0x00000001 << ii);
FreeScreen ++;
}
killNum --;
}
}
UpdateCurScreenInfo();
}
}
int nCh = 0;
for (int nScrn = 0; nScrn < CUR_MAXCHAN; nScrn++)
{
if (((freeFlag >> nScrn)& 0x00000001) && (nCh < FreeScreen) && (nCh < chNum))
{
OpenSingleChannel(pInfo, nCh, nScrn, subtype);
nCh++;
}
}
// m_normalBtnPannel.SetSplit(CUR_SPLIT);
// m_curScreen = 0;
// m_screenPannel.SetShowPlayWin(CUR_SPLIT, 0);
// UpdateScreen(CUR_SPLIT + 1);
}
BOOL CNetSDKDemoDlg::ProcessCloseAllChannel(DeviceNode *pInfo)
{
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
LONG nID = pInfo->LoginID;
LONG curID = 0;
BOOL ret = TRUE;
for(int i = 0 ; i < CUR_MAXCHAN; i++)
{
BOOL ret = GetSplitInfo_Main(i, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
return FALSE;
}
if(SPLIT_TYPE_NULL == siNode.Type)
{
continue;
}
else if(SPLIT_TYPE_MONITOR == siNode.Type)
{
SplitMonitorParam *mParam = (SplitMonitorParam *)siNode.Param;
curID = mParam->pDevice->LoginID;
}
else if (SPLIT_TYPE_NETPLAY == siNode.Type)
{
SplitNetPlayParam *nParam = (SplitNetPlayParam *)siNode.Param;
curID = nParam->pFileInfo->pDevice->LoginID;
}
else if (SPLIT_TYPE_MULTIPLAY == siNode.Type)
{
curID = ((DeviceNode *)siNode.Param)->LoginID;
}
else if (SPLIT_TYPE_CYCLEMONITOR == siNode.Type)
{
SplitCycleParam *mParam = (SplitCycleParam *)siNode.Param;
curID = mParam->pDevice->LoginID;
}
else if (SPLIT_TYPE_PBBYTIME == siNode.Type)
{
SplitPBByTimeParam *mParam = (SplitPBByTimeParam *)siNode.Param;
curID = mParam->pDevice->LoginID;
}
if (nID == curID)
{
if (!ProcessCloseScreen(i))
{
ret = FALSE;
}
else
{
CPlayWnd *plWnd = (CPlayWnd *)m_screenPannel.GetPage(i);
if (!plWnd)
{
MessageBox(ConvertString("!!big error!!"));
return FALSE;
}
plWnd->PostMessage(VIDEO_REPAINT);
}
}
curID = 0;
}
UpdateCurScreenInfo();
return ret;
}
void CNetSDKDemoDlg::SwitchFullScreen()
{
m_screenPannel.SetFullScreen(!m_screenPannel.GetFullScreen());
}
//void CNetSDKDemoDlg::ReturnOrignalSplit()
//{
// if (m_bFullSCRN)
// {
// SwitchFullScreen();
// }
//}
//打开轮循列表中下一个通道
void CNetSDKDemoDlg::NextCycleMonitor(UINT nID)
{
// EnterCriticalSection(&g_csCycle);
UINT nScreen = nID;
SplitInfoNode siNode;
memset(&siNode, 0, sizeof(siNode));
BOOL ret = GetSplitInfo_Main(nScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while getting split info"));
return;
}
if (siNode.Type != SPLIT_TYPE_CYCLEMONITOR || NULL == siNode.Param)
{
return;
}
//取轮循列表的下一个通道值
CycleChannelInfo *tempnode;
POSITION nPos = ((SplitCycleParam *)siNode.Param)->pChannelList->GetHeadPosition();
tempnode = (CycleChannelInfo *)((SplitCycleParam *)siNode.Param)->pChannelList->GetNext(nPos);
int nextPosition = ((SplitCycleParam *)siNode.Param)->iCurPosition + 1;
//如果已经到了列表末尾,则返回列表头
if (nextPosition >= ((SplitCycleParam *)siNode.Param)->iChannelCount)
{
nextPosition = 0;
}
else
{
//否则取下一个
for (int x = 0; x < nextPosition; x++)
{
tempnode = (CycleChannelInfo *)((SplitCycleParam *)siNode.Param)->pChannelList->GetNext(nPos);
}
}
ret = TRUE;
if (siNode.iHandle != 0)
{
CLIENT_StopRealPlay(siNode.iHandle);
}
if(ret)
{
DeviceNode *pDev = (DeviceNode *)(tempnode->dwDeviceID);
((SplitCycleParam *)siNode.Param)->pDevice = pDev;
LONG nID = pDev->LoginID;
int nCh = tempnode->iChannel;
CWnd *plWnd = m_screenPannel.GetPage(nScreen);
if (!plWnd)
{
MessageBox(ConvertString("fatal error!"));
}
LONG nChannelID = CLIENT_RealPlay(nID, nCh, plWnd->m_hWnd/*m_playWnd[nScreen].m_hWnd*/);
// if(!nChannelID)
// {
// LastError();
// KillTimer(nScreen);
// MessageBox(ConvertString(MSG_CYCLE_OPENCHANNELFAILED));
// if (siNode.Param)
// {
// DeleteCycleParam(nScreen);
// }
//
// //刷新该窗口显示
// //m_playWnd[nScreen].ShowWindow(SW_HIDE);
// //m_playWnd[nScreen].ShowWindow(SW_NORMAL);
// goto exit;
// }
//设置当前轮循位置
((SplitCycleParam *)siNode.Param)->iCurPosition = nextPosition;
//获取视频参数
byte bVideo[4];
BOOL nRet = CLIENT_ClientGetVideoEffect(nChannelID, &bVideo[0],&bVideo[1],&bVideo[2],&bVideo[3]);
if (!nRet)
{
LastError();
}
siNode.nVideoParam.dwParam = *(DWORD *)bVideo;
siNode.iHandle = nChannelID;
ret = SetSplitInfo_Main(nScreen, &siNode);
if (!ret)
{
MessageBox(ConvertString("error while setting split info"));
}
//设置轮循计时器
UINT interval = ((SplitCycleParam *)siNode.Param)->iInterval;
SetTimer((UINT)nScreen, interval * 1000, NULL);
goto exit;
}
else
{
//通道关闭失败
KillTimer(nScreen);
if (siNode.Param)
{
MessageBox(ConvertString(MSG_CYCLE_CLOSECHANNELFAILED));
DeleteCycleParam(nScreen);
}
goto exit;
}
exit:
// LeaveCriticalSection(&g_csCycle);
return;
}
void CNetSDKDemoDlg::CloseAllChannel()
{
DeviceNode *pDev = (DeviceNode *)GetCurDeviceInfo();
if (NULL == pDev)
{
return;
}
ProcessCloseAllChannel(pDev);
}
void CNetSDKDemoDlg::SeleteNormalPannel() //显示“常规功能”页面
{
m_normalBtnPannel.ShowWindow(SW_SHOW);
m_advanceBtnPannel.ShowWindow(SW_HIDE);
m_saveDataPannel.ShowWindow(SW_HIDE);
m_ptzPannel.ShowWindow(SW_HIDE);
}
void CNetSDKDemoDlg::SeleteAdvancePannel() //显示“高级”功能页面
{
m_advanceBtnPannel.ShowWindow(SW_SHOW);
m_normalBtnPannel.ShowWindow(SW_HIDE);
m_saveDataPannel.ShowWindow(SW_HIDE);
m_ptzPannel.ShowWindow(SW_HIDE);
}
void CNetSDKDemoDlg::SeletePTZPannel() //显示“云台控制”功能页面
{
m_ptzPannel.ShowWindow(SW_SHOW);
m_advanceBtnPannel.ShowWindow(SW_HIDE);
m_normalBtnPannel.ShowWindow(SW_HIDE);
m_saveDataPannel.ShowWindow(SW_HIDE);
}
void CNetSDKDemoDlg::SeleteSaveDataPannel() //显示“数据保存”功能页面
{
m_saveDataPannel.ShowWindow(SW_SHOW);
m_colorPannel.ShowWindow(SW_HIDE);
m_devicelist.ShowWindow(SW_HIDE);
m_playctrlPannel.ShowWindow(SW_HIDE);
}
void CNetSDKDemoDlg::SeleteColorPannel() //显示“颜色调整”功能页面
{
m_colorPannel.ShowWindow(SW_SHOW);
m_devicelist.ShowWindow(SW_HIDE);
m_playctrlPannel.ShowWindow(SW_HIDE);
m_saveDataPannel.ShowWindow(SW_HIDE);
}
void CNetSDKDemoDlg::SeletePlayCtrlPannel() //显示“播放控制”功能页面
{
m_playctrlPannel.ShowWindow(SW_SHOW);
m_devicelist.ShowWindow(SW_HIDE);
m_colorPannel.ShowWindow(SW_HIDE);
m_saveDataPannel.ShowWindow(SW_HIDE);
}
void CNetSDKDemoDlg::SeleteDevListPannel() //显示“设备列表”功能页面
{
m_devicelist.ShowWindow(SW_SHOW);
m_colorPannel.ShowWindow(SW_HIDE);
m_playctrlPannel.ShowWindow(SW_HIDE);
m_saveDataPannel.ShowWindow(SW_HIDE);
}
//窗口改变时的处理
void CNetSDKDemoDlg::OnSize(UINT nType, int cx, int cy)
{
CDialog::OnSize(nType, cx, cy);
//窗口最小化与窗口大小无变化不处理
if ((cx ==0 && cy == 0) ||
(cx == m_clientRect.Width() && cy == m_clientRect.Height()))
{
return;
}
else
{
UpdatePannelPosition();
UpdateScreen(m_normalBtnPannel.GetSplit());
Invalidate();
}
}
void CNetSDKDemoDlg::UpdatePannelPosition()
{
GetClientRect(&m_clientRect);
m_screenRect.top = m_clientRect.top/* + 5*/;
m_screenRect.bottom = m_clientRect.bottom/* - 20*/;
m_screenRect.left = m_clientRect.left/* + 10*/;
m_screenRect.right = m_clientRect.right - 210;
GetDlgItem(IDC_SCREEN_WINDOW)->MoveWindow(m_screenRect);
m_pannelRect.top = m_clientRect.top + 100;
m_pannelRect.bottom = m_clientRect.bottom - 263;
m_pannelRect.right = m_clientRect.right - 2;
m_pannelRect.left = m_pannelRect.right - 197;
GetDlgItem(IDC_FRAME_PANNEL)->MoveWindow(m_pannelRect);
m_selectRect.left = m_pannelRect.left;
m_selectRect.right = m_pannelRect.right;
m_selectRect.top = m_pannelRect.bottom;
m_selectRect.bottom = m_selectRect.top + 50;
m_btnAreaRect.left = m_selectRect.left;
m_btnAreaRect.right = m_selectRect.right;
m_btnAreaRect.top = m_selectRect.bottom;
m_btnAreaRect.bottom = m_btnAreaRect.top + 203;
GetDlgItem(IDC_FRAME_BTN_AREA)->MoveWindow(m_btnAreaRect);
m_runtimeMsgRect.left = m_pannelRect.left;
m_runtimeMsgRect.right = m_pannelRect.right;
m_runtimeMsgRect.top = m_pannelRect.top - 95;
m_runtimeMsgRect.bottom = m_runtimeMsgRect.top + 90;
m_selectPannel.MoveWindow(m_selectRect);
m_saveDataPannel.MoveWindow(m_pannelRect);
m_colorPannel.MoveWindow(m_pannelRect);
m_playctrlPannel.MoveWindow(m_pannelRect);
m_devicelist.MoveWindow(m_pannelRect); //设备列表,非子窗口
m_normalBtnPannel.MoveWindow(m_btnAreaRect);
m_advanceBtnPannel.MoveWindow(m_btnAreaRect);
m_ptzPannel.MoveWindow(m_btnAreaRect);
m_runtimeMsgPannel.MoveWindow(m_runtimeMsgRect);
m_screenPannel.MoveWindow(m_screenRect);
}
void CNetSDKDemoDlg::LastError()
{
m_runtimeMsgPannel.ShowLastError();
}
BOOL CNetSDKDemoDlg::PreTranslateMessage(MSG* pMsg)
{
// TODO: Add your specialized code here and/or call the base class
if (WM_KEYDOWN == pMsg->message &&
(VK_ESCAPE == pMsg->wParam || VK_RETURN == pMsg->wParam))
{
if (VK_ESCAPE == pMsg->wParam && m_screenPannel.GetFullScreen())
{
m_screenPannel.SetFullScreen(FALSE);
}
return TRUE;
}
if (WM_SIZING == pMsg->message)
{
RECT* rc = (RECT*)(pMsg->lParam);
if (rc)
{
CRect rect(rc);
//if (rect. || cy < 584)
//{
// return TRUE;
//}
}
}
return CDialog::PreTranslateMessage(pMsg);
}
void CNetSDKDemoDlg::OnDestroy()
{
CDialog::OnDestroy();
// TODO: Add your message handler code here
m_selectPannel.DestroyWindow();
m_screenPannel.DestroyWindow();
m_saveDataPannel.DestroyWindow();
m_colorPannel.DestroyWindow();
m_playctrlPannel.DestroyWindow();
m_devicelist.DestroyWindow();
m_advanceBtnPannel.DestroyWindow();
m_ptzPannel.DestroyWindow();
m_runtimeMsgPannel.DestroyWindow();
}
void CNetSDKDemoDlg::SwitchMultiWnd(int nSplit)
{
if (SPLIT1 == nSplit)
{
m_screenPannel.SetMultiScreen(FALSE);
return ;
}
else
{
m_screenPannel.SetMultiScreen(TRUE);
m_screenPannel.SetShowPlayWin(nSplit, m_curScreen);
}
}
int CNetSDKDemoDlg::GetCurWinID(void)
{
CPlayWnd* pWnd = (CPlayWnd*)m_screenPannel.GetActivePage();
if (pWnd && ::IsWindow(pWnd->GetSafeHwnd()))
{
return pWnd->GetWinID();
}
return -1;
}
LRESULT CNetSDKDemoDlg::DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
// TODO: Add your specialized code here and/or call the base class
// if (WM_SIZING == message)
// {
// RECT* rc = (RECT*)(lParam);
// if (rc)
// {
// CRect rect(rc);
//
// if (rect.Width() < 800 || rect.Height() < 584)
// {
// return 0;
// }
// }
//
// }
//
return CDialog::DefWindowProc(message, wParam, lParam);
}
BOOL CNetSDKDemoDlg::GetSplitInfo_Main(int nIndex, SplitInfoNode* info)
{
if (nIndex < 0 || nIndex > MAX_CHANNUM)
{
return FALSE;
}
CPlayWnd *plWnd = (CPlayWnd*)m_screenPannel.GetPage(nIndex);
if (!plWnd)
{
MessageBox(ConvertString("oops!"));
return FALSE;
}
return plWnd->GetSplitInfo(info);
}
BOOL CNetSDKDemoDlg::SetSplitInfo_Main(int nIndex, SplitInfoNode* info)
{
if (nIndex < 0 || nIndex > MAX_CHANNUM)
{
return FALSE;
}
CPlayWnd *plWnd = (CPlayWnd*)m_screenPannel.GetPage(nIndex);
if (!plWnd)
{
MessageBox(ConvertString("oops!"));
return FALSE;
}
return plWnd->SetSplitInfo(info);
}
void CNetSDKDemoDlg::SetSplit(int split)
{
m_normalBtnPannel.SetSplit(split);
}
int CNetSDKDemoDlg::GetSplit()
{
return m_normalBtnPannel.GetSplit();
}
void CNetSDKDemoDlg::GetDeviceWorkstate() //"设备工作状态"按键响应函数
{
DeviceNode *pDev = (DeviceNode *)GetCurDeviceInfo();
if(pDev == NULL)
{
return;
}
CDeviceWorkState dlg;
dlg.SetDevice(pDev);
dlg.DoModal();
}
void CNetSDKDemoDlg::DeviceControldisk() //"硬盘控制"按键响应函数
{
DeviceNode *pDev = (DeviceNode *)GetCurDeviceInfo();
if(pDev == NULL)
{
return;
}
CDiskControl dlg;
dlg.SetDeviceId(pDev);
dlg.DoModal();
/*
DISKCTRL_PARAM diskParam;
diskParam.dwSize = sizeof(DISKCTRL_PARAM);
diskParam.nIndex = 0; //硬盘号
diskParam.ctrlType = 0; // 0 - clear data, 1 - set as read-write, 2 - set as read-only
//3 - set as redundant, 4 - error recovery
CLIENT_ControlDevice(pDev->LoginID, CTRL_DISK, &diskParam);
*/
}
void CNetSDKDemoDlg::DeviceUserinfo() //"用户信息"按键响应函数
{
DeviceNode *pDev = (DeviceNode *)GetCurDeviceInfo();
if(pDev == NULL)
{
return;
}
CUserManage dlg;
dlg.SetDeviceId(pDev);
dlg.DoModal();
}
int CALLBACK ListenCallBack(LONG lServerHandle, char* ip, WORD port, int nCmd, void* pParam, DWORD dwUserData)
{
CNetSDKDemoDlg* pThis = (CNetSDKDemoDlg*)dwUserData;
return pThis->ListenCallBack_Imp(lServerHandle, ip, port, nCmd, pParam);
}
int CNetSDKDemoDlg::ListenCallBack_Imp(LONG lServerHandle, char* ip, WORD port, int nCmd, void* pParam)
{
switch(nCmd)
{
case DVR_SERIAL_RETURN_CB:
{
m_mylsdata.state = 1; //ready
strcpy(m_mylsdata.ip, ip);
strcpy(m_mylsdata.serial, (const char*)pParam);
m_mylsdata.port = port;
}
break;
case DVR_DISCONNECT_CB:
{
int jjjj = 0;
}
break;
default:
break;
}
return 0;
}
void CNetSDKDemoDlg::TestProc()
{
DeviceNode *pDev = (DeviceNode *)GetCurDeviceInfo();
if(pDev == NULL)
{
return;
}
int retlen = 0;
DEV_DISK_RECORD_INFO stuDiskRecordInfo = {0};
BOOL bSuccess = CLIENT_QueryDevState(pDev->LoginID, DEVSTATE_RECORD_TIME, (char*)&stuDiskRecordInfo, sizeof(DEV_DISK_RECORD_INFO), &retlen, 3000);
if (bSuccess && retlen == sizeof(DEV_DISK_RECORD_INFO))
{
int a = 0;
}
}
| [
"guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd"
] | [
[
[
1,
5458
]
]
] |
87fc541e5d0d4f555e16a48491c4d682d9dc735c | 3eae8bea68fd2eb7965cca5afca717b86700adb5 | /Engine/Project/Core/GnMesh/Source/GActionMove.h | 5ced4b4ad3fe445a26baf7a49538057991973a44 | [] | no_license | mujige77/WebGame | c0a218ee7d23609076859e634e10e29c92bb595b | 73d36f9d8bfbeaa944c851e8a1cfa5408ce1d3dd | refs/heads/master | 2021-01-01T15:51:20.045414 | 2011-10-03T01:02:59 | 2011-10-03T01:02:59 | 455,950 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,388 | h | #ifndef __HiroCat__GActionMove__
#define __HiroCat__GActionMove__
#include "GAction.h"
class GActionMove : public GAction
{
GnDeclareFlags( guint32 );
enum
{
MASK_MOVELEFT = 0x00000001,
MASK_MOVERIGHT = 0x00000002,
MASK_MOVEUP = 0x00000004,
MASK_MOVEDOWN = 0x00000008,
};
public:
enum eMoveType
{
MOVELEFT,
MOVERIGHT,
MOVEUP,
MOVEDOWN,
MOVELEFTUP,
MOVERIGHTUP,
MOVELEFTDOWN,
MOVERIGHTDOWN,
MOVE_MAX,
};
protected:
GnVector2 mMoveRange;
GnVector2 mMoveVector;
GLayer* mpActorLayer;
public:
GActionMove(GActorController* pController);
public:
virtual void Update(float fDeltaTime);
virtual void SetMove(gtuint uiType);
virtual void SetMoveX(bool bLeft, bool bRight);
virtual void SetMoveY(bool bUp, bool bDown);
virtual inline gtint GetActionType() {
return ACTION_MOVE;
}
inline void AttachActionToController()
{
GetController()->GetActor()->SetTargetAnimation( ANI_WALK );
GetController()->GetActor()->Update( 0.0f );
}
public:
inline GnVector2& GetMoveRange() {
return mMoveRange;
}
inline void SetMoveRange(GnVector2 val) {
mMoveRange = val;
}
inline void SetMoveRangeX(float val) {
mMoveRange.x = val;
}
inline void SetMoveRangeY(float val) {
mMoveRange.y = val;
}
inline GnVector2& GetMoveVector() {
return mMoveVector;
}
inline virtual void SetMoveVector(GnVector2 val) {
mMoveVector = val;
}
inline void SetMoveLeft(bool val) {
SetBit( val, MASK_MOVELEFT );
}
inline bool GetMoveLeft() {
return GetBit( MASK_MOVELEFT );
}
inline void SetMoveRight(bool val) {
SetBit( val, MASK_MOVERIGHT );
}
inline bool GetMoveRight() {
return GetBit( MASK_MOVERIGHT );
}
inline void SetMoveUp(bool val) {
SetBit( val, MASK_MOVEUP );
}
inline bool GetMoveUp() {
return GetBit( MASK_MOVEUP );
}
inline void SetMoveDown(bool val) {
SetBit( val, MASK_MOVEDOWN );
}
inline bool GetMoveDown() {
return GetBit( MASK_MOVEDOWN );
}
inline void SetActorLayer(GLayer* pActorLayer) {
mpActorLayer = pActorLayer;
}
GNFORCEINLINE void CleanMove() {
SetMoveLeft( false );
SetMoveRight( false );
SetMoveUp( false );
SetMoveDown( false );
mMoveVector.x = 0.0f;
mMoveVector.y = 0.0f;
}
protected:
inline GLayer* GetActorLayer() {
return mpActorLayer;
}
};
#endif
| [
"[email protected]"
] | [
[
[
1,
111
]
]
] |
5230f12ad7950c6aa9c5ec6198341890874e8d0f | 28ba648bc8e18d3ad3878885ad39a05ebfb9259c | /CGWorkOpenGL/MainFrm.cpp | b2656fdeed188e453b0246a7b78efb6d10e9ac21 | [] | no_license | LinusTIAN/cg1-winter10 | 67da233f27dcf2fa693d830598473fde7d402ece | 0b929141c6eac3b96c038656e58620767ff52d9f | refs/heads/master | 2020-05-05T08:12:56.957326 | 2011-01-31T13:24:08 | 2011-01-31T13:24:08 | 36,010,723 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,689 | cpp | // MainFrm.cpp : implementation of the CMainFrame class
//
#include "stdafx.h"
#include "OpenGL.h"
#include "MainFrm.h"
#ifdef _DEBUG
//#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CMainFrame
IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd)
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
//{{AFX_MSG_MAP(CMainFrame)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code !
ON_WM_CREATE()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
static UINT indicators[] =
{
ID_SEPARATOR, // status line indicator
ID_INDICATOR_CAPS,
ID_INDICATOR_NUM,
ID_INDICATOR_SCRL,
};
/////////////////////////////////////////////////////////////////////////////
// CMainFrame construction/destruction
CMainFrame::CMainFrame()
{
// TODO: add member initialization code here
}
CMainFrame::~CMainFrame()
{
}
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
return -1;
if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP
| CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
!m_wndToolBar.LoadToolBar(IDR_MAINFRAME))
{
TRACE0("Failed to create toolbar\n");
return -1; // fail to create
}
if (!m_wndStatusBar.Create(this) ||
!m_wndStatusBar.SetIndicators(indicators,
sizeof(indicators)/sizeof(UINT)))
{
TRACE0("Failed to create status bar\n");
return -1; // fail to create
}
// TODO: Delete these three lines if you don't want the toolbar to
// be dockable
m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
EnableDocking(CBRS_ALIGN_ANY);
DockControlBar(&m_wndToolBar);
return 0;
}
BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
if( !CFrameWnd::PreCreateWindow(cs) )
return FALSE;
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// CMainFrame diagnostics
#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
CFrameWnd::AssertValid();
}
void CMainFrame::Dump(CDumpContext& dc) const
{
CFrameWnd::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CMainFrame message handlers
// Return by Reference the status bar. This is used so that ChildView can place
// text at will.
CStatusBar& CMainFrame::getStatusBar() {
return m_wndStatusBar;
}
| [
"slavak@2ff579a8-b8b1-c11a-477f-bc6c74f83876"
] | [
[
[
1,
117
]
]
] |
42281b34f86f74faddbadc251ed9d1379327f743 | 5ac13fa1746046451f1989b5b8734f40d6445322 | /minimangalore/Nebula2/code/nebula2/src/scene/nvectoranimator_cmds.cc | 70fc431f7228d41a918d5e48f60778528acbf9aa | [] | no_license | moltenguy1/minimangalore | 9f2edf7901e7392490cc22486a7cf13c1790008d | 4d849672a6f25d8e441245d374b6bde4b59cbd48 | refs/heads/master | 2020-04-23T08:57:16.492734 | 2009-08-01T09:13:33 | 2009-08-01T09:13:33 | 35,933,330 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,232 | cc | //------------------------------------------------------------------------------
// nvectoranimator_cmds.cc
// (C) 2003 RadonLabs GmbH
//------------------------------------------------------------------------------
#include "scene/nvectoranimator.h"
#include "kernel/npersistserver.h"
static void n_addkey(void* slf, nCmd* cmd);
static void n_getnumkeys(void* slf, nCmd* cmd);
static void n_getkeyat(void* slf, nCmd* cmd);
//------------------------------------------------------------------------------
/**
@scriptclass
nvectoranimator
@cppclass
nVectorAnimator
@superclass
nshaderanimator
@classinfo
Animate a vector attribute of a nabstractshadernode.
*/
void
n_initcmds(nClass* cl)
{
cl->BeginCmds();
cl->AddCmd("v_addkey_fffff", 'ADDK', n_addkey);
cl->AddCmd("i_getnumkeys_v", 'GNKS', n_getnumkeys);
cl->AddCmd("fffff_getkeyat_i", 'GKAT', n_getkeyat);
cl->EndCmds();
}
//------------------------------------------------------------------------------
/**
@cmd
addkey
@input
f(Time), f(X), f(Y), f(Z), f(W)
@output
v
@info
Add a vector key to the animation key array.
*/
void
n_addkey(void* slf, nCmd* cmd)
{
nVectorAnimator* self = (nVectorAnimator*) slf;
float f0;
vector4 v0;
f0 = cmd->In()->GetF();
v0.x = cmd->In()->GetF();
v0.y = cmd->In()->GetF();
v0.z = cmd->In()->GetF();
v0.w = cmd->In()->GetF();
self->AddKey(f0, v0);
}
//------------------------------------------------------------------------------
/**
@cmd
getnumkeys
@input
v
@output
i(NumKeys)
@info
Returns number of key in animation array.
*/
void
n_getnumkeys(void* slf, nCmd* cmd)
{
nVectorAnimator* self = (nVectorAnimator*) slf;
cmd->Out()->SetI(self->GetNumKeys());
}
//------------------------------------------------------------------------------
/**
@cmd
getkeyat
@input
i(KeyIndex)
@output
f(Time), f(X), f(Y), f(Z), f(W)
@info
Returns key at given index.
*/
void
n_getkeyat(void* slf, nCmd* cmd)
{
nVectorAnimator* self = (nVectorAnimator*) slf;
float f0;
vector4 v0;
self->GetKeyAt(cmd->In()->GetI(), f0, v0);
cmd->Out()->SetF(f0);
cmd->Out()->SetF(v0.x);
cmd->Out()->SetF(v0.y);
cmd->Out()->SetF(v0.z);
cmd->Out()->SetF(v0.w);
}
//------------------------------------------------------------------------------
/**
*/
bool
nVectorAnimator::SaveCmds(nPersistServer* ps)
{
if (nShaderAnimator::SaveCmds(ps))
{
nCmd* cmd;
//--- addkey ---
int i;
int numKeys = this->GetNumKeys();
for (i = 0; i < numKeys; i++)
{
float time;
vector4 val;
cmd = ps->GetCmd(this, 'ADDK');
this->GetKeyAt(i, time, val);
cmd->In()->SetF(time);
cmd->In()->SetF(val.x);
cmd->In()->SetF(val.y);
cmd->In()->SetF(val.z);
cmd->In()->SetF(val.w);
ps->PutCmd(cmd);
}
return true;
}
return false;
}
| [
"BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c"
] | [
[
[
1,
134
]
]
] |
6441f0f80d5af226a3e85975f95a5c8495eb3569 | 57574cc7192ea8564bd630dbc2a1f1c4806e4e69 | /Poker/Servidor/EstadoRondaRiver.h | 0bc101aaaf4dac538a4e98f39f55793ae3c5852c | [] | no_license | natlehmann/taller-2010-2c-poker | 3c6821faacccd5afa526b36026b2b153a2e471f9 | d07384873b3705d1cd37448a65b04b4105060f19 | refs/heads/master | 2016-09-05T23:43:54.272182 | 2010-11-17T11:48:00 | 2010-11-17T11:48:00 | 32,321,142 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 624 | h | #ifndef _ESTADO_RONDARIVER_H_
#define _ESTADO_RONDARIVER_H_
#include "EstadoJuego.h"
#include "EstadoEvaluandoGanador.h"
class EstadoRondaRiver : public EstadoJuego
{
private:
EstadoEvaluandoGanador* evaluandoGanador;
public:
EstadoRondaRiver(EstadoEvaluandoGanador* evaluandoGanador);
virtual ~EstadoRondaRiver(void);
void setEstadoEvaluandoGanador(EstadoEvaluandoGanador* evaluandoGanador);
virtual EstadoJuego* getSiguienteEstado();
virtual string getEscenarioJuego(int idJugador);
virtual string getEscenarioJuego(int idJugador, string mensaje);
};
#endif //_ESTADO_RONDARIVER_H_
| [
"[email protected]@a9434d28-8610-e991-b0d0-89a272e3a296"
] | [
[
[
1,
25
]
]
] |
f46abb0ce05c5b0d44b0fa417e482eee087f6ee3 | 66581a883c3eab4c6c7b7c1d5850892485a5cab8 | /Action Bros Now/BaseGameEntity.h | 85eddfd0bcbc5f7d0377a733ffdc54b19cd3516c | [] | no_license | nrolando/d-m-seniorprojectgsp | 9457841f43697a73d956b202541064022dd4a189 | 503f311142bf4995f3e5c6fc6110317babde08f9 | refs/heads/master | 2021-01-10T05:49:14.926897 | 2010-02-17T03:29:10 | 2010-02-17T03:29:10 | 49,738,324 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,636 | h | #ifndef BASEGAMEENTITY_H
#define BASEGAMEENTITY_H
#include "Status.h"
#include "common.h"
#include "spriteContainer.h"
#include <string>
#include <ctime>
#define ANIMATIONGAP 90
//all sprite sheets will have same frame width/height? if so, take out of eSprInfo and just use this
//right now, the player is instatiated with these values and the enemy reads its dimensions from file
//this is not being used
#define FRAME_WIDTH 128
#define FRAME_HEIGHT 128
#define E_FRAME_WIDTH 256
#define E_FRAME_HEIGHT 256
class Player;
class EntityManager;
class BaseGameEntity
{
private:
int entity_ID;
static int entity_NextID;
//----------------------------------------------------------
protected:
//stat variables
int health,maxHealth;
//variables for the boss and player to be accessed by game
int maxSpecial,special,sPower;
//power for Enemy class
int power;
char key;
//sprites info: pos, RECTs, image w/h, ss ptr,
eSprInfo sprInfo;
//set by getnameofentity(ID);
std::string name;
bool alive,miss;
//entity velocity
float speed;
D3DXVECTOR3 vel;
//animations varibales
clock_t stunStart, stunTime, aniFStart;
//this is the state of the entity, and the current animation frame
int state, anim;
bool faceRight; //keeps track of which direction the entity is facing
bool passLvl; //for player, allows him to move off the lvl
bool tagged;
//aggressive frames
int hitFrames[3];
//this variable keeps an aggressive frame from attacking more than once
int lastAttFrame;
public:
BaseGameEntity(int ID)
{
setID(ID);
name = GetNameOfEntity(ID);
state = anim = 0;
}
//the constructor for enemies and bosses
BaseGameEntity(int ID, char _key, D3DXVECTOR3 pos, spriteSheet *ptr);
//the constructor for the player
BaseGameEntity(std::string n);
virtual ~BaseGameEntity(){}
//Update Functions
virtual void UpdateState(Player*,std::vector<BaseGameEntity*>) = 0;
virtual void calcDrawRECT() = 0;
virtual void UpdateStat(int, int) = 0;
virtual void stun() = 0;
virtual void stun(int) = 0; //para: add-on to regular stun. extra stun time
virtual void die() = 0;
//move player according to velocity
void move(clock_t TIME);
void setID(int val);
//get methods
std::string getName() { return name; }
spriteSheet* getSSPtr() { return sprInfo.ss_ptr; }
RECT getSrc() { return sprInfo.drawRect; }
D3DXVECTOR3 getPos() { return sprInfo.POS; }
int getHealth() { return health;}
int getMaxHealth() { return maxHealth;}
int getPower() { return power; }
int getWidth() { return sprInfo.width; }
int getHeight() { return sprInfo.height; }
const int ID() { return entity_ID;}
eSprInfo getDrawInfo() { return sprInfo; }
int getStatus() { return state;}
int getAnimFrame() { return anim; }
int getState() { return state; }
int getLastAttFrame(){ return lastAttFrame;}
char getKey() { return key; }
bool getPassLvl() { return passLvl; }
int getCurrHealth() { return int(float(health)/float(maxHealth)*100);}
bool isFacing() { return faceRight;}
bool isAlive() { return alive; }
bool Missed() { return miss;}
/*for the boss, quick and dirty*/
int getSpecial() {return special;}
int getMaxSpecial() {return maxSpecial;}
int getsPower() {return sPower;}
//set methods
void missedAtk() { miss = true;}
void resetAtk() { miss = false;}
void setAlive(bool a) { alive = a; }
void setFace(bool f) { faceRight = f; }
void setHealth(int h) { health = h; }
void setPower(int p) { power = p; }
void setPassLvl(bool b) { passLvl = b; }
void setSprInfo(eSprInfo esi) { sprInfo = esi; }
void setPos(D3DXVECTOR3 p) { sprInfo.POS = p; }
void setVel(D3DXVECTOR3 v) { vel = v; }
void setSrc(RECT rect) { sprInfo.drawRect = rect; }
void setSSPtr(spriteSheet *p) { sprInfo.ss_ptr = p; }
void setStatus(int s) { state = s;}//if(state != s){state=s; anim = 0;}}
void resetHitFrames() { hitFrames[0] = hitFrames[1] = hitFrames[2] = 0;}
void setLAF(int f) { lastAttFrame = f; }
void setAnim(int a) { anim = a; }
void setHitFrames(int n1, int n2, int n3) { hitFrames[0] = n1; hitFrames[1] = n2; hitFrames[2] = n3; }
//check if the current animation frame is an aggressive frame and not equal to the last aggressive frame
bool checkFrames()
{
if((anim == hitFrames[0] || anim == hitFrames[1] || anim == hitFrames[2]) && anim != lastAttFrame)
return true;
else
return false;
}
void resetTimes()
{
aniFStart = clock();
}
};
#endif | [
"nicklamort@2c89e556-c775-11de-bfbd-4d0f0f27293a",
"dheardjr@2c89e556-c775-11de-bfbd-4d0f0f27293a",
"DHeardjr@2c89e556-c775-11de-bfbd-4d0f0f27293a"
] | [
[
[
1,
18
],
[
22,
25
],
[
27,
39
],
[
41,
50
],
[
52,
59
],
[
61,
63
],
[
66,
66
],
[
68,
70
],
[
73,
73
],
[
75,
80
],
[
83,
87
],
[
90,
92
],
[
94,
94
],
[
99,
100
],
[
102,
111
],
[
114,
124
],
[
126,
145
]
],
[
[
19,
21
],
[
26,
26
],
[
51,
51
],
[
60,
60
],
[
64,
64
],
[
71,
71
],
[
74,
74
],
[
81,
82
],
[
93,
93
],
[
125,
125
]
],
[
[
40,
40
],
[
65,
65
],
[
67,
67
],
[
72,
72
],
[
88,
89
],
[
95,
98
],
[
101,
101
],
[
112,
113
]
]
] |
24ada96680fd524a75192858b0504fae19978841 | d397b0d420dffcf45713596f5e3db269b0652dee | /src/Axe/DispatcherException.cpp | 5696691e1d05be6660871c87d9f8f4078e53b2ed | [] | no_license | irov/Axe | 62cf29def34ee529b79e6dbcf9b2f9bf3709ac4f | d3de329512a4251470cbc11264ed3868d9261d22 | refs/heads/master | 2021-01-22T20:35:54.710866 | 2010-09-15T14:36:43 | 2010-09-15T14:36:43 | 85,337,070 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,386 | cpp | # include "pch.hpp"
# include <Axe/DispatcherException.hpp>
# include <Axe/ArchiveInvocation.hpp>
# include <Axe/ArchiveDispatcher.hpp>
namespace Axe
{
//////////////////////////////////////////////////////////////////////////
void DispatcherServantRelocateException::rethrow() const
{
throw *this;
}
//////////////////////////////////////////////////////////////////////////
void DispatcherServantRelocateException::write( ArchiveInvocation & _ar ) const
{
_ar << servantId;
_ar << adapterId;
}
//////////////////////////////////////////////////////////////////////////
void DispatcherServantRelocateException::read( ArchiveDispatcher & _ar )
{
_ar >> servantId;
_ar >> adapterId;
}
//////////////////////////////////////////////////////////////////////////
void DispatcherServantNotFoundException::rethrow() const
{
throw *this;
}
//////////////////////////////////////////////////////////////////////////
void DispatcherServantNotFoundException::write( ArchiveInvocation & _ar ) const
{
_ar << servantId;
_ar << adapterId;
}
//////////////////////////////////////////////////////////////////////////
void DispatcherServantNotFoundException::read( ArchiveDispatcher & _ar )
{
_ar >> servantId;
_ar >> adapterId;
}
//////////////////////////////////////////////////////////////////////////
} | [
"yuriy_levchenko@b35ac3e7-fb55-4080-a4c2-184bb04a16e0"
] | [
[
[
1,
46
]
]
] |
a2a053107e6e4e8eaf8fa14d3a3953339a82e44c | 38fa90e0adaf61d02802e77962075f6913a3cdfa | /include/AoTK/window/window.h | 9dba4072c11d884b19c7fb98c4ed393e3f983220 | [] | no_license | r-englund/AoTK | 49097b39906c5f9cad1c79f3e22f867cbfe806e3 | 7a52b0788c25710b00fa5e582ef2fcbc4c839a8f | refs/heads/master | 2021-01-17T11:54:34.889565 | 2011-09-01T20:19:38 | 2011-09-01T20:19:38 | 1,339,861 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,524 | h | #ifndef WINDOW_H
#define WINDOW_H
#include <functional>
#include <map>
#include <AoTK/aotk.h>
#include "../math.h"
namespace AoTK{
class Window{
std::vector<Listeners::KeyboardListener*> keyboardListeners;
std::map<int,std::function<void(KEY key)> > keyUpListenerFunctions; unsigned int __keyUpId;
std::map<int,std::function<void(KEY key)> > keyDownListenerFunctions; unsigned int __keyDownId;
std::map<int,std::function<void(unsigned char key)> > keyImpuleListenerFunctions; unsigned int __keyImpulseId;
std::vector<Listeners::ResizeListener*> resizeListeners;
std::map<int,std::function<void(unsigned int, unsigned int)> > resizeListenerFunctions; unsigned int __resizeId;
std::vector<Listeners::MouseListener*> mouseListeners;
std::map<int,std::function<void(MOUSE_BUTTON mb,unsigned int x,unsigned int y)> > mousePressListenerFunctions; unsigned int __mousePressId;
std::map<int,std::function<void(MOUSE_BUTTON mb,unsigned int x,unsigned int y)> > mouseReleaseListenerFunctions; unsigned int __mouseReleaseId;
std::vector<Listeners::MouseMotionListener*> mouseMotionListeners;
std::map<int,std::function<void (int dx,int dy)> > mouseMotionListenerFunctions; unsigned int __mouseMotionId;
std::map<int,std::function<void (int dx,int dy)> > passiveMouseMotionListenerFunctions; unsigned int __mousePassiveMotionId;
std::vector<Listeners::ScrollListener*> scrollListeners;
std::map<int,std::function<void(int p)> > scrollListenerFunctions; unsigned int __scrollId;
std::vector<Listeners::IdleListener*> idleListeners;
std::map<int,std::function<void()> > idleListenerFunctions; unsigned int __idleId;
uint16_t window_width,window_height;
uint16_t client_width,client_height;
std::string title;
bool redisplay;
Window()
{
}
Window(const Window &w);
Window& operator=(const Window &w);
~Window();
void checkForMessages();
void swapBuffers();
void setSizes();
bool __run;
bool fullscreen;
std::function<void()> __dispFunc;
#ifdef AoTK_WIN
HWND hwnd; //Window handler
GLuint pixelformat;//Pixelforment
WNDCLASSEX wincl; //Window class
HDC hDC; //display content
HGLRC hRC; //rendering content
long styles;
bool initWindowClass();
bool createWindow(std::string);
bool setPixelFormat();
#endif
#ifdef AoTK_UNIX
XVisualInfo* vi;
GLXContext glContext;
bool GL3;
XSetWindowAttributes XAttr;
Colormap cmap;
Atom wmDelete;
::Window win;
unsigned long windowAttributes;
#endif
unsigned long long __start;
void fullscreenOn(unsigned int device = 0);
void fullscreenOff();
AoTK::Math::Vector2<uint16_t> oldSize;
AoTK::Math::Vector2<uint16_t> oldPos;
public:
unsigned long long getRunTime();
void redraw(){redisplay = true;}
void addKeyboardListener(Listeners::KeyboardListener *l);
unsigned int addKeyUpListener(std::function<void (KEY key)> );
unsigned int addKeyDownListener(std::function<void (KEY key)> );
unsigned int addKeyImpulseListener(std::function<void (unsigned char key)> );
void addResizeListener(Listeners::ResizeListener *l);
unsigned int addResizeListener(std::function<void (unsigned int, unsigned int)> );
void addMouseListener(Listeners::MouseListener *l);
unsigned int addMousePressListener(std::function<void(MOUSE_BUTTON mb,unsigned int x,unsigned int y)> );
unsigned int addMouseReleaseListener(std::function<void(MOUSE_BUTTON mb,unsigned int x,unsigned int y)> );
void addMouseMotionListener(Listeners::MouseMotionListener *l);
unsigned int addMouseMotionListener(std::function<void(int dx,int dy)> );
unsigned int addPassiveMouseMotionListener(std::function<void(int dx,int dy)> );
void addScrollListener(Listeners::ScrollListener *l);
unsigned int addScrollListener(std::function<void(int p)> );
void addIdleListener(Listeners::IdleListener *l);
unsigned int addIdleListener(std::function<void()> );
void setFullscreen(bool set = true,unsigned int device = 0);
void toggleFullscreen();
bool isFullscreen()const;
void removeKeyboardListener(Listeners::KeyboardListener *l);
void removeResizeListener(Listeners::ResizeListener *l);
void removeMouseListener(Listeners::MouseListener *l);
void removeMouseMotionListener(Listeners::MouseMotionListener *l);
void removeScrollListener(Listeners::ScrollListener *l);
void removeIdleListener(Listeners::IdleListener *l);
void removeKeyUpListener(unsigned int id);
void removeKeyDownListener(unsigned int id);
void removeKeyImpulseListener(unsigned int id);
void removeResizeListener(unsigned int id);
void removeMousePressListener(unsigned int id);
void removeMouseReleaseListener(unsigned int id);
void removeMouseMotionListener(unsigned int id);
void removePassiveMouseMotionListener(unsigned int id);
void removeScrollListener(unsigned int id);
void removeIdleListener(unsigned int id);
void keyDownEvent(KEY key);
void keyUpEvent(KEY key);
void keyImpulseEvent(unsigned char key);
void resizeEvent();
void mousePressEvent(MOUSE_BUTTON mb,unsigned int x,unsigned int y);
void mouseReleaseEvent(MOUSE_BUTTON mb,unsigned int x,unsigned int y);
void mousemotionEvent(int dx,int dy);
void passiveMousemotionEvent(int dx,int dy);
void scrollEvent(int p);
void idleEvent();
void start();
void stop();
static Window* createWindow(uint16_t width,uint16_t height,std::string title,bool force32 = false);
static Window* getWindow();
void setDisplayFunction(std::function<void()> dispFunc){
__dispFunc = dispFunc;
}
void getWindowSize(uint16_t &width,uint16_t &height)const;
void getClientSize(uint16_t &width,uint16_t &height)const;
};
};
#endif
| [
"[email protected]"
] | [
[
[
1,
174
]
]
] |
d90a52898d7e4d782f27d33bae109954e8de3238 | c95a83e1a741b8c0eb810dd018d91060e5872dd8 | /Game/ClientShellDLL/TO2/HUDDamageDir.h | fa6e6b06a95cfab3a7852f03c7e6c4a559319eac | [] | 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 | 1,073 | h | // ----------------------------------------------------------------------- //
//
// MODULE : HUDDamageDir.h
//
// PURPOSE : HUDItem to display directional damage info
//
// (c) 2002 Monolith Productions, Inc. All Rights Reserved
//
// ----------------------------------------------------------------------- //
#ifndef __HUD_DAMAGE_DIR_H
#define __HUD_DAMAGE_DIR_H
#include "HUDItem.h"
//******************************************************************************************
//** HUD directional damage display
//******************************************************************************************
class CHUDDamageDir : public CHUDItem
{
public:
CHUDDamageDir();
LTBOOL Init();
void Term();
void Render();
void Update();
void UpdateLayout();
void UpdateScale();
private:
uint16 m_nSize;
LTBOOL m_bDraw;
float m_fScale;
enum eConstants
{
kNumDamageSectors = 12,
};
LTPoly_GT4 m_Poly[kNumDamageSectors];
HTEXTURE m_hArrow;
};
#endif | [
"[email protected]"
] | [
[
[
1,
55
]
]
] |
71c4b5b5a54801d8e09675e4f1d207fba3e2a1c0 | 59a6020b36f5a757b62034471381b75985a4bb3d | /src/util/utility.cpp | 6053946cfc0a057385ed5ceaedfbfe875f1d8730 | [] | no_license | feengg/MeshLib | 74322ba7a88a69d727612d0869858c48c0b734c7 | ae212df1c75c07fe4ab2b1f5a239be02b72f9da5 | refs/heads/master | 2020-03-28T16:43:52.332838 | 2011-06-26T14:56:50 | 2011-06-26T14:56:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,125 | cpp | #include "utility.h"
#include <cassert>
void Util::ResolveFileName(const std::string& filename, std::string& file_path, std::string& file_title, std::string& file_ext)
{
//! TODO: add linux . .. tracing
char separator;
#ifdef __WIN32
separator = '\\';
#else
separator = '/';
#endif
size_t i;
size_t lash_index = filename.rfind(separator);
size_t dot_index = filename.rfind('.');
size_t length = filename.length();
for(i = 0; i <= lash_index; ++ i)
file_path += filename[i];
for(i = lash_index+1; i < dot_index; ++ i)
file_title += filename[i];
for(i = dot_index; i < length; ++ i)
file_ext += filename[i];
}
void Util::MakeLower(std::string& str)
{
size_t length = str.length();
for(size_t i = 0; i < length; ++ i){
char& ch = str[i];
if(ch >= 'A' && ch <= 'Z') ch = ch - 'A' + 'a';
}
}
void Util::MakeUpper(std::string& str)
{
size_t length = str.length();
for(size_t i = 0; i < length; ++ i){
char& ch = str[i];
if(ch >= 'a' && ch <= 'a') ch = ch - 'a' + 'A';
}
}
| [
"[email protected]"
] | [
[
[
1,
44
]
]
] |
746f5c13ed70e233842a1771b0e3020179a237b4 | e3a67b819e6c8072ea587f070214c2c075b2dee3 | /IntegratedImpedanceSensingSystem/Global.cpp | 93f1df6cf7ad4ef008b18bdf358df42792b04777 | [] | no_license | pmanandhar1452/ImpedanceSensingSystem | 46f32a57d3c19ebc011c539746fab5facf5e0c71 | 0c4a0472c75f280857d549630fabb881c452e791 | refs/heads/master | 2021-01-17T16:43:17.019071 | 2011-11-15T01:40:45 | 2011-11-15T01:40:45 | 62,420,080 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,367 | cpp | /*
* Global.cpp
*
* Created on: Mar 24, 2010
* Author: Chhitiz
*/
#include "Global.h"
#include <QDebug>
#include <math.h>
#include <cbw.h>
Global * Global::pI = NULL;
Global::Global() {
// load settings
settings = new QSettings(QSettings::IniFormat, QSettings::UserScope,
"p-manandhar.info", "ImpedanceAnalsysisDAQ");
}
QString Global::getA33220ADeviceID()
{
return settings->value("Ag33220ID").toString();
}
void Global::setA33220ADeviceID(QString id)
{
settings->setValue("Ag33220ID", id);
settings->sync();
}
QString Global::getU2751ADeviceID()
{
return settings->value("U2751AID").toString();
}
void Global::setU2751ADeviceID(QString id)
{
settings->setValue("U2751AID", id);
settings->sync();
}
void Global::setNumSweep(int v)
{
settings->setValue("NumSweep", v);
settings->sync();
}
int Global::getNumSweep()
{
return (settings->value("NumSweep").toUInt());
}
Global::~Global() {
delete settings;
}
double Global::getAmplitude()
{
return settings->value("Amplitude").toDouble();
}
void Global::setAmplitude(double v)
{
settings->setValue("Amplitude", v);
settings->sync();
}
double Global::getFrequencyStart()
{
return settings->value("FrequencyStart").toDouble();
}
void Global::setFrequencyStart(double v)
{
settings->setValue("FrequencyStart", v);
settings->sync();
}
double Global::getFrequencyEnd()
{
return settings->value("FrequencyEnd").toDouble();
}
void Global::setFrequencyEnd(double v)
{
settings->setValue("FrequencyEnd", v);
settings->sync();
}
int Global::getFrequencySteps()
{
int s = settings->value("FrequencySteps").toUInt();
if (s == 0)
{
s = 1;
setFrequencySteps(s);
}
return s;
}
void Global::setFrequencySteps(int v)
{
settings->setValue("FrequencySteps", v);
settings->sync();
}
void Global::setFreqSweep(int v)
{
qDebug() << "Frequency Sweep Changed To: " << v;
settings->setValue("FrequencySweep", v);
settings->sync();
}
int Global::getFreqSweep()
{
return (settings->value("FrequencySweep").toUInt());
}
void Global::setCyclesPerIm(int v)
{
settings->setValue("CyclesPerImpedanceMeasurement", v);
settings->sync();
}
int Global::getCyclesPerIm()
{
return (settings->value("CyclesPerImpedanceMeasurement").toUInt());
}
void Global::setChannelSelect(QVector<bool> csel)
{
QString s;
for (int i = 0; i < N_CHANNELS; i++)
{
if (csel[i]) s += '1';
else s += '0';
}
settings->setValue("DAQChannelsSelect", s);
settings->sync();
}
QVector<bool> Global::getChannelSelect()
{
QVector<bool> csel(N_CHANNELS);
QString s(settings->value("DAQChannelsSelect").toString());
for (int i = 0; i < N_CHANNELS; i++)
{
if (s.size() <= i) csel[i] = false;
else
csel[i] = (s[i] == QChar('1'));
}
return csel;
}
void Global::setChannelScaling(QVector<ChannelInformation::DAQ_SCALING> c)
{
QString s;
for (int i = 0; i < N_CHANNELS; i++)
{
s += QString("%1").arg(c[i]);
}
settings->setValue("DAQChannelsResolution", s);
settings->sync();
}
QVector<ChannelInformation::DAQ_SCALING> Global::getChannelScaling()
{
QVector<ChannelInformation::DAQ_SCALING> csel(N_CHANNELS);
QString s(settings->value("DAQChannelsResolution").toString());
for (int i = 0; i < N_CHANNELS; i++)
{
if (s.size() <= i) csel[i] = ChannelInformation::DAQPM_5V;
else
csel[i] = (ChannelInformation::DAQ_SCALING)(QString(s[i]).toInt());
}
return csel;
}
void Global::setChannelType(QVector<ChannelInformation::CHAN_TYPE> c)
{
QString s;
for (int i = 0; i < N_CHANNELS; i++)
{
s += QString("%1").arg(c[i]);
}
settings->setValue("DAQChannelType", s);
settings->sync();
}
QVector<ChannelInformation::CHAN_TYPE> Global::getChannelType()
{
QVector<ChannelInformation::CHAN_TYPE> csel(N_CHANNELS);
QString s(settings->value("DAQChannelType").toString());
for (int i = 0; i < N_CHANNELS; i++)
{
if (s.size() <= i) csel[i] = ChannelInformation::CT_IMPEDANCE;
else
csel[i] = (ChannelInformation::CHAN_TYPE)
(QString(s[i]).toInt());
}
return csel;
}
void Global::setSamplingFactor(int v)
{
settings->setValue("SamplingFactor", v);
settings->sync();
}
int Global::getSamplingFactor()
{
int v (settings->value("SamplingFactor").toUInt());
if (v < 2)
{
v = 2;
setSamplingFactor(2);
}
return v;
}
void Global::setSamplingMax(int v)
{
settings->setValue("SamplingMax", v);
settings->sync();
}
int Global::getSamplingMax()
{
int v = (settings->value("SamplingMax").toUInt());
if (v < 100)
{
v = 100;
setSamplingMax(v);
}
return v;
}
void Global::setSeed(int v)
{
settings->setValue("Seed", v);
settings->sync();
}
int Global::getSeed()
{
int v = (settings->value("Seed").toUInt());
return v;
}
void Global::setNumEvents(int v)
{
settings->setValue("NumEvents", v);
settings->sync();
}
int Global::getNumEvents()
{
int v = (settings->value("NumEvents").toUInt());
return v;
}
QVector<ChannelInformation> Global::getChannelInformation() {
QVector<bool> cSel = getChannelSelect();
QVector<ChannelInformation::DAQ_SCALING> cS = getChannelScaling();
QVector<ChannelInformation::CHAN_TYPE> cT = getChannelType();
QVector<double> cR = getSeriesR();
QVector<ChannelInformation> cI(cSel.count(true));
int n = 0;
for (int i = 0; i < N_CHANNELS; i++) {
if (cSel.value(i)) {
cI[n].ChannelNumber = i;
cI[n].Units = cS.value(i);
cI[n].Type = cT.value(i);
cI[n].SeriesR = cR.value(i);
n++;
}
}
return cI;
}
void Global::setAngleAdjust(int v)
{
settings->setValue("AngleAdjust", v);
settings->sync();
}
int Global::getAngleAdjust()
{
int v = (settings->value("AngleAdjust").toInt());
return v;
}
void Global::setSpeedAdjust(int v)
{
settings->setValue("SpeedAdjust", v);
settings->sync();
}
int Global::getSpeedAdjust()
{
int v = (settings->value("SpeedAdjust").toUInt());
return v;
}
int Global::getTimeBetweenEvents()
{
return settings->value("TimeBetweenEvents").toUInt();
}
void Global::setTimeBetweenEvents(int v)
{
settings->setValue("TimeBetweenEvents", v);
settings->sync();
}
int Global::getTimeBetweenEventsSD()
{
return settings->value("TimeBetweenEventsSD").toUInt();
}
void Global::setTimeBetweenEventsSD(int v)
{
settings->setValue("TimeBetweenEventsSD", v);
settings->sync();
}
void Global::setRbtSpeed(int v)
{
settings->setValue("RbtSpeed", v);
settings->sync();
}
int Global::getRbtSpeed()
{
int v = (settings->value("RbtSpeed").toUInt());
return v;
}
void Global::setRbtSpeedSD(int v)
{
settings->setValue("RbtSpeedSD", v);
settings->sync();
}
int Global::getRbtSpeedSD()
{
int v = (settings->value("RbtSpeedSD").toUInt());
return v;
}
void Global::setMechCycles(int v)
{
settings->setValue("MechCycles", v);
settings->sync();
}
int Global::getMechCycles()
{
int v = (settings->value("MechCycles").toUInt());
return v;
}
void Global::setMechCyclesSD(int v)
{
settings->setValue("MechCyclesSD", v);
settings->sync();
}
int Global::getMechCyclesSD()
{
int v = (settings->value("MechCyclesSD").toUInt());
return v;
}
void Global::setMechAmp(int v)
{
settings->setValue("MechAmp", v);
settings->sync();
}
int Global::getMechAmp()
{
int v = (settings->value("MechAmp").toUInt());
return v;
}
void Global::setMechAmpSD(int v)
{
settings->setValue("MechAmpSD", v);
settings->sync();
}
int Global::getMechAmpSD()
{
int v = (settings->value("MechAmpSD").toUInt());
return v;
}
void Global::setDataFolder(QString v)
{
settings->setValue("DataFolder", v);
settings->sync();
}
QString Global::getDataFolder()
{
QString v = (settings->value("DataFolder").toString());
if (v.isEmpty())
{
v = "C:/ImpedanceData";
setDataFolder(v);
}
return v;
}
QVector<double> Global::getSeriesR()
{
QVector<double> rlist(Global::N_CHANNELS);
for (int i = 0; i < Global::N_CHANNELS; i++)
{
QString key = QString("SeriesR%1").arg(i);
double v = (settings->value(key).toDouble());
rlist[i] = v;
}
return rlist;
}
void Global::setSeriesR(QVector<double> rlist)
{
for (int i = 0; i < Global::N_CHANNELS; i++)
{
QString key = QString("SeriesR%1").arg(i);
settings->setValue(key, rlist[i]);
}
settings->sync();
}
int Global::getEITExpCycles()
{
return settings->value("EITExpCycles").toUInt();
}
void Global::setEITExpCycles(int v)
{
settings->setValue("EITExpCycles", v);
settings->sync();
}
int Global::getEITSamplingFreq()
{
return settings->value("EITSamplingFreq").toUInt();
}
void Global::setEITSamplingFreq(int v)
{
settings->setValue("EITSamplingFreq", v);
settings->sync();
}
int Global::getEITOnTime()
{
return settings->value("EITOnTime").toUInt();
}
void Global::setEITOnTime(int v)
{
settings->setValue("EITOnTime", v);
settings->sync();
}
int Global::getEITOffTime()
{
return settings->value("EITOffTime").toUInt();
}
void Global::setEITOffTime(int v)
{
settings->setValue("EITOffTime", v);
settings->sync();
}
double Global::getEITSeriesR()
{
return settings->value("EITSeriesR").toDouble();
}
void Global::setEITSeriesR(double v)
{
settings->setValue("EITSeriesR", v);
settings->sync();
}
QString Global::toHrMinSec (double T)
{
QString strT = QString("%1s").arg(T);
if (T > 60) {
int h = floor(T/60/60);
int m = floor((T - h*60*60)/60);
double s = T - h*60*60 - m*60;
strT += QString("\n [ %1 hr %2 min %3 secs]").arg(h).arg(m).arg(s);
}
return strT;
}
short Global::vMaxToGain(ChannelInformation::DAQ_SCALING r)
{
switch(r) {
case ChannelInformation::DAQPM_50mV:
return BIPPT05VOLTS;
case ChannelInformation::DAQPM_500mV:
return BIPPT5VOLTS;
case ChannelInformation::DAQPM_5V:
return BIP5VOLTS;
}
return BIP10VOLTS;
}
| [
"jaa_saaymi@d83832b1-3638-4858-8a38-9f153b6b3474"
] | [
[
[
1,
535
]
]
] |
88a22a3a7b7597fad02684f705c49dedd6a5d08b | 4323418f83efdc8b9f8b8bb1cc15680ba66e1fa8 | /Trunk/Battle Cars/Battle Cars/Source/CHUD.h | 36874e97dce47408d72b6b64d5c0c449b5e7028c | [] | 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 | 656 | h | #ifndef _CHUD_H
#define _CHUD_H
class CPlayer;
class CPrintFont;
class CSGD_TextureManager;
class CHUD
{
private:
CPlayer* m_pOwner;
CPrintFont* m_pPF;
CSGD_TextureManager* m_pTM;
int m_nMiniMapID;
int m_nScoreBoardID;
int m_nHealthID;
int m_nPistolID;
int m_nMissileID;
int m_nMiniBG;
int m_nMiniBG2;
float m_fMiniMapPosX;
float m_fMiniMapPosY;
public:
CHUD(void);
~CHUD(void);
void Update(float fElapsedTime);
void Render(void);
void SetOwner(CPlayer* owner) { m_pOwner = owner; }
float GetMiniMapXPos(){ return m_fMiniMapPosX;}
float GetMiniMapYPos(){ return m_fMiniMapPosY;}
};
#endif | [
"[email protected]@598269ab-7e8a-4bc4-b06e-4a1e7ae79330",
"[email protected]@598269ab-7e8a-4bc4-b06e-4a1e7ae79330"
] | [
[
[
1,
21
],
[
25,
33
],
[
37,
40
]
],
[
[
22,
24
],
[
34,
36
]
]
] |
a48f712afe09e4322d2fce686326b44212dc4fc1 | a36d7a42310a8351aa0d427fe38b4c6eece305ea | /core_billiard/CameraOrthographicImp.h | cbcd4d7e006eefef6fcb5872791a3b0ff70d68e6 | [] | no_license | newpolaris/mybilliard01 | ca92888373c97606033c16c84a423de54146386a | dc3b21c63b5bfc762d6b1741b550021b347432e8 | refs/heads/master | 2020-04-21T06:08:04.412207 | 2009-09-21T15:18:27 | 2009-09-21T15:18:27 | 39,947,400 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 543 | h | #pragma once
namespace my_render_imp {
class CameraOrthographicImp : public CameraCommonImp, IMPLEMENTS_INTERFACE( CameraOrthographic ) {
public:
virtual float getXMag() OVERRIDE;
virtual float getYMag() OVERRIDE;
virtual void setXMag( float magx ) OVERRIDE;
virtual void setYMag( float magy ) OVERRIDE;
virtual void getProjectionMatrix44( float * returnMatrix44, bool bRightHand, bool bRowMajor ) OVERRIDE;
public:
CameraOrthographicImp();
private:
float x_mag_;
float y_mag_;
};
} | [
"wrice127@af801a76-7f76-11de-8b9f-9be6f49bd635"
] | [
[
[
1,
25
]
]
] |
742949acc6ff88094e4c6365506c03a5ee7e4f75 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/AccountServer/dpdbsrvr.h | 8b428801007c2e671aa3a552a8abb8ffd09a473f | [] | no_license | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,166 | h | #ifndef __DPDBSRVR_H__
#define __DPDBSRVR_H__
#include "dpmng.h"
#include "msghdr.h"
#undef theClass
#define theClass CDPDBSrvr
#undef theParameters
#define theParameters CAr & ar, DPID dpid, LPBYTE lpBuf, u_long uBufSize
class CAccount;
class CDPDBSrvr : public CDPMng<CBuffer>
{
public:
// Constructions
CDPDBSrvr();
virtual ~CDPDBSrvr();
// Overrides
virtual void SysMessageHandler( LPDPMSG_GENERIC lpMsg, DWORD dwMsgSize, DPID dpId );
virtual void UserMessageHandler( LPDPMSG_GENERIC lpMsg, DWORD dwMsgSize, DPID dpId );
// Operations
void SendOneHourNotify( CAccount* pAccount );
void SendPlayerCount( void );
void OnRemoveConnection( DPID dpid );
void SendCloseExistingConnection( const char*lpszAccount, LONG lError );
void SendFail( long lError, const char* lpszAccount, DPID dpid );
void SendBuyingInfo( PBUYING_INFO2 pbi2 );
void SendLogSMItem( );
#ifdef __LOG_PLAYERCOUNT_CHANNEL
vector<CString> m_vecstrChannelAccount;
#endif // __LOG_PLAYERCOUNT_CHANNEL
/*
#ifdef __S0114_RELOADPRO
void SendReloadAccount();
#endif // __S0114_RELOADPRO
*/
// Handlers
USES_PFNENTRIES;
void OnAddConnection( CAr & ar, DPID dpid, LPBYTE lpBuf, u_long uBufSize );
void OnRemoveAccount( CAr & ar, DPID dpid, LPBYTE lpBuf, u_long uBufSize );
void OnGetPlayerList( CAr & ar, DPID dpid, LPBYTE lpBuf, u_long uBufSize );
#ifdef __REMOVE_PLAYER_0221
void OnRemovePlayer( CAr & ar, DPID dpid, LPBYTE lpBuf, u_long uBufSize );
#endif // __REMOVE_PLAYER_0221
void OnJoin( CAr & ar, DPID dpid, LPBYTE lpBuf, u_long uBufSize );
void OnRemoveAllAccounts( CAr & ar, DPID dpid, LPBYTE lpBuf, u_long uBufSize );
void OnBuyingInfo( CAr & ar, DPID dpid, LPBYTE lpBuf, u_long uBufSize );
// void OnOpenBattleServer( CAr & ar, DPID dpid, LPBYTE lpBuf, u_long uBufSize );
// void OnCloseBattleServer( CAr & ar, DPID dpid, LPBYTE lpBuf, u_long uBufSize );
void OnServerEnable( CAr & ar, DPID dpid, LPBYTE lpBuf, u_long uBufSize );
/*
#ifdef __S0114_RELOADPRO
void OnCompleteReloadProject( CAr & ar, DPID dpid, LPBYTE lpBuf, u_long uBufSize );
#endif // __S0114_RELOADPRO
*/
};
#endif // __DPDBSRVR_H__ | [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
63
]
]
] |
17e9fb1a7e86901bcd137cb9d400f2fac366d5ce | 27c26f4507ca383922f718d8cf725fa1ebed6721 | /inc/PodOClockTracer.h | c758eef51c04cae765b219db7685cfdd275b2e2a | [] | no_license | hugovk/podoclock | 453bedcd0b5462bd3e21c04e391723b864184b89 | c527b616aba9bc25347f50b9bb6a322b3d97b030 | refs/heads/master | 2021-01-23T09:28:46.153771 | 2011-09-04T17:42:33 | 2011-09-04T17:42:33 | 32,327,744 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 6,561 | h | /*
Pod O'Clock for S60 phones.
Copyright (C) 2006 Marko Kivijärvi
Copyright (C) 2010 Hugo van Kemenade
Originally from:
http://wiki.forum.nokia.com/index.php/Trace_Function_Enter,_Exit_and_Leave
http://code.google.com/p/podoclock/
This file is part of Pod O'Clock.
Pod O'Clock 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.
Pod O'Clock is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Pod O'Clock. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __PODOCLOCKTRACER_H__
#define __PODOCLOCKTRACER_H__
#include <e32base.h>
// Define tracer logging method
// 0 = Logging off
// 1 = Log to RDebug
// 2 = Log to file (RFileLogger)
#ifdef _DEBUG
#define TRACER_LOG_METHOD 2
#else
#define TRACER_LOG_METHOD 0
#endif
// ============================================================================
// Logging off, define empty macros and skip all the rest
#if (TRACER_LOG_METHOD == 0) || !defined(_DEBUG)
#define TRACER(func)
#define TRACER_RET(func,format)
#define TRACER_AUTO
#define TRACER_AUTO_RET
#define LOGTEXT(a)
#define LOGBUF(a)
#define LOGINT(a)
#else // Logging on
// Macro to print function entry, exit and leave.
// Example: TRACER("CMyClass::MyFunction");
#define TRACER(func) TTracer function_tracer( _S(func), _S("") );
// Macro to print function return value in addition to entry, exit
// and leave conditions. Second parameter is a formatting string used
// to print the return value. Example to print an integer return value:
// TRACER_RET("CMyclass::MyFunction", "%d");
#define TRACER_RET(func,format) TTracer func_tracer( _S(func), _S(format) );
// Macro to print function entry, exit and leave.
// Gets the function name automatically.
// Example: TRACER_AUTO;
// Substract 1 from MaxLength() because PtrZ() adds the zero terminator.
#define TRACER_AUTO \
TPtrC8 __ptr8((const TUint8*)__PRETTY_FUNCTION__); \
TBuf<150> __buf; \
__buf.Copy( __ptr8.Left( __buf.MaxLength() - 1 ) ); \
TTracer function_tracer( __buf.PtrZ(), _S("") )
// Macro to print function entry, exit and leave.
// Gets the function name automatically.
// Example: TRACER_AUTO_RET("%d");
// Substract 1 from MaxLength() because PtrZ() adds the zero terminator.
#define TRACER_AUTO_RET(format) \
TPtrC8 __ptr8((const TUint8*)__PRETTY_FUNCTION__); \
TBuf<150> __buf; \
__buf.Copy( __ptr8.Left( __buf.MaxLength() - 1 ) ); \
TTracer function_tracer( __buf.PtrZ(), _S(format) )
#if TRACER_LOG_METHOD == 1 // Print to RDebug
#include <e32debug.h>
#define TRACER_PRINT(a) RDebug::Print(a,&iFunc);
#define TRACER_PRINT_RET(a,b) RDebug::Print(a,&iFunc,b);
#elif TRACER_LOG_METHOD == 2 // Print to file
#include <flogger.h>
_LIT( KLogDir, "podoclock" ); // Log directory: C:\logs\podoclock
_LIT( KLogFile, "podoclock.txt" ); // Log file: c:\logs\podoclock\podoclock.txt
#define TRACER_PRINT(a) RFileLogger::WriteFormat(KLogDir, \
KLogFile,EFileLoggingModeAppend,a,&iFunc);
#define TRACER_PRINT_RET(a,b) RFileLogger::WriteFormat(KLogDir, \
KLogFile,EFileLoggingModeAppend,a,&iFunc,b);
#define LOGTEXT(a) RFileLogger::Write(KLogDir, \
KLogFile,EFileLoggingModeAppend,_L(a));
#define LOGBUF(a) RFileLogger::Write(KLogDir, \
KLogFile,EFileLoggingModeAppend,a);
#define LOGINT(a) RFileLogger::WriteFormat(KLogDir, \
KLogFile,EFileLoggingModeAppend,_L("%d"),a);
#endif
_LIT( KLogEnter, "%S: ENTER" );
_LIT( KLogExit, "%S: EXIT" );
_LIT( KLogLeave, "%S: LEAVE!" );
_LIT( KLogExitRet, "%S: EXIT, Returning " );
/**
* Simple tracer class that logs function enter, exit, or leave
*/
class TTracer
{
public:
/**
* inline constructor to write log of entering a function
*/
TTracer( const TText* aFunc, const TText* aRetFormat )
: iFunc( aFunc )
, iRetFormat( aRetFormat )
{
TRACER_PRINT( KLogEnter );
}
/**
* inline destructor to write log of exiting a function
* normally or with a leave
*/
~TTracer()
{
if ( std::uncaught_exception() ) // Leave is an exception
{
// The function exited with a leave
TRACER_PRINT( KLogLeave );
}
else
{
// The function exited normally
if ( iRetFormat.Length() == 0 )
{
TRACER_PRINT( KLogExit );
}
else
{
// Log the return value
#ifdef __WINS__
TInt32 retVal( 0 );
// The assembly bit. This needs to be reimplemented
// for every target.
_asm( mov retVal, ebx );
TBuf<100> format( KLogExitRet );
format.Append( iRetFormat );
TRACER_PRINT_RET( format, retVal );
#else
TRACER_PRINT( KLogExit );
#endif
}
}
}
private:
/**
* Pointer descriptor to function signature that is to be logged.
*/
TPtrC iFunc;
/**
* Formatting string used to print the function return value
*/
TPtrC iRetFormat;
};
#endif // TRACER_LOG_METHOD == 0
#endif // __PODOCLOCKTRACER_H__
// End of file
| [
"hugovk@373d2494-ea07-43fc-4ece-a9e515d930fe"
] | [
[
[
1,
189
]
]
] |
cf80478afc3592adf467ac6039838a8445cb11f0 | 061348a6be0e0e602d4a5b3e0af28e9eee2d257f | /Examples/Tutorial/UserInterface/15TabPanel.cpp | 1d64e8d84dc63cd15ee0985a51ba1ca425b53a68 | [] | no_license | passthefist/OpenSGToolbox | 4a76b8e6b87245685619bdc3a0fa737e61a57291 | d836853d6e0647628a7dd7bb7a729726750c6d28 | refs/heads/master | 2023-06-09T22:44:20.711657 | 2010-07-26T00:43:13 | 2010-07-26T00:43:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,797 | cpp | // OpenSG Tutorial Example: Creating a Border
//
// This tutorial explains how to implement the
// TabPanel and its characteristics
//
// Includes: TabPanel creation and example TabPanel, as well as
// utilizing ActionListeners to add/remove Tabs on mouseclicks
// General OpenSG configuration, needed everywhere
#include "OSGConfig.h"
// Methods to create simple geometry: boxes, spheres, tori etc.
#include "OSGSimpleGeometry.h"
// A little helper to simplify scene management and interaction
#include "OSGSimpleSceneManager.h"
#include "OSGNode.h"
#include "OSGGroup.h"
#include "OSGViewport.h"
// The general scene file loading handler
#include "OSGSceneFileHandler.h"
// Input
#include "OSGWindowUtils.h"
// UserInterface Headers
#include "OSGUIForeground.h"
#include "OSGInternalWindow.h"
#include "OSGUIDrawingSurface.h"
#include "OSGGraphics2D.h"
#include "OSGLookAndFeelManager.h"
// Activate the OpenSG namespace
OSG_USING_NAMESPACE
// The SimpleSceneManager to manage simple applications
SimpleSceneManager *mgr;
WindowEventProducerRefPtr TutorialWindow;
// Forward declaration so we can have the interesting stuff upfront
void display(void);
void reshape(Vec2f Size);
// 15TabPanel Headers
#include <sstream>
#include "OSGButton.h"
#include "OSGLabel.h"
#include "OSGLayers.h"
#include "OSGBoxLayout.h"
#include "OSGFlowLayout.h"
//#include "OSGUIDefines.h"
#include "OSGPanel.h"
#include "OSGTabPanel.h"
// Create a class to allow for the use of the Ctrl+q
class TutorialKeyListener : public KeyListener
{
public:
virtual void keyPressed(const KeyEventUnrecPtr e)
{
if(e->getKey() == KeyEvent::KEY_Q && e->getModifiers() & KeyEvent::KEY_MODIFIER_COMMAND)
{
TutorialWindow->closeWindow();
}
}
virtual void keyReleased(const KeyEventUnrecPtr e)
{
}
virtual void keyTyped(const KeyEventUnrecPtr e)
{
}
};
/******************************************************
Create TabPanel and some of the Buttons
up front so the ActionListeners can
reference them
******************************************************/
TabPanelRefPtr ExampleTabPanel;
ButtonRefPtr ExampleTabContentA;
ButtonRefPtr ExampleTabContentB;
/******************************************************
Create ActionListeners
******************************************************/
class AddTabActionListener : public ActionListener
{
public:
virtual void actionPerformed(const ActionEventUnrecPtr e)
{
/******************************************************
Create a Tab and edit texts accordingly.
******************************************************/
LabelRefPtr AddedTabLabel = Label::create();
ButtonRefPtr AddedTabContent = Button::create();
AddedTabLabel->setText("Tab7");
AddedTabLabel->setBorders(NULL);
AddedTabLabel->setBackgrounds(NULL);
AddedTabContent->setText("This is where the new Tab content hangs out");
// Determine if the number of Tabs is 6 and
// if so, add a 7th Tab
if( ExampleTabPanel->getMFTabs()->getSize() == 6)
{
ExampleTabPanel->addTab(AddedTabLabel, AddedTabContent);
// Change the text on the Tabs
ExampleTabContentA->setText("Remove Tab7 under Tab2!");
ExampleTabContentB->setText("Remove Tab7");
}
}
};
class RemoveTabActionListener : public ActionListener
{
public:
virtual void actionPerformed(const ActionEventUnrecPtr e)
{
/******************************************************
Remove the last Tab and change texts
accordingly.
Note: removeTab()
can take either the TabName or index
number
******************************************************/
// If the number of Tabs is 7 (one was added)
// then remove it
if( ExampleTabPanel->getMFTabs()->getSize() == 7)
{
ExampleTabPanel->removeTab(6);
ExampleTabContentA->setText("Add another Tab");
// Change the text on the Tabs
ExampleTabContentB->setText("Add a Tab under Tab1!");
}
}
};
int main(int argc, char **argv)
{
// OSG init
osgInit(argc,argv);
// Set up Window
TutorialWindow = createNativeWindow();
TutorialWindow->initWindow();
TutorialWindow->setDisplayCallback(display);
TutorialWindow->setReshapeCallback(reshape);
TutorialKeyListener TheKeyListener;
TutorialWindow->addKeyListener(&TheKeyListener);
// Make Torus Node
NodeRefPtr TorusGeometryNode = makeTorus(.5, 2, 16, 16);
// Make Main Scene Node and add the Torus
NodeRefPtr scene = OSG::Node::create();
scene->setCore(OSG::Group::create());
scene->addChild(TorusGeometryNode);
// Create the Graphics
GraphicsRefPtr TutorialGraphics = OSG::Graphics2D::create();
// Initialize the LookAndFeelManager to enable default settings
LookAndFeelManager::the()->getLookAndFeel()->init();
/******************************************************
Create Button Components to be used with
TabPanel and specify their characteristics.
Note: Buttons are used for simplicity,
any Component can be used as Tab content
or as a Tab. A Panel with several
Buttons within it is also added.
******************************************************/
LabelRefPtr ExampleTabLabel1 = OSG::Label::create();
LabelRefPtr ExampleTabLabel2 = OSG::Label::create();
LabelRefPtr ExampleTabLabel3 = OSG::Label::create();
LabelRefPtr ExampleTabLabel4 = OSG::Label::create();
LabelRefPtr ExampleTabLabel5 = OSG::Label::create();
LabelRefPtr ExampleTabLabel6 = OSG::Label::create();
ExampleTabContentA = OSG::Button::create();
ExampleTabContentB = OSG::Button::create();
ButtonRefPtr ExampleTabContentC = OSG::Button::create();
ButtonRefPtr ExampleTabContentD = OSG::Button::create();
ButtonRefPtr ExampleTabContentE = OSG::Button::create();
ButtonRefPtr ExampleTabContentF = OSG::Button::create();
ExampleTabLabel1->setText("Tab1");
ExampleTabLabel1->setBorders(NULL);
ExampleTabLabel1->setBackgrounds(NULL);
ExampleTabLabel2->setText("Tab2");
ExampleTabLabel2->setBorders(NULL);
ExampleTabLabel2->setBackgrounds(NULL);
ExampleTabLabel3->setText("Tab3");
ExampleTabLabel3->setBorders(NULL);
ExampleTabLabel3->setBackgrounds(NULL);
ExampleTabLabel4->setText("Tab4");
ExampleTabLabel4->setBorders(NULL);
ExampleTabLabel4->setBackgrounds(NULL);
ExampleTabLabel5->setText("Tab5");
ExampleTabLabel5->setBorders(NULL);
ExampleTabLabel5->setBackgrounds(NULL);
ExampleTabLabel6->setText("Tab6");
ExampleTabLabel6->setBorders(NULL);
ExampleTabLabel6->setBackgrounds(NULL);
ExampleTabContentA->setText("Add another Tab");
// Add ActionListener
AddTabActionListener TheAddTabActionListener;
ExampleTabContentA->addActionListener( &TheAddTabActionListener);
ExampleTabContentB->setText("Add a Tab in Tab1!");
// Add ActionListener
RemoveTabActionListener TheRemoveTabActionListener;
ExampleTabContentB->addActionListener( &TheRemoveTabActionListener);
ExampleTabContentC->setText("Stuff for Tab3");
ExampleTabContentD->setText("Stuff for Tab5");
ExampleTabContentE->setText("Stuff for Tab6");
/******************************************************
Create a Panel to add to the TabPanel
******************************************************/
// Create and edit the Panel Buttons
ButtonRefPtr ExampleTabPanelButton1 = OSG::Button::create();
ButtonRefPtr ExampleTabPanelButton2 = OSG::Button::create();
ButtonRefPtr ExampleTabPanelButton3 = OSG::Button::create();
ButtonRefPtr ExampleTabPanelButton4 = OSG::Button::create();
ButtonRefPtr ExampleTabPanelButton5 = OSG::Button::create();
ButtonRefPtr ExampleTabPanelButton6 = OSG::Button::create();
ExampleTabPanelButton1->setText("This");
ExampleTabPanelButton2->setText("is a");
ExampleTabPanelButton3->setText("sample");
ExampleTabPanelButton4->setText("Panel");
ExampleTabPanelButton5->setText("within");
ExampleTabPanelButton6->setText("TabPanel");
// Create and edit Panel Layout
BoxLayoutRefPtr TabPanelLayout = OSG::BoxLayout::create();
TabPanelLayout->setOrientation(BoxLayout::VERTICAL_ORIENTATION);
// Create and edit Panel
PanelRefPtr ExampleTabPanelPanel = OSG::Panel::create();
ExampleTabPanelPanel->setPreferredSize(Vec2f(180, 500));
ExampleTabPanelPanel->pushToChildren(ExampleTabPanelButton1);
ExampleTabPanelPanel->pushToChildren(ExampleTabPanelButton2);
ExampleTabPanelPanel->pushToChildren(ExampleTabPanelButton3);
ExampleTabPanelPanel->pushToChildren(ExampleTabPanelButton4);
ExampleTabPanelPanel->pushToChildren(ExampleTabPanelButton5);
ExampleTabPanelPanel->pushToChildren(ExampleTabPanelButton6);
ExampleTabPanelPanel->setBorders(NULL);
ExampleTabPanelPanel->setBackgrounds(NULL);
ExampleTabPanelPanel->setLayout(TabPanelLayout);
/******************************************************
Create TabPanel. TabPanel automatically
sizes objects within it to cause the appearance
of Tabs. The following functions are
unique to TabPanel:
-addTab(TAB_OBJECT, TAB_CONENT):
Determine the Tab and content for a new
Tab. See below for detailed explanation
of arguments.
-removeTab(TAB_OBJECT or TAB_INDEX):
Remove a Tab based on either the Tab name
or the index of the Tab. See below for
detailed explanation of arguments.
-setActiveTab(TAB_INDEX): Determine which Tab
is Active (ie shown) based in index.
See below for detailed explanation of
arguments.
-insertTab(TAB_OBJECT or TAB_INDEX, NEW_TAB_OBJECT,
NEW_TAB_CONTENT): Insert a new Tab by
either an existing Tab (the Tab will
be inserted before this Tab) or by
its index.
-tabAlignment(ENUM): Determine the alignment
of the Tabs. Takes AXIS_CENTER_ALIGNMENT,
AXIS_MAX_ALIGNMENT, and AXIS_MIN_ALIGNMENT
arguments.
-tabPlacement(ENUM): Determine location of
the Tabs around the Tab content. Takes
PLACEMENT_NORTH, PLACEMENT_SOUTH,
PLACEMENT_WEST, and PLACEMENT_EAST
arguments.
Definition of terms:
TAB_OBJECT: This denotes a component which
is used as the Tab itself.
TAB_INDEX: This denotes the index within
the "list" of Tabs. The first Tab
is indexed as 0, and subsequent Tabs
are 1, 2, etc.
TAB_CONTENT: This denotes the Component
which will be displayed within the
Tab.
Note: The TabPanel has a PreferredSize
which it displays at and if the Frame is
too small, then the TabPanel will appear
distorted. Also, removeTab/addTab are most
useful when combined with ActionListeners
to allow for interactability with the
TabPanel. An example of this is shown
above, allowing for a Tab to be created/
removed by the user.
******************************************************/
ExampleTabPanel = OSG::TabPanel::create();
ExampleTabPanel->setPreferredSize(Vec2f(600,600));
ExampleTabPanel->addTab(ExampleTabLabel1, ExampleTabContentA);
ExampleTabPanel->addTab(ExampleTabLabel2, ExampleTabContentB);
ExampleTabPanel->addTab(ExampleTabLabel3, ExampleTabContentC);
ExampleTabPanel->addTab(ExampleTabLabel4, ExampleTabPanelPanel);
ExampleTabPanel->addTab(ExampleTabLabel5, ExampleTabContentD);
ExampleTabPanel->addTab(ExampleTabLabel6, ExampleTabContentE);
ExampleTabPanel->setTabAlignment(0.5f);
ExampleTabPanel->setTabPlacement(TabPanel::PLACEMENT_NORTH);
ExampleTabPanel->setSelectedIndex(3);
/******************************************************
By using CardLayout, the TabPanel
automatically takes up the entire
MainFrame (which can be very useful
with TabPanel).
******************************************************/
LayoutRefPtr MainInternalWindowLayout = OSG::FlowLayout::create();
// Create The Main InternalWindow
// Create Background to be used with the Main InternalWindow
ColorLayerRefPtr MainInternalWindowBackground = OSG::ColorLayer::create();
MainInternalWindowBackground->setColor(Color4f(1.0,1.0,1.0,0.5));
InternalWindowRefPtr MainInternalWindow = OSG::InternalWindow::create();
MainInternalWindow->pushToChildren(ExampleTabPanel);
MainInternalWindow->setLayout(MainInternalWindowLayout);
MainInternalWindow->setBackgrounds(MainInternalWindowBackground);
MainInternalWindow->setAlignmentInDrawingSurface(Vec2f(0.5f,0.5f));
MainInternalWindow->setScalingInDrawingSurface(Vec2f(0.85f,0.85f));
MainInternalWindow->setDrawTitlebar(false);
MainInternalWindow->setResizable(false);
// Create the Drawing Surface
UIDrawingSurfaceRefPtr TutorialDrawingSurface = UIDrawingSurface::create();
TutorialDrawingSurface->setGraphics(TutorialGraphics);
TutorialDrawingSurface->setEventProducer(TutorialWindow);
TutorialDrawingSurface->openWindow(MainInternalWindow);
// Create the UI Foreground Object
UIForegroundRefPtr TutorialUIForeground = OSG::UIForeground::create();
TutorialUIForeground->setDrawingSurface(TutorialDrawingSurface);
// Create the SimpleSceneManager helper
mgr = new SimpleSceneManager;
// Tell the Manager what to manage
mgr->setWindow(TutorialWindow);
mgr->setRoot(scene);
// Add the UI Foreground Object to the Scene
ViewportRefPtr TutorialViewport = mgr->getWindow()->getPort(0);
TutorialViewport->addForeground(TutorialUIForeground);
// Show the whole Scene
mgr->showAll();
//Open Window
Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
TutorialWindow->openWindow(WinPos,
WinSize,
"15TabPanel");
//Enter main Loop
TutorialWindow->mainLoop();
osgExit();
return 0;
}
// Callback functions
// Redraw the window
void display(void)
{
mgr->redraw();
}
// React to size changes
void reshape(Vec2f Size)
{
mgr->resize(Size.x(), Size.y());
}
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
9
],
[
11,
12
],
[
14,
15
],
[
20,
21
],
[
23,
24
],
[
26,
28
],
[
34,
39
],
[
41,
43
],
[
45,
47
],
[
56,
56
],
[
80,
80
],
[
84,
84
],
[
86,
86
],
[
94,
98
],
[
100,
100
],
[
102,
102
],
[
119,
120
],
[
130,
137
],
[
139,
139
],
[
141,
141
],
[
154,
154
],
[
163,
173
],
[
179,
179
],
[
183,
183
],
[
185,
186
],
[
190,
191
],
[
193,
198
],
[
247,
250
],
[
252,
255
],
[
262,
263
],
[
265,
265
],
[
267,
268
],
[
287,
288
],
[
291,
292
],
[
304,
306
],
[
371,
372
],
[
377,
377
],
[
394,
395
],
[
402,
402
],
[
406,
410
],
[
412,
414
],
[
417,
420
],
[
433,
445
],
[
447,
448
]
],
[
[
10,
10
],
[
13,
13
],
[
16,
19
],
[
22,
22
],
[
25,
25
],
[
29,
33
],
[
40,
40
],
[
44,
44
],
[
48,
55
],
[
57,
79
],
[
81,
83
],
[
85,
85
],
[
87,
93
],
[
99,
99
],
[
101,
101
],
[
103,
118
],
[
121,
129
],
[
138,
138
],
[
140,
140
],
[
142,
153
],
[
155,
162
],
[
174,
178
],
[
180,
182
],
[
184,
184
],
[
187,
189
],
[
192,
192
],
[
199,
246
],
[
251,
251
],
[
256,
261
],
[
264,
264
],
[
266,
266
],
[
269,
286
],
[
289,
290
],
[
293,
303
],
[
307,
370
],
[
373,
376
],
[
378,
393
],
[
396,
401
],
[
403,
405
],
[
411,
411
],
[
415,
416
],
[
421,
432
],
[
446,
446
],
[
449,
449
]
]
] |
818c891cd5d1f992a0a23463b30bd86e6defadd8 | 460b4422ba8b81fbc001a22da31969cf9d28ed12 | /SslPyFilter/PyInstance.h | f868f1165c523a4b1a8151d04c2db3fe9d9b2245 | [] | no_license | killvxk/sslpyfilter | 02d953dd96aec622b8a78e16efa818cb301e776d | 6803ee2e27039628d6cc94b9a7f521598894c39f | refs/heads/master | 2020-12-07T19:27:48.627612 | 2008-04-14T23:04:08 | 2008-04-14T23:04:08 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,741 | h | // ========================================================================================================================
// SslPyFilter
//
// Copyright ©2007-2008 Liam Kirton <[email protected]>
// ========================================================================================================================
// PyInstance.h
//
// Created: 23/04/2007
// ========================================================================================================================
#pragma once
// ========================================================================================================================
#include <windows.h>
#ifdef _DEBUG
#undef _DEBUG
#include <python.h>
#define _DEBUG
#else
#include <python.h>
#endif
#include <string>
// ========================================================================================================================
class PyInstance
{
public:
PyInstance();
~PyInstance();
void Load(const std::string &path);
void Unload();
void EncryptMessageFilter(unsigned int process, unsigned int thread, BSTR *encryptBuffer, BSTR *modifiedEncryptBuffer);
void DecryptMessageFilter(unsigned int process, unsigned int thread, BSTR *decryptBuffer, BSTR *modifiedDecryptBuffer);
static PyInstance *GetInstance();
static PyObject *PyInstance::SetEncryptFilter(PyObject *dummy, PyObject *args);
static PyObject *PyInstance::SetDecryptFilter(PyObject *dummy, PyObject *args);
private:
void Lock();
void Unlock();
HANDLE hMutex_;
PyObject *pyEncryptFilter_;
PyObject *pyDecryptFilter_;
};
// ========================================================================================================================
| [
"[email protected]"
] | [
[
[
1,
55
]
]
] |
9124760e53b908c9cd493d6e6305aea429f7bb44 | 259319e5fe06036972de9036f0078b8f5faba86e | /records/Uint16Key.h | 1856b0306a3ee8febdbfdd5822f4f3efedb80e4a | [] | no_license | ferromera/sancus | 652d05fc2a28987ac37309b9293cbd7f92448186 | 0f5d9b2e0bf1b6e099ade36edcf75e9640788589 | refs/heads/master | 2021-01-01T16:56:39.380388 | 2011-12-04T01:01:55 | 2011-12-04T01:01:55 | 32,414,828 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,256 | h | #ifndef UINT16KEY_H_INCLUDED
#define UINT16KEY_H_INCLUDED
#include "Record.h"
#include "stdint.h"
class Uint16Key: public Record::Key{
uint16_t buffer;
public:
static const bool isVariable=false;
static const bool isString=false;
Uint16Key(char ** input); //Load the key from input.
Uint16Key(uint16_t key=0);
Uint16Key(const Uint16Key &);
void setKey(uint16_t i);
void setKey(const Record::Key & rk);
uint16_t getKey()const;
unsigned int getUint() const{return getKey();}
void read(char ** input);
void write(char ** output)const;
bool operator <(const Record::Key &r)const;
bool operator ==(const Record::Key &r)const;
bool operator <=(const Record::Key & r)const;
bool operator >(const Record::Key &r)const;
bool operator !=(const Record::Key &r)const;
bool operator >=(const Record::Key & r)const;
Record::Key & operator=(const Record::Key & rk);
Uint16Key & operator=(const Uint16Key & rk);
Uint16Key & operator=(uint16_t i);
unsigned int size()const{ return 2; }
~Uint16Key(){}
};
#endif // UINT16KEY_H_INCLUDED
| [
"[email protected]@b06ae71c-7d8b-23a7-3f8b-8cb8ce3c93c2",
"pinus06@b06ae71c-7d8b-23a7-3f8b-8cb8ce3c93c2"
] | [
[
[
1,
17
],
[
19,
38
]
],
[
[
18,
18
]
]
] |
d2eee265f2d8071e7f84589c20a3ac7fd336d9a4 | 25d9a28105493df10beeb96a6c9ba63264c6975c | /sqlite/CppSQLite3.h | e337633624b4d26a3359c0e92a53f870c5ce3c69 | [] | no_license | daniel-white/mountain-cms | 3d3da729a1da5dc31dd3ad1a7c1a9d885476807b | 6249596d41d4544f4066d4a31282f9382bf5a4da | refs/heads/master | 2021-01-10T12:47:37.315587 | 2008-05-09T03:26:26 | 2008-05-09T03:26:26 | 55,194,179 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,421 | h | ////////////////////////////////////////////////////////////////////////////////
// CppSQLite3 - A C++ wrapper around the SQLite3 embedded database library.
//
// Copyright (c) 2004 Rob Groves. All Rights Reserved. [email protected]
//
// Permission to use, copy, modify, and distribute this software and its
// documentation for any purpose, without fee, and without a written
// agreement, is hereby granted, provided that the above copyright notice,
// this paragraph and the following two paragraphs appear in all copies,
// modifications, and distributions.
//
// IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT,
// INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST
// PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION,
// EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF
// ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". THE AUTHOR HAS NO OBLIGATION
// TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
//
// V3.0 03/08/2004 -Initial Version for sqlite3
//
// V3.1 16/09/2004 -Implemented getXXXXField using sqlite3 functions
// -Added CppSQLiteDB3::tableExists()
////////////////////////////////////////////////////////////////////////////////
#ifndef _CppSQLite3_H_
#define _CppSQLite3_H_
#include "sqlite3.h"
#include <cstdio>
#include <cstring>
#include <stdexcept>
#define CPPSQLITE_ERROR 1000
class CppSQLite3Exception : public std::exception
{
public:
CppSQLite3Exception(const int nErrCode,
char* szErrMess,
bool bDeleteMsg=true);
CppSQLite3Exception(const CppSQLite3Exception& e);
virtual ~CppSQLite3Exception() throw();
const int errorCode() { return mnErrCode; }
const char* errorMessage() const { return mpszErrMess; }
static const char* errorCodeAsString(int nErrCode);
virtual const char* what() const throw() { return errorMessage(); }
private:
int mnErrCode;
char* mpszErrMess;
};
class CppSQLite3Buffer
{
public:
CppSQLite3Buffer();
~CppSQLite3Buffer();
const char* format(const char* szFormat, ...);
operator const char*() { return mpBuf; }
void clear();
private:
char* mpBuf;
};
class CppSQLite3Binary
{
public:
CppSQLite3Binary();
~CppSQLite3Binary();
void setBinary(const unsigned char* pBuf, int nLen);
void setEncoded(const unsigned char* pBuf);
const unsigned char* getEncoded();
const unsigned char* getBinary();
int getBinaryLength();
unsigned char* allocBuffer(int nLen);
void clear();
private:
unsigned char* mpBuf;
int mnBinaryLen;
int mnBufferLen;
int mnEncodedLen;
bool mbEncoded;
};
class CppSQLite3Query
{
public:
CppSQLite3Query();
CppSQLite3Query(const CppSQLite3Query& rQuery);
CppSQLite3Query(sqlite3* pDB,
sqlite3_stmt* pVM,
bool bEof,
bool bOwnVM=true);
CppSQLite3Query& operator=(const CppSQLite3Query& rQuery);
virtual ~CppSQLite3Query();
int numFields();
int fieldIndex(const char* szField);
const char* fieldName(int nCol);
const char* fieldDeclType(int nCol);
int fieldDataType(int nCol);
const char* fieldValue(int nField);
const char* fieldValue(const char* szField);
int getIntField(int nField, int nNullValue=0);
int getIntField(const char* szField, int nNullValue=0);
double getFloatField(int nField, double fNullValue=0.0);
double getFloatField(const char* szField, double fNullValue=0.0);
const char* getStringField(int nField, const char* szNullValue="");
const char* getStringField(const char* szField, const char* szNullValue="");
const unsigned char* getBlobField(int nField, int& nLen);
const unsigned char* getBlobField(const char* szField, int& nLen);
bool fieldIsNull(int nField);
bool fieldIsNull(const char* szField);
bool eof();
void nextRow();
void finalize();
private:
void checkVM();
sqlite3* mpDB;
sqlite3_stmt* mpVM;
bool mbEof;
int mnCols;
bool mbOwnVM;
};
class CppSQLite3Table
{
public:
CppSQLite3Table();
CppSQLite3Table(const CppSQLite3Table& rTable);
CppSQLite3Table(char** paszResults, int nRows, int nCols);
virtual ~CppSQLite3Table();
CppSQLite3Table& operator=(const CppSQLite3Table& rTable);
int numFields();
int numRows();
const char* fieldName(int nCol);
const char* fieldValue(int nField);
const char* fieldValue(const char* szField);
int getIntField(int nField, int nNullValue=0);
int getIntField(const char* szField, int nNullValue=0);
double getFloatField(int nField, double fNullValue=0.0);
double getFloatField(const char* szField, double fNullValue=0.0);
const char* getStringField(int nField, const char* szNullValue="");
const char* getStringField(const char* szField, const char* szNullValue="");
bool fieldIsNull(int nField);
bool fieldIsNull(const char* szField);
void setRow(int nRow);
void finalize();
private:
void checkResults();
int mnCols;
int mnRows;
int mnCurrentRow;
char** mpaszResults;
};
class CppSQLite3Statement
{
public:
CppSQLite3Statement();
CppSQLite3Statement(const CppSQLite3Statement& rStatement);
CppSQLite3Statement(sqlite3* pDB, sqlite3_stmt* pVM);
virtual ~CppSQLite3Statement();
CppSQLite3Statement& operator=(const CppSQLite3Statement& rStatement);
int execDML();
CppSQLite3Query execQuery();
void bind(int nParam, const char* szValue);
void bind(int nParam, const int nValue);
void bind(int nParam, const double dwValue);
void bind(int nParam, const unsigned char* blobValue, int nLen);
void bindNull(int nParam);
int getColumnCount();
const char* getColumnName(int nColumn);
const char* getColumnType(int nColumn);
void reset();
void finalize();
private:
void checkDB();
void checkVM();
sqlite3* mpDB;
sqlite3_stmt* mpVM;
};
class CppSQLite3DB
{
public:
CppSQLite3DB();
virtual ~CppSQLite3DB();
void open(const char* szFile);
void close();
bool tableExists(const char* szTable);
int execDML(const char* szSQL);
CppSQLite3Query execQuery(const char* szSQL);
int execScalar(const char* szSQL);
CppSQLite3Table getTable(const char* szSQL);
CppSQLite3Statement compileStatement(const char* szSQL);
sqlite_int64 lastRowId();
void interrupt() { sqlite3_interrupt(mpDB); }
void setBusyTimeout(int nMillisecs);
static const char* SQLiteVersion() { return SQLITE_VERSION; }
private:
CppSQLite3DB(const CppSQLite3DB& db);
CppSQLite3DB& operator=(const CppSQLite3DB& db);
sqlite3_stmt* compile(const char* szSQL);
void checkDB();
sqlite3* mpDB;
int mnBusyTimeoutMs;
};
#endif
| [
"thetrueaplus@a6c76449-3c4b-0410-9e40-efb2f4630036"
] | [
[
[
1,
313
]
]
] |
493b838f9267aa1ef25c32ef519c4ecc4042a9e1 | de0881d85df3a3a01924510134feba2fbff5b7c3 | /apps/dev/neuralNetworkDemo/src/testApp.h | cac4242bef44359ce23e021be9afb68f6fcb4312 | [] | no_license | peterkrenn/ofx-dev | 6091def69a1148c05354e55636887d11e29d6073 | e08e08a06be6ea080ecd252bc89c1662cf3e37f0 | refs/heads/master | 2021-01-21T00:32:49.065810 | 2009-06-26T19:13:29 | 2009-06-26T19:13:29 | 146,543 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,425 | h | #ifndef _TEST_APP
#define _TEST_APP
#define width 256
#define height 256
#include "ofMain.h"
#include "ofxProcessing.h"
#include "ofxNeuralNetwork.h"
class testApp : public ofBaseApp{
public:
NeuralNetwork* nn;
ofTexture screen;
void setup() {
ofSetFrameRate(30);
nn = NULL;
Connection::learningRate = 0.01;
Connection::maxInitWeight = 1;
init();
}
void init(int _x=2, int _y=3, int _b=3) {
vector<int> dimensions(3);
dimensions[0] = _x;
dimensions[1] = _y;
dimensions[2] = _b;
if(nn != NULL) delete nn;
nn = new NeuralNetwork(dimensions);
//if(nn == NULL) {
// nn = new NeuralNetwork(dimensions);
//}
unsigned char pixels[width * height * 3];
for(int y = 0; y < height; y++) {
for(int x = 0; x < width; x++) {
vector<float> input(2);
input[0] = ofMap(x, 0, width, -1, +1);
input[1] = ofMap(y, 0, height, -1, +1);
vector<float>* output = nn->run(input);
int position = y * (width * 3) + (x * 3);
for(int i = 0; i < 3; i++)
pixels[position + i] = (unsigned char) ofMap(output->at(i), -1, +1, 0, 255);
delete output;
}
}
screen.allocate(width, height, GL_RGB);
screen.loadData(pixels, width, height, GL_RGB);
cout << "init x:" << _x << " y:" << _y;
}
void draw() {
screen.draw(0, 0);
}
void mousePressed(int x, int y, int button){
init(x,y);
}
};
#endif
| [
"[email protected]"
] | [
[
[
1,
66
]
]
] |
60762f910a1e7e346b2fcd838229e2d70461eb01 | a2a02e60accf212ddbb8fdd54e7915819d45061c | /Ogre/NameGenerator.cpp | 4b2889526693d7ca14052beb5281679a078e3856 | [] | no_license | TimToxopeus/mazeofdespair | 79a28698b619a5552bc10eef64beb9041157c1a6 | 827ea8403d6bcc825b06def9d161d0dfe76837be | refs/heads/master | 2021-01-01T19:34:12.268847 | 2008-04-09T22:03:40 | 2008-04-09T22:03:40 | 41,954,537 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,591 | cpp | /************************************************************************************
* Assignment 5 - The maze of despair *
* Tim Toxopeus - 3206947 *
* Cetin Demir - 3236943 *
************************************************************************************/
#include "NameGenerator.h"
#include "string.h"
int CNameGenerator::CharacterIndex( char character )
{
int index = 0;
if ( character >= 97 && character <= 122 )
index = character - 97;
if ( character == '\'' )
index = 26;
return index;
}
char CNameGenerator::IndexCharacter( int index )
{
if ( index < 0 )
{
index = index;
}
if ( index < 26 )
return (char)(index + 97);
return '\'';
}
bool CNameGenerator::IsVowel( char input )
{
if ( input == 'a' || input == 'e' || input == 'i' || input == 'o' || input == 'u' || input == 'y' )
return true;
return false;
}
bool CNameGenerator::IsAcceptable( char *input )
{
char prevChar = 0;
int row = 1;
for ( int i = 0; i<strlen(input); i++ )
{
if ( input[i] != prevChar )
{
prevChar = input[i];
row = 1;
}
else
{
row++;
if ( row >= 3 )
return false;
}
}
row = 0;
for ( int i = 0; i<strlen(input); i++ )
{
if ( IsVowel(input[i]) )
{
row++;
if ( row >= 3 )
return false;
}
else
{
row = 0;
}
}
row = 0;
for ( int i = 0; i<strlen(input); i++ )
{
if ( !IsVowel(input[i]) )
{
row++;
if ( row >= 3 )
return false;
}
else
{
row = 0;
}
}
return true;
}
| [
"tim.toxopeus@caf72609-6e49-0410-a68d-6564f63caef6"
] | [
[
[
1,
86
]
]
] |
ccabb0ab2ae6905a713bb44e99dfa839f85d46cf | 9310fd7bac6871c98b216a2e081b19e9232c14ed | /lib/agr/tests/include/TestMovement.h | 185a3ede3a605fffd22e3e8ef4a0b3b63b0b19d7 | [] | no_license | baloo/wiidrums | 1345525c759a2325274ddbfe182a9549c6c4e325 | ed3832d4f91cd9932bfeb321b8aa57340a502d48 | refs/heads/master | 2016-09-09T18:19:06.403352 | 2009-05-21T02:04:09 | 2009-05-21T02:04:09 | 179,309 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 800 | h | /**
* \file TestMovement.h
* \brief Declaraction for testing cMovement
* \date 28/02/08
*/
#ifndef _TESTMOVEMENT_H_
#define _TESTMOVEMENT_H_
#include <cppunit/extensions/HelperMacros.h>
namespace AGR {
class cVector3int; // forward declaration
class cMovement;
}
/**
* \classe cTestMovement
* \brief Test class for cMovement
* To be used with CPPUnit
*/
class cTestMovement : public CPPUNIT_NS::TestFixture
{
CPPUNIT_TEST_SUITE(cTestMovement);
CPPUNIT_TEST( uninitialised );
CPPUNIT_TEST( initialisation );
CPPUNIT_TEST( manipulation );
CPPUNIT_TEST_SUITE_END();
public:
virtual void setUp();
virtual void tearDown();
void uninitialised();
void initialisation();
void manipulation();
protected:
};
#endif // _TESTMOVEMENT_H_
| [
"[email protected]"
] | [
[
[
1,
45
]
]
] |
ae7e74f9581e86a1b2f529276e7716228d1208ba | df238aa31eb8c74e2c208188109813272472beec | /BCGInclude/BCGPSDPlaceMarkerWnd.h | 78d9faac60df892959b65331af4a454574265459 | [] | no_license | myme5261314/plugin-system | d3166f36972c73f74768faae00ac9b6e0d58d862 | be490acba46c7f0d561adc373acd840201c0570c | refs/heads/master | 2020-03-29T20:00:01.155206 | 2011-06-27T15:23:30 | 2011-06-27T15:23:30 | 39,724,191 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,197 | h | #if !defined(AFX_BCGPSDPLACEMARKERWND_H__FA84F558_73E5_40AA_9C70_4D69E9FF496C__INCLUDED_)
#define AFX_BCGPSDPLACEMARKERWND_H__FA84F558_73E5_40AA_9C70_4D69E9FF496C__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
//*******************************************************************************
// COPYRIGHT NOTES
// ---------------
// This is a part of BCGControlBar Library Professional Edition
// Copyright (C) 1998-2008 BCGSoft Ltd.
// All rights reserved.
//
// This source code can be used, distributed or modified
// only under terms and conditions
// of the accompanying license agreement.
//*******************************************************************************
//
// BCGPSDPlaceMarkerWnd.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CBCGPSDPlaceMarkerWnd window
class CBCGPSDPlaceMarkerWnd : public CWnd
{
friend class CBCGPSmartDockingManager;
// Construction
public:
CBCGPSDPlaceMarkerWnd ();
void Create (CWnd* pwndOwner);
void SetDockingWnd (CWnd* pDockingWnd)
{
m_pDockingWnd = pDockingWnd;
}
void ShowAt (CRect rect);
void ShowTabbedAt (CRect rect, CRect rectTab);
void Hide ();
// Attributes
protected:
CWnd* m_pWndOwner;
CWnd* m_pDockingWnd;
CRect m_rectLast;
CRect m_rectTab;
BOOL m_bTabbed;
BOOL m_bShown;
BOOL m_bUseThemeColorInShading;
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CBCGPSDPlaceMarkerWnd)
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CBCGPSDPlaceMarkerWnd();
// Generated message map functions
protected:
//{{AFX_MSG(CBCGPSDPlaceMarkerWnd)
afx_msg void OnPaint();
afx_msg void OnClose();
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_BCGPSDPLACEMARKERWND_H__FA84F558_73E5_40AA_9C70_4D69E9FF496C__INCLUDED_)
| [
"myme5261314@ec588229-7da7-b333-41f6-0e1ebc3afda5"
] | [
[
[
1,
82
]
]
] |
19ebea7896691dff937c22456e3dd66c7a0ebeab | 5fa8f06181e88d96a9166cb238d05b185ebe7a92 | /sliq/attribute_list.hh | 38392208640c91e8af6f622f41578b1d116b006f | [] | no_license | mohitkg/sliqimp | 6834092760a8a078428876baaa7cdab91b37e355 | 54f05bc55ad9c6b7e73abc51fcc0bd8e995d6b69 | refs/heads/master | 2016-09-07T07:13:04.793483 | 2007-06-20T10:49:44 | 2007-06-20T10:49:44 | 33,323,734 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 343 | hh | namespace Sliq
{
namespace Attribute
{
// Liste d'attributs (seulement des entiers)
// Créé avant le lancement de la construction de l'arbre
class List
{
public:
private:
std::vector<int> value_;
std::vector<int> index_;
};
}
}
| [
"davidlandais@af1a0f03-5433-0410-83de-a7259e581374"
] | [
[
[
1,
16
]
]
] |
f119165e53c4de8d1d057f7ec5d0a9ddcdef5bc9 | 986d745d6a1653d73a497c1adbdc26d9bef48dba | /iostreams/examples/inc/ocdatestream_212.h | 8ee021af4195732138aa3c9679f8516cd8645a64 | [] | no_license | AnarNFT/books-code | 879f75327c1dad47a13f9c5d71a96d69d3cc7d3c | 66750c2446477ac55da49ade229c21dd46dffa99 | refs/heads/master | 2021-01-20T23:40:30.826848 | 2011-01-17T11:14:34 | 2011-01-17T11:14:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,281 | h | /*
author: "Klaus Wittlich" <[email protected]>
Based on source code published in the book "Standard C++ IOStreams
and Locales" by Angelika Langer & Klaus Kreft, Copyright (c) 2000 by
Addison Wesley Longman, Inc.
Permission to use, copy, and modify this software for any non-profit
purpose is hereby granted without fee. Neither the author of this
source code, Klaus Wittlich, nor the authors of the above mentioned
book, Angelika Langer and Klaus Kreft, nor the publisher, Addison
Wesley Longman, Inc., make any representations about the suitability of this
software for any purpose. It is provided "as is" without express or
implied warranty.
*/
/*
#include "ocdatestream_212.h"
*/
#ifndef CONCRETEOSTREAM_H
#define CONCRETEOSTREAM_H
#include "datefmt_210.h"
// p. 212 {{{
template <class ConcreteOStream>
class ocdatestream
: public ConcreteOStream, public datefmt<typename ConcreteOStream::char_type>
{
public:
typedef typename ConcreteOStream::char_type char_type;
ocdatestream (const char *s, ios_base::openmode mode, const char_type * fmt) // !!! different: in book fmt = 0;
: ConcreteOStream(s, mode),
datefmt<char_type>(fmt)
{ }
// ...
};
// }}}
#endif | [
"[email protected]"
] | [
[
[
1,
43
]
]
] |
2829bbe7c50e67bf1bb660ba28dd8a39de9bb154 | 854ee643a4e4d0b7a202fce237ee76b6930315ec | /arcemu_svn/src/arcemu-logonserver/LogonOpcodes.cpp | d06052d91822433f761b948ade6baa9cb8f05d59 | [] | no_license | miklasiak/projekt | df37fa82cf2d4a91c2073f41609bec8b2f23cf66 | 064402da950555bf88609e98b7256d4dc0af248a | refs/heads/master | 2021-01-01T19:29:49.778109 | 2008-11-10T17:14:14 | 2008-11-10T17:14:14 | 34,016,391 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,292 | cpp | /*
* ArcEmu MMORPG Server
* Copyright (C) 2008 <http://www.ArcEmu.org/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
// Opcode implementation file
#include "LogonStdAfx.h"
/*
NameTableEntry g_logonOpcodeNames[] = {
{ RSMSG_AUTH_CHALLENGE, "RSMSG_AUTH_CHALLENGE" },
{ RCMSG_AUTH_RESPONSE, "RCMSG_AUTH_RESPONSE" },
{ RSMSG_AUTH_AUTHORIZED, "RSMSG_AUTH_AUTHORIZED" },
{ RSMSG_CLIENT_INFORMATION, "RSMSG_CLIENT_INFORMATION" },
{ RCMSG_CLIENT_INFORMATION, "RCMSG_CLIENT_INFORMATION" },
{ RSMSG_CLIENT_CLOSE_SESSION, "RSMSG_CLIENT_CLOSE_SESSION" },
{ RSMSG_PING, "RSMSG_PING" },
{ RCMSG_PONG, "RCMSG_PONG" },
};
*/
| [
"[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef",
"[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef"
] | [
[
[
1,
1
],
[
4,
33
]
],
[
[
2,
3
]
]
] |
dc67345b385058bca80ebbcfc0dc8eb87046e55b | 49b6646167284329aa8644c8cf01abc3d92338bd | /SEP2_M6/FSM/Puck_FSM_1.cpp | fda52a4d085ed0b1bfa1c785768bdca65391017d | [] | no_license | StiggyB/javacodecollection | 9d017b87b68f8d46e09dcf64650bd7034c442533 | bdce3ddb7a56265b4df2202d24bf86a06ecfee2e | refs/heads/master | 2020-08-08T22:45:47.779049 | 2011-10-24T12:10:08 | 2011-10-24T12:10:08 | 32,143,796 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 11,720 | cpp | /**
* Puck_FSM 1
*
* SE2 (+ SY and PL) Project SoSe 2011
*
* Milestone 4: Automatenimplementierung
*
* Authors: Rico Flaegel,
* Tell Mueller-Pettenpohl,
* Torsten Krane,
* Jan Quenzel
*
* Class for machine 1 - sort out WP with correct/incorrect height
*
*
*/
//TODO // stop all timer, wenn band 1 auf band2 wartet
#include "Puck_FSM_1.h"
Puck_FSM_1::Puck_FSM_1(std::vector<Puck_FSM*>* puck_listobj) {
puck_list = puck_listobj;
current = new FSM_1_start_state;
current->entry(this);
minTimerId = timer->getnextid();
maxTimerId = timer->getnextid();
printf("my minTimerid: %i, maxTimer: %i\n", minTimerId, maxTimerId);
checkSlide_TID = timer->getnextid();
closeSwitch_TID = timer->getnextid();
#ifdef PUCK_FSM_1_DEBUG
printf("FSM Band1 is up\n");
#endif
}
Puck_FSM_1::~Puck_FSM_1() {
}
//functions for Start_M1
void FSM_1_start_state::entry(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_start_state: entry" << endl;
#endif
fsm->location = ON_FIRST_LB;
fsm->engine_should_be_started = true;
}
void FSM_1_start_state::ls_b0(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_start_state: LS_B0 wurde ausgelöst" << endl;
#endif
if (fsm->check_last_lb() == 0) {
// cout << "PUCK IS NOT BLOCKING LAST LB_0!!!" << endl;
fsm->setCurrent(new FSM_1_after_ls_b0());
}//if
}
void FSM_1_start_state::ls_b7_out(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_start_state: ls_b7_out" << endl;
#endif
if (fsm->check_last_lb() == 0) {
// cout << "PUCK IS NOT BLOCKING LAST LB_7!!!" << endl;
fsm->setCurrent(new FSM_1_after_ls_b0());
}//if
}
void FSM_1_start_state::exit(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_start_state: exit" << endl;
#endif
//Callback in errorState in reference time x
fsm->setDummyTimer(MIN_TIME_B1);
fsm->setErrorStateTimer(MAX_TIME_B1);
}
//functions for Band1_aufgelegt
void FSM_1_after_ls_b0::entry(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_after_ls_b0: entry" << endl;
#endif
fsm->location = AFTER_FIRST_LB;
// cout << "need engine: " << fsm->engine_should_be_started << endl;
fsm->starts_engine_if_nessecary();
}
void FSM_1_after_ls_b0::ls_b1(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_after_ls_b0: LS_B1 wurde ausgelöst" << endl;
#endif
if (fsm->timer->existTimer(fsm->minTimerId)) {
fsm->checked_to_early = true;
fsm->errorState();
return;
}
fsm->setCurrent(new FSM_1_height_measure());
}
void FSM_1_after_ls_b0::errorState(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_after_ls_b0: errorState" << endl;
#endif
fsm->setCurrent(new FSM_1_ErrorState());
}
void FSM_1_after_ls_b0::exit(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_after_ls_b0: exit" << endl;
#endif
}
//functions for Band1_hoehenmessung
void FSM_1_height_measure::entry(Puck_FSM * fsm) {
fsm->timer->deleteTimer(fsm->maxTimerId);
int height = fsm->hc->identifyHeight();
fsm->location = AFTER_HEIGH_MEASURE;
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_height_measure: entry" << endl;
cout << "height: " << height << endl;
#endif
if (height == NORMAL_WP || height == POCKET_WP) {
if (height == POCKET_WP) {
fsm->hasPocket = 1;
}//if
fsm->setCurrent(new FSM_1_correct_height());
} else {
fsm->setCurrent(new FSM_1_sort_out());
}//if
}
void FSM_1_height_measure::errorState(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_height_measure: errorState" << endl;
#endif
fsm->setCurrent(new FSM_1_ErrorState());
}
void FSM_1_height_measure::exit(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_height_measure: exit" << endl;
#endif
//Callback in errorState in reference time x
fsm->setDummyTimer(MIN_TIME_B3);
fsm->setErrorStateTimer(MAX_TIME_B3);
}
//functions for ausschleusen
void FSM_1_sort_out::entry(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_sort_out: entry" << endl;
#endif
}
void FSM_1_sort_out::ls_b3(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_sort_out: LS_B3" << endl;
#endif
if (fsm->timer->existTimer(fsm->minTimerId)) {
fsm->checked_to_early = true;
fsm->errorState();
return;
}
fsm->timer->deleteTimer(fsm->maxTimerId);
fsm->location = AFTER_METAL_SENSOR;
fsm->engine_should_be_started = 1;
fsm->starts_engine_if_nessecary();
fsm->lamp->shine(YELLOW);
fsm->setCurrent(new FSM_1_ls_b3_passed_sort_out());
}
void FSM_1_sort_out::errorState(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_sort_out: errorState" << endl;
#endif
fsm->setCurrent(new FSM_1_ErrorState());
}
void FSM_1_sort_out::exit(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_sort_out: exit" << endl;
#endif
fsm->setDummyTimer(MIN_TIME_B6);
fsm->setErrorStateTimer(MAX_TIME_B6);
}
//functions for Weiche_zu
void FSM_1_ls_b3_passed_sort_out::entry(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_ls_b3_passed: entry" << endl;
#endif
}
void FSM_1_ls_b3_passed_sort_out::ls_b6(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_ls_b3_passed: LS_B6" << endl;
#endif
if (fsm->timer->existTimer(fsm->minTimerId)) {
fsm->checked_to_early = true;
fsm->errorState();
return;
}
fsm->timer->deleteTimer(fsm->maxTimerId);
fsm->hc->engineStop();
fsm->engine_should_be_started = 0;
fsm->location = SORT_OUT;
fsm->starts_engine_if_nessecary();
fsm->setCurrent(new FSM_1_wp_in_slide());
}
void FSM_1_ls_b3_passed_sort_out::errorState(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_ls_b3_passed: errorState" << endl;
#endif
fsm->setCurrent(new FSM_1_ErrorState());
}
void FSM_1_ls_b3_passed_sort_out::exit(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_ls_b3_passed: exit" << endl;
#endif
}
//functions for WS_im_Schacht
void FSM_1_wp_in_slide::entry(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_wp_in_slide: entry" << endl;
#endif
fsm->setCurrent(new FSM_1_check_slide());
}
void FSM_1_wp_in_slide::errorState(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_wp_in_slide: errorState" << endl;
#endif
fsm->setCurrent(new FSM_1_ErrorState());
}
void FSM_1_wp_in_slide::exit(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_wp_in_slide: exit" << endl;
#endif
}
//functions for pruef_schacht_voll
void FSM_1_check_slide::entry(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_check_slide: entry" << endl;
#endif
CallInterface<CallBackThrower, void>* checkSlide = (CallInterface<
CallBackThrower, void>*) FunctorMaker<Puck_FSM, void>::makeFunctor(
fsm, &Puck_FSM::isSlideFull);
fsm->timer->addTimerFunction(checkSlide, MAX_TIME_IN_SLIDE,
fsm->checkSlide_TID);
}
void FSM_1_check_slide::errorState(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_check_slide: errorState" << endl;
#endif
fsm->setCurrent(new FSM_1_ErrorState());
}
void FSM_1_check_slide::exit(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_check_slide: exit" << endl;
#endif
}
//functions for durchschleusen
void FSM_1_correct_height::entry(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_correct_height: entry" << endl;
#endif
}
void FSM_1_correct_height::ls_b3(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_correct_height: LS_B3 wurde ausgelöst" << endl;
#endif
if (fsm->timer->existTimer(fsm->minTimerId)) {
fsm->checked_to_early = true;
fsm->errorState();
return;
}
fsm->timer->deleteTimer(fsm->maxTimerId);
fsm->location = AFTER_METAL_SENSOR_FORWARD;
fsm->hc->openSwitch();
fsm->setCurrent(new FSM_1_ls_b3_passed_correct_height());
}
void FSM_1_correct_height::errorState(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_correct_height: errorState" << endl;
#endif
fsm->setCurrent(new FSM_1_ErrorState());
}
void FSM_1_correct_height::exit(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_correct_height: exit" << endl;
#endif
if(fsm->timer->existTimer(fsm->gv->getSwitch_TID())) {
fsm->timer->deleteTimer(fsm->gv->getSwitch_TID());
}
CallInterface<CallBackThrower, void>* callCloseSwitch = (CallInterface<
CallBackThrower, void>*) FunctorMaker<HALCore, void>::makeFunctor(
fsm->hc, &HALCore::closeSwitch);
//fsm->timer->addUnstoppableFunction(callCloseSwitch);
fsm->timer->addTimerFunction(callCloseSwitch, 700, fsm->gv->getSwitch_TID());
fsm->setDummyTimer(MIN_TIME_B7);
fsm->setErrorStateTimer(MAX_TIME_B7);
}
//functions for durchschleusen_bei_LS3
void FSM_1_ls_b3_passed_correct_height::entry(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_ls_b3_passed_correct_height: entry" << endl;
#endif
}
void FSM_1_ls_b3_passed_correct_height::ls_b7_in(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_ls_b3_passed_correct_height: LS_B7 in" << endl;
#endif
if (fsm->timer->existTimer(fsm->minTimerId)) {
fsm->checked_to_early = true;
fsm->errorState();
return;
}
fsm->timer->deleteTimer(fsm->maxTimerId);
fsm->hc->engineStop();
fsm->engine_should_be_started = 0;
fsm->location = ON_LAST_LB;
fsm->serial->send(REQUEST_FREE, 4);
fsm->timer->stopAll_actual_Timer();
fsm->setCurrent(new FSM_1_end_state());
}
void FSM_1_ls_b3_passed_correct_height::errorState(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_ls_b3_passed_correct_height: errorState" << endl;
#endif
fsm->setCurrent(new FSM_1_ErrorState());
}
void FSM_1_ls_b3_passed_correct_height::exit(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_ls_b3_passed_correct_height: exit" << endl;
#endif
}
//functions for pruef_LS7
void FSM_1_end_state::entry(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_end_state: entry" << endl;
#endif
}
void FSM_1_end_state::ls_b7_out(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_end_state: ls_b7 out" << endl;
#endif
fsm->location = AFTER_LAST_LB;
// fsm->starts_engine_if_nessecary();
//Callback in errorState in reference time x
//TODO WTH do this statement?!
// fsm->setGlobalUnstoppable = true;
fsm->setErrorStateTimer(MAX_TIME_FSM2);
}
void FSM_1_end_state::errorState(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_end_state: errorState" << endl;
#endif
fsm->setCurrent(new FSM_1_ErrorState());
}
void FSM_1_end_state::exit(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_end_state: exit" << endl;
#endif
}
//functions for errorState
void FSM_1_ErrorState::entry(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_ErrorState: entry" << endl;
#endif
fsm->timer->stopAll_actual_Timer();
fsm->setErrorNoticed(true);
fsm->hc->engineStop();
fsm->removeAllLights();
fsm->lamp->flash(500, RED);
fsm->selectErrorType();
}
void FSM_1_ErrorState::ls_b6(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_ErrorState: LS_B6" << endl;
#endif
if (fsm->errType == SLIDE_FULL_B6) {
if (fsm->hc->checkSlide() == false) {
//should be work without removeLight or need removeAll
fsm->removeAllLights();
fsm->lamp->flash(1000, RED);
if (fsm->getErrorNoticed() == true) { //error was noticed
fsm->noticed_error_confirmed();
} else {
fsm->noticed_error_confirmed();
}//if
}//if
}//if
}
void FSM_1_ErrorState::reset(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_ErrorState: reset_button_pushed" << endl;
#endif
fsm->lamp->flash(1000, RED);
fsm->noticed_error_confirmed();
}
void FSM_1_ErrorState::exit(Puck_FSM * fsm) {
#ifdef PUCK_FSM_1_DEBUG
cout << "FSM_1_ErrorState: exit" << endl;
#endif
}
| [
"[email protected]@72d44fe2-11f0-84eb-49d3-ba3949d4c1b1",
"[email protected]@72d44fe2-11f0-84eb-49d3-ba3949d4c1b1",
"[email protected]@72d44fe2-11f0-84eb-49d3-ba3949d4c1b1",
"[email protected]@72d44fe2-11f0-84eb-49d3-ba3949d4c1b1"
] | [
[
[
1,
12
],
[
14,
17
],
[
19,
25
],
[
31,
35
],
[
40,
52
],
[
54,
61
],
[
63,
70
],
[
73,
80
],
[
82,
88
],
[
90,
137
],
[
140,
151
],
[
153,
173
],
[
176,
187
],
[
190,
190
],
[
194,
239
],
[
242,
266
],
[
268,
268
],
[
272,
286
],
[
290,
292
],
[
297,
306
],
[
308,
308
],
[
310,
310
],
[
314,
318
],
[
320,
344
],
[
350,
367
],
[
369,
378
],
[
381,
383
],
[
385,
404
]
],
[
[
13,
13
],
[
18,
18
],
[
28,
28
],
[
30,
30
],
[
36,
39
],
[
89,
89
],
[
152,
152
],
[
188,
189
],
[
191,
193
],
[
240,
241
],
[
267,
267
],
[
269,
271
],
[
287,
289
],
[
293,
294
],
[
307,
307
],
[
309,
309
],
[
311,
313
],
[
319,
319
],
[
345,
349
],
[
368,
368
],
[
379,
380
],
[
384,
384
]
],
[
[
26,
27
],
[
29,
29
],
[
71,
72
],
[
138,
139
],
[
174,
175
],
[
295,
296
]
],
[
[
53,
53
],
[
62,
62
],
[
81,
81
]
]
] |
bb27c229d77d51d222bc07334e9627752d496ac8 | 45c0d7927220c0607531d6a0d7ce49e6399c8785 | /GlobeFactory/src/useful/user_input.hh | ffb99269634dd2bf0721d457523ce50b7fe3654c | [] | 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 | 4,186 | hh | ////////////////////////////////////////////////////////////////////////////////
// Filename : user_input.hh
// Authors : Creteur Clement
// Last edit : 01/11/09 - 19h14
// Comment : Event that can be interpreted by the input listener. Two kind of
// event (deriving of BaseEvent) : MouseEvent and KeyboardEvent.
// They both have informations about CTRL, ALT and Shift State.
////////////////////////////////////////////////////////////////////////////////
#ifndef USER_INPUT_HH
#define USER_INPUT_HH
#include <SDL/SDL.h>
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
class BaseEvent
{
public:
BaseEvent(bool parUp = false)
: MIsMasked(true),
MIsKeyUp(parUp),
MIsShiftDown(false),
MIsControlDown(false),
MIsAltDown(false)
{}
~BaseEvent() {}
inline void SetKeyStates(bool parShift, bool parControl, bool parAlt)
{
MIsShiftDown = parShift;
MIsControlDown = parControl;
MIsAltDown = parAlt;
}
inline void SetMasked() {MIsMasked = true;}
inline bool IsMasked() const {return MIsMasked;}
inline bool IsKeyUp() const {return MIsKeyUp;}
inline bool IsKeyDown() const {return !MIsKeyUp;}
inline bool IsShiftDown() const {return MIsShiftDown;}
inline bool IsControlDown() const {return MIsControlDown;}
inline bool IsAltDown() const {return MIsAltDown;}
protected:
bool MIsMasked;
bool MIsKeyUp;
bool MIsShiftDown;
bool MIsControlDown;
bool MIsAltDown;
};
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
class KeyboardEvent : public BaseEvent
{
public:
KeyboardEvent(bool parUp, int parVK, Uint8 parSC, Uint16 parUC)
: BaseEvent(parUp),
MVirtualKey(parVK),
MScanCode(parSC),
MUniCode(parUC)
{
}
~KeyboardEvent() {}
inline int GetVirtualKey() const {return MVirtualKey;}
inline Uint8 GetScanCode() const {return MScanCode;}
inline Uint16 GetUniCode() const {return MUniCode;}
private:
int MVirtualKey;
Uint8 MScanCode;
Uint16 MUniCode;
};
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
class MouseEvent : public BaseEvent
{
public:
enum Type
{
EVT_CLICK_MOUSE1,
EVT_CLICK_MOUSE2,
EVT_CLICK_MOUSE3,
EVT_DCLICK_MOUSE1,
EVT_DCLICK_MOUSE2,
EVT_DCLICK_MOUSE3,
EVT_ROLL_UP,
EVT_ROLL_DOWN,
EVT_MOVE
};
MouseEvent(bool parUp, int parX, int parY, Type parType)
: BaseEvent(parUp),
MX(parX),
MY(parY),
MDx(0),
MDy(0),
MType(parType)
{
}
MouseEvent(int parX, int parY, int parDx, int parDy)
: BaseEvent(false),
MX(parX),
MY(parY),
MDx(parDx),
MDy(parDy),
MType(EVT_MOVE)
{
}
~MouseEvent() {}
void Double ()
{
switch(MType)
{
case EVT_CLICK_MOUSE1:
MType = EVT_DCLICK_MOUSE1;
break;
case EVT_CLICK_MOUSE2:
MType = EVT_DCLICK_MOUSE2;
break;
case EVT_CLICK_MOUSE3:
MType = EVT_DCLICK_MOUSE3;
break;
default:
break;
}
}
inline int GetX() const {return MX;}
inline int GetY() const {return MY;}
inline int GetDx() const {return MDx;}
inline int GetDy() const {return MDy;}
inline Type GetType() const {return MType;}
private:
int MX;
int MY;
int MDx;
int MDy;
Type MType;
};
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
#endif
| [
"creteur.c@8e971d8e-9cf3-0c36-aa0f-a7c54ab41ffc"
] | [
[
[
1,
154
]
]
] |
4eea47ed546c51220fe092c0e7ad43aa0cfb945e | 9773c3304eecc308671bcfa16b5390c81ef3b23a | /MDI AIPI V.6.92 2003 ( Correct Save Fired Rules, AM =-1, g_currentLine)/AIPI/CadLib/Interface/VC/CadLib.cpp | 368c01896cff07a86e495acccaf262694ef8ff01 | [] | no_license | 15831944/AiPI-1 | 2d09d6e6bd3fa104d0175cf562bb7826e1ac5ec4 | 9350aea6ac4c7870b43d0a9f992a1908a3c1c4a8 | refs/heads/master | 2021-12-02T20:34:03.136125 | 2011-10-27T00:07:54 | 2011-10-27T00:07:54 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 29,066 | cpp | /*-------------------------------------------------------------------*\
| CadLib Version 2.1 |
| Written by Omid Shahabi <[email protected]> |
| Copyright © 2002-2004 |
| Pars Technology Development Co. |
| |
| This software is distributed on an "AS IS" basis, WITHOUT WARRANTY |
| OF ANY KIND, either express or implied. |
| |
| |
| CadLib.cpp: The interface for CadIO.dll |
\*-------------------------------------------------------------------*/
#include "stdafx.h"
#include "CadLib.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define ISLIBRARYLOADED(); \
if(!isLibraryLoaded) \
{ \
/* Library is not loaded*/ \
return FALSE; \
} \
/********************************************************************
* CDXFFileWrite Class Implementation *
********************************************************************/
// Initialization & UnInitialization -------------------------------
CDxfFileWrite::CDxfFileWrite()
{
bool result;
isLibraryLoaded = true;
// load CadIO.dll
hinstCadIO = LoadLibrary( _T("CadIO.dll") );
if( !hinstCadIO )
{
// Cannot load CadIO.dll
isLibraryLoaded = false;
return;
}
result = true;
result &= ((dxfWriteParamString = (BOOL(*)(HDXF, int, LPCTSTR))
GetProcAddress( hinstCadIO, "dxfWriteParamString" )) != NULL);
result &= ((dxfWriteParamInteger = (BOOL(*)(HDXF, int, int))
GetProcAddress( hinstCadIO, "dxfWriteParamInteger" )) != NULL);
result &= ((dxfWriteParamDouble = (BOOL(*)(HDXF, int, double))
GetProcAddress( hinstCadIO, "dxfWriteParamDouble" )) != NULL);
result &= ((dxfCreateFile = (HDXF(*)(LPCTSTR))
GetProcAddress( hinstCadIO, "dxfCreateFile" )) != NULL);
result &= ((dxfCloseFile = (BOOL(*)(HDXF))
GetProcAddress( hinstCadIO, "dxfCloseFile" )) != NULL);
result &= ((dxfSetCurrentColor = (BOOL(*)(HDXF, int))
GetProcAddress( hinstCadIO, "dxfSetCurrentColor" )) != NULL);
result &= ((dxfSectionBegin = (BOOL(*)(HDXF hDxf, DWORD dwSection))
GetProcAddress( hinstCadIO, "dxfSectionBegin" )) != NULL);
result &= ((dxfSectionEnd = (BOOL(_cdecl*)(HDXF hDxf))
GetProcAddress( hinstCadIO, "dxfSectionEnd" )) != NULL);
result &= ((dxfTableTypeBegin = (BOOL(_cdecl*)(HDXF hDxf, DWORD dwTableType))
GetProcAddress( hinstCadIO, "dxfTableTypeBegin" )) != NULL);
result &= ((dxfTableTypeEnd = (BOOL(_cdecl*)(HDXF hDxf))
GetProcAddress( hinstCadIO, "dxfTableTypeEnd" )) != NULL);
result &= ((dxfAddLayer = (BOOL(_cdecl*)( HDXF hDxf, char* Name, int Color, char* Linetype ))
GetProcAddress( hinstCadIO, "dxfAddLayer" )) != NULL);
result &= ((dxfSetCurrentLayer = (BOOL(_cdecl*)(HDXF hDxf, char* Name, char* LineType))
GetProcAddress( hinstCadIO, "dxfSetCurrentLayer" )) != NULL);
result &= ((dxfAddLinetype = (BOOL(_cdecl*)(HDXF hDxf, PDXFLTYPE pLineType))
GetProcAddress( hinstCadIO, "dxfAddLinetype" )) != NULL);
result &= ((dxfSetCurrentLinetype = (BOOL(_cdecl*)(HDXF hDxf, char* Name))
GetProcAddress( hinstCadIO, "dxfSetCurrentLinetype" )) != NULL);
result &= ((dxfAddTextStyle = (BOOL(_cdecl*)(HDXF hDxf, PDXFSTYLE pTextStyle))
GetProcAddress( hinstCadIO, "dxfAddTextStyle" )) != NULL);
result &= ((dxfSetCurrentTextStyle = (BOOL(_cdecl*)(HDXF hDxf, char* Name))
GetProcAddress( hinstCadIO, "dxfSetCurrentTextStyle" )) != NULL);
result &= ((dxfAddDimStyle = (BOOL(_cdecl*)(HDXF, PDXFDIMSTYLE))
GetProcAddress( hinstCadIO, "dxfAddDimStyle" )) != NULL);
result &= ((dxfSetCurrentDimStyle = (BOOL(_cdecl*)(HDXF, LPCTSTR))
GetProcAddress( hinstCadIO, "dxfSetCurrentDimStyle" )) != NULL);
result &= ((dxfLine = (BOOL(_cdecl*)(HDXF hDxf, double x1, double y1, double x2, double y2))
GetProcAddress( hinstCadIO, "dxfLine" )) != NULL);
result &= ((dxfCircle = (BOOL(_cdecl*)(HDXF hDxf, double cx, double cy, double r))
GetProcAddress( hinstCadIO, "dxfCircle" )) != NULL);
result &= ((dxfSolid = (BOOL(_cdecl*)(HDXF hDxf, REALPOINT& Point0, REALPOINT& Point1, REALPOINT& Point2, REALPOINT& Point3))
GetProcAddress( hinstCadIO, "dxfSolid" )) != NULL);
result &= ((dxfText = (BOOL(_cdecl*)( HDXF hDxf, LPCTSTR Text, double x1, double y1, double x2, double y2, double Height, double Rotation, DWORD Justification, double WidthFactor, LPCTSTR StyleName ))
GetProcAddress( hinstCadIO, "dxfText" )) != NULL);
result &= ((dxfDimLinear = (BOOL(_cdecl*)( HDXF, double, double, double, double, double, double, double, LPCTSTR))
GetProcAddress( hinstCadIO, "dxfDimLinear" )) != NULL);
result &= ((dxfArc = (BOOL(_cdecl*)( HDXF, double, double, double, double, double, double ))
GetProcAddress( hinstCadIO, "dxfArc" )) != NULL);
result &= ((dxfInsertBlock = (BOOL(_cdecl*)( HDXF hDxf, LPCTSTR BlockName, double x, double y, double xScale, double yScale, double Rotation ))
GetProcAddress( hinstCadIO, "dxfInsertBlock" )) != NULL);
result &= ((dxfBlockBegin = (BOOL(_cdecl*)( HDXF hDxf, LPCTSTR BlockName, LPCTSTR LayerName, double bx, double by, char flags ))
GetProcAddress( hinstCadIO, "dxfBlockBegin" )) != NULL);
result &= ((dxfBlockEnd = (BOOL(_cdecl*)( HDXF hDxf ))
GetProcAddress( hinstCadIO, "dxfBlockEnd" )) != NULL);
if(!result)
{
// Cannot load all functions from library
isLibraryLoaded = false;
return;
}
isFileOpen = false;
}
CDxfFileWrite::~CDxfFileWrite()
{
// Close file, if it is opened
if(isFileOpen)
Close();
// Unload CadIO.dll
if(isLibraryLoaded)
FreeLibrary ( hinstCadIO );
isLibraryLoaded = false;
}
// Construction & Destruction -------------------------------------
BOOL CDxfFileWrite::Create( CString filename, bool overwrite )
{
return Create( filename.GetBuffer(512), overwrite );
}
BOOL CDxfFileWrite::Create( TCHAR* filename, bool overwrite )
{
ISLIBRARYLOADED();
if( (m_hDxf=dxfCreateFile( filename ))==NULL )
{
// Cannot create new dxf file
return FALSE;
}
isFileOpen = true;
return TRUE;
}
BOOL CDxfFileWrite::Close( )
{
ISLIBRARYLOADED();
if(dxfCloseFile( m_hDxf ))
{
isFileOpen = false;
return TRUE;
}
else
return FALSE;
}
// Initialization -------------------------------------------------
BOOL CDxfFileWrite::SetCurrentColor( int Color )
{
ISLIBRARYLOADED();
return dxfSetCurrentColor( m_hDxf, Color );
}
// Sections --------------------------------------------------------
BOOL CDxfFileWrite::BeginSection( DWORD dwSection )
{
ISLIBRARYLOADED();
return dxfSectionBegin( m_hDxf, dwSection );
}
BOOL CDxfFileWrite::EndSection( )
{
ISLIBRARYLOADED();
return dxfSectionEnd( m_hDxf );
}
// TABLES section --------------------------------------------------
BOOL CDxfFileWrite::BeginTableType( DWORD dwTableType )
{
ISLIBRARYLOADED();
return dxfTableTypeBegin( m_hDxf, dwTableType );
}
BOOL CDxfFileWrite::EndTableType( )
{
ISLIBRARYLOADED();
return dxfTableTypeEnd( m_hDxf );
}
BOOL CDxfFileWrite::AddLayer( char* Name, int Color, char* Linetype )
{
ISLIBRARYLOADED();
return dxfAddLayer( m_hDxf, Name, Color, Linetype );
}
BOOL CDxfFileWrite::SetCurrentLayer( char* Name, char* LineType )
{
ISLIBRARYLOADED();
return dxfSetCurrentLayer( m_hDxf, Name, LineType );
}
BOOL CDxfFileWrite::AddLinetype( PDXFLTYPE pLineType )
{
ISLIBRARYLOADED();
return dxfAddLinetype( m_hDxf, pLineType );
}
BOOL CDxfFileWrite::SetCurrentLinetype( char* Name )
{
ISLIBRARYLOADED();
return dxfSetCurrentLinetype( m_hDxf, Name );
}
BOOL CDxfFileWrite::AddTextStyle( PDXFSTYLE pTextStyle )
{
ISLIBRARYLOADED();
return dxfAddTextStyle( m_hDxf, pTextStyle );
}
BOOL CDxfFileWrite::SetCurrentTextStyle( char* Name )
{
ISLIBRARYLOADED();
return dxfSetCurrentTextStyle( m_hDxf, Name );
}
BOOL CDxfFileWrite::AddDimStyle( PDXFDIMSTYLE pDimStyle )
{
ISLIBRARYLOADED();
return dxfAddDimStyle( m_hDxf, pDimStyle );
}
BOOL CDxfFileWrite::SetCurrentDimStyle( LPCTSTR Name )
{
ISLIBRARYLOADED();
return dxfSetCurrentDimStyle( m_hDxf, Name );
}
// ENTITIES section ------------------------------------------------
BOOL CDxfFileWrite::Line( double x1, double y1, double x2, double y2 )
{
ISLIBRARYLOADED();
return dxfLine( m_hDxf, x1, y1, x2, y2 );
}
BOOL CDxfFileWrite::Circle( double cx, double cy, double r )
{
ISLIBRARYLOADED();
return dxfCircle( m_hDxf, cx, cy, r );
}
BOOL CDxfFileWrite::Solid( int PointsNum, PREALPOINT Points )
{
ISLIBRARYLOADED();
if(PointsNum==3)
return dxfSolid( m_hDxf, Points[0], Points[1], Points[2], Points[2] );
else if(PointsNum==4)
return dxfSolid( m_hDxf, Points[0], Points[1], Points[2], Points[3] );
else
return FALSE;
}
BOOL CDxfFileWrite::Text( LPCTSTR Text, double x1, double y1, double x2, double y2, double Height, DWORD Justification, double Rotation, double WidthFactor, LPCTSTR StyleName )
{
ISLIBRARYLOADED();
return dxfText( m_hDxf, Text, x1, y1, x2, y2, Height, Rotation, Justification, WidthFactor, StyleName );
}
BOOL CDxfFileWrite::Text( LPCTSTR Text, double x, double y, double Height, double Rotation, double WidthFactor, LPCTSTR StyleName )
{
ISLIBRARYLOADED();
return dxfText( m_hDxf, Text, x, y, x, y, Height, Rotation, TJ_LEFT, WidthFactor, StyleName );
}
BOOL CDxfFileWrite::DimLinear( double x1, double y1, double x2, double y2, double x3, double y3, double angle, LPCTSTR text )
{
ISLIBRARYLOADED();
return dxfDimLinear( m_hDxf, x1, y1, x2, y2, x3, y3, angle, text );
}
BOOL CDxfFileWrite::Arc( double cx, double cy, double r, double StartAngle, double EndAngle, double Thickness )
{
ISLIBRARYLOADED();
return dxfArc( m_hDxf, cx, cy, r, StartAngle, EndAngle, Thickness );
}
BOOL CDxfFileWrite::InsertBlock( LPCTSTR BlockName, double x, double y, double xScale, double yScale, double Rotation )
{
ISLIBRARYLOADED();
return dxfInsertBlock( m_hDxf, BlockName, x, y, xScale, yScale, Rotation );
}
// BLOCKS section --------------------------------------------------
BOOL CDxfFileWrite::BlockBegin( LPCTSTR BlockName, LPCTSTR LayerName, double bx, double by, char flags )
{
ISLIBRARYLOADED();
return dxfBlockBegin( m_hDxf, BlockName, LayerName, bx, by, flags );
}
BOOL CDxfFileWrite::BlockEnd()
{
ISLIBRARYLOADED();
return dxfBlockEnd( m_hDxf );
}
// Base Functions --------------------------------------------------
CDxfFileWrite::WriteParameter( int GroupCode, LPCTSTR Value )
{
ISLIBRARYLOADED();
return dxfWriteParamString( m_hDxf, GroupCode, Value );
}
CDxfFileWrite::WriteParameter( int GroupCode, double Value )
{
ISLIBRARYLOADED();
return dxfWriteParamDouble( m_hDxf, GroupCode, Value );
}
CDxfFileWrite::WriteParameter( int GroupCode, int Value )
{
ISLIBRARYLOADED();
return dxfWriteParamInteger( m_hDxf, GroupCode, Value );
}
/********************************************************************
* CDrawing Class Implementation *
********************************************************************/
// Initialization & UnInitialization -------------------------------
CDrawing::CDrawing()
{
bool result;
m_hDrawing = NULL;
isLibraryLoaded = true;
// load CadIO.dll
hinstCadIO = LoadLibrary( _T("CadIO.dll") );
if( !hinstCadIO )
{
// Cannot load CadIO.dll
isLibraryLoaded = false;
return;
}
result = true;
// Construction & Destruction
result &= ((drwCreate = (HDRAWING(*)())
GetProcAddress( hinstCadIO, "drwCreate" )) != NULL);
result &= ((drwDestroy = (BOOL(*)(HDRAWING))
GetProcAddress( hinstCadIO, "drwDestroy" )) != NULL);
// TABLES
result &= ((drwAddTableType = (OBJHANDLE(*)(HDRAWING, DWORD, LPVOID))
GetProcAddress( hinstCadIO, "drwAddTableType" )) != NULL);
result &= ((drwDeleteTableType = (BOOL(*)(HDRAWING, DWORD, OBJHANDLE))
GetProcAddress( hinstCadIO, "drwDeleteTableType" )) != NULL);
result &= ((drwFindTableType = (OBJHANDLE(*)(HDRAWING, DWORD, DWORD, LPVOID))
GetProcAddress( hinstCadIO, "drwFindTableType" )) != NULL);
// BLOCKS
result &= ((drwAddBlock = (OBJHANDLE(*)(HDRAWING, PBLOCKHEADER))
GetProcAddress( hinstCadIO, "drwAddBlock" )) != NULL);
result &= ((drwDeleteBlock = (BOOL(*)(HDRAWING, OBJHANDLE))
GetProcAddress( hinstCadIO, "drwDeleteBlock" )) != NULL);
result &= ((drwFindBlock = (OBJHANDLE(*)(HDRAWING, DWORD, PBLOCKHEADER))
GetProcAddress( hinstCadIO, "drwFindBlock" )) != NULL);
// ENTITIES
result &= ((drwAddEntity = (OBJHANDLE(*)(HDRAWING, OBJHANDLE, PENTITYHEADER, LPVOID))
GetProcAddress( hinstCadIO, "drwAddEntity" )) != NULL);
result &= ((drwDeleteEntity = (BOOL(*)(HDRAWING, LPCTSTR, OBJHANDLE))
GetProcAddress( hinstCadIO, "drwDeleteEntity" )) != NULL);
result &= ((drwChangeEntity = (BOOL(*)(HDRAWING, LPCTSTR, PENTITYHEADER, LPVOID))
GetProcAddress( hinstCadIO, "drwChangeEntity" )) != NULL);
result &= ((drwFindEntity = (OBJHANDLE(*)(HDRAWING, LPCTSTR, PENTITYHEADER, LPVOID, DWORD))
GetProcAddress( hinstCadIO, "drwFindEntity" )) != NULL);
// Datafile dataexchange
result &= ((drwSaveDataToFile = (BOOL(*)(HDRAWING, DWORD, LPCTSTR, HWND))
GetProcAddress( hinstCadIO, "drwSaveDataToFile" )) != NULL);
result &= ((drwLoadDataFromFile = (BOOL(*)(HDRAWING, OBJHANDLE, DWORD, LPCTSTR, HWND))
GetProcAddress( hinstCadIO, "drwLoadDataFromFile" )) != NULL);
// Drawing Window View
result &= ((drwInitView = (BOOL(*)(HDRAWING, int, int, int, int))
GetProcAddress( hinstCadIO, "drwInitView" )) != NULL);
result &= ((drwPaint = (BOOL(*)(HDRAWING, HDC))
GetProcAddress( hinstCadIO, "drwPaint" )) != NULL);
result &= ((drwGetViewProperties = (BOOL(*)(HDRAWING, PVIEW))
GetProcAddress( hinstCadIO, "drwGetViewProperties" )) != NULL);
result &= ((drwSetViewProperties = (BOOL(*)(HDRAWING, PVIEW))
GetProcAddress( hinstCadIO, "drwSetViewProperties" )) != NULL);
result &= ((drwGetDrawingBorder = (BOOL(*)(HDRAWING, PREALRECT))
GetProcAddress( hinstCadIO, "drwGetDrawingBorder" )) != NULL);
result &= ((drwZoomExtents = (BOOL(*)(HDRAWING))
GetProcAddress( hinstCadIO, "drwZoomExtents" )) != NULL);
if(!result)
{
// Cannot load all functions from library
isLibraryLoaded = false;
return;
}
}
CDrawing::~CDrawing()
{
if(m_hDrawing!=NULL)
Destroy();
// Unload CadIO.dll
if(isLibraryLoaded)
FreeLibrary ( hinstCadIO );
isLibraryLoaded = false;
}
BOOL CDrawing::isOpen()
{
if((!isLibraryLoaded) || (m_hDrawing==NULL))
return FALSE;
else
return TRUE;
}
// Construction & Destruction -------------------------------------
BOOL CDrawing::Create( )
{
ISLIBRARYLOADED();
if(m_hDrawing!=NULL)
{
// Drawing is already created
return FALSE;
}
if((m_hDrawing = drwCreate())!=NULL)
{
m_EntityHeader.LayerObjhandle = CurrentLayerObjhandle = 0;// Layer 0
m_EntityHeader.LTypeObjhandle = CurrentLTypeObjhandle = 0;// ByLayer
m_EntityHeader.Color = CurrentColor = 256; // ByLayer
m_EntityHeader.Thickness = CurrentThickness = 0;
m_EntityHeader.LineTypeScale = 1.0;
CurrentDimStyleObjhandle = 0;
CurrentStyleObjhandle = 0;
ActiveBlockObjhandle = 0; // Entities section
}
return (m_hDrawing!=NULL);
}
BOOL CDrawing::Destroy( )
{
BOOL result;
ISLIBRARYLOADED();
result = drwDestroy(m_hDrawing);
if(result)
m_hDrawing = NULL;
return result;
}
// Drawing View
BOOL CDrawing::InitView( int x, int y, int nWidth, int nHeight )
{
ISLIBRARYLOADED();
if(m_hDrawing!=NULL)
return drwInitView(m_hDrawing, x, y, nWidth, nHeight);
else
return NULL;
}
BOOL CDrawing::Paint( HDC hdc )
{
ISLIBRARYLOADED();
return drwPaint(m_hDrawing, hdc );
}
double CDrawing::GetZoomLevel( )
{
ISLIBRARYLOADED();
VIEW drwview;
if(drwGetViewProperties(m_hDrawing, &drwview))
return drwview.ZoomLevel;
else
return 0;
}
BOOL CDrawing::SetZoomLevel(double ZoomLevel)
{
ISLIBRARYLOADED();
VIEW drwview;
if(drwGetViewProperties(m_hDrawing, &drwview))
{
double cx;
double cy;
cx = drwview.ViewLeft + ((drwview.WindowRight-drwview.WindowLeft)/2)*(1/(drwview.PPU*drwview.ZoomLevel));
cy = drwview.ViewBottom + ((drwview.WindowBottom-drwview.WindowTop)/2)*(1/(drwview.PPU*drwview.ZoomLevel));
drwview.ZoomLevel = ZoomLevel;
drwview.ViewLeft = cx - ((drwview.WindowRight-drwview.WindowLeft)/2)*(1/(drwview.PPU*drwview.ZoomLevel));
drwview.ViewBottom = cy - ((drwview.WindowBottom-drwview.WindowTop)/2)*(1/(drwview.PPU*drwview.ZoomLevel));
if(drwSetViewProperties(m_hDrawing, &drwview))
return TRUE;
}
return FALSE;
}
BOOL CDrawing::GetViewProperties( PVIEW pView )
{
ISLIBRARYLOADED();
return drwGetViewProperties(m_hDrawing, pView);
}
BOOL CDrawing::SetViewProperties( PVIEW pView )
{
ISLIBRARYLOADED();
return drwSetViewProperties(m_hDrawing, pView);
}
BOOL CDrawing::GetDrawingBorder( PREALRECT pRect )
{
ISLIBRARYLOADED();
return drwGetDrawingBorder(m_hDrawing, pRect);
}
BOOL CDrawing::ZoomExtents( )
{
ISLIBRARYLOADED();
return drwZoomExtents(m_hDrawing);
}
// Configuration ---------------------------------------------------
BOOL CDrawing::SetLayer( LPCTSTR Name )
{
LAYER Layer;
TCHAR *LayerName = (TCHAR*)Layer.Name;
_tcscpy(LayerName, Name);
if(drwFindTableType(m_hDrawing, TAB_LAYER, FIND_BYNAME, &Layer)>0)
{
CurrentLayerObjhandle = Layer.Objhandle;
m_EntityHeader.LayerObjhandle = CurrentLayerObjhandle;
SetLineType(NULL); // Set linetype to default
return TRUE;
}
else
return FALSE;
}
BOOL CDrawing::SetLineType( LPCTSTR Name )
{
LTYPE LType;
// Check for default linetype
if(Name==NULL)
{
CurrentLTypeObjhandle = 0;
m_EntityHeader.LTypeObjhandle = 0;
return TRUE;
}
TCHAR *LTypeName = (TCHAR*)LType.Name;
_tcscpy(LTypeName, Name);
if(drwFindTableType(m_hDrawing, TAB_LTYPE, FIND_BYNAME, <ype)>0)
{
CurrentLTypeObjhandle = LType.Objhandle;
m_EntityHeader.LTypeObjhandle = CurrentLTypeObjhandle;
return TRUE;
}
else
return FALSE;
}
BOOL CDrawing::SetTextStyle( LPCTSTR Name )
{
STYLE Style;
TCHAR *StyleName = (TCHAR*)Style.Name;
_tcscpy(StyleName, Name);
if(drwFindTableType(m_hDrawing, TAB_STYLE, FIND_BYNAME, &Style)>0)
{
CurrentStyleObjhandle = Style.Objhandle;
return TRUE;
}
else
return FALSE;
}
BOOL CDrawing::SetDimStyle( LPCTSTR Name )
{
DIMSTYLE DimStyle;
TCHAR *DimStyleName = (TCHAR*)DimStyle.Name;
_tcscpy(DimStyleName, Name);
if(drwFindTableType(m_hDrawing, TAB_DIMSTYLE, FIND_BYNAME, &DimStyle)>0)
{
CurrentDimStyleObjhandle = DimStyle.Objhandle;
return TRUE;
}
else
return FALSE;
}
BOOL CDrawing::SetColor( short Color )
{
CurrentColor = Color;
m_EntityHeader.Color = CurrentColor;
return TRUE;
}
BOOL CDrawing::SetThickness( double Thickness )
{
CurrentThickness = Thickness;
m_EntityHeader.Thickness = CurrentThickness;
return TRUE;
}
double CDrawing::SetLineTypeScale( double LineTypeScale )
{
double prevLineTypeScale = m_EntityHeader.LineTypeScale;
m_EntityHeader.LineTypeScale = LineTypeScale;
return prevLineTypeScale;
}
// TABLES ----------------------------------------------------------
OBJHANDLE CDrawing::AddTableType( DWORD dwTableType, LPVOID pTableType )
{
ISLIBRARYLOADED();
return drwAddTableType(m_hDrawing, dwTableType, pTableType);
}
OBJHANDLE CDrawing::AddLayer( PLAYER pLayer )
{
return AddTableType(TAB_LAYER, pLayer);
}
OBJHANDLE CDrawing::AddLinetype( PLTYPE pLineType )
{
return AddTableType(TAB_LTYPE, pLineType);
}
OBJHANDLE CDrawing::AddTextStyle( PSTYLE pTextStyle )
{
return AddTableType(TAB_STYLE, pTextStyle);
}
OBJHANDLE CDrawing::AddDimStyle( PDIMSTYLE pDimStyle )
{
return AddTableType(TAB_DIMSTYLE, pDimStyle);
}
BOOL CDrawing::DeleteTableType( DWORD dwTableType, OBJHANDLE TableTypeObjhandle )
{
ISLIBRARYLOADED();
return drwDeleteTableType(m_hDrawing, dwTableType, TableTypeObjhandle);
}
BOOL CDrawing::DeleteLayer( OBJHANDLE LayerObjhandle )
{
return DeleteTableType(TAB_LAYER, LayerObjhandle);
}
BOOL CDrawing::DeleteLinetype( OBJHANDLE LineTypeObjhandle )
{
return DeleteTableType(TAB_LTYPE, LineTypeObjhandle);
}
BOOL CDrawing::DeleteTextStyle( OBJHANDLE TextStyleObjhandle )
{
return DeleteTableType(TAB_STYLE, TextStyleObjhandle);
}
BOOL CDrawing::DeleteDimStyle( OBJHANDLE DimStyleObjhandle )
{
return DeleteTableType(TAB_DIMSTYLE, DimStyleObjhandle);
}
OBJHANDLE CDrawing::FindTableType( DWORD dwTableType, DWORD dwFindType, LPVOID pTableType )
{
ISLIBRARYLOADED();
return drwFindTableType(m_hDrawing, dwTableType, dwFindType, pTableType);
}
// BLOCKS ----------------------------------------------------------
OBJHANDLE CDrawing::AddBlock( PBLOCKHEADER pBlockHeader, LPCTSTR strFileName )
{
OBJHANDLE result;
ISLIBRARYLOADED();
result = drwAddBlock(m_hDrawing, pBlockHeader);
if((strFileName!=NULL) && result)
drwLoadDataFromFile(m_hDrawing, result, 0, strFileName, NULL);
return result;
}
BOOL CDrawing::DeleteBlock( OBJHANDLE BlockObjhandle )
{
ISLIBRARYLOADED();
return drwDeleteBlock(m_hDrawing, BlockObjhandle);
}
OBJHANDLE CDrawing::FindBlock( DWORD dwFindType, PBLOCKHEADER pBlockHeader )
{
ISLIBRARYLOADED();
return drwFindBlock(m_hDrawing, dwFindType, pBlockHeader );
}
BOOL CDrawing::SetActiveBlock( OBJHANDLE ohBlock )
{
ISLIBRARYLOADED();
if(ohBlock==NULL)
ActiveBlockObjhandle = NULL; // Entities section is active now
else
{
BLOCKHEADER BlockHeader;
OBJHANDLE ohBlockHeader;
BlockHeader.Objhandle = ohBlock;
ohBlockHeader = drwFindBlock(m_hDrawing, FIND_BYHANDLE, &BlockHeader);
if(ohBlockHeader==0) // Block Not Found
return FALSE;
else
ActiveBlockObjhandle = ohBlockHeader;
}
return TRUE;
}
BOOL CDrawing::SetActiveBlock( LPCTSTR strBlockName )
{
ISLIBRARYLOADED();
if(strBlockName==NULL)
ActiveBlockObjhandle = NULL; // Entities section is active now
else
{
BLOCKHEADER BlockHeader;
OBJHANDLE ohBlockHeader;
TCHAR *BlockHeaderName = (TCHAR*)BlockHeader.Name;
_tcscpy(BlockHeaderName, strBlockName);
ohBlockHeader = drwFindBlock(m_hDrawing, FIND_BYNAME, &BlockHeader);
if(ohBlockHeader==0) // Block Not Found
return FALSE;
else
ActiveBlockObjhandle = ohBlockHeader;
}
return TRUE;
}
OBJHANDLE CDrawing::GetActiveBlock( )
{
ISLIBRARYLOADED();
return ActiveBlockObjhandle;
}
// ENTITIES --------------------------------------------------------
OBJHANDLE CDrawing::AddEntity( OBJHANDLE BlockObjhandle, PENTITYHEADER pEntityHeader, LPVOID pEntityData )
{
ISLIBRARYLOADED();
return drwAddEntity(m_hDrawing, BlockObjhandle, pEntityHeader, pEntityData);
}
BOOL CDrawing::DeleteEntity( LPCTSTR strBlockName, OBJHANDLE EntityObjhandle )
{
ISLIBRARYLOADED();
return drwDeleteEntity(m_hDrawing, strBlockName, EntityObjhandle);
}
BOOL CDrawing::ChangeEntity( PENTITYHEADER pEntityHeader, LPVOID pEntityData, LPCTSTR strBlockName )
{
ISLIBRARYLOADED();
return drwChangeEntity(m_hDrawing, strBlockName, pEntityHeader, pEntityData);
}
OBJHANDLE CDrawing::FindEntity( DWORD dwFindType, PENTITYHEADER pEntityHeader, LPVOID pEntityData, LPCTSTR strBlockName )
{
ISLIBRARYLOADED();
return drwFindEntity(m_hDrawing, strBlockName, pEntityHeader, pEntityData, dwFindType);
}
OBJHANDLE CDrawing::Arc( double cx, double cy, double r, double StartAngle, double EndAngle )
{
ENTARC arc;
arc.Point0.x = cx;
arc.Point0.y = cy;
arc.Radius = r;
arc.StartAngle = StartAngle;
arc.EndAngle = EndAngle;
m_EntityHeader.EntityType = ENT_ARC;
return AddEntity(ActiveBlockObjhandle, &m_EntityHeader, &arc);
}
OBJHANDLE CDrawing::Circle( double cx, double cy, double r )
{
ENTCIRCLE circle;
circle.Point0.x = cx;
circle.Point0.y = cy;
circle.Radius = r;
m_EntityHeader.EntityType = ENT_CIRCLE;
return AddEntity(ActiveBlockObjhandle, &m_EntityHeader, &circle);
}
/*OBJHANDLE CDrawing::Ellipse( double cx, double cy, double ex, double ey, double Ratio, double StartParam, double EndParam )
{
ENTELLIPSE ellipse;
ellipse.CenterPoint.x = cx;
ellipse.CenterPoint.y = cy;
ellipse.MajorAxisEndPoint.x = ex;
ellipse.MajorAxisEndPoint.y = ey;
ellipse.MinorToMajorRatio = Ratio;
ellipse.StartParam = StartParam;
ellipse.EndParam = EndParam;
m_EntityHeader.EntityType = ENT_ELLIPSE;
return AddEntity(ActiveBlockObjhandle, &m_EntityHeader, &ellipse);
}
*/
OBJHANDLE CDrawing::DimLinear( double x1, double y1, double x2, double y2, double x3, double y3, double angle, LPCTSTR text )
{
ENTDIMENSION dimension;
TCHAR *dimensionDimText = (TCHAR*)dimension.DimText;
ZeroMemory(&dimension, sizeof(ENTDIMENSION));
dimension.DefPoint3.x = x1;
dimension.DefPoint3.y = y1;
dimension.DefPoint4.x = x2;
dimension.DefPoint4.y = y2;
dimension.DimLineDefPoint.x = x3;
dimension.DimLineDefPoint.y = y3;
dimension.DimRotationAngle = angle;
_tcscpy(dimensionDimText, text);
dimension.DimStyleObjhandle = CurrentDimStyleObjhandle;
m_EntityHeader.EntityType = ENT_DIMENSION;
return AddEntity(ActiveBlockObjhandle, &m_EntityHeader, &dimension);
}
OBJHANDLE CDrawing::InsertBlock( OBJHANDLE BlockObjhandle, double x, double y, double xScale, double yScale, double Rotation )
{
ENTINSERT insert;
insert.BlockHeaderObjhandle = BlockObjhandle;
insert.Point0.x = x;
insert.Point0.y = y;
insert.XScale = xScale;
insert.YScale = yScale;
insert.RotationAngle = Rotation;
m_EntityHeader.EntityType = ENT_INSERT;
return AddEntity(ActiveBlockObjhandle, &m_EntityHeader, &insert);
}
OBJHANDLE CDrawing::InsertBlock( LPCTSTR BlockName, double x, double y, double xScale, double yScale, double Rotation )
{
BLOCKHEADER BlockHeader;
OBJHANDLE BlockHandle;
TCHAR *BlockHeaderName = (TCHAR*)BlockHeader.Name;
_tcscpy(BlockHeaderName, BlockName);
BlockHandle = drwFindBlock(m_hDrawing, FIND_BYNAME, &BlockHeader);
if(BlockHandle==0) // Block Not Found
return 0;
else
return InsertBlock( BlockHandle, x, y, xScale, yScale, Rotation );
}
OBJHANDLE CDrawing::Line( double x1, double y1, double x2, double y2 )
{
ENTLINE line;
line.Point0.x = x1;
line.Point0.y = y1;
line.Point1.x = x2;
line.Point1.y = y2;
m_EntityHeader.EntityType = ENT_LINE;
return AddEntity(ActiveBlockObjhandle, &m_EntityHeader, &line);
}
OBJHANDLE CDrawing::Solid( REALPOINT &Point0, REALPOINT &Point1, REALPOINT &Point2, REALPOINT &Point3 )
{
ENTSOLID solid;
solid.Point0 = Point0;
solid.Point1 = Point1;
solid.Point2 = Point2;
solid.Point3 = Point3;
m_EntityHeader.EntityType = ENT_SOLID;
return AddEntity(ActiveBlockObjhandle, &m_EntityHeader, &solid);
}
OBJHANDLE CDrawing::Text( LPCTSTR Text, double x1, double y1, double x2, double y2, double Height, short Justification, double Rotation, double WidthFactor )
{
ENTTEXT text;
TCHAR *textstrText = (TCHAR*)text.strText;
text.Point0.x = x1;
text.Point0.y = y1;
_tcscpy(textstrText, Text);
text.TextData.Height = Height;
text.TextData.RotationAngle = Rotation;
text.TextData.WidthFactor = WidthFactor;
// double Oblique;
// char GenerationFlag;
text.TextData.Justification = Justification;
text.TextData.SecondAlignmentPoint.x = x2;
text.TextData.SecondAlignmentPoint.y = y2;
text.TextData.TextStyleObjhandle = CurrentStyleObjhandle;
m_EntityHeader.EntityType = ENT_TEXT;
return AddEntity(ActiveBlockObjhandle, &m_EntityHeader, &text);
}
OBJHANDLE CDrawing::Text( LPCTSTR Text, double x, double y, double Height, double Rotation, double WidthFactor )
{
return this->Text(Text, x, y, x, y, Height, TJ_LEFT, Rotation, WidthFactor);
}
OBJHANDLE CDrawing::PolyLine( PENTVERTEX pVertex, int nVertex, unsigned short Flag )
{
ENTPOLYLINE polyline;
polyline.pVertex = pVertex;
polyline.nVertex = nVertex;
polyline.Flag = Flag;
m_EntityHeader.EntityType = ENT_POLYLINE;
return AddEntity(ActiveBlockObjhandle, &m_EntityHeader, &polyline);
}
// Datafile data-exchange ------------------------------------------
BOOL CDrawing::SaveDXFFile( LPCTSTR FileName, HWND hWndProgress )
{
ISLIBRARYLOADED();
return drwSaveDataToFile(m_hDrawing, 0, FileName, hWndProgress);
}
BOOL CDrawing::LoadDXFFile( LPCTSTR FileName, HWND hWndProgress )
{
ISLIBRARYLOADED();
return drwLoadDataFromFile(m_hDrawing, NULL, 0, FileName, hWndProgress);
}
| [
"[email protected]"
] | [
[
[
1,
945
]
]
] |
5db3202de8afd965af1da71f08b9cd6997f46676 | f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0 | /Depend/MyGUI/Wrappers/MyGUI.Managed/Generate/MyGUI.Managed_WidgetEvent.h | 3926c5517c198c63502998887ccbcf6dc4eb5045 | [] | 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 | 23,534 | h | /*!
@file
@author Generate utility by Albert Semenov
@date 01/2009
@module
*/
#pragma once
#include "MyGUI.Managed_WidgetUserData.h"
namespace MyGUI
{
namespace Managed
{
public ref class WidgetEvent abstract : public WidgetUserData
{
private:
typedef MyGUI::Widget ThisType;
public:
WidgetEvent() : WidgetUserData() { }
internal:
WidgetEvent( MyGUI::Widget* _native ) : WidgetUserData(_native) { }
//InsertPoint
public:
delegate void HandleChangeProperty(
Convert<MyGUI::Widget *>::Type _sender ,
Convert<const std::string &>::Type _key ,
Convert<const std::string &>::Type _value );
event HandleChangeProperty^ EventChangeProperty
{
void add(HandleChangeProperty^ _value)
{
mDelegateChangeProperty += _value;
MMYGUI_CHECK_NATIVE(mNative);
static_cast<ThisType*>(mNative)->eventChangeProperty =
static_cast< MyGUI::delegates::IDelegate3<
MyGUI::Widget * ,
const std::string & ,
const std::string & > *>(
new Delegate3< HandleChangeProperty^ ,
MyGUI::Widget * ,
const std::string & ,
const std::string & >(mDelegateChangeProperty) );
}
void remove(HandleChangeProperty^ _value)
{
mDelegateChangeProperty -= _value;
MMYGUI_CHECK_NATIVE(mNative);
if (mDelegateChangeProperty == nullptr)
static_cast<ThisType*>(mNative)->eventChangeProperty = nullptr;
else
static_cast<ThisType*>(mNative)->eventChangeProperty =
static_cast< MyGUI::delegates::IDelegate3<
MyGUI::Widget * ,
const std::string & ,
const std::string & > *>(
new Delegate3< HandleChangeProperty^ ,
MyGUI::Widget * ,
const std::string & ,
const std::string & >(mDelegateChangeProperty) );
}
}
private:
HandleChangeProperty^ mDelegateChangeProperty;
public:
delegate void HandleActionInfo(
Convert<MyGUI::Widget *>::Type _sender ,
Convert<const std::string &>::Type _key ,
Convert<const std::string &>::Type _value );
event HandleActionInfo^ EventActionInfo
{
void add(HandleActionInfo^ _value)
{
mDelegateActionInfo += _value;
MMYGUI_CHECK_NATIVE(mNative);
static_cast<ThisType*>(mNative)->eventActionInfo =
static_cast< MyGUI::delegates::IDelegate3<
MyGUI::Widget * ,
const std::string & ,
const std::string & > *>(
new Delegate3< HandleActionInfo^ ,
MyGUI::Widget * ,
const std::string & ,
const std::string & >(mDelegateActionInfo) );
}
void remove(HandleActionInfo^ _value)
{
mDelegateActionInfo -= _value;
MMYGUI_CHECK_NATIVE(mNative);
if (mDelegateActionInfo == nullptr)
static_cast<ThisType*>(mNative)->eventActionInfo = nullptr;
else
static_cast<ThisType*>(mNative)->eventActionInfo =
static_cast< MyGUI::delegates::IDelegate3<
MyGUI::Widget * ,
const std::string & ,
const std::string & > *>(
new Delegate3< HandleActionInfo^ ,
MyGUI::Widget * ,
const std::string & ,
const std::string & >(mDelegateActionInfo) );
}
}
private:
HandleActionInfo^ mDelegateActionInfo;
public:
delegate void HandleToolTip(
Convert<MyGUI::Widget *>::Type _sender ,
Convert<const MyGUI::ToolTipInfo &>::Type _info );
event HandleToolTip^ EventToolTip
{
void add(HandleToolTip^ _value)
{
mDelegateToolTip += _value;
MMYGUI_CHECK_NATIVE(mNative);
static_cast<ThisType*>(mNative)->eventToolTip =
static_cast< MyGUI::delegates::IDelegate2<
MyGUI::Widget * ,
const MyGUI::ToolTipInfo & > *>(
new Delegate2< HandleToolTip^ ,
MyGUI::Widget * ,
const MyGUI::ToolTipInfo & >(mDelegateToolTip) );
}
void remove(HandleToolTip^ _value)
{
mDelegateToolTip -= _value;
MMYGUI_CHECK_NATIVE(mNative);
if (mDelegateToolTip == nullptr)
static_cast<ThisType*>(mNative)->eventToolTip = nullptr;
else
static_cast<ThisType*>(mNative)->eventToolTip =
static_cast< MyGUI::delegates::IDelegate2<
MyGUI::Widget * ,
const MyGUI::ToolTipInfo & > *>(
new Delegate2< HandleToolTip^ ,
MyGUI::Widget * ,
const MyGUI::ToolTipInfo & >(mDelegateToolTip) );
}
}
private:
HandleToolTip^ mDelegateToolTip;
public:
delegate void HandleRootKeyChangeFocus(
Convert<MyGUI::Widget *>::Type _sender ,
Convert<bool>::Type _focus );
event HandleRootKeyChangeFocus^ EventRootKeyChangeFocus
{
void add(HandleRootKeyChangeFocus^ _value)
{
mDelegateRootKeyChangeFocus += _value;
MMYGUI_CHECK_NATIVE(mNative);
static_cast<ThisType*>(mNative)->eventRootKeyChangeFocus =
static_cast< MyGUI::delegates::IDelegate2<
MyGUI::Widget * ,
bool > *>(
new Delegate2< HandleRootKeyChangeFocus^ ,
MyGUI::Widget * ,
bool >(mDelegateRootKeyChangeFocus) );
}
void remove(HandleRootKeyChangeFocus^ _value)
{
mDelegateRootKeyChangeFocus -= _value;
MMYGUI_CHECK_NATIVE(mNative);
if (mDelegateRootKeyChangeFocus == nullptr)
static_cast<ThisType*>(mNative)->eventRootKeyChangeFocus = nullptr;
else
static_cast<ThisType*>(mNative)->eventRootKeyChangeFocus =
static_cast< MyGUI::delegates::IDelegate2<
MyGUI::Widget * ,
bool > *>(
new Delegate2< HandleRootKeyChangeFocus^ ,
MyGUI::Widget * ,
bool >(mDelegateRootKeyChangeFocus) );
}
}
private:
HandleRootKeyChangeFocus^ mDelegateRootKeyChangeFocus;
public:
delegate void HandleRootMouseChangeFocus(
Convert<MyGUI::Widget *>::Type _sender ,
Convert<bool>::Type _focus );
event HandleRootMouseChangeFocus^ EventRootMouseChangeFocus
{
void add(HandleRootMouseChangeFocus^ _value)
{
mDelegateRootMouseChangeFocus += _value;
MMYGUI_CHECK_NATIVE(mNative);
static_cast<ThisType*>(mNative)->eventRootMouseChangeFocus =
static_cast< MyGUI::delegates::IDelegate2<
MyGUI::Widget * ,
bool > *>(
new Delegate2< HandleRootMouseChangeFocus^ ,
MyGUI::Widget * ,
bool >(mDelegateRootMouseChangeFocus) );
}
void remove(HandleRootMouseChangeFocus^ _value)
{
mDelegateRootMouseChangeFocus -= _value;
MMYGUI_CHECK_NATIVE(mNative);
if (mDelegateRootMouseChangeFocus == nullptr)
static_cast<ThisType*>(mNative)->eventRootMouseChangeFocus = nullptr;
else
static_cast<ThisType*>(mNative)->eventRootMouseChangeFocus =
static_cast< MyGUI::delegates::IDelegate2<
MyGUI::Widget * ,
bool > *>(
new Delegate2< HandleRootMouseChangeFocus^ ,
MyGUI::Widget * ,
bool >(mDelegateRootMouseChangeFocus) );
}
}
private:
HandleRootMouseChangeFocus^ mDelegateRootMouseChangeFocus;
public:
delegate void HandleKeyButtonReleased(
Convert<MyGUI::Widget *>::Type _sender ,
Convert<MyGUI::KeyCode>::Type _key );
event HandleKeyButtonReleased^ EventKeyButtonReleased
{
void add(HandleKeyButtonReleased^ _value)
{
mDelegateKeyButtonReleased += _value;
MMYGUI_CHECK_NATIVE(mNative);
static_cast<ThisType*>(mNative)->eventKeyButtonReleased =
static_cast< MyGUI::delegates::IDelegate2<
MyGUI::Widget * ,
MyGUI::KeyCode > *>(
new Delegate2< HandleKeyButtonReleased^ ,
MyGUI::Widget * ,
MyGUI::KeyCode >(mDelegateKeyButtonReleased) );
}
void remove(HandleKeyButtonReleased^ _value)
{
mDelegateKeyButtonReleased -= _value;
MMYGUI_CHECK_NATIVE(mNative);
if (mDelegateKeyButtonReleased == nullptr)
static_cast<ThisType*>(mNative)->eventKeyButtonReleased = nullptr;
else
static_cast<ThisType*>(mNative)->eventKeyButtonReleased =
static_cast< MyGUI::delegates::IDelegate2<
MyGUI::Widget * ,
MyGUI::KeyCode > *>(
new Delegate2< HandleKeyButtonReleased^ ,
MyGUI::Widget * ,
MyGUI::KeyCode >(mDelegateKeyButtonReleased) );
}
}
private:
HandleKeyButtonReleased^ mDelegateKeyButtonReleased;
public:
delegate void HandleKeyButtonPressed(
Convert<MyGUI::Widget *>::Type _sender ,
Convert<MyGUI::KeyCode>::Type _key ,
Convert<unsigned int>::Type _char );
event HandleKeyButtonPressed^ EventKeyButtonPressed
{
void add(HandleKeyButtonPressed^ _value)
{
mDelegateKeyButtonPressed += _value;
MMYGUI_CHECK_NATIVE(mNative);
static_cast<ThisType*>(mNative)->eventKeyButtonPressed =
static_cast< MyGUI::delegates::IDelegate3<
MyGUI::Widget * ,
MyGUI::KeyCode ,
unsigned int > *>(
new Delegate3< HandleKeyButtonPressed^ ,
MyGUI::Widget * ,
MyGUI::KeyCode ,
unsigned int >(mDelegateKeyButtonPressed) );
}
void remove(HandleKeyButtonPressed^ _value)
{
mDelegateKeyButtonPressed -= _value;
MMYGUI_CHECK_NATIVE(mNative);
if (mDelegateKeyButtonPressed == nullptr)
static_cast<ThisType*>(mNative)->eventKeyButtonPressed = nullptr;
else
static_cast<ThisType*>(mNative)->eventKeyButtonPressed =
static_cast< MyGUI::delegates::IDelegate3<
MyGUI::Widget * ,
MyGUI::KeyCode ,
unsigned int > *>(
new Delegate3< HandleKeyButtonPressed^ ,
MyGUI::Widget * ,
MyGUI::KeyCode ,
unsigned int >(mDelegateKeyButtonPressed) );
}
}
private:
HandleKeyButtonPressed^ mDelegateKeyButtonPressed;
public:
delegate void HandleKeySetFocus(
Convert<MyGUI::Widget *>::Type _sender ,
Convert<MyGUI::Widget *>::Type _old );
event HandleKeySetFocus^ EventKeySetFocus
{
void add(HandleKeySetFocus^ _value)
{
mDelegateKeySetFocus += _value;
MMYGUI_CHECK_NATIVE(mNative);
static_cast<ThisType*>(mNative)->eventKeySetFocus =
static_cast< MyGUI::delegates::IDelegate2<
MyGUI::Widget * ,
MyGUI::Widget * > *>(
new Delegate2< HandleKeySetFocus^ ,
MyGUI::Widget * ,
MyGUI::Widget * >(mDelegateKeySetFocus) );
}
void remove(HandleKeySetFocus^ _value)
{
mDelegateKeySetFocus -= _value;
MMYGUI_CHECK_NATIVE(mNative);
if (mDelegateKeySetFocus == nullptr)
static_cast<ThisType*>(mNative)->eventKeySetFocus = nullptr;
else
static_cast<ThisType*>(mNative)->eventKeySetFocus =
static_cast< MyGUI::delegates::IDelegate2<
MyGUI::Widget * ,
MyGUI::Widget * > *>(
new Delegate2< HandleKeySetFocus^ ,
MyGUI::Widget * ,
MyGUI::Widget * >(mDelegateKeySetFocus) );
}
}
private:
HandleKeySetFocus^ mDelegateKeySetFocus;
public:
delegate void HandleKeyLostFocus(
Convert<MyGUI::Widget *>::Type _sender ,
Convert<MyGUI::Widget *>::Type _new );
event HandleKeyLostFocus^ EventKeyLostFocus
{
void add(HandleKeyLostFocus^ _value)
{
mDelegateKeyLostFocus += _value;
MMYGUI_CHECK_NATIVE(mNative);
static_cast<ThisType*>(mNative)->eventKeyLostFocus =
static_cast< MyGUI::delegates::IDelegate2<
MyGUI::Widget * ,
MyGUI::Widget * > *>(
new Delegate2< HandleKeyLostFocus^ ,
MyGUI::Widget * ,
MyGUI::Widget * >(mDelegateKeyLostFocus) );
}
void remove(HandleKeyLostFocus^ _value)
{
mDelegateKeyLostFocus -= _value;
MMYGUI_CHECK_NATIVE(mNative);
if (mDelegateKeyLostFocus == nullptr)
static_cast<ThisType*>(mNative)->eventKeyLostFocus = nullptr;
else
static_cast<ThisType*>(mNative)->eventKeyLostFocus =
static_cast< MyGUI::delegates::IDelegate2<
MyGUI::Widget * ,
MyGUI::Widget * > *>(
new Delegate2< HandleKeyLostFocus^ ,
MyGUI::Widget * ,
MyGUI::Widget * >(mDelegateKeyLostFocus) );
}
}
private:
HandleKeyLostFocus^ mDelegateKeyLostFocus;
public:
delegate void HandleMouseButtonDoubleClick(
Convert<MyGUI::Widget *>::Type _sender );
event HandleMouseButtonDoubleClick^ EventMouseButtonDoubleClick
{
void add(HandleMouseButtonDoubleClick^ _value)
{
mDelegateMouseButtonDoubleClick += _value;
MMYGUI_CHECK_NATIVE(mNative);
static_cast<ThisType*>(mNative)->eventMouseButtonDoubleClick =
static_cast< MyGUI::delegates::IDelegate1<
MyGUI::Widget * > *>(
new Delegate1< HandleMouseButtonDoubleClick^ ,
MyGUI::Widget * >(mDelegateMouseButtonDoubleClick) );
}
void remove(HandleMouseButtonDoubleClick^ _value)
{
mDelegateMouseButtonDoubleClick -= _value;
MMYGUI_CHECK_NATIVE(mNative);
if (mDelegateMouseButtonDoubleClick == nullptr)
static_cast<ThisType*>(mNative)->eventMouseButtonDoubleClick = nullptr;
else
static_cast<ThisType*>(mNative)->eventMouseButtonDoubleClick =
static_cast< MyGUI::delegates::IDelegate1<
MyGUI::Widget * > *>(
new Delegate1< HandleMouseButtonDoubleClick^ ,
MyGUI::Widget * >(mDelegateMouseButtonDoubleClick) );
}
}
private:
HandleMouseButtonDoubleClick^ mDelegateMouseButtonDoubleClick;
public:
delegate void HandleMouseButtonClick(
Convert<MyGUI::Widget *>::Type _sender );
event HandleMouseButtonClick^ EventMouseButtonClick
{
void add(HandleMouseButtonClick^ _value)
{
mDelegateMouseButtonClick += _value;
MMYGUI_CHECK_NATIVE(mNative);
static_cast<ThisType*>(mNative)->eventMouseButtonClick =
static_cast< MyGUI::delegates::IDelegate1<
MyGUI::Widget * > *>(
new Delegate1< HandleMouseButtonClick^ ,
MyGUI::Widget * >(mDelegateMouseButtonClick) );
}
void remove(HandleMouseButtonClick^ _value)
{
mDelegateMouseButtonClick -= _value;
MMYGUI_CHECK_NATIVE(mNative);
if (mDelegateMouseButtonClick == nullptr)
static_cast<ThisType*>(mNative)->eventMouseButtonClick = nullptr;
else
static_cast<ThisType*>(mNative)->eventMouseButtonClick =
static_cast< MyGUI::delegates::IDelegate1<
MyGUI::Widget * > *>(
new Delegate1< HandleMouseButtonClick^ ,
MyGUI::Widget * >(mDelegateMouseButtonClick) );
}
}
private:
HandleMouseButtonClick^ mDelegateMouseButtonClick;
public:
delegate void HandleMouseButtonReleased(
Convert<MyGUI::Widget *>::Type _sender ,
Convert<int>::Type _left ,
Convert<int>::Type _top ,
Convert<MyGUI::MouseButton>::Type _id );
event HandleMouseButtonReleased^ EventMouseButtonReleased
{
void add(HandleMouseButtonReleased^ _value)
{
mDelegateMouseButtonReleased += _value;
MMYGUI_CHECK_NATIVE(mNative);
static_cast<ThisType*>(mNative)->eventMouseButtonReleased =
static_cast< MyGUI::delegates::IDelegate4<
MyGUI::Widget * ,
int ,
int ,
MyGUI::MouseButton > *>(
new Delegate4< HandleMouseButtonReleased^ ,
MyGUI::Widget * ,
int ,
int ,
MyGUI::MouseButton >(mDelegateMouseButtonReleased) );
}
void remove(HandleMouseButtonReleased^ _value)
{
mDelegateMouseButtonReleased -= _value;
MMYGUI_CHECK_NATIVE(mNative);
if (mDelegateMouseButtonReleased == nullptr)
static_cast<ThisType*>(mNative)->eventMouseButtonReleased = nullptr;
else
static_cast<ThisType*>(mNative)->eventMouseButtonReleased =
static_cast< MyGUI::delegates::IDelegate4<
MyGUI::Widget * ,
int ,
int ,
MyGUI::MouseButton > *>(
new Delegate4< HandleMouseButtonReleased^ ,
MyGUI::Widget * ,
int ,
int ,
MyGUI::MouseButton >(mDelegateMouseButtonReleased) );
}
}
private:
HandleMouseButtonReleased^ mDelegateMouseButtonReleased;
public:
delegate void HandleMouseButtonPressed(
Convert<MyGUI::Widget *>::Type _sender ,
Convert<int>::Type _left ,
Convert<int>::Type _top ,
Convert<MyGUI::MouseButton>::Type _id );
event HandleMouseButtonPressed^ EventMouseButtonPressed
{
void add(HandleMouseButtonPressed^ _value)
{
mDelegateMouseButtonPressed += _value;
MMYGUI_CHECK_NATIVE(mNative);
static_cast<ThisType*>(mNative)->eventMouseButtonPressed =
static_cast< MyGUI::delegates::IDelegate4<
MyGUI::Widget * ,
int ,
int ,
MyGUI::MouseButton > *>(
new Delegate4< HandleMouseButtonPressed^ ,
MyGUI::Widget * ,
int ,
int ,
MyGUI::MouseButton >(mDelegateMouseButtonPressed) );
}
void remove(HandleMouseButtonPressed^ _value)
{
mDelegateMouseButtonPressed -= _value;
MMYGUI_CHECK_NATIVE(mNative);
if (mDelegateMouseButtonPressed == nullptr)
static_cast<ThisType*>(mNative)->eventMouseButtonPressed = nullptr;
else
static_cast<ThisType*>(mNative)->eventMouseButtonPressed =
static_cast< MyGUI::delegates::IDelegate4<
MyGUI::Widget * ,
int ,
int ,
MyGUI::MouseButton > *>(
new Delegate4< HandleMouseButtonPressed^ ,
MyGUI::Widget * ,
int ,
int ,
MyGUI::MouseButton >(mDelegateMouseButtonPressed) );
}
}
private:
HandleMouseButtonPressed^ mDelegateMouseButtonPressed;
public:
delegate void HandleMouseWheel(
Convert<MyGUI::Widget *>::Type _sender ,
Convert<int>::Type _rel );
event HandleMouseWheel^ EventMouseWheel
{
void add(HandleMouseWheel^ _value)
{
mDelegateMouseWheel += _value;
MMYGUI_CHECK_NATIVE(mNative);
static_cast<ThisType*>(mNative)->eventMouseWheel =
static_cast< MyGUI::delegates::IDelegate2<
MyGUI::Widget * ,
int > *>(
new Delegate2< HandleMouseWheel^ ,
MyGUI::Widget * ,
int >(mDelegateMouseWheel) );
}
void remove(HandleMouseWheel^ _value)
{
mDelegateMouseWheel -= _value;
MMYGUI_CHECK_NATIVE(mNative);
if (mDelegateMouseWheel == nullptr)
static_cast<ThisType*>(mNative)->eventMouseWheel = nullptr;
else
static_cast<ThisType*>(mNative)->eventMouseWheel =
static_cast< MyGUI::delegates::IDelegate2<
MyGUI::Widget * ,
int > *>(
new Delegate2< HandleMouseWheel^ ,
MyGUI::Widget * ,
int >(mDelegateMouseWheel) );
}
}
private:
HandleMouseWheel^ mDelegateMouseWheel;
public:
delegate void HandleMouseMove(
Convert<MyGUI::Widget *>::Type _sender ,
Convert<int>::Type _left ,
Convert<int>::Type _top );
event HandleMouseMove^ EventMouseMove
{
void add(HandleMouseMove^ _value)
{
mDelegateMouseMove += _value;
MMYGUI_CHECK_NATIVE(mNative);
static_cast<ThisType*>(mNative)->eventMouseMove =
static_cast< MyGUI::delegates::IDelegate3<
MyGUI::Widget * ,
int ,
int > *>(
new Delegate3< HandleMouseMove^ ,
MyGUI::Widget * ,
int ,
int >(mDelegateMouseMove) );
}
void remove(HandleMouseMove^ _value)
{
mDelegateMouseMove -= _value;
MMYGUI_CHECK_NATIVE(mNative);
if (mDelegateMouseMove == nullptr)
static_cast<ThisType*>(mNative)->eventMouseMove = nullptr;
else
static_cast<ThisType*>(mNative)->eventMouseMove =
static_cast< MyGUI::delegates::IDelegate3<
MyGUI::Widget * ,
int ,
int > *>(
new Delegate3< HandleMouseMove^ ,
MyGUI::Widget * ,
int ,
int >(mDelegateMouseMove) );
}
}
private:
HandleMouseMove^ mDelegateMouseMove;
public:
delegate void HandleMouseDrag(
Convert<MyGUI::Widget *>::Type _sender ,
Convert<int>::Type _left ,
Convert<int>::Type _top );
event HandleMouseDrag^ EventMouseDrag
{
void add(HandleMouseDrag^ _value)
{
mDelegateMouseDrag += _value;
MMYGUI_CHECK_NATIVE(mNative);
static_cast<ThisType*>(mNative)->eventMouseDrag =
static_cast< MyGUI::delegates::IDelegate3<
MyGUI::Widget * ,
int ,
int > *>(
new Delegate3< HandleMouseDrag^ ,
MyGUI::Widget * ,
int ,
int >(mDelegateMouseDrag) );
}
void remove(HandleMouseDrag^ _value)
{
mDelegateMouseDrag -= _value;
MMYGUI_CHECK_NATIVE(mNative);
if (mDelegateMouseDrag == nullptr)
static_cast<ThisType*>(mNative)->eventMouseDrag = nullptr;
else
static_cast<ThisType*>(mNative)->eventMouseDrag =
static_cast< MyGUI::delegates::IDelegate3<
MyGUI::Widget * ,
int ,
int > *>(
new Delegate3< HandleMouseDrag^ ,
MyGUI::Widget * ,
int ,
int >(mDelegateMouseDrag) );
}
}
private:
HandleMouseDrag^ mDelegateMouseDrag;
public:
delegate void HandleMouseSetFocus(
Convert<MyGUI::Widget *>::Type _sender ,
Convert<MyGUI::Widget *>::Type _old );
event HandleMouseSetFocus^ EventMouseSetFocus
{
void add(HandleMouseSetFocus^ _value)
{
mDelegateMouseSetFocus += _value;
MMYGUI_CHECK_NATIVE(mNative);
static_cast<ThisType*>(mNative)->eventMouseSetFocus =
static_cast< MyGUI::delegates::IDelegate2<
MyGUI::Widget * ,
MyGUI::Widget * > *>(
new Delegate2< HandleMouseSetFocus^ ,
MyGUI::Widget * ,
MyGUI::Widget * >(mDelegateMouseSetFocus) );
}
void remove(HandleMouseSetFocus^ _value)
{
mDelegateMouseSetFocus -= _value;
MMYGUI_CHECK_NATIVE(mNative);
if (mDelegateMouseSetFocus == nullptr)
static_cast<ThisType*>(mNative)->eventMouseSetFocus = nullptr;
else
static_cast<ThisType*>(mNative)->eventMouseSetFocus =
static_cast< MyGUI::delegates::IDelegate2<
MyGUI::Widget * ,
MyGUI::Widget * > *>(
new Delegate2< HandleMouseSetFocus^ ,
MyGUI::Widget * ,
MyGUI::Widget * >(mDelegateMouseSetFocus) );
}
}
private:
HandleMouseSetFocus^ mDelegateMouseSetFocus;
public:
delegate void HandleMouseLostFocus(
Convert<MyGUI::Widget *>::Type _sender ,
Convert<MyGUI::Widget *>::Type _new );
event HandleMouseLostFocus^ EventMouseLostFocus
{
void add(HandleMouseLostFocus^ _value)
{
mDelegateMouseLostFocus += _value;
MMYGUI_CHECK_NATIVE(mNative);
static_cast<ThisType*>(mNative)->eventMouseLostFocus =
static_cast< MyGUI::delegates::IDelegate2<
MyGUI::Widget * ,
MyGUI::Widget * > *>(
new Delegate2< HandleMouseLostFocus^ ,
MyGUI::Widget * ,
MyGUI::Widget * >(mDelegateMouseLostFocus) );
}
void remove(HandleMouseLostFocus^ _value)
{
mDelegateMouseLostFocus -= _value;
MMYGUI_CHECK_NATIVE(mNative);
if (mDelegateMouseLostFocus == nullptr)
static_cast<ThisType*>(mNative)->eventMouseLostFocus = nullptr;
else
static_cast<ThisType*>(mNative)->eventMouseLostFocus =
static_cast< MyGUI::delegates::IDelegate2<
MyGUI::Widget * ,
MyGUI::Widget * > *>(
new Delegate2< HandleMouseLostFocus^ ,
MyGUI::Widget * ,
MyGUI::Widget * >(mDelegateMouseLostFocus) );
}
}
private:
HandleMouseLostFocus^ mDelegateMouseLostFocus;
};
} // namespace Managed
} // namespace MyGUI
| [
"albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c"
] | [
[
[
1,
772
]
]
] |
a0f4b44347c580de39ae69c129fad6faf56bc513 | 1f66c42a9c00e6c95656493abcb27c3d2c465cf5 | / mts-file-joiner --username thesuperstitions/InterprocessQueueTest/MessageQueue/FederateIO_HandlerOutputThread.h | 7dc5778498937ebee0bb715e48bc01eff842b7f7 | [] | no_license | thesuperstitions/mts-file-joiner | b040dd5049cc0e8f865d49aece3e09e8cd56c7ae | 182b22968b589eeaa8a0553786cfa33f20a019e6 | refs/heads/master | 2020-05-18T18:52:58.630448 | 2009-04-08T11:33:57 | 2009-04-08T11:33:57 | 32,318,120 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,127 | h | /*********************************************************************
Rhapsody : 7.1
Login : rosskw1
Component : DefaultComponent
Configuration : DefaultConfig
Model Element : Framework::IO::FederateIO_HandlerOutputThread
//! Generated Date : Thu, 3, Apr 2008
File Path : DefaultComponent\DefaultConfig\FederateIO_HandlerOutputThread.h
*********************************************************************/
#ifndef FederateIO_HandlerOutputThread_H
#define FederateIO_HandlerOutputThread_H
#include <oxf/oxf.h>
#include <string>
#include <algorithm>
#include <sstream>
#include <iomanip>
#include <iostream>
#include "Configuration.h"
#include "RTI\RTI1516.h"
#include "IO.h"
#include <vector>
#include <iterator>
// link itsFederateMessage
#include "FederateMessage.h"
// class FederateIO_HandlerOutputThread
#include "Thread.h"
#include "boost/thread/mutex.hpp"
//----------------------------------------------------------------------------
// FederateIO_HandlerOutputThread.h
//----------------------------------------------------------------------------
namespace Framework {
namespace IO {
class FederateInterface;
class FederateIO_Handler;
class PostOffice;
}
}
//## package Framework::IO
#ifdef _MSC_VER
// disable Microsoft compiler warning (debug information truncated)
#pragma warning(disable: 4786)
#endif
namespace Framework {
namespace IO {
//## class FederateIO_HandlerOutputThread
class FederateIO_HandlerOutputThread : public Thread {
//// Constructors and destructors ////
public :
//## operation FederateIO_HandlerOutputThread(FederateInterface*)
FederateIO_HandlerOutputThread(FederateInterface* federateInterface);
//## operation FederateIO_HandlerOutputThread()
FederateIO_HandlerOutputThread();
//## auto_generated
virtual ~FederateIO_HandlerOutputThread();
//// Operations ////
public :
//## operation addFederateMessage(FederateMessage*)
virtual void addFederateMessage(FederateMessage* message);
//## operation threadOperation()
virtual void threadOperation();
//// Additional operations ////
public :
//## auto_generated
FederateInterface* getFederateInterface() const;
//## auto_generated
void setFederateInterface(FederateInterface* p_federateInterface);
//## auto_generated
FederateIO_Handler* getItsFederateIO_Handler() const;
//## auto_generated
void setItsFederateIO_Handler(FederateIO_Handler* p_FederateIO_Handler);
//## auto_generated
std::vector<FederateMessage*>::const_iterator getItsFederateMessage() const;
//## auto_generated
std::vector<FederateMessage*>::const_iterator getItsFederateMessageEnd() const;
//## auto_generated
void addItsFederateMessage(FederateMessage* p_FederateMessage);
//## auto_generated
void removeItsFederateMessage(FederateMessage* p_FederateMessage);
//## auto_generated
void clearItsFederateMessage();
//// Framework operations ////
public :
//## auto_generated
void __setItsFederateIO_Handler(FederateIO_Handler* p_FederateIO_Handler);
//## auto_generated
void _setItsFederateIO_Handler(FederateIO_Handler* p_FederateIO_Handler);
//## auto_generated
void _clearItsFederateIO_Handler();
protected :
//## auto_generated
void cleanUpRelations();
//// Attributes ////
protected :
FederateInterface* federateInterface; //## attribute federateInterface
boost::mutex myMutex; //## attribute myMutex
//// Relations and components ////
protected :
FederateIO_Handler* itsFederateIO_Handler; //## link itsFederateIO_Handler
std::vector<FederateMessage*> itsFederateMessage; //## link itsFederateMessage
};
}
}
#endif
/*********************************************************************
File Path : DefaultComponent\DefaultConfig\FederateIO_HandlerOutputThread.h
*********************************************************************/
| [
"thesuperstitions@a5dd5fbb-a553-0410-a858-5d8807c0469a"
] | [
[
[
1,
161
]
]
] |
c5e38e8e67ce9922b0c236ac78cd6b5b99aa4dc5 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/type_traits/test/is_convertible_test.cpp | d48bb93542a0e4b68acfb949841fa55fee7ec4f2 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,190 | cpp |
// (C) Copyright John Maddock 2000.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include "test.hpp"
#include "check_integral_constant.hpp"
#ifdef TEST_STD
# include <type_traits>
#else
# include <boost/type_traits/is_convertible.hpp>
#endif
template <class T>
struct convertible_from
{
convertible_from(T);
};
struct base2 { };
struct middle2 : virtual base2 { };
struct derived2 : middle2 { };
TT_TEST_BEGIN(is_convertible)
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<Derived,Base>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<Derived,Derived>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<Base,Base>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<Base,Derived>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<Derived,Derived>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<NonDerived,Base>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float,int>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<virtual_inherit2,virtual_inherit1>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<VD,VB>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<polymorphic_derived1,polymorphic_base>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<polymorphic_derived2,polymorphic_base>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<polymorphic_base,polymorphic_derived1>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<polymorphic_base,polymorphic_derived2>::value), false);
#ifndef TEST_STD
// Ill-formed behaviour, supported by Boost as an extension:
#ifndef BOOST_NO_IS_ABSTRACT
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<test_abc1,test_abc1>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<Base,test_abc1>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<polymorphic_derived2,test_abc1>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int,test_abc1>::value), false);
#endif
#endif
// The following four do not compile without member template support:
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float,void>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<void,void>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<void,float>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<enum1, int>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<Derived*, Base*>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<Base*, Derived*>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<Derived&, Base&>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<Base&, Derived&>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<const Derived*, const Base*>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<const Base*, const Derived*>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<const Derived&, const Base&>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<const Base&, const Derived&>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<const int *, int*>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<const int&, int&>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<const int*, int[3]>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<const int&, int>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int(&)[4], const int*>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int(&)(int), int(*)(int)>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int *, const int*>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int&, const int&>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int[2], int*>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int[2], const int*>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<const int[2], int*>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int*, int[3]>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<test_abc3, const test_abc1&>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<non_pointer, void*>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<non_pointer, int*>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<non_int_pointer, int*>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<non_int_pointer, void*>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<test_abc1&, test_abc2&>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<test_abc1&, int_constructible>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int_constructible, test_abc1&>::value), false);
#ifndef BOOST_NO_IS_ABSTRACT
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<test_abc1&, test_abc2>::value), false);
#endif
//
// the following tests all involve user defined conversions which do
// not compile with Borland C++ Builder 5:
//
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int, int_constructible>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float,convertible_from<float> >::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float,convertible_from<float const&> >::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float,convertible_from<float&> >::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float,convertible_from<char> >::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float,convertible_from<char const&> >::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float,convertible_from<char&> >::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<char,convertible_from<char> >::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<char,convertible_from<char const&> >::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<char,convertible_from<char&> >::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float&,convertible_from<float> >::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float const&,convertible_from<float> >::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float&,convertible_from<float&> >::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float const&,convertible_from<float const&> >::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float&,convertible_from<float const&> >::value), true);
//
// the following all generate warnings unless we can find a way to
// suppress them:
//
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float,int>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<double,int>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<double,float>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<long,int>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int,char>::value), true);
#ifdef BOOST_HAS_LONG_LONG
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<long long,int>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<long long,char>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<long long,float>::value), true);
#elif defined(BOOST_HAS_MS_INT64)
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<__int64,int>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<__int64,char>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<__int64,float>::value), true);
#endif
TT_TEST_END
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
142
]
]
] |
392298b48011d92701e399f189dc1a3749169c1d | 3da0b0276bc8c3d7d1bcdbabfb0e763a38d3a24c | /zju.finished/1197.cpp | 18e3934c01bdb771f6bc76a2bef2d5ac4b9a6f37 | [] | no_license | usherfu/zoj | 4af6de9798bcb0ffa9dbb7f773b903f630e06617 | 8bb41d209b54292d6f596c5be55babd781610a52 | refs/heads/master | 2021-05-28T11:21:55.965737 | 2009-12-15T07:58:33 | 2009-12-15T07:58:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,878 | cpp | #include<iostream>
#include<cstring>
#include<cstdlib>
// perfect match for biparty
using namespace std;
enum {
SIZ = 108,
};
struct Rect{
int lx, ly, hx, hy;
bool in(int x, int y){
return x>min(lx,hx)&&x<max(lx,hx) && y>min(ly, hy) && y<max(ly, hy);
}
};
int num;
Rect r[SIZ];
int tab[SIZ][SIZ];
int mat[SIZ];
int vis[SIZ];
int dfs(int p){
int i,t;
for(i=0;i< num;i++)
if(tab[i][p] && !vis[i]){
vis[i]=1;
t=mat[i];
mat[i]=p;
if(t==-1 || dfs(t))
return 1;
mat[i]=t;
}
return 0;
}
int get_match(){
int i,res=0;
memset(mat,-1,sizeof(mat));
for(i=0;i< num;i++){
memset(vis,0,sizeof(vis));
if(dfs(i))
res++;
}
return num - res;
}
void fun(){
get_match();
int t;
bool ok = false;
for (int i=0; i<num; ++i){
t = mat[i];
if (t == -1) continue;
memset(vis, 0, sizeof(vis));
mat[i] = -1;
tab[i][t] = 0;
if (!dfs(t)){
if (ok) printf(" ");
ok = true;
mat[i] = t;
printf("(%c,%d)", i+'A', t+1);
}
tab[i][t] = 1;
}
if (!ok){
printf("none");
}
printf("\n");
}
int readIn(){
scanf("%d", &num);
int i,j;
int x, y;
for(i=0; i<num; i++){
scanf("%d%d%d%d", &r[i].lx, &r[i].hx, &r[i].ly, &r[i].hy);
}
memset(tab, 0, sizeof(tab));
for(i=0; i<num ;i++){
scanf("%d%d", &x, &y);
for(j=0;j<num;j++){
tab[j][i] = r[j].in(x, y);
}
}
return num;
}
int main(){
int tst = 0;
while( readIn() > 0){
printf("Heap %d\n", ++tst);
fun();
printf("\n");
}
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
95
]
]
] |
def93d9ced7579bde3a6dd24fda0135bbc399072 | c3531ade6396e9ea9c7c9a85f7da538149df2d09 | /Param/src/ModelMesh/MeshModelRender.h | 609a646f2675fc928f9c290814a68e31259d9033 | [] | no_license | feengg/MultiChart-Parameterization | ddbd680f3e1c2100e04c042f8f842256f82c5088 | 764824b7ebab9a3a5e8fa67e767785d2aec6ad0a | refs/heads/master | 2020-03-28T16:43:51.242114 | 2011-04-19T17:18:44 | 2011-04-19T17:18:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,959 | h | /* ================== Library Information ================== */
// [Name]
// MeshLib Library
//
// [Developer]
// Xu Dong
// State Key Lab of CAD&CG, Zhejiang University
//
// [Date]
// 2005-08-05
//
// [Goal]
// A general, flexible, versatile and easy-to-use mesh library for research purpose.
// Supporting arbitrary polygonal meshes as input, but with a
// primary focus on triangle meshes.
/* ================== File Information ================== */
// [Name]
// MeshModelRender.h
//
// [Developer]
// Xu Dong
// State Key Lab of CAD&CG, Zhejiang University
//
// [Date]
// 2005-08-05
//
// [Goal]
// Defining various rendering modes
// Including polygon (flag/smooth), wireframe, point, texture mapping, etc
#include "MeshModelKernel.h"
#include "MeshModelAuxData.h"
#include "../Common/Utility.h"
#include "../OpenGL/GLElement.h"
#pragma once
/* ================== Render Model Macros ================== */
#define RENDER_MODEL_VERTICES 0X00000001
#define RENDER_MODEL_WIREFRAME 0X00000002
#define RENDER_MODEL_SOLID_FLAT 0X00000003
#define RENDER_MODEL_SOLID_SMOOTH 0X00000004
#define RENDER_MODEL_SOLID_WITH_SHARPNESS 0X00000005
#define RENDER_MODEL_SOLID_AND_WIREFRAME 0X00000006
#define RENDER_MODEL_HIGHLIGHT_ONLY 0X00000007
#define RENDER_MODEL_TEXTURE_MAPPING 0X00000008
#define RENDER_MODEL_VERTEX_COLOR 0X00000009
#define RENDER_MODEL_FACE_COLOR 0X0000000A
#define RENDER_MODEL_TRANSPARENT 0X0000000B
#define RENDER_MODEL_AXIS 0X00000100
#define RENDER_MODEL_BOUNDING_BOX 0X00000200
#define RENDER_MODEL_LIGHTING 0X00000400
#define RENDER_MODEL_COLOR 0X00000800 //
#define RENDER_MODEL_POINT 0X00010000
#define RENDER_MODEL_LINE 0X00020000
#define RENDER_MODEL_POLYGON 0X00040000
#define RENDER_MODEL_ELEMENT 0X00080000
#define RENDER_MODEL_KMIN_CURVATURE 0X00100000
#define RENDER_MODEL_KMAX_CURVATURE 0X00200000
#define RENDER_MODEL_PARAM_TEXTURE 0X00400000
/* ================== Material ================== */
class Material
{
public:
float m_Ambient[4];
float m_Diffuse[4];
float m_Specular[4];
float m_Emissive[4];
float m_Shininess;
float m_Transparency;
public:
// Constructor
Material() {}
Material(float ambient[4], float diffuse[4], float specular[4], float emissive[4], float shininess, float transparency = 0.0f)
{
for(int i = 0; i < 4; ++ i)
{
m_Ambient[i] = ambient[i];
m_Diffuse[i] = diffuse[i];
m_Specular[i] = specular[i];
m_Emissive[i] = emissive[i];
m_Shininess = shininess;
m_Transparency = transparency;
}
}
// Destructor
~Material() {}
// Operator
Material& operator =(Material& mat)
{
for(int i = 0; i < 4; ++ i)
{
m_Ambient[i] = mat.m_Ambient[i];
m_Diffuse[i] = mat.m_Diffuse[i];
m_Specular[i] = mat.m_Specular[i];
m_Emissive[i] = mat.m_Emissive[i];
m_Shininess = mat.m_Shininess;
m_Transparency = mat.m_Transparency;
}
return *this;
}
};
/* ================== Mesh Model Render ================== */
class MeshModelRender
{
private:
int m_Mode;
int m_State;
Color m_BbColor;
Color m_DftVtxColor;
Color m_DftEdgeColor;
Color m_DftFaceColor;
Color m_DftPointColor;
Color m_DftLineColor;
Color m_DftPolygonColor;
Color m_DftElementColor;
Color m_DftHltVtxColor;
Color m_DftHltEdgeColor;
Color m_DftHltFaceColor;
float m_DftVtxSize;
float m_DftEdgeWidth;
float m_DftPointSize;
float m_DftLineWidth;
float m_DftBdyVtxSize;
float m_DftBdyEdgeWidth;
float m_DftHltVtxSize;
float m_DftHltEdgeWidth;
Material m_ModelMaterial;
Material m_ElementMaterial;
GLMaterial m_DefaultMaterial;
MeshModelKernel* kernel;
MeshModelAuxData* auxdata;
private:
Utility util;
// Various rendering functions
void DrawModelVertices();
void DrawModelWireframe();
void DrawModelSolidFlat();
void DrawModelSolidSmooth();
void DrawModelSolidWithSharpness();
void DrawModelSolidAndWireframe();
void DrawModelHighlightOnly();
void DrawModelTextureMapping();
void DrawModelVertexColor();
void DrawModelFaceColor();
void DrawModelTransparent();
void DrawModelFaceTexture();
// Only render the depth of the model
void DrawModelDepth();
// Various auxiliary data rendering functions
void DrawPoint();
void DrawLine();
void DrawPolygon();
// Various utility rendering functions
void DrawAxis();
void DrawBoundingBox();
void DrawMeshCurvature(int mode);
void DrawVector(double scale, Coord& start, Coord& vec, Coord& normal);
public:
// Constructor
MeshModelRender();
// Destructor
~MeshModelRender();
// Initializer
void ClearData();
void AttachKernel(MeshModelKernel* pKernel);
void AttachAuxData(MeshModelAuxData* pAuxData);
// Get/Set functions
int& Mode() { return m_Mode; }
int& State() { return m_State; }
Color& BbColor() { return m_BbColor; }
Color& DftVtxColor() { return m_DftVtxColor; }
Color& DftEdgeColor() { return m_DftEdgeColor; }
Color& DftFaceColor() { return m_DftFaceColor; }
Color& DftPointColor() { return m_DftPointColor; }
Color& DftLineColor() { return m_DftLineColor; }
Color& DftPolygonColor() { return m_DftPolygonColor; }
Color& DftElementColor() { return m_DftElementColor; }
Color& DftHltVtxColor() { return m_DftHltVtxColor; }
Color& DftHltEdgeColor() { return m_DftHltEdgeColor; }
Color& DftHltFaceColor() { return m_DftHltFaceColor; }
float& DftVtxSize() { return m_DftVtxSize; }
float& DftEdgeWidth() { return m_DftEdgeWidth; }
float& DftPointSize() { return m_DftPointSize; }
float& DftLineWidth() { return m_DftLineWidth; }
float& DftBdyVtxSize() { return m_DftBdyVtxSize; }
float& DftBdyEdgeWidth() { return m_DftBdyEdgeWidth; }
float& DftHltVtxSize() { return m_DftHltVtxSize; }
float& DftHltEdgeWidth() { return m_DftHltEdgeWidth; }
Material& ModelMaterial() { return m_ModelMaterial; }
Material& ElementMaterial() { return m_ElementMaterial; }
// Rendering entrance function
void DrawModel();
int CreateTexture(const std::string& file_name);
}; | [
"[email protected]"
] | [
[
[
1,
248
]
]
] |
251767ca1d45ef39826e6fa3dad1824c9348c7b2 | 9c62af23e0a1faea5aaa8dd328ba1d82688823a5 | /rl/tags/v0-1/engine/dialog/src/Utils.cpp | 3c2e1d08a145e84d5539fdd2d73a117591d7dd15 | [
"ClArtistic",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | jacmoe/dsa-hl-svn | 55b05b6f28b0b8b216eac7b0f9eedf650d116f85 | 97798e1f54df9d5785fb206c7165cd011c611560 | refs/heads/master | 2021-04-22T12:07:43.389214 | 2009-11-27T22:01:03 | 2009-11-27T22:01:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,873 | cpp | /* 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.
*/
#include "Utils.h"
//-- Utils.cpp
namespace rl
{
CeGuiString toUpper(const CeGuiString &str)
{
CeGuiString result = str;
for ( register unsigned int ix = 0; ix < result.length(); ++ix )
result[ix] = toupper(result[ix]);
return result;
}
CeGuiString toLower(const CeGuiString &str)
{
CeGuiString result = str;
for ( register unsigned int ix = 0; ix < result.length(); ++ix )
result[ix] = toupper(result[ix]);
return result;
}
//-- possibly a bug in here
CeGuiString trim(const CeGuiString &str)
{
CeGuiString result = str;
CeGuiString::size_type index = result.find_last_not_of(" \t\n\r");
if ( index != CeGuiString::npos )
{
result.erase(index + 1, CeGuiString::npos);
} else {
return "";
}
index = result.find_first_not_of(" \t\n\r");
if ( index != CeGuiString::npos )
result.erase(0, index);
return result;
}
static const CeGuiString WS = " \n\t\r";
bool checkHeadWS(const CeGuiString &data)
{
CeGuiString::size_type index = data.find_first_not_of(WS);
return index != 0 && index != CeGuiString::npos;
}
bool checkTailWS(const CeGuiString &data)
{
CeGuiString::size_type index = data.find_last_not_of(WS);
return index != CeGuiString::npos && index != data.length() - 1;
}
CeGuiString normalise(const CeGuiString &data)
{
CeGuiString buffer = data;
CeGuiString::size_type index = buffer.find_first_not_of(WS);
if ( index != CeGuiString::npos )
buffer.erase(0, index);
index = buffer.find_last_not_of(WS);
if ( index != CeGuiString::npos && index < buffer.length() - 1 )
{
buffer.erase(index + 1, CeGuiString::npos);
} else if ( index == CeGuiString::npos ) {
return "";
}
CeGuiString result;
bool addedSpace = false;
for ( index = 0; index < buffer.length(); ++index )
{
if ( WS.find(buffer[index]) != CeGuiString::npos )
{
if ( addedSpace ) continue;
else
{
result += ' ';
addedSpace = true;
}
} else {
result += buffer[index];
addedSpace = false;
}
}
return result;
}
}
//-- end-of-file
| [
"blakharaz@4c79e8ff-cfd4-0310-af45-a38c79f83013"
] | [
[
[
1,
102
]
]
] |
ac0e091333d494d8a94abd1427360a0843d980f9 | f71e82b7ed19200280b7164a2e959310d9bfa210 | /ExampleAIModule/ExampleAIModule/Grafo.cpp | b2765343fe310e2f27a78cea2385cf419c782074 | [] | no_license | albertouri/manolobot | 05cf4ee217e85f1332e0e063fcc209da4b71c7b5 | 44e7fee46abcf4f1efa6d292ea8ec7cdc57eb7c8 | refs/heads/master | 2021-01-02T08:32:48.281836 | 2011-02-03T23:28:08 | 2011-02-03T23:28:08 | 39,591,406 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,894 | cpp | #include "Grafo.h"
Grafo::Grafo(int cantNodos)
{
// creo el arreglo dinamico con la cantidad de nodos que tendra el grafo
listaAdy = new Nodo[cantNodos];
std::set<Region*>::const_iterator It;
It = BWTA::getRegions().begin();
std::set<Chokepoint*>::const_iterator It2;
Nodo *actual;
int cont = 0;
while (It != BWTA::getRegions().end()){
listaAdy[cont].setRegion((*It));
actual = &listaAdy[cont];
// agrega los adyacentes a la region actual al grafo
It2 = (*It)->getChokepoints().begin();
while (It2 != (*It)->getChokepoints().end()){
// si la primer region del chokepoint no es la region actual la agrega al grafo
if ((*It2)->getRegions().first != (*It))
actual->setSiguiente(new Nodo((*It2)->getRegions().first));
else
actual->setSiguiente(new Nodo((*It2)->getRegions().second));
actual = actual->getSiguiente();
It2++;
}
cont++;
It++;
}
//Broodwar->printf("Grafo creado con exito");
// crea la lista para visitar las regiones con un recorrido por niveles
crearListaNiveles();
//Broodwar->printf("El mapa tiene %d regiones", BWTA::getRegions().size());
//Broodwar->printf("La lista niveles tiene %d elementos", niveles.size());
}
Grafo::~Grafo(void)
{
}
int Grafo::indiceRegion(Region *reg){
int cont = 0;
while (listaAdy[cont].getRegion() != reg)
cont++;
return cont;
}
void Grafo::crearListaNiveles(){
//-- NUEVO
std::list<Region*> nivelesRegiones;
std::list<Region*>::iterator ItNivelesRegiones;
//--
std::set<Region*> visitados;
//std::list<Region*>::iterator ItLista;
//std::list<Position*>::iterator ItLista;
std::set<Chokepoint*>::const_iterator ItChoke;
//--
// crea la lista para el recorrido por niveles
Region *inicio = BWTA::getStartLocation(Broodwar->self())->getRegion();
// inserta la region de inicio en la lista
nivelesRegiones.push_back(inicio);
niveles.push_back(new Position(inicio->getCenter().x(), inicio->getCenter().y()));
visitados.insert(inicio);
ItNivelesRegiones = nivelesRegiones.begin();
while (ItNivelesRegiones != nivelesRegiones.end()){
// itera sobre los chokepoints para agregar las regiones adyacentes a la lista
ItChoke = (*ItNivelesRegiones)->getChokepoints().begin();
while (ItChoke != (*ItNivelesRegiones)->getChokepoints().end()){
if ((*ItChoke)->getRegions().first != (*ItNivelesRegiones)){
if (visitados.find((*ItChoke)->getRegions().first) == visitados.end()){
std::set<BaseLocation*>::const_iterator b = (*ItChoke)->getRegions().first->getBaseLocations().begin();
nivelesRegiones.push_back((*ItChoke)->getRegions().first);
while (b != (*ItChoke)->getRegions().first->getBaseLocations().end()){
niveles.push_back(new Position((*b)->getPosition().x(), (*b)->getPosition().y()));
b++;
}
visitados.insert((*ItChoke)->getRegions().first);
}
}
else{
if (visitados.find((*ItChoke)->getRegions().second) == visitados.end()){
std::set<BaseLocation*>::const_iterator b = (*ItChoke)->getRegions().second->getBaseLocations().begin();
nivelesRegiones.push_back((*ItChoke)->getRegions().second);
while (b != (*ItChoke)->getRegions().second->getBaseLocations().end()){
niveles.push_back(new Position((*b)->getPosition().x(), (*b)->getPosition().y()));
b++;
}
visitados.insert((*ItChoke)->getRegions().second);
}
}
ItChoke++;
}
ItNivelesRegiones++;
}
}
Position* Grafo::primerNodoNiveles(){
ItNiveles = niveles.begin();
return (*ItNiveles);
}
Position* Grafo::siguienteNodoNiveles(){
ItNiveles++;
if (ItNiveles == niveles.end())
return NULL;
else
return (*ItNiveles);
}
void Grafo::dibujarPuntosVisitar(){
std::list<Position*>::iterator It = niveles.begin();
while (It != niveles.end()){
Broodwar->drawBoxMap((*It)->x(), (*It)->y(), (*It)->x() + 8, (*It)->y() + 8, Colors::White, true);
It++;
}
//Broodwar->printf("Dibuje los puntos en el mapa");
}
/*void Grafo::dibujarRegionesNiveles(){
std::list<Region*>::iterator It = niveles.begin();
while (It != niveles.end()){
Polygon p = (*It)->getPolygon();
for(int j=0;j<(int)p.size();j++)
{
Position point1=p[j];
Position point2=p[(j+1) % p.size()];
Broodwar->drawLine(CoordinateType::Map,point1.x(),point1.y(),point2.x(),point2.y(),Colors::Green);
}
It++;
}
// une con una linea los centros de las regiones a visitar
if (niveles.size() > 1){
std::list<Region*>::iterator It1, It2;
It1 = niveles.begin();
It2 = niveles.begin();
It2++;
while (It2 != niveles.end()){
Broodwar->drawLineMap((*It1)->getCenter().x(), (*It1)->getCenter().y(), (*It2)->getCenter().x(),(*It2)->getCenter().y(), Colors::White);
It1++;
It2++;
}
}
}*/ | [
"marianomoreno3@82b963ee-1e64-6eb5-a9c5-6632919fd137"
] | [
[
[
1,
183
]
]
] |
70f382fed92e4c3a071bd53c2b8e3d5beb930188 | 1e299bdc79bdc75fc5039f4c7498d58f246ed197 | /ServerLib/ChangeNotificationSubSystem.cpp | cc9e9112c9e44b08930b145723c9520fd48fcaee | [] | no_license | moosethemooche/Certificate-Server | 5b066b5756fc44151b53841482b7fa603c26bf3e | 887578cc2126bae04c09b2a9499b88cb8c7419d4 | refs/heads/master | 2021-01-17T06:24:52.178106 | 2011-07-13T13:27:09 | 2011-07-13T13:27:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,428 | cpp | //--------------------------------------------------------------------------------
// Copyright (c) 2001 MarkCare Medical Solutions, Inc.
// Created...: 6/9/01
// Author....: Rich Schonthal
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
#include "stdafx.h"
#include "ChangeNotificationSubSystem.h"
#include "ChangeNotificationThread.h"
#include "ChangeNotificationDirThread.h"
#include <Directory.h>
//--------------------------------------------------------------------------------
IMPLEMENT_DYNAMIC(CChangeNotificationSubSystem, CSubSystem)
//--------------------------------------------------------------------------------
void AFXAPI DestructElements<CFileNotifyInformation*>(CFileNotifyInformation** pElements, int nCount)
{
for(int i = 0; i < nCount; i++)
delete *pElements;
}
//--------------------------------------------------------------------------------
CChangeNotificationSubSystem::CChangeNotificationSubSystem(CSystem* pParent)
: CThreadPoolSubSystem(pParent)
, m_nQueueSize(0)
{
}
//--------------------------------------------------------------------------------
CChangeNotificationSubSystem::~CChangeNotificationSubSystem()
{
}
//--------------------------------------------------------------------------------
bool CChangeNotificationSubSystem::GetNextInfo(CFileNotifyInformation*& pInfo, LPCTSTR& pPath)
{
CSingleLock lock(&m_mutex, false);
if(! lock.Lock(1000))
return false;
CFileNotifyInformationContainer* pHead = m_queue.GetHead();
m_queue.RemoveHead();
pInfo = pHead->m_pInfo;
pPath = GetPath(pHead->m_nPathIndex);
delete pHead;
::InterlockedDecrement(&m_nQueueSize);
return true;
}
//--------------------------------------------------------------------------------
int CChangeNotificationSubSystem::GetNotifyCount()
{
return (int) m_nQueueSize;
}
//--------------------------------------------------------------------------------
bool CChangeNotificationSubSystem::AddToQueue(const FILE_NOTIFY_INFORMATION* pOrigInfo, int nIndex)
{
CSingleLock lock(&m_mutex, false);
if(! lock.Lock(1000))
return false;
CFileNotifyInformationContainer* pNew = new CFileNotifyInformationContainer;
if(pNew == NULL)
return false;
pNew->m_pInfo = new CFileNotifyInformation(pOrigInfo);
if(pNew->m_pInfo == NULL)
{
delete pNew;
return false;
}
pNew->m_nPathIndex = nIndex;
m_queue.AddTail(pNew);
::InterlockedIncrement(&m_nQueueSize);
return true;
}
//--------------------------------------------------------------------------------
bool CChangeNotificationSubSystem::AddWatchPath(LPCTSTR pPath, bool bWatchSubDir, DWORD nFilter)
{
CSingleLock lock(&m_mutPaths, false);
if(! lock.Lock())
return false;
if(! PreAddWatchPath(pPath))
return false;
int nIndex = m_sWatchedPaths.Add(pPath);
AddThread((CThreadObject*) new CChangeNotificationThread(this, nIndex, bWatchSubDir, nFilter));
return true;
}
//--------------------------------------------------------------------------------
LPCTSTR CChangeNotificationSubSystem::GetPath(int nIndex)
{
CSingleLock lock(&m_mutPaths, false);
if(! lock.Lock())
return NULL;
if(nIndex >= m_sWatchedPaths.GetSize())
return NULL;
return m_sWatchedPaths.GetAt(nIndex);
}
| [
"[email protected]"
] | [
[
[
1,
108
]
]
] |
4e253bf2844b0a06f2aa7f39d5639d16744df42f | 65a392af0450708ed4fa26f66393e12bdf387634 | /Include/mU/Kernel.h | 4a67a5ff2ec65cbecf4150848414804dfb58fd2d | [] | no_license | zhouxs1023/mU | d5abea6e883cb746aa28ff6ee2b3902babb053d8 | c9ecc5f0a4fd13567b3c9ca24ff05ba149af743e | refs/heads/master | 2021-05-27T11:37:59.464639 | 2011-06-17T22:39:25 | 2011-06-17T22:39:25 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 10,184 | h | #pragma once
#include "Var.h"
#include "UnicodeDevice.h"
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#ifdef _MSC_VER
#define DLLMAIN_DECL
#else
#ifdef __MINGW32__
#define DLLMAIN_DECL extern "C"
#else
#error "unknown toolchain"
#endif
#endif
#define DLLMAIN(x)\
DLLMAIN_DECL BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)\
{\
switch (ul_reason_for_call)\
{\
case DLL_PROCESS_ATTACH: x(); break;\
case DLL_THREAD_ATTACH:\
case DLL_THREAD_DETACH:\
case DLL_PROCESS_DETACH:\
break;\
}\
return TRUE;\
}
#else
#define DLLMAIN(x) extern "C" void DllMain(){x();}
#include <sys/time.h>
#endif
namespace mU {
//////////////////////////////////////
#ifdef _WIN32
struct timer
{
timer() { QueryPerformanceFrequency(&Frequency); }
void start() { QueryPerformanceCounter(&timerB); }
void end()
{
QueryPerformanceCounter(&timerE);
value = (double)(timerE.QuadPart - timerB.QuadPart)
/ (double)Frequency.QuadPart * 1000000.0;
}
LARGE_INTEGER timerB, timerE, Frequency;
double value;
};
#else
struct timer
{
timer() {}
void start() { gettimeofday(&timerB,NULL); }
void end()
{
gettimeofday(&timerE,NULL);
value = (double)((timerE.tv_usec - timerB.tv_usec)
+ (timerE.tv_sec - timerB.tv_sec) * 1000000);
}
timeval timerB, timerE;
double value;
};
#endif
// 内核初始化函数
API void Initialize();
// 表达式排序相关函数
API int Compare(Var,Var);
inline bool Before(Var x, Var y) { return Compare(x,y) < 0; }
inline bool Same(Var x, Var y) { return Compare(x,y) == 0; }
inline bool After(Var x, Var y) { return Compare(x,y) > 0; }
struct Before2 { inline bool operator()(Var x, Var y) const { return Before(x,y); } };
struct After2 { inline bool operator()(Var x, Var y) const { return After(x,y); } };
API int Order(Var,Var);
inline bool Less(Var x, Var y) { return Order(x,y) < 0; }
inline bool Equal(Var x, Var y) { return Order(x,y) == 0; }
inline bool Greater(Var x, Var y) { return Order(x,y) > 0; }
struct Less2 { inline bool operator()(Var x, Var y) const { return Less(x,y); } };
struct Greater2 { inline bool operator()(Var x, Var y) const { return Greater(x,y); } };
inline void Sort(Var x) { std::sort(CVec(x).begin(),CVec(x).end(),Less); }
API bool FreeQ(Var,Var);
// 符号定义相关
typedef std::map<Var,var> map_t;
typedef std::map<var,var,Before2> dict_t;
typedef std::map<var,std::pair<var,var>,Before2> def_t;
typedef std::set<Var> attr_t;
typedef var(*CProc)(Var);
typedef var(*COper)(Var,Var);
API map_t OwnValues;
API std::map<Var,dict_t> FactValues;
API std::map<Var,def_t> DownValues;
API std::map<Var,def_t> SubValues;
API std::map<Var,map_t> Properties;
API std::map<Var,attr_t> Attributes;
API stdext::hash_map<Var,CProc> CProcs;
API stdext::hash_map<Var,COper> COpers;
API var Eval(Var);
API void Set(Var,Var);
API void Unset(Var);
API void Clear(Var);
API var Thread(Var,Var);
API void Flatten(Var,Var);
API void Flatten(Var,Var,Var);
API void FlattenAll(Var,Var);
API void FlattenAll(Var,Var,Var);
// 测试某个表达式中是否不含有模式??
API bool FixQ(Var);
API var Supply(Var,Var,Var);
template <typename T>
var Subs(const T& m, Var x)
{
typename T::const_iterator
iter = m.find(x);
if(iter != m.end())
return iter->second;
if(VecQ(x))
{
size_t n = Size(x);
var r = Vec(n);
for(size_t i = 0; i < n; ++i)
At(r,i) = Subs(m,At(x,i));
return r;
}
if(ExQ(x))
return Ex(Subs(m,Head(x)),Subs(m,Body(x)));
return x;
}
// 符号表相关
API var Contexts;
API stdext::hash_map<Var,const wchar*> ContextName;
API std::stack<Var> ContextStack;
API std::stack<std::list<Var> > ContextPath;
inline var Context() { return ContextStack.top(); }
inline void Begin(Var x) { ContextStack.push(x); }
inline void End() { ContextStack.pop(); }
API void BeginPackage(Var);
API void EndPackage();
API var Ctx(const wstring&);
API var Sym(const wstring&);
API var Ctx2(const wchar*);
API var Sym2(const wchar*);
API wstring Unique();
API var Optimi(Var);
API var Read(wistream&,Var = 0);
API var Parse(wistream& = wcin);
inline var ParseString(const wstring &x)
{
wistringstream i(x);
return Parse(i);
}
inline var ParseFile(const wstring &x)
{
// TODO: 考察在各个平台下这样读入文件时系统是否都会正确的做字符编码转换
// 在GNU/Linux下,使用locale::global应用默认区域设置之后就OK
// Windows平台待测试
wifstream i(to_string(x.c_str(), x.length()).c_str());
return Parse(i);
}
API var Pretty(Var);
API void Write(wostream&,Var);
API void Print(Var,wostream& = wcout,size_t = 0);
inline void Println(Var x, wostream &f = wcout)
{
Print(Pretty(x),f);
f << std::endl;
}
API void FullPrint(Var,wostream& = wcout);
API void BoxPrint(Var,wostream& = wcout,size_t = 0);
#define TAG(x) tag_##x
#define WRAP(x) wrap_##x
#define Wrap(f) var WRAP(f)(Var x)
#define Wrap2(f) var WRAP(f)(Var x, Var y)
API var
Global, System, Null, True, False, Nil,
Constant, Flat, HoldAll, HoldAllComplete, HoldFirst,
HoldRest, Listable, Locked, NHoldAll, NHoldFirst,
NHoldRest, NumericFunction, OneIdentity, Orderless, Protected,
ReadProtected, SequenceHold, Stub, Temporary,
TAG(Symbol), TAG(List), TAG(String), TAG(Integer), TAG(Rational), TAG(Real),
TAG(Postfix), TAG(Prefix), TAG(Differential), TAG(Minus), TAG(Divide), TAG(Plus),
TAG(Times), TAG(Power), TAG(Return), TAG(Continue), TAG(Break), TAG(Set), TAG(Rule),
TAG(Pattern), TAG(Blank), TAG(Optional), TAG(Condition), TAG(PatternTest),
TAG(Unevaluated), TAG(Derivative), TAG(Function), TAG(Slot), TAG(BlankSequence),
TAG(SlotSequence), TAG(Part), TAG(Property), TAG(Sequence), TAG(Sqrt), TAG(Radical),
TAG(RuleDelayed), TAG(SetDelayed), TAG(CompoundExpression), TAG(Integrate), TAG(D), TAG(Sum), TAG(Limit),
TAG(Infinity), TAG(Pi), TAG(E), TAG(I), TAG(Mod), TAG(Dot), TAG(Pow),
TAG(Timing), TAG(And), TAG(Or), TAG(Not), TAG(If), TAG(For), TAG(While), TAG(Flatten), TAG(FlattenAll),
TAG(SameQ), TAG(Less), TAG(Equal), TAG(Greater), TAG(UnsameQ), TAG(GreaterEqual), TAG(Unequal), TAG(LessEqual),
TAG(FreeQ), TAG(MatchQ), TAG(MemberQ), TAG(With), TAG(Block), TAG(Module), TAG(ReplaceRepeated),
TAG(Replace), TAG(ReplaceAll), TAG(OddQ), TAG(EvenQ), TAG(SetAttributes), TAG(StringJoin), TAG(Join), TAG(Attributes),
TAG(Get), TAG(Put), TAG(PutAppend), TAG(Install), TAG(Uninstall), TAG(NumberQ), TAG(AtomQ), TAG(IntegerQ),
TAG(SymbolQ), TAG(StringQ), TAG(Pretty), TAG(Input), TAG(Print), TAG(Clear), TAG(BeginPackage), TAG(EndPackage),
TAG(Begin), TAG(End), TAG(Evaluate), TAG(Dispatch), TAG(Length), TAG(Path), TAG(Head), TAG(Context),
TAG(Contexts), TAG(ContextPath), TAG(Apply), TAG(Map), TAG(Unset), TAG(Full), TAG(ToString), TAG(ToExpression),
TAG(Exit), TAG(Quit), TAG(Hold), TAG(Run), TAG(Task), TAG(Kill), TAG(Array), TAG(Table), TAG(Do), TAG(Box),
TAG(N), TAG(IntegerPart), TAG(Floor), TAG(Ceiling), TAG(Round), TAG(Expand), TAG(Variables), TAG(Coefficient),
TAG(Exponent), TAG(Deg), TAG(CoefficientList), TAG(FromCoefficientList), TAG(Graphics2D), TAG(Graphics3D),
TAG(Options), TAG(StringLength), TAG(StringInsert), TAG(StringTake), TAG(StringDrop);
#define DEF_SYSTEM_SYM(x) x = Sym(_W(#x),System);
#define DEF_SYSTEM_TAG_SYM(x) TAG(x) = Sym(_W(#x),System);
#define DEF_CPROC(x) CProcs[TAG(x)] = x;
#define DEF_WRAPPED_CPROC(x) CProcs[TAG(x)] = WRAP(x);
#define DECL_TAG_SYM_WRAPPED_CPROC(x) var DEF_SYSTEM_TAG_SYM(x)DEF_WRAPPED_CPROC(x)
#define DEF_WRAPPED_COPER(x) COpers[TAG(x)] = WRAP(x);
#define DECL_TAG_SYM_WRAPPED_COPER(x) var DEF_SYSTEM_TAG_SYM(x)DEF_WRAPPED_COPER(x)
#define SET_ATTR(x,y) Attributes[TAG(x)].insert(y);
inline var Tag(Var x)
{
switch(Type(x))
{
case TYPE(obj): return (dynamic_cast<obj_t*>(x))->tag();
case TYPE(int): return TAG(Integer);
case TYPE(rat): return TAG(Rational);
case TYPE(flt): return TAG(Real);
case TYPE(str): return TAG(String);
case TYPE(sym): return TAG(Symbol);
case TYPE(vec): return TAG(List);
default:
return Head(x);
}
}
inline bool ZeroQ(Var x)
{
return (IntQ(x) && mpz_cmp_ui(CInt(x),0L) == 0)
|| (RatQ(x) && mpq_cmp_ui(CRat(x),0L,1L) == 0)
|| (FltQ(x) && mpf_cmp_ui(CFlt(x),0L) == 0)
;
}
inline bool OneQ(Var x)
{
return (IntQ(x) && mpz_cmp_ui(CInt(x),1L) == 0)
|| (RatQ(x) && mpq_cmp_ui(CRat(x),1L,1L) == 0)
|| (FltQ(x) && mpf_cmp_ui(CFlt(x),1L) == 0)
;
}
inline bool NOneQ(Var x)
{
return (IntQ(x) && mpz_cmp_si(CInt(x),-1L) == 0)
|| (RatQ(x) && mpq_cmp_si(CRat(x),-1L,1L) == 0)
|| (FltQ(x) && mpf_cmp_si(CFlt(x),-1L) == 0)
;
}
inline bool OddQ(Var x)
{
return IntQ(x) && mpz_odd_p(CInt(x));
}
inline bool EvenQ(Var x)
{
return IntQ(x) && mpz_even_p(CInt(x));
}
// 四则运算
API var Plus(Var);
API var Plus(Var,Var);
API var Times(Var);
API var Times(Var,Var);
API var Power(Var,Var);
API var Mod(Var,Var);
API var Dot(Var);
API var Dot(Var,Var);
API void Do(Var,size_t,const var*);
API var Table(Var,size_t,const var*);
API var Array(Var,Var,size_t,const var*);
API var Array(Var,Var,size_t,const var*,const var*);
// 基本数值计算
API var Evalf(Var);
API var Evalf(Var,size_t);
API var IntegerPart(Var);
API var Floor(Var);
API var Ceiling(Var);
API var Round(Var);
inline var Timing(Var x)
{
timer t;
t.start();
var r = Eval(x);
t.end();
return Vec(Int(t.value),r);
}
API wstring Path();
API var Install(const wstring&);
API bool Uninstall(Var);
API bool Run(const wstring&);
//API var Task(Var);
//API bool Kill(Var);
// 多项式基本操作
API void Expand(Var,Var,Var);
API var Expand(Var,Var);
API var Expand(Var);
API var Variables(Var);
API void Coefficient(Var,Var,Var);
API var Coefficient(Var,Var);
API var Exponent(Var,Var);
API var Deg(Var,Var);
API var Coefficients(Var,Var);
API var CoefficientList(Var,Var);
API var FromCoefficients(Var,Var);
API var FromCoefficientList(Var,Var);
//////////////////////////////////////
}
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
2
],
[
4,
29
],
[
35,
36
],
[
38,
65
],
[
68,
68
],
[
71,
76
],
[
78,
84
],
[
89,
102
],
[
104,
107
],
[
109,
113
],
[
116,
116
],
[
118,
118
],
[
120,
138
],
[
141,
153
],
[
156,
156
],
[
158,
166
],
[
171,
182
],
[
184,
213
],
[
224,
227
],
[
229,
238
],
[
240,
246
],
[
248,
254
],
[
256,
262
],
[
275,
282
],
[
284,
287
],
[
290,
295
],
[
297,
304
],
[
306,
309
],
[
314,
327
]
],
[
[
3,
3
],
[
30,
34
],
[
37,
37
],
[
66,
67
],
[
69,
70
],
[
77,
77
],
[
85,
88
],
[
103,
103
],
[
108,
108
],
[
114,
115
],
[
117,
117
],
[
119,
119
],
[
139,
140
],
[
154,
155
],
[
157,
157
],
[
167,
170
],
[
183,
183
],
[
214,
223
],
[
228,
228
],
[
239,
239
],
[
247,
247
],
[
255,
255
],
[
263,
274
],
[
283,
283
],
[
288,
289
],
[
296,
296
],
[
305,
305
],
[
310,
313
]
]
] |
02483ab64ac906f6bb045bdd14b2b69c83cba3aa | 1e01b697191a910a872e95ddfce27a91cebc57dd | /GrfInsertTextOnceToFloatingLocation.h | 682a440a4708bb4937a6c71d516eb4d109a45d1c | [] | no_license | canercandan/codeworker | 7c9871076af481e98be42bf487a9ec1256040d08 | a68851958b1beef3d40114fd1ceb655f587c49ad | refs/heads/master | 2020-05-31T22:53:56.492569 | 2011-01-29T19:12:59 | 2011-01-29T19:12:59 | 1,306,254 | 7 | 5 | null | null | null | null | IBM852 | C++ | false | false | 2,277 | h | /* "CodeWorker": a scripting language for parsing and generating text.
Copyright (C) 1996-1997, 1999-2010 CÚdric Lemaire
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
To contact the author: [email protected]
*/
#ifndef _GrfInsertTextOnceToFloatingLocation_h_
#define _GrfInsertTextOnceToFloatingLocation_h_
//##protect##"INCLUDE FILES"
//##protect##"INCLUDE FILES"
#include "GrfCommand.h"
namespace CodeWorker {
class ExprScriptExpression;
class GrfInsertTextOnceToFloatingLocation : public GrfCommand {
private:
ExprScriptExpression* _pLocation;
ExprScriptExpression* _pText;
//##protect##"attributes"
DtaScriptVariable* const* _pOutputCoverage;
//##protect##"attributes"
public:
GrfInsertTextOnceToFloatingLocation() : _pLocation(NULL), _pText(NULL) {
//##protect##"constructor"
_pOutputCoverage = NULL;
//##protect##"constructor"
}
virtual ~GrfInsertTextOnceToFloatingLocation();
virtual const char* getFunctionName() const { return "insertTextOnceToFloatingLocation"; }
inline void setLocation(ExprScriptExpression* pLocation) { _pLocation = pLocation; }
inline void setText(ExprScriptExpression* pText) { _pText = pText; }
//##protect##"interface"
void prepareCoverage(DtaScriptVariable* const* pOutputCoverage);
//##protect##"interface"
virtual void compileCpp(CppCompilerEnvironment& theCompilerEnvironment) const;
protected:
virtual SEQUENCE_INTERRUPTION_LIST executeInternal(DtaScriptVariable& visibility);
//##protect##"declarations"
//##protect##"declarations"
};
}
#endif
| [
"cedric.p.r.lemaire@28b3f5f3-d42e-7560-b87f-5f53cf622bc4"
] | [
[
[
1,
71
]
]
] |
c793e9b110be58374c143febc6cc12b2142df796 | e220295e53990c314fab38f90f8d1021b5e656a4 | /Queue.h | 5279185472f98a4285beb18363e31bec0a80d34c | [] | no_license | mcteapot/TowerOfHanoi | 41b917fb6635f073ca791826543f38a75572ab49 | 40e9982f957be4c64dc2aeafd95c3401f2b9c3c1 | refs/heads/master | 2016-09-06T10:19:38.126050 | 2011-04-25T00:38:06 | 2011-04-25T00:38:06 | 1,629,072 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,075 | h |
#ifndef QUEUE_H
#define QUEUE_H
#include <iostream>
#include <cstdlib>
#include <assert.h>
#include <cmath>
#include "Node.h"
using namespace std;
//NOTE: THE HIGHER THE PRIORITY NUMBER, THE HIGHER IT'S PRIORITY ALSO THE NEWEST IT IS.
// THE LOWER THE PRIORITY NUMBER THE OLDER THE DISK IS ON THE POLE AND THE LOWER ITS
// PLACE IS IN THE QUEUE.
template<class T>
class Queue
{
public:
//NOTE: when creating an instance of a pole other than pole #1,
// use single arguement constructor... i.e B(A), C(A) and put A as arguement.
//NOTE: for pole #1, create the instance with the size the user enters
// as its arguement ... A(size). and THEN CREATE it using the create()
// function. i.e A.create(); this will fill up the first pole
// for gameplay. Refer to main.cpp for more examples...
Queue();//default constructor
Queue(int size);
~Queue();//destructor
//Queue(Queue& other);
Queue& operator=(Queue& other);
//void copy(Queue& other);
void fresh();//sets variables to 0 and ptrs to null.
void display();//prints out all elements in queue
void create();//creates first list at pole 1 with desired number of disks
Queue(Queue &object);//Gets the number of disks user enters from object A and assigns to
//newly created object... Sets standard number of disks available
//at any time in game play to all poles (rods) and assigns it.
T front(); // newest node in queue
T top();
int disks();//accessor of private variable qty. Total disks in play. User input.
T back();//oldest node in queue
int size();//returns size of queue
T prev();//returns node 2nd node from the back(). second disk down from top of pole
void enqueue(T item);
void dequeue();
void push(T item);
void pop();
void clear();
bool search(T item);//returns true if node exists in queue
bool isEmpty();//returns true if queue is empty
bool empty();//calls isEmpty() and returns bool
bool isFull();//returns true if queue is full
bool checks(T item); //test
private:
int count, qty;//count is the number or nodes on pole and qty is the number of disks in game
static int temp; //"size"
node<T> *low, *high, *entry, *newnode;//points of type node to help walk link list and etc
void deLinkList();//destroys link list
void initQueue();//initialize link list
};
template<class T>
int Queue<T>::temp = 0;//done
template<class T>
T Queue<T>::back()//done
{
entry = low;
assert(entry != NULL);
entry = entry->ptr;
return entry->priority;
}
template<class T>
T Queue<T>::front()//done
{
if(low != NULL)
{
assert(high != NULL);
return high->priority;
}
return 0;
/* ALTERNATE CODE FOR ABOVE...
{
int temp = 0;
entry = low->ptr;
for(entry=entry->ptr; entry->ptr != NULL; entry = entry->ptr)
temp = entry->priority;
return temp;
}
*/
}
template<class T>
void Queue<T>::fresh()
{
low = NULL;
high = NULL;
newnode = NULL;
entry = NULL;
count = 0;
qty = 0;
}
template<class T>
Queue<T>::Queue()//done
{
low = new node<T>;
low->ptr = NULL;
high = low;
count = 0;
qty = 0;
initQueue();
}
template<class T>
Queue<T>::Queue(int size)//done
{
low = new node<T>;
low->ptr = NULL;
high = low;
qty = size;
count = 0;
initQueue();
}
template<class T>
Queue<T>::Queue(Queue &object)//done
{
low = new node<T>;
low->ptr = NULL;
high = low;
count = 0;
initQueue();
qty = object.disks();
}
template<class T>
int Queue<T>::disks()
{
return qty;
}
template<class T>
T Queue<T>::top()
{
return front();
}
template<class T>
void Queue<T>::initQueue()//done
{
newnode = new node<T>;
//newnode->priority = 0;
newnode->ptr = NULL;
high->ptr = newnode;
high = newnode;
low = newnode;
}
template<class T>
Queue<T>::~Queue()
{
//fresh();
deLinkList();
}
template<class T>
void Queue<T>::create()//done
{
for(int k = qty; k > 0; k--)
{
newnode = new node<T>;
newnode->priority = k;
newnode->ptr = NULL;
high->ptr = newnode;
high = newnode;
}
}
template<class T>
void Queue<T>::deLinkList()
{
node<T> *current, *tmp;
current = low->ptr;
low->ptr = NULL;
while(current != NULL)
{
tmp = current->ptr;
delete(current);
current = tmp;
}
high = NULL;
count = 0;
qty = 0;
}
template<class T>
void Queue<T>::enqueue(T item)//done
{
//if(check(item))
//{
node<T> *temp;
temp = new node<T>;
temp->priority = item;
temp->ptr = NULL;
high = low;
while(high->ptr != NULL)
{
high = high->ptr;
}
if(high->ptr == NULL)
{
high->ptr = temp;
high = temp;
count++;
qty++;
//cout << "Successfull enqueue!\n";
}
//else
//cout << "Enqueue unsuccessful!\n";
//}
//else
//cout << "full or disk already exists\n";
}
template<class T>
void Queue<T>::pop()//done
{
dequeue();
}
template<class T>
void Queue<T>::push(T item)//done
{
enqueue(item);
}
template<class T>
void Queue<T>::clear()
{
deLinkList();
}
template<class T>
void Queue<T>::dequeue()//done
{
if(checks(-2))
{
node<T> *next;
high = low;
//system("pause");
next = high->ptr;
while(next->ptr != NULL)
{
high = high->ptr;
next = next->ptr;
}
if(next->ptr == NULL)
{
temp = next->priority;
high->ptr = next->ptr;
count--;
qty--;
delete next;
}
//cout << "Dequeue Successful!\n";}
//else
//cout << "Dequeue unsuccessful!\n";
}
//else
// cout << "Dequeue Empty\n";
}
template<class T>
int Queue<T>::size()//done
{
count = 0;
entry = low->ptr;
if(low->ptr != NULL)
{
//cout << "beore assignment\n";
//entry = low->ptr;
//cout << "outside while loop\n";
while(entry != NULL)
{
entry = entry->ptr;
++count;
}
}
else
;
//cout << "low->ptr = NULL " << endl;
return count;
}
template<class T>
bool Queue<T>::search(T item)//done
{
node<T> *entry;
entry = new node<T>;
entry = low->ptr;
while(entry != NULL && item != entry->priority)
entry = entry->ptr;
if (entry == NULL)
{
delete entry;
return false;
}
else
delete entry;
return true;
}
template<class T>
void Queue<T>::display()//done
{
//if(checks(-3))
//{
//cout << "Queue for pole is ...\n";
entry = low->ptr;
while(entry != NULL)
{
cout << "Priority: " << entry->priority << endl;
entry = entry->ptr;
}
//}
//else
//cout << "empty\n";
}
template<class T>
bool Queue<T>::isEmpty()//done
{
if (size() == 0)
return true;
return false;
}
template<class T>
bool Queue<T>::empty()
{
return isEmpty();
}
template<class T>
bool Queue<T>::isFull()//done
{
return (size() == qty);
}
template<class T>
bool Queue<T>::checks(T item)//done. Works like a switch statement. item is a function code.
{
if (item == -2 && !isEmpty()) { //if -2 is passed, then calling
return true; //from the dequeue function or prev or somethin else.
}
else if(item == -3 && size() > 0) { //meant for prev function
return true;
}
else if(item == -4 && front() < prev()) {// code (-4) is used for comparing
return true; //priorities amongst the queue. true if disk to
//be added is smaller than the one already there.
}
else if(!isFull() && item > 0 && !search(item)) { //calling from enqueue function
return true;
}
else{
return false;
}
}
template<class T>
T Queue<T>::prev()//function code (-3). done
{
if(checks(-3))
{
node<T> *current;
high = low;
current = high->ptr;
while(current->ptr != NULL)//in here, current is the leader and high is following one behind...
{ // so if current->ptr == NULL then current is the last node and is
high = high->ptr; // represented by back(). high is then the node one below in priority.
current = current->ptr;
}
return high->priority;
}
else
return -3;
}
#endif // QUEUE_H
| [
"[email protected]"
] | [
[
[
1,
415
]
]
] |
444a0b295d14302c2c3bbd49a42e87a73a2f5d17 | 2a6a2adbc18d74e89152324dacd7ffe190fcd7cc | /old/B(n, k)/B(n, k)/tabloid test/TabloidTest.cpp | 7b5c4c296720744cb01a7a34cd0169ef9c7100aa | [] | no_license | swenson/Tabloid-Terror | fcb848e2bd9817009f8e0d5312162bd0d7d44825 | 8880b2af2da6f0635a311105d80f8b94bd7cc072 | refs/heads/master | 2021-01-16T22:46:01.908023 | 2010-12-08T02:29:21 | 2010-12-08T02:29:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,587 | cpp | #include <iostream>
#include "poset homology\tabloid.h"
#include "Partition.h"
#include "poset homology\Perm.h"
void main(void) {
cout << "\nTesting blank constructor";
tabloid t;
cout << "\nTesting constructor of a tabloid of shape 311";
Partition lambda;
lambda.Add(3);
lambda.Add(2);
lambda.Add(1);
tabloid s(lambda);
cout << "\nGetting the standard tabloid of shape 311";
s = standardoid(lambda);
cout << "\nTesting output";
cout << s;
cout << "\nTesting Sn action";
Perm sigma(6);
sigma[1]=6;
sigma[2]=3;
sigma[3]=1;
sigma[4]=2;
sigma[5]=5;
sigma[6]=4;
cout << "\nApplying ";
cout << sigma;
cout << sigma * s;
cout << "\nNote that ";
cout << s;
cout << " has " << s.RowNumber() << " of rows";
cout << " and the second row is \n";
rows temp = s.Row(2);
for (rows::const_iterator iter2 = temp.begin(); iter2 != temp.end(); ++iter2) {
cout << " " << *iter2;
}
// reorder the rows of a tabloid Note it no longer have the shape of a paritition
Perm tau(3);
tau[1]=2;
tau[2]=3;
tau[3]=1;
cout << "\nReordering rows of ";
cout << s;
cout << " with ";
cout << tau;
tabloid q = reorderrows(tau, s);
cout << q;
// void insert(const vector<int> row);
cout << "\nNow we insert a row of 7, 8, 9";
vector<int> rowtemp;
rowtemp.push_back(7);
rowtemp.push_back(8);
rowtemp.push_back(9);
q.insert(rowtemp);
cout << q;
// void Add(const int row, const int value);
cout << "\nNow we add a 10 to row 2";
q.Add(2,10);
cout << q;
int crap;
cin >> crap;
} | [
"smaug@blue.(none)"
] | [
[
[
1,
75
]
]
] |
e6f74a1d0954e5ae861909adbf400e1d26f13176 | 6f796044ae363f9ca58c66423c607e3b59d077c7 | /source/GuiBase/TextRender.cpp | 642523b69a08ef522ee687c1c7907959c0c3bc12 | [] | no_license | Wiimpathy/bluemsx-wii | 3a68d82ac82268a3a1bf1b5ca02115ed5e61290b | fde291e57fe93c0768b375a82fc0b62e645bd967 | refs/heads/master | 2020-05-02T22:46:06.728000 | 2011-10-06T20:57:54 | 2011-10-06T20:57:54 | 178,261,485 | 2 | 0 | null | 2019-03-28T18:32:30 | 2019-03-28T18:32:30 | null | UTF-8 | C++ | false | false | 6,347 | cpp | /***************************************************************
*
* Copyright (C) 2008-2011 Tim Brugman
*
* Based on code of "DragonMinded"
*
* This file may be licensed under the terms of of the
* GNU General Public License Version 2 (the ``GPL'').
*
* Software distributed under the License is distributed
* on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either
* express or implied. See the GPL for the specific language
* governing rights and limitations.
*
* You should have received a copy of the GPL along with this
* program. If not, go to http://www.gnu.org/licenses/gpl.html
* or write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
***************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <malloc.h>
#include "TextRender.h"
TextRender::TextRender()
{
// Initialize the library
FT_Error error = FT_Init_FreeType(&m_library);
// Default values
m_yspacing = DEFAULT_Y_CUSHION;
if(error)
{
// Better handling in the future
exit(0);
}
}
TextRender::~TextRender()
{
// Free the library (and all resources)
FT_Done_FreeType(m_library);
}
void TextRender::SetFont(string path)
{
// Initialize a font
FT_Error error = FT_New_Face(m_library, path.c_str(), 0, &m_face);
if ( error )
{
// Better handling in the future
exit(0);
}
}
void TextRender::SetFont(const unsigned char* font, int size)
{
// Initialize a font
FT_Error error = FT_New_Memory_Face(m_library, font, size, 0, &m_face);
m_fontheight = size;
if ( error )
{
// Better handling in the future
exit(0);
}
}
void TextRender::SetColor(GXColor c)
{
m_color = c;
}
void TextRender::SetSize(int s)
{
// Set up the font face (see freetype samples for magic values)
FT_Set_Pixel_Sizes(m_face, 0, s);
m_fontheight = s;
}
void TextRender::SetYSpacing(int s)
{
m_yspacing = s + DEFAULT_Y_CUSHION;
}
void TextRender::SetBuffer(uint8_t *buf, int width, int height, int bufwidth)
{
// Set up a buffer to render to (RGBA quads, most likely to be blitted into a GuiTextImage and rendered using libwiisprite)
m_buf = buf;
m_width = width;
m_height = height;
m_bufwidth = bufwidth;
}
void TextRender::Blit(FT_Bitmap *bmp, int left, int top)
{
int runWidth = bmp->width;
int runHeight = bmp->rows;
// Precalculate the width
if((left + bmp->width) >= m_width)
{
// Run height needs adjustment
runWidth = m_width - (left + bmp->width);
}
// Precalculate the height
if((top + bmp->rows) >= m_height)
{
// Run height needs adjustment
runHeight = m_height - (top + bmp->rows);
}
// Copy alpha data over, setting the color to the predefined color and the alpha to the value of the glyph
for(int y = 0; y < runHeight; y++)
{
// Precalculate
int sywidth = (y * bmp->width);
int dywidth = ((y + top) * m_bufwidth);
for(int x = 0; x < runWidth; x++)
{
// Precalculate
int srcloc = x + sywidth;
int dstloc = ((x + left) + dywidth) << 2;
// Copy data over
m_buf[dstloc] = m_color.b;
m_buf[dstloc + 1] = m_color.g;
m_buf[dstloc + 2] = m_color.r;
m_buf[dstloc + 3] = ((uint8_t *)bmp->buffer)[srcloc];
}
}
}
extern "C" void archThreadSleep(int milliseconds);
void TextRender::RenderSimple(const char *out, bool center, int *sx, int *sy)
{
// Remember x position
int maxx = 0;
int x = DEFAULT_X;
int y = DEFAULT_Y;
// Shortcut from examples
FT_GlyphSlot slot = m_face->glyph;
// Render
bool newline = true;
for(uint32_t i = 0; i < strlen(out); i++)
{
if(center && newline) {
int j = i;
int s = 0;
while(out[j] != '\0' && out[j] != '\r' && out[j] != '\n') {
FT_Error error = FT_Load_Char(m_face, out[j], FT_LOAD_RENDER);
if(error) break; /* break on error */
s += slot->advance.x >> 6;
j++;
}
x += (m_width - s) >> 1;
if( x < 0 ) x = 0;
newline = false;
}
if(out[i] == '\r' || out[i] == '\n')
{
// Newline
x = DEFAULT_X;
y += m_fontheight + m_yspacing;
newline = true;
continue;
}
else if(out[i] == '\t')
{
// Truncate to floor (nearest bounds)
x /= DEFAULT_TAB_SPACE;
x *= DEFAULT_TAB_SPACE;
// Add tab stop
x += DEFAULT_TAB_SPACE;
continue;
}
// Render glyph
FT_Error error = FT_Load_Char(m_face, out[i], FT_LOAD_RENDER);
if(error) continue; /* ignore errors */
// Blit glyph to surface
if( sx == NULL && sy == NULL ) {
Blit(&slot->bitmap, x + slot->bitmap_left, (y + m_fontheight) - slot->bitmap_top - 4);
}
// Advance the position
x += slot->advance.x >> 6;
if( x > maxx ) maxx = x;
}
if( sx ) *sx = maxx + 1;
if( sy ) *sy = y + m_fontheight + 4;
}
void TextRender::GetTextSize(int *sx, int *sy, bool center, const char *fmt, ...)
{
// Need to make room for the sprintf'd text
char *out = (char *)malloc(1024);
// Build using sprintf
va_list marker;
va_start(marker,fmt);
vsprintf(out,fmt,marker);
va_end(marker);
// Call rendering engine
RenderSimple(out, center, sx, sy);
// Free memory
free(out);
}
void TextRender::Render(const char *fmt, ...)
{
// Need to make room for the sprintf'd text
char *out = (char *)malloc(1024);
// Build using sprintf
va_list marker;
va_start(marker,fmt);
vsprintf(out,fmt,marker);
va_end(marker);
// Call rendering engine
RenderSimple(out);
// Free memory
free(out);
}
| [
"[email protected]",
"timbrug@c2eab908-c631-11dd-927d-974589228060"
] | [
[
[
1,
20
],
[
32,
32
],
[
35,
35
],
[
47,
47
],
[
53,
53
],
[
62,
62
],
[
65,
66
],
[
77,
77
],
[
83,
84
],
[
89,
89
],
[
94,
98
],
[
107,
107
],
[
110,
110
],
[
114,
114
],
[
117,
117
],
[
125,
125
],
[
134,
137
],
[
152,
152
],
[
162,
162
],
[
167,
167
],
[
176,
176
],
[
194,
194
],
[
199,
199
],
[
207,
207
]
],
[
[
21,
31
],
[
33,
34
],
[
36,
46
],
[
48,
52
],
[
54,
61
],
[
63,
64
],
[
67,
76
],
[
78,
82
],
[
85,
88
],
[
90,
93
],
[
99,
106
],
[
108,
109
],
[
111,
113
],
[
115,
116
],
[
118,
124
],
[
126,
133
],
[
138,
151
],
[
153,
161
],
[
163,
166
],
[
168,
175
],
[
177,
193
],
[
195,
198
],
[
200,
206
],
[
208,
244
]
]
] |
a628a3f7ef2a0058e5438acb9dede9535f7537c5 | 58ef4939342d5253f6fcb372c56513055d589eb8 | /Tangram3D/src/Tangram3DApplication.cpp | 3d82e455654d378cda3f83a3997858989c9c3c03 | [] | no_license | flaithbheartaigh/lemonplayer | 2d77869e4cf787acb0aef51341dc784b3cf626ba | ea22bc8679d4431460f714cd3476a32927c7080e | refs/heads/master | 2021-01-10T11:29:49.953139 | 2011-04-25T03:15:18 | 2011-04-25T03:15:18 | 50,263,327 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,292 | cpp | /*
============================================================================
Name : Tangram3DApplication.cpp
Author :
Copyright : Your copyright notice
Description : Main application class
============================================================================
*/
// INCLUDE FILES
#include "Tangram3D.hrh"
#include "Tangram3DDocument.h"
#include "Tangram3DApplication.h"
// ============================ MEMBER FUNCTIONS ===============================
// -----------------------------------------------------------------------------
// CTangram3DApplication::CreateDocumentL()
// Creates CApaDocument object
// -----------------------------------------------------------------------------
//
CApaDocument* CTangram3DApplication::CreateDocumentL()
{
// Create an Tangram3D document, and return a pointer to it
return CTangram3DDocument::NewL(*this);
}
// -----------------------------------------------------------------------------
// CTangram3DApplication::AppDllUid()
// Returns application UID
// -----------------------------------------------------------------------------
//
TUid CTangram3DApplication::AppDllUid() const
{
// Return the UID for the Tangram3D application
return KUidTangram3DApp;
}
// End of File
| [
"zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494"
] | [
[
[
1,
39
]
]
] |
8e8266efc77c22ef2c8716e62b25e700867ba109 | 2dbbca065b62a24f47aeb7ec5cd7a4fd82083dd4 | /OUAN/OUAN/Src/Audio/AudioComponent/AudioComponent.h | 0b449fe36161e50c0273904a32292493153b3571 | [] | no_license | juanjmostazo/once-upon-a-night | 9651dc4dcebef80f0475e2e61865193ad61edaaa | f8d5d3a62952c45093a94c8b073cbb70f8146a53 | refs/heads/master | 2020-05-28T05:45:17.386664 | 2010-10-06T12:49:50 | 2010-10-06T12:49:50 | 38,101,059 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 913 | h | #ifndef AUDIOCOMPONENTH_H
#define AUDIOCOMPONENTH_H
#include "../../Component/Component.h"
namespace OUAN{
/// The keys represent sound identifiers, whereas the values
/// will be the channel indexes.
typedef std::map<std::string, int> TAudioComponentMap;
class AudioSubsystem;
typedef boost::shared_ptr<AudioSubsystem> AudioSubsystemPtr;
class AudioComponent: public Component
{
public:
AudioComponent(AudioSubsystemPtr audioSS);
~AudioComponent();
void update(long elapsedTime);
void playSound(const std::string& soundID);
void stopSound(const std::string& soundID);
void setPauseSound(const std::string& soundID,bool pause);
void setSounds(const TAudioComponentMap& sounds);
bool isPlaying(const std::string& soundID);
bool isPaused(const std::string& soundID);
private:
TAudioComponentMap mSounds;
AudioSubsystemPtr mAudioSS;
};
}
#endif | [
"ithiliel@1610d384-d83c-11de-a027-019ae363d039"
] | [
[
[
1,
34
]
]
] |
53193e58de7adc325f649b454768c0d91aa95b10 | 3d7d8969d540b99a1e53e00c8690e32e4d155749 | /AppSrc/ImagicAppUi.cpp | 0845eaa80117cb1b92aa369d1c089cee4f2af606 | [] | no_license | SymbianSource/oss.FCL.sf.incubator.photobrowser | 50c4ea7142102068f33fc62e36baab9d14f348f9 | 818b5857895d2153c4cdd653eb0e10ba6477316f | refs/heads/master | 2021-01-11T02:45:51.269916 | 2010-10-15T01:18:29 | 2010-10-15T01:18:29 | 70,931,013 | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 21,093 | cpp | /*
* Copyright (c) 2009 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: Juha Kauppinen, Mika Hokkanen
*
* Description: Photo Browser
*
*/
// INCLUDE FILES
#include "ImagicAppUi.h"
#include <IEImage.h>
#include "ImagicViewBrowser.h"
#include "Imagic.hrh"
#include "MSVSTD.HRH"
#include <avkon.hrh>
#include <ImageConversion.h>
#include <aknutils.h>
#include "ImagicContainerBrowser.h"
//statuspane
#include <eikbtgpc.h>
#include <avkon.rsg>
//for loading text from resource
#include <aknnotewrappers.h>
#include <stringloader.h>
#include <PhotoBrowser.rsg>
#include "ImagicUtils.h"
// ================= MEMBER FUNCTIONS =======================
//
// ----------------------------------------------------------
// CImagicAppUi::ConstructL()
// ----------------------------------------------------------
//
void CImagicAppUi::ConstructL()
{
DP0_IMAGIC(_L("CImagicAppUi::ConstructL++"));
//CArrayFix<TCoeHelpContext>* buf = CCoeAppUi::AppHelpContextL();
//HlpLauncher::LaunchHelpApplicationL(iEikonEnv->WsSession(), buf);
iTNGenerationOnGoing = ETrue;
iMenuOn = EFalse;
iAppForeGround = ETrue;
//Set the font
//SetFont();
iImagesLoaded = EFalse;
iImageIndex = 0;
iWzContainerSatus = EFalse;
//iTotalNumOfImages = 0;
//iNumOfImagesLoaded = 0;
//iNumOfFacesLoaded = 0;
iNumberOfIterations = 0;
iUIDrawMode = EImages;
iBrowserContainer = NULL;
#ifdef USE_OOM
ROomMonitorSession oomMonitor;
oomMonitor.Connect();
TInt errorCode = oomMonitor.RequestFreeMemory( 1024*12 );
if ( errorCode != KErrNone )
{
// try one more time
errorCode = oomMonitor.RequestFreeMemory( 1024*12 );
}
oomMonitor.Close();
#endif
User::LeaveIfError(iFileServer.Connect());
//Initialises this app UI with standard values.
//The application’s standard resource file will be read unless
//the ENoAppResourceFile or ENonStandardResourceFile flags are passed.
BaseConstructL(0x08 | EAknEnableSkin); // Use ELayoutAwareAppFlag (0x08) to make the application support scalable UI on FP3 devices.
//Create engine and trap if there is error
iIEngine = CIEEngine::NewL(*this);
CleanupStack::PushL(iIEngine);
//Browser view
CImagicViewBrowser* viewBrowser = new (ELeave) CImagicViewBrowser;
CleanupStack::PushL( viewBrowser );
viewBrowser->ConstructL(this);
AddViewL( viewBrowser ); // transfer ownership to CAknViewAppUi
CleanupStack::Pop( viewBrowser );
iViewIdBrowser = viewBrowser->Id(); // view id to get view from CAknViewAppUi
SetDefaultViewL( *viewBrowser );
SetActiveView(BrowserView);
//disable statuspane to get full screen
StatusPane()->MakeVisible(EFalse);
//Creating Utility class
iImagicUtils = CImagicUtils::NewL(iFileServer);
//Create timer to release Browser view resources and init opengl
iPeriodic = CPeriodic::NewL( CActive::EPriorityIdle );
//Force orientation to be always landscape
SetOrientationL(CAknAppUiBase::EAppUiOrientationLandscape);
//SetOrientationL(CAknAppUiBase::EAppUiOrientationPortrait);
CleanupStack::Pop(iIEngine);
DP0_IMAGIC(_L("CImagicAppUi::ConstructL--"));
}
CArrayFix<TCoeHelpContext>* CImagicAppUi::HelpContextL() const
{
/*
//#warning "Please see comment about help and UID3..."
CArrayFixFlat<TCoeHelpContext>* array = new(ELeave)CArrayFixFlat<TCoeHelpContext>(1);
CleanupStack::PushL(array);
array->AppendL(TCoeHelpContext(KUidrsdApp, KGeneral_Information));
CleanupStack::Pop(array);
return array;
*/
}
void CImagicAppUi::CImagicAppUiReady()
{
iIEngine->AppUIReady();
}
// ----------------------------------------------------
// CImagicAppUi::~CImagicAppUi()
// Destructor
// Frees reserved resources
// ----------------------------------------------------
//
CImagicAppUi::~CImagicAppUi()
{
DP0_IMAGIC(_L("CImagicAppUi::~CImagicAppUi++"));
if(iImagicUtils)
{
delete iImagicUtils;
iImagicUtils = NULL;
}
iWizardBitmapArray.Close();
if(iPeriodic->IsActive())
iPeriodic->Cancel();
delete iPeriodic;
// Doesn't delete engine yet, since container needs it when destroyed!
//DestructEngine();
iFileServer.Close();
DP0_IMAGIC(_L("CImagicAppUi::~CImagicAppUi--"));
}
void CImagicAppUi::DestructEngine()
{
DP0_IMAGIC(_L("CImagicAppUi::DestructEngine++"));
delete iIEngine;
iIEngine = NULL;
DP0_IMAGIC(_L("CImagicAppUi::DestructEngine--"));
}
/*TInt CImagicAppUi::GetErrorCode()
{
return iEngineCreationError;
}*/
// ------------------------------------------------------------------------------
// CImagicAppUi::DynInitMenuPaneL(TInt aResourceId,CEikMenuPane* aMenuPane)
// This function is called by the EIKON framework just before it displays
// a menu pane. Its default implementation is empty, and by overriding it,
// the application can set the state of menu items dynamically according
// to the state of application data.
// ------------------------------------------------------------------------------
//
void CImagicAppUi::DynInitMenuPaneL(
TInt /*aResourceId*/,CEikMenuPane* /*aMenuPane*/)
{
DP0_IMAGIC(_L("CImagicAppUi::DynInitMenuPaneL"));
}
void CImagicAppUi::BrowserContainerInitialized()
{
if(((CImagicViewBrowser*) View(iViewIdBrowser))->GetContainer() != NULL)
{
iBrowserContainer = ((CImagicViewBrowser*) View(iViewIdBrowser))->GetContainer();
iBrowserContainer->ImageListChanged(0, EFalse); // TODO: cheap trick to update coords
}
}
// ------------------------------------------------------------------------------
// CImagicAppUi::HandleForegroundEventL(TBool aForeground)
// This function is called by the framework when the screen loses or gains focus.
// i.e. when it goes to the background or to the foreground. Incoming call
// softnote is an example.
// This event applies to the entire application, all views.
// ------------------------------------------------------------------------------
//
void CImagicAppUi::HandleForegroundEventL(TBool aForeground)
{
DP0_IMAGIC(_L("CImagicAppUi::HandleForegroundEventL++"));
//SetOrientationL(CAknAppUiBase::EAppUiOrientationPortrait);
if(iBrowserContainer)
if (aForeground)
{
DP0_IMAGIC(_L("CImagicAppUi::HandleForegroundEventL - App Foreground"));
//We were switched to foreground
iAppForeGround = ETrue;
//ScreenImmeadetaUpdate();
if(iPeriodic->IsActive())
iPeriodic->Cancel();
iIEngine->StartAccSensorMonitoring();
iBrowserContainer->SetDeleteTextures(EFalse);
iAppActiveState = ETrue;
if(iViewNro == BrowserView)
{
if(iBrowserContainer && !iBrowserContainer->IsOpenGLInit())
{
iBrowserContainer->InitAfterPowerSaveL();
}
else
{
if(iBrowserContainer)
iBrowserContainer->EnableDisplayDraw();
}
}
if(iBrowserContainer)
{
iBrowserContainer->DrawNow();
iBrowserContainer->EnableDisplayDraw();
}
}
else
{//We were switched to background
DP0_IMAGIC(_L("CImagicAppUi::HandleForegroundEventL - App Background"));
iAppForeGround = EFalse;
//ScreenImmeadetaUpdate();
if(iViewNro == BrowserView)
{
//... disable frame loop timer ...
//iBrowserContainer->DisableDisplayDraw();
//... start a timer for 3 seconds to call to a power save callback ...
iPeriodic->Start( 3000000, 1000000000, TCallBack( CImagicAppUi::TimerCallBack, this ) );
//iBrowserContainer = ((CImagicViewBrowser*) View(iViewIdBrowser))->GetContainer();
}
//iIEngine->StopAccSensorMonitoring();
iAppActiveState = EFalse;
if(iBrowserContainer)
{
iBrowserContainer->DrawNow();
iBrowserContainer->DisableDisplayDraw();
}
}
DP0_IMAGIC(_L("CImagicAppUi::HandleForegroundEventL--"));
}
//Power save timer callback function
//Cleans memory allocations for openGl draving
TInt CImagicAppUi::TimerCallBack(TAny* aInstance)
{
DP0_IMAGIC(_L("CImagicAppUi::TimerCallBack++"));
CImagicAppUi* instance = (CImagicAppUi*) aInstance;
instance->iIEngine->StopAccSensorMonitoring();
if(instance->iViewNro == BrowserView)
{
if(instance->iBrowserContainer && instance->iBrowserContainer->IsOpenGLInit())
{
DP0_IMAGIC(_L("CImagicAppUi::TimerCallBack - DeleteTextures"));
//instance->iBrowserContainer->DeleteTextures();
instance->iBrowserContainer->SetDeleteTextures(ETrue);
}
}
DP0_IMAGIC(_L("CImagicAppUi::TimerCallBack--"));
return 0;
}
void CImagicAppUi::SetTNGenerationFlag(TBool aValue)
{
iTNGenerationOnGoing = aValue;
}
// ----------------------------------------------------
// CImagicAppUi::HandleKeyEventL(
// const TKeyEvent& aKeyEvent,TEventCode /*aType*/)
// Here we handle key events: Right and left arrow key
// to change view.
// ----------------------------------------------------
//
TKeyResponse CImagicAppUi::HandleKeyEventL(const TKeyEvent& /*aKeyEvent*/, TEventCode /*aType*/)
{
DP0_IMAGIC(_L("CImagicAppUi::HandleKeyEventL"));
//No need to handle events here
return EKeyWasNotConsumed;
}
// ----------------------------------------------------
// CImagicAppUi::HandleCommandL(TInt aCommand)
// Here we handle commands on the application level.
// In addition, each view has their own HandleCommandL()
// ----------------------------------------------------
//
void CImagicAppUi::HandleCommandL(TInt aCommand)
{
DP0_IMAGIC(_L("CImagicAppUi::HandleCommandL"));
switch ( aCommand )
{
case EEikCmdExit:
{
iIEngine->Stop();
// send to background
TApaTask apaTask( CEikonEnv::Static()->WsSession() );
apaTask.SetWgId( iCoeEnv->RootWin().Identifier() );
apaTask.SendToBackground();
// Wait until engine is stopped
while (iIEngine->IsRunning())
{
User::After(200000); // 200ms
}
DP0_IMAGIC(_L("CImagicAppUi::HandleCommandL end wait"));
if(iTNGenerationOnGoing)
{
TInt i = KErrNone;
//iIEngine->StopFaceDetection(i);
iIEngine->StopTNGeneration(i);
}
Exit();
break;
}
case EImagicCmdViewCmd1:
{
break;
}
// You can add your all application applying commands here.
// You would handle here menu commands that are valid for all views.
}
}
TInt CImagicAppUi::ExitTimerCallBack(TAny* aInstance)
{
CImagicAppUi* instance = (CImagicAppUi*) aInstance;
instance->iNumberOfIterations++;
if(instance->iTNGenerationOnGoing)
{
if(instance->iNumberOfIterations == 10)
{
instance->iNumberOfIterations = 0;
instance->iPeriodic->Cancel();
//instance->CancelExitDialog();
instance->iImagicUtils->CancelWaitDialog();
User::Exit(KErrNone);
}
else
{
//nothing.. continue...
}
}
else
{
instance->iPeriodic->Cancel();
//instance->CancelExitDialog();
instance->iImagicUtils->CancelWaitDialog();
User::Exit(KErrNone);
}
return 0;
}
// -----------------------------------------------------------------------------
// CImagicAppUi::HandleResourceChangeL( TInt aType )
// Called by framework when layout is changed.
// -----------------------------------------------------------------------------
//
void CImagicAppUi::HandleResourceChangeL( TInt aType )
{
DP0_IMAGIC(_L("CImagicAppUi::HandleResourceChangeL"));
//on = aType = 268457666, off = aType = 268457667
if(iBrowserContainer != NULL)
{
if(aType == 268457666)
{
iMenuOn = ETrue;
//ScreenImmeadetaUpdate();
if(iBrowserContainer)
{
iBrowserContainer->SetScreenImmeadetaUpdate(ETrue);
iBrowserContainer->DisableDisplayDraw();
}
}
else if(aType == 268457667)
{
iMenuOn = EFalse;
//ScreenImmeadetaUpdate();
if(iBrowserContainer)
{
iBrowserContainer->SetScreenImmeadetaUpdate(EFalse);
iBrowserContainer->EnableDisplayDraw();
}
}
iBrowserContainer->DrawNow();
}
CAknAppUi::HandleResourceChangeL( aType );
// ADDED FOR SCALABLE UI SUPPORT
// *****************************
if ( aType==KEikDynamicLayoutVariantSwitch )
{
((CImagicViewBrowser*) View( iViewIdBrowser) )->HandleClientRectChange( );
}
}
TBool CImagicAppUi::IsAppOnTop()
{
if(iMenuOn)
{
DP0_IMAGIC(_L("CImagicAppUi::IsAppOnTop: EFalse"));
return EFalse;
}
else if(!iAppForeGround)
{
DP0_IMAGIC(_L("CImagicAppUi::IsAppOnTop: EFalse"));
return EFalse;
}
else
{
DP0_IMAGIC(_L("CImagicAppUi::IsAppOnTop: ETrue"));
return ETrue;
}
}
void CImagicAppUi::ScreenImmeadetaUpdate()
{
if(iMenuOn || !iAppForeGround)
iBrowserContainer->SetScreenImmeadetaUpdate(ETrue);
else
iBrowserContainer->SetScreenImmeadetaUpdate(EFalse);
}
void CImagicAppUi::SetImageIndex(TInt aIndex)
{
DP0_IMAGIC(_L("CImagicAppUi::SetImageIndex"));
if(aIndex >= iIEngine->GetTotalNumOfImages())
aIndex = 0;
if(aIndex < 0)
aIndex = iIEngine->GetTotalNumOfImages()-1;
iImageIndex = aIndex;
}
TInt CImagicAppUi::GetImageIndex()
{
DP0_IMAGIC(_L("CImagicAppUi::GetImageIndex"));
return iImageIndex;
}
#ifdef _ACCELEROMETER_SUPPORTED_
void CImagicAppUi::ImageRotated(TImagicDeviceOrientation aDeviceOrientation)
{
DP1_IMAGIC(_L("CImagicAppUi::ImageRotated, angle: %d"),aDeviceOrientation);
iBrowserContainer->PhoneRotated(aDeviceOrientation);
}
#endif
void CImagicAppUi::SetActiveView(TUid aViewNro)
{
DP0_IMAGIC(_L("CImagicAppUi::SetActiveView"));
iViewNro = aViewNro;
}
TUid CImagicAppUi::GetActiveView()
{
DP0_IMAGIC(_L("CImagicAppUi::GetActiveView"));
return iViewNro;
}
//Callback from engine that loaded Bitmap image is ready for drawing
void CImagicAppUi::ImagesLoadedL(TInt aError)
{
DP0_IMAGIC(_L("CImagicAppUi::ImagesLoaded++"));
if(iViewNro == BrowserView)
{
((CImagicViewBrowser*) View(iViewIdBrowser))->BitmapLoadedByEngineL(aError);
}
DP0_IMAGIC(_L("CImagicAppUi::ImagesLoaded--"));
}
//To get engine interface for other class usage
CIEEngine* CImagicAppUi::GetEngine()
{
DP0_IMAGIC(_L("CImagicAppUi::GetEngine"));
return iIEngine;
}
void CImagicAppUi::SetUIDrawMode(TImageArrayMode aMode)
{
iUIDrawMode = aMode;
}
/*
TImageArrayMode CImagicAppUi::GetUIDrawMode()
{
return iUIDrawMode;
}
TRgb CImagicAppUi::GetTransparentWhite()
{
return iTransparentWhite;
}
TRgb CImagicAppUi::GetTransparentBlack()
{
return iTransparentBlack;
}
const CFont* CImagicAppUi::GetFont()
{
return iFont;
}
*/
CImagicUtils* CImagicAppUi::GetImagicUtils()
{
return iImagicUtils;
}
/*void CImagicAppUi::SetFont()
{
DP0_IMAGIC(_L("CImagicAppUi::SetFont"));
// set the font
iFont = AknLayoutUtils::FontFromId(EAknLogicalFontPrimaryFont);
//Set alpha colors
iTransparentWhite=TRgb(KRgbWhite);
iTransparentWhite.SetAlpha(128);
iTransparentBlack=TRgb(KRgbBlack);
iTransparentBlack.SetAlpha(128+64);
}*/
void CImagicAppUi::ImageListChanged(TInt aIndex, TBool aAdded)
{
DP2_IMAGIC(_L("CImagicAppUi::ImageListChanged %d %d"), aIndex, aAdded);
if (iBrowserContainer)
iBrowserContainer->ImageListChanged(aIndex, aAdded);
}
//This is called when single face Detection has been completed
void CImagicAppUi::SingleFaceDetectionComplete()
{
DP0_IMAGIC(_L("CImagicAppUi::SingleFaceDetectionComplete"));
//((CImagicViewBrowser*) View(iViewIdBrowser))->SingleFaceDetectionComplete();
}
//Callback function from engine that BackGround Face Detection has been completed
void CImagicAppUi::FaceDetectionComplete()
{
DP0_IMAGIC(_L("CImagicAppUi::FaceDetectionComplete"));
((CImagicViewBrowser*) View(iViewIdBrowser))->FaceDetectionComplete();
}
//Callback function from engine that Face Browsing creation has been completed
void CImagicAppUi::SingleTNCreationCompletedL(TInt /*aIndex*/, TThumbSize aTnRes)
{
DP1_IMAGIC(_L("CImagicAppUi::SingleTNCreationCompletedL - res: %d"),aTnRes);
iBrowserContainer->NewImageAdded();
iBrowserContainer->SetLoadingOn(ETrue);
//iBrowserContainer->DrawScreen();
iBrowserContainer->DrawNow();
}
//Callback function from engine that TN creation has been completed
void CImagicAppUi::TNCreationCompleteL(TThumbSize aTnRes)
{
DP0_IMAGIC(_L("CImagicAppUi::TNCreationComplete++"));
iTNGenerationOnGoing = EFalse;
((CImagicViewBrowser*) View(iViewIdBrowser))->TNCreationComplete();
iBrowserContainer->DrawNow();
/*TApplicationFeature appFeature = ((CImagicViewBrowser*)View(iViewIdBrowser))->GetAppFeature();
//This is in case we were editing and we did not have 320x320 tn created
if(appFeature == EAppFeatureEditing && aTnRes == ESize32x32)
{
iTNGenerationOnGoing = EFalse;
((CImagicViewBrowser*) View(iViewIdBrowser))->TNCreationComplete();
}
else if(appFeature == EAppFeatureNone )
{
iTNGenerationOnGoing = EFalse;
((CImagicViewBrowser*) View(iViewIdBrowser))->TNCreationComplete();
}
else if((appFeature == EAppFeatureEditing || appFeature == EAppFeatureCropping) && (aTnRes == ESize512x512 || aTnRes == ENotDefined))
{
iTNGenerationOnGoing = EFalse;
((CImagicViewBrowser*) View(iViewIdBrowser))->TNCreationComplete();
}*/
DP0_IMAGIC(_L("CImagicAppUi::TNCreationComplete--"));
}
TInt CImagicAppUi::DeleteImage(TInt aIndex)
{
DP0_IMAGIC(_L("CImagicAppUi::DeleteImage++"));
TInt err = iIEngine->DeleteFile(aIndex);
DP0_IMAGIC(_L("CImagicAppUi::DeleteImage--"));
return err;
}
void CImagicAppUi::AllFilesScanned()
{
DP0_IMAGIC(_L("CImagicAppUi::AllFilesScanned++"));
if(iIEngine->GetTotalNumOfImages() <= 0)
GetImagicUtils()->ExecuteQueryDialog(0/*GetErrorCode()*/, R_NO_IMAGES_DIALOG);
iBrowserContainer->DrawNow();
DP0_IMAGIC(_L("CImagicAppUi::AllFilesScanned--"));
}
TInt CImagicAppUi::GetGleMaxRes()
{
return iBrowserContainer->GetGleMaxRes();
}
// End of File
| [
"none@none"
] | [
[
[
1,
702
]
]
] |
75e3944c6b5981976e8aa1a267f7d6bd0684f91c | c7120eeec717341240624c7b8a731553494ef439 | /src/cplusplus/freezone-samp/src/vehicles.cpp | 2b24a42fe95573b812d5f4d934836f0b497b9ccc | [] | no_license | neverm1ndo/gta-paradise-sa | d564c1ed661090336621af1dfd04879a9c7db62d | 730a89eaa6e8e4afc3395744227527748048c46d | refs/heads/master | 2020-04-27T22:00:22.221323 | 2010-09-04T19:02:28 | 2010-09-04T19:02:28 | 174,719,907 | 1 | 0 | null | 2019-03-09T16:44:43 | 2019-03-09T16:44:43 | null | WINDOWS-1251 | C++ | false | false | 46,782 | cpp | #include "config.hpp"
#include "vehicles.hpp"
#include <algorithm>
#include <functional>
#include <map>
#include <boost/lexical_cast.hpp>
#include <boost/foreach.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>
#include <boost/optional.hpp>
#include "core/module_c.hpp"
#include "checkpoints.hpp"
#include "map_icons.hpp"
#include "mta10_loader.hpp"
#include "server_paths.hpp"
#include "server_configuration.hpp"
REGISTER_IN_APPLICATION(vehicles);
vehicles::ptr vehicles::instance() {
return application::instance()->get_item<vehicles>();
}
vehicles::vehicles(): is_first_player_connected(true), is_dump_vehicles_on_config(false) {
}
vehicles::~vehicles() {
}
void vehicles::create() {
command_add("vehicle_paintjob", std::tr1::bind(&vehicles::cmd_vehicle_paintjob, this, std::tr1::placeholders::_1, std::tr1::placeholders::_2, std::tr1::placeholders::_3, std::tr1::placeholders::_4, std::tr1::placeholders::_5), cmd_game, std::tr1::bind(&vehicles::cmd_vehicle_paintjob_access_checker, this, std::tr1::placeholders::_1, std::tr1::placeholders::_2));
command_add("vehicle_color", std::tr1::bind(&vehicles::cmd_vehicle_color, this, std::tr1::placeholders::_1, std::tr1::placeholders::_2, std::tr1::placeholders::_3, std::tr1::placeholders::_4, std::tr1::placeholders::_5), cmd_game, std::tr1::bind(&vehicles::cmd_vehicle_color_access_checker, this, std::tr1::placeholders::_1, std::tr1::placeholders::_2));
command_add("vehicle_modification", std::tr1::bind(&vehicles::cmd_vehicle_modification, this, std::tr1::placeholders::_1, std::tr1::placeholders::_2, std::tr1::placeholders::_3, std::tr1::placeholders::_4, std::tr1::placeholders::_5), cmd_game, std::tr1::bind(&vehicles::cmd_vehicle_modification_access_checker, this, std::tr1::placeholders::_1, std::tr1::placeholders::_2));
command_add("vehicle_color_list", bind(&vehicles::cmd_vehicle_color_list, this, std::tr1::placeholders::_1, std::tr1::placeholders::_2, std::tr1::placeholders::_3, std::tr1::placeholders::_4, std::tr1::placeholders::_5), cmd_info_only, std::tr1::bind(&vehicles::cmd_vehicle_color_access_checker, this, std::tr1::placeholders::_1, std::tr1::placeholders::_2));
command_add("vehicle_modification_list", bind(&vehicles::cmd_vehicle_modification_list, this, std::tr1::placeholders::_1, std::tr1::placeholders::_2, std::tr1::placeholders::_3, std::tr1::placeholders::_4, std::tr1::placeholders::_5), cmd_info_only, std::tr1::bind(&vehicles::cmd_vehicle_modification_access_checker, this, std::tr1::placeholders::_1, std::tr1::placeholders::_2));
}
void vehicles::on_first_player_connected() {
std::vector<int> vehicle_ids;
vehiclesgame.get_keys(vehicle_ids);
std::for_each(vehicle_ids.begin(), vehicle_ids.end(),
std::tr1::bind(&samp::api::set_vehicle_to_respawn, samp::api::instance(), std::tr1::placeholders::_1)
);
}
void vehicles::configure_pre() {
plate = "PLATE___";
vehicle_defs.clear();
vehicle_component_defs.clear();
vehicle_component_ignore_duplicate.clear();
vehiclesgame.update_begin();
vehicles_static.clear();
vehicle_colors.clear();
vehicle_color_price = 150;
vehicle_paintjob_price = 250;
mod_garages_destroy();
mod_garages.clear();
repair_garages_destroy();
repair_garages.clear();
is_block_on_vehicle_mod = false;
is_block_on_vehicle_paintjob = false;
is_block_on_vehicle_respray = false;
is_trace_enter_leave_mod = false;
is_dump_vehicles_on_config = false;
}
void vehicles::configure(buffer::ptr const& buff, def_t const& def) {
SERIALIZE_ITEM(plate);
SERIALIZE_ITEM(vehicle_defs);
SERIALIZE_ITEM(vehicle_component_defs);
SERIALIZE_ITEM(vehicle_component_ignore_duplicate);
SERIALIZE_NAMED_ITEM(vehiclesgame.update_get_data(), "vehicles");
SERIALIZE_ITEM(vehicles_static);
SERIALIZE_ITEM(vehicle_colors);
SERIALIZE_ITEM(vehicle_color_price);
SERIALIZE_ITEM(vehicle_paintjob_price);
SERIALIZE_ITEM(mod_garages);
SERIALIZE_ITEM(repair_garages);
SERIALIZE_ITEM(is_block_on_vehicle_mod);
SERIALIZE_ITEM(is_block_on_vehicle_paintjob);
SERIALIZE_ITEM(is_block_on_vehicle_respray);
SERIALIZE_ITEM(is_trace_enter_leave_mod);
// Загружаем объекты из файлов MTA-SA 1.0
mta10_loader loader(PATH_MTA10_DIR);
mta10_loader_vehicles_t loader_mta10;
SERIALIZE_ITEM(loader_mta10);
loader.load_items(loader_mta10, vehiclesgame.update_get_data());
SERIALIZE_ITEM(is_dump_vehicles_on_config);
}
void vehicles::configure_post() {
if (is_dump_vehicles_on_config) {
// Вызываем до vehiclesgame.update_end
dump_vehicles(vehiclesgame.update_get_data());
}
vehiclesgame.update_end(std::tr1::bind(&vehicles::vehicle_create, this, std::tr1::placeholders::_1), std::tr1::bind(&vehicles::vehicle_destroy, this, std::tr1::placeholders::_1));
mod_garages_create();
repair_garages_create();
}
int vehicles::vehicle_create(pos_vehicle const& pos) {
vehicle_t vehicle(*this, pos);
if (vehicle.create()) {
vehicles_state.insert(std::make_pair(vehicle.get_id(), vehicle));
}
return vehicle.get_id();
/*
samp::api::ptr api_ptr = samp::api::instance();
vehicle_t state(pos.color1, pos.color2);
if (state.is_need_change_color()) {
// Пытаемся найти цвета - если нашли, то ставим наш
vehicle_defs_t::const_iterator local_def_it = vehicle_defs.find(pos.model_id);
if (vehicle_defs.end() != local_def_it && !local_def_it->second.color_items.empty()) {
vehicle_def_t::color_item_t const& color_item = local_def_it->second.color_items[std::rand() % local_def_it->second.color_items.size()];
if (vehicle_t::any_color == state.color1) state.color1 = color_item.color1;
if (vehicle_t::any_color == state.color2) state.color2 = color_item.color2;
}
}
int vehicle_id = api_ptr->create_vehicle(pos.model_id, pos.x, pos.y, pos.z, pos.rz, state.color1, state.color2, pos.respawn_delay);
api_ptr->link_vehicle_to_interior(vehicle_id, pos.interior);
api_ptr->set_vehicle_virtualworld(vehicle_id, pos.world);
vehicles_state.insert(std::make_pair(vehicle_id, state));
if (!is_first_player_connected) {
api_ptr->set_vehicle_to_respawn(vehicle_id);
}
return vehicle_id;
*/
}
void vehicles::vehicle_destroy(int id) {
samp::api::instance()->destroy_vehicle(id);
vehicles_state.erase(id);
}
void vehicles::on_gamemode_init(AMX* amx, samp::server_ver ver) {
BOOST_FOREACH(pos_vehicle const& vehicle_static, vehicles_static) {
vehicle_t vehicle(*this, vehicle_static);
if (vehicle.create_static()) {
vehicles_state.insert(std::make_pair(vehicle.get_id(), vehicle));
}
}
}
void vehicles::on_vehicle_spawn(int vehicle_id) {
samp::api::ptr api_ptr = samp::api::instance();
api_ptr->set_vehicle_number_plate(vehicle_id, plate);
vehicles_state_t::iterator vehicle_curr_it = vehicles_state.find(vehicle_id);
if (vehicles_state.end() != vehicle_curr_it) {
vehicle_curr_it->second.clear();
int model_id = api_ptr->get_vehicle_model(vehicle_id);
vehicle_defs_t::const_iterator local_def_it = vehicle_defs.find(model_id);
if (vehicle_defs.end() != local_def_it) {
// Может из-за этого вылетает
if (vehicle_curr_it->second.is_need_change_color() &&!local_def_it->second.color_items.empty()) {
//vehicle_def_t::color_item_t const& color_item = local_def_it->second.color_items[std::rand() % local_def_it->second.color_items.size()];
//vehicle_curr_it->second.color1 = color_item.color1;
//vehicle_curr_it->second.color2 = color_item.color2;
//api_ptr->change_vehicle_color(vehicle_id, color_item.color1, color_item.color2);
}
}
}
pos_vehicle curr_v;
if (vehiclesgame.get_obj_by_key(curr_v, vehicle_id)) {
// Нашли координаты нашего транспорта
//api_ptr->link_vehicle_to_interior(vehicle_id, curr_v.interior);
//api_ptr->set_vehicle_virtualworld(vehicle_id, curr_v.world);
}
}
void vehicles::on_player_connect(int player_id) {
if (is_first_player_connected) {
is_first_player_connected = false;
on_first_player_connected();
}
}
bool vehicles::get_component_from_id(int component_id, vehicle_component_defs_t::const_iterator& comp_it) const {
for (vehicle_component_defs_t::const_iterator it = vehicle_component_defs.begin(), end = vehicle_component_defs.end(); end != it; ++it) {
vehicle_component_def_t::ids_t const& ids = it->second.ids;
if (ids.end() != std::find(ids.begin(), ids.end(), component_id)) {
// Нашли наш ид
comp_it = it;
return true;
}
}
// Ничего не нашли
return false;
}
bool vehicles::on_vehicle_mod(int player_id, int vehicle_id, int component_id) {
if (player::ptr player_ptr = players::instance()->get_player(player_id)) {
if (player_ptr->block_get()) return false;
int model_id = samp::api::instance()->get_vehicle_model(vehicle_id);
messages_item msg_item;
msg_item.get_params()
("vehicle_id", vehicle_id)
("model_id", model_id)
("component_id", component_id)
("player_name", player_ptr->name_get_full())
;
if (is_block_on_vehicle_mod) {
player_ptr->block("vehicle/mod", msg_item.get_params().process_all_vars("$(vehicle_id) $(model_id) $(component_id)"));
return false;
}
if (is_valid_component(model_id, component_id)) {
msg_item.get_sender()("<log_section mod/debug/>$(player_name) $(vehicle_id) $(model_id) $(component_id)", msg_debug);
return true;
}
else {
msg_item.get_sender()("<log_section mod/error/>$(player_name) $(vehicle_id) $(model_id) $(component_id)", msg_debug);
return false;
}
}
return false;
}
bool vehicles::on_vehicle_paintjob(int player_id, int vehicle_id, int paintjob_id) {
if (player::ptr player_ptr = players::instance()->get_player(player_id)) {
if (player_ptr->block_get()) return false;
int model_id = samp::api::instance()->get_vehicle_model(vehicle_id);
messages_item msg_item;
msg_item.get_params()
("vehicle_id", vehicle_id)
("model_id", model_id)
("paintjob_id", paintjob_id)
("player_name", player_ptr->name_get_full())
;
if (is_block_on_vehicle_paintjob) {
player_ptr->block("vehicle/paintjob", msg_item.get_params().process_all_vars("$(vehicle_id) $(model_id) $(paintjob_id)"));
return false;
}
if (is_valid_paintjob(model_id, paintjob_id)) {
msg_item.get_sender()("<log_section paintjob/debug/>$(player_name) $(vehicle_id) $(model_id) $(paintjob_id)", msg_debug);
return true;
}
else {
msg_item.get_sender()("<log_section paintjob/error/>$(player_name) $(vehicle_id) $(model_id) $(paintjob_id)", msg_debug);
return false;
}
}
return false;
}
bool vehicles::on_vehicle_respray(int player_id, int vehicle_id, int color1, int color2) {
if (player::ptr player_ptr = players::instance()->get_player(player_id)) {
if (player_ptr->block_get()) return false;
int model_id = samp::api::instance()->get_vehicle_model(vehicle_id);
messages_item msg_item;
msg_item.get_params()
("vehicle_id", vehicle_id)
("model_id", model_id)
("color1", color1)
("color2", color2)
("player_name", player_ptr->name_get_full())
;
if (is_block_on_vehicle_respray) {
player_ptr->block("vehicle/respray", msg_item.get_params().process_all_vars("$(vehicle_id) $(model_id) $(color1) $(color2)"));
return false;
}
if (is_valid_colors(model_id, color1, color2)) {
msg_item.get_sender()("<log_section respray/debug/>$(player_name) $(vehicle_id) $(model_id) $(color1) $(color2)", msg_debug);
return true;
}
else {
msg_item.get_sender()("<log_section respray/error/>$(player_name) $(vehicle_id) $(model_id) $(color1) $(color2)", msg_debug);
return false;
}
}
return false;
}
bool vehicles::is_valid_component(int model_id, int component_id) {
vehicle_defs_t::const_iterator def_it = vehicle_defs.find(model_id);
if (vehicle_defs.end() != def_it) {
vehicle_component_defs_t::const_iterator comp_it;
if (get_component_from_id(component_id, comp_it)) {
if (def_it->second.components.end() != def_it->second.components.find(comp_it->first)) {
// Нашли среди разрешенных компонентов
return true;
}
}
}
return false;
}
bool vehicles::is_valid_component(int model_id, std::string const& component_name) {
vehicle_defs_t::const_iterator def_it = vehicle_defs.find(model_id);
if (vehicle_defs.end() != def_it) {
vehicle_component_defs_t::const_iterator comp_it = vehicle_component_defs.find(component_name);
if (vehicle_component_defs.end() != comp_it) {
if (def_it->second.components.end() != def_it->second.components.find(comp_it->first)) {
// Нашли среди разрешенных компонентов
return true;
}
}
}
return false;
}
bool vehicles::is_valid_paintjob(int model_id, int paintjob_id) {
if (-1 == paintjob_id || 0 == paintjob_id || 1 == paintjob_id || 2 == paintjob_id) {
return true;
}
return false;
}
bool vehicles::is_valid_colors(int model_id, int color1, int color2) {
if (0 <= color1 && 127 >= color1 && 0 <= color2 && 127 >= color2) {
return true;
}
return false;
}
bool vehicles::is_player_can_tune(player_ptr_t const& player_ptr) {
garage_vals_t::const_iterator garage_vals_it = garage_vals.find(checkpoints::instance()->get_active_checkpoint(player_ptr));
if (garage_vals.end() == garage_vals_it) {
return false;
}
garage_val_t const& garage_val = garage_vals_it->second;
int vehicle_id;
vehicle_defs_t::const_iterator vehicle_def_it;
if (!get_vehicle_def_by_player(player_ptr, vehicle_id, vehicle_def_it)) {
return false;
}
return garage_val.mod_garage_ptr->valid_vehicles.end() != garage_val.mod_garage_ptr->valid_vehicles.find(vehicle_def_it->second.sys_name);
}
bool vehicles::get_vehicle_def_by_player(player_ptr_t const& player_ptr, int& vehicle_id, vehicle_defs_t::const_iterator& vehicle_def_it) const {
int local_vehicle_id;
int model_id;
bool is_driver;
if (!player_ptr->get_vehicle(local_vehicle_id, model_id, is_driver)) return false;
vehicle_defs_t::const_iterator local_def_it = vehicle_defs.find(model_id);
if (vehicle_defs.end() == local_def_it) return false;
vehicle_id = local_vehicle_id;
vehicle_def_it = local_def_it;
return true;
}
bool vehicles::get_trailer_def_by_player(player_ptr_t const& player_ptr, int& trailer_id, vehicle_defs_t::const_iterator& trailer_def_it) const {
int local_vehicle_id;
int model_id;
bool is_driver;
if (!player_ptr->get_vehicle(local_vehicle_id, model_id, is_driver)) return false;
samp::api::ptr api_ptr = samp::api::instance();
if (!api_ptr->is_trailer_attached_to_vehicle(local_vehicle_id)) return false;
int local_trailer_id = api_ptr->get_vehicle_trailer(local_vehicle_id);
int trailer_model_id = api_ptr->get_vehicle_model(local_trailer_id);
vehicle_defs_t::const_iterator local_def_it = vehicle_defs.find(trailer_model_id);
if (vehicle_defs.end() == local_def_it) return false;
trailer_id = local_trailer_id;
trailer_def_it = local_def_it;
return true;
}
bool vehicles::cmd_vehicle_paintjob_access_checker_impl(player_ptr_t const& player_ptr) {
int vehicle_id;
vehicle_defs_t::const_iterator def_it;
if (!get_vehicle_def_by_player(player_ptr, vehicle_id, def_it)) return false;
return !def_it->second.paintjobs.empty();
}
bool vehicles::cmd_vehicle_color_access_checker_impl(player_ptr_t const& player_ptr) {
int vehicle_id;
vehicle_defs_t::const_iterator def_it;
if (!get_vehicle_def_by_player(player_ptr, vehicle_id, def_it)) return false;
return 0 != def_it->second.colors;
}
bool vehicles::cmd_vehicle_modification_access_checker_impl(player_ptr_t const& player_ptr) {
int vehicle_id;
vehicle_defs_t::const_iterator def_it;
if (!get_vehicle_def_by_player(player_ptr, vehicle_id, def_it)) return false;
return !def_it->second.components.empty();
}
bool vehicles::cmd_vehicle_paintjob_access_checker(player_ptr_t const& player_ptr, std::string const& cmd_name) {
if (!is_player_can_tune(player_ptr)) return false;
return cmd_vehicle_paintjob_access_checker_impl(player_ptr);
}
bool vehicles::cmd_vehicle_color_access_checker(player_ptr_t const& player_ptr, std::string const& cmd_name) {
if (!is_player_can_tune(player_ptr)) return false;
return cmd_vehicle_color_access_checker_impl(player_ptr);
}
bool vehicles::cmd_vehicle_modification_access_checker(player_ptr_t const& player_ptr, std::string const& cmd_name) {
if (!is_player_can_tune(player_ptr)) return false;
return cmd_vehicle_modification_access_checker_impl(player_ptr);
}
command_arguments_rezult vehicles::cmd_vehicle_paintjob(player_ptr_t const& player_ptr, std::string const& arguments, messages_pager& pager, messages_sender const& sender, messages_params& params) {
int vehicle_id;
vehicle_defs_t::const_iterator vehicle_def_it;
if (!get_vehicle_def_by_player(player_ptr, vehicle_id, vehicle_def_it)) return cmd_arg_process_error;
params("v_id", vehicle_id); set_params(vehicle_def_it, params, "v_");
int paintjobs_count = vehicle_def_it->second.paintjobs.size();
vehicles_state_t::iterator vehicle_curr_it = vehicles_state.find(vehicle_id);
garage_vals_t::const_iterator garage_vals_it = garage_vals.find(checkpoints::instance()->get_active_checkpoint(player_ptr));
if (garage_vals.end() == garage_vals_it) {
assert(false);
return cmd_arg_process_error;
}
garage_val_t const& garage_val = garage_vals_it->second;
params
("mod_garage_name", garage_val.mod_garage_ptr->name)
("mod_garage_sys_name", garage_val.mod_garage_ptr->sys_name)
("garage_sys_name", garage_val.garage_ptr->sys_name)
;
int paintjob_id;
{ // Парсинг
std::istringstream iss(arguments);
iss>>paintjob_id;
if (iss.fail() || !iss.eof()) {
return cmd_arg_syntax_error;
}
}
params
("money", vehicle_paintjob_price)
("id", paintjob_id)
("id_max", paintjobs_count);
if (paintjob_id < 1 || paintjob_id > paintjobs_count) {
pager("$(cmd_vehicle_paintjob_error_out_of_range)");
return cmd_arg_process_error;
}
if (!player_ptr->get_item<player_money_item>()->can_take(vehicle_paintjob_price)) {
pager("$(money_error_low_money)");
return cmd_arg_process_error;
}
int paintjob_gta_id = vehicle_def_it->second.paintjobs[paintjob_id - 1];
params("gta_id", paintjob_gta_id);
if (vehicles_state.end() != vehicle_curr_it) {
if (vehicle_curr_it->second.paintjob_id == paintjob_gta_id) {
pager("$(cmd_vehicle_paintjob_error_duplicate)");
return cmd_arg_process_error;
}
vehicle_curr_it->second.paintjob_id = paintjob_gta_id;
}
player_ptr->get_item<player_money_item>()->take(vehicle_paintjob_price);
samp::api::instance()->change_vehicle_paintjob(vehicle_id, paintjob_gta_id);
pager("$(cmd_vehicle_paintjob_done)");
sender("$(cmd_vehicle_paintjob_done_log)", msg_log);
return cmd_arg_ok;
}
command_arguments_rezult vehicles::cmd_vehicle_color(player_ptr_t const& player_ptr, std::string const& arguments, messages_pager& pager, messages_sender const& sender, messages_params& params) {
int vehicle_id, trailer_id;
vehicle_defs_t::const_iterator vehicle_def_it, trailer_def_it;
vehicles_state_t::iterator vehicle_curr_it = vehicles_state.end(), trailer_curr_it = vehicles_state.end();
if (!get_vehicle_def_by_player(player_ptr, vehicle_id, vehicle_def_it)) return cmd_arg_process_error;
bool is_has_trailer = get_trailer_def_by_player(player_ptr, trailer_id, trailer_def_it);
params("v_id", vehicle_id); set_params(vehicle_def_it, params, "v_");
int colors_count = vehicle_def_it->second.colors;
vehicle_curr_it = vehicles_state.find(vehicle_id);
if (is_has_trailer) {
colors_count += trailer_def_it->second.colors;
params("t_id", trailer_id); set_params(trailer_def_it, params, "t_");
trailer_curr_it = vehicles_state.find(trailer_id);
}
garage_vals_t::const_iterator garage_vals_it = garage_vals.find(checkpoints::instance()->get_active_checkpoint(player_ptr));
if (garage_vals.end() == garage_vals_it) {
assert(false);
return cmd_arg_process_error;
}
garage_val_t const& garage_val = garage_vals_it->second;
params
("mod_garage_name", garage_val.mod_garage_ptr->name)
("mod_garage_sys_name", garage_val.mod_garage_ptr->sys_name)
("garage_sys_name", garage_val.garage_ptr->sys_name)
;
enum {max_colors = 3};
boost::optional<int> colors[max_colors];
int colors_change_count = 0;
{ // Парсинг
std::string not_change_string = params.process_all_vars("$(cmd_vehicle_color_param_notchange)");
std::istringstream iss(arguments);
std::string colors_text[max_colors];
if (colors_count > max_colors) colors_count = max_colors;
if (3 == colors_count) {
iss>>colors_text[0]>>colors_text[1]>>colors_text[2];
}
else if (2 == colors_count) {
iss>>colors_text[0]>>colors_text[1];
}
else if (1 == colors_count) {
iss>>colors_text[0];
}
else {
assert(false);
return cmd_arg_process_error;
}
if (iss.fail() || !iss.eof()) {
pager("$(cmd_vehicle_color_error_arg" + boost::lexical_cast<std::string>(colors_count) +")");
return cmd_arg_process_error;
}
try {
for (int i = 0; i < colors_count; ++i) {
if (!boost::iequals(not_change_string, colors_text[i], locale_ru)) {
colors[i].reset(boost::lexical_cast<int>(colors_text[i]));
++colors_change_count;
}
}
}
catch (boost::bad_lexical_cast &) {
pager("$(cmd_vehicle_color_error_arg" + boost::lexical_cast<std::string>(colors_count) +")");
return cmd_arg_process_error;
}
}
if (0 == colors_change_count) {
pager("$(cmd_vehicle_color_error_not_colors)");
return cmd_arg_process_error;
}
for (int i = 0; i < colors_count; ++i) {
if (colors[i] && (*colors[i] < 1 || *colors[i] > static_cast<int>(vehicle_colors.size()))) {
params("id", *colors[i])("id_max", vehicle_colors.size());
pager("$(cmd_vehicle_color_error_out_of_range)");
return cmd_arg_process_error;
}
}
params("money", vehicle_color_price * colors_change_count);
params("money_item", vehicle_color_price);
if (!player_ptr->get_item<player_money_item>()->can_take(vehicle_color_price * colors_change_count)) {
pager("$(money_error_low_money)");
return cmd_arg_process_error;
}
// Все проверки пройдены - перекрашиваем
player_ptr->get_item<player_money_item>()->take(vehicle_color_price * colors_change_count);
{ // Перекрашиваем вихл
int gta_colors[2] = {0, 0};
bool gta_colors_change[2] = {false, false};
for (int i = 0; i < vehicle_def_it->second.colors; ++i) {
if (colors[i]) {
gta_colors_change[i] = true;
gta_colors[i] = vehicle_colors[*colors[i]-1].id;
set_params_colors(*colors[i], params, (boost::format("color%1%_") % (i + 1)).str());
pager((boost::format("$(cmd_vehicle_color_done%1%)") % (i + 1)).str());
sender((boost::format("$(cmd_vehicle_color_done%1%_log)") % (i + 1)).str(), msg_log);
}
}
if (vehicles_state.end() != vehicle_curr_it) {
if (0 < vehicle_def_it->second.colors) {
if (colors[0]) {
vehicle_curr_it->second.color1 = gta_colors[0];
}
else {
gta_colors[0] = vehicle_curr_it->second.color1;
}
}
if (1 < vehicle_def_it->second.colors) {
if (colors[1]) {
vehicle_curr_it->second.color2 = gta_colors[1];
}
else {
gta_colors[1] = vehicle_curr_it->second.color2;
}
}
}
if (gta_colors_change[0] || gta_colors_change[1]) {
samp::api::instance()->change_vehicle_color(vehicle_id, gta_colors[0], gta_colors[1]);
}
}
if (is_has_trailer && 0 != trailer_def_it->second.colors) {
// Перекрашиваем прицеп
int index = vehicle_def_it->second.colors;
if (colors[index]) {
int gta_color = vehicle_colors[*colors[index]-1].id;
set_params_colors(*colors[index], params, "color_trailer_");
pager("$(cmd_vehicle_color_done_trailer)");
sender("$(cmd_vehicle_color_done_trailer_log)", msg_log);
if (vehicles_state.end() != trailer_curr_it) {
trailer_curr_it->second.color1 = gta_color;
}
samp::api::instance()->change_vehicle_color(trailer_id, gta_color, gta_color);
}
}
return cmd_arg_ok;
}
command_arguments_rezult vehicles::cmd_vehicle_modification(player_ptr_t const& player_ptr, std::string const& arguments, messages_pager& pager, messages_sender const& sender, messages_params& params) {
command_arguments_rezult rezult = cmd_arg_syntax_error;
for (boost::split_iterator<std::string::const_iterator> args_it = boost::make_split_iterator(arguments, boost::token_finder(boost::is_any_of(params.process_all_vars("$(cmd_vehicle_modification_arg_delimiter)")), boost::token_compress_on)), end; args_it != end; ++args_it) {
rezult = cmd_vehicle_modification_impl(player_ptr, boost::trim_copy(boost::copy_range<std::string>(*args_it)), pager, sender, params);
if (cmd_arg_ok != rezult) {
break;
}
}
return rezult;
}
command_arguments_rezult vehicles::cmd_vehicle_modification_impl(player_ptr_t const& player_ptr, std::string const& arguments, messages_pager& pager, messages_sender const& sender, messages_params& params) {
std::string group_name;
bool is_has_id;
int id;
{ // Парсинг
// Пробуем распарсить 2 параметра
std::istringstream iss2(arguments);
iss2>>group_name>>id;
if (iss2.fail() || !iss2.eof()) {
// Пробуем распарсить 1 параметр
std::istringstream iss1(arguments);
iss1>>group_name;
if (iss1.fail() || !iss1.eof()) {
return cmd_arg_syntax_error;
}
else {
is_has_id = false;
id = 1;
}
}
else {
is_has_id = true;
}
}
params
("user_group_name", group_name)
("id", id);
int vehicle_id, trailer_id;
vehicle_defs_t::const_iterator vehicle_def_it, trailer_def_it;
vehicles_state_t::iterator vehicle_curr_it = vehicles_state.end(), trailer_curr_it = vehicles_state.end();
if (!get_vehicle_def_by_player(player_ptr, vehicle_id, vehicle_def_it)) return cmd_arg_process_error;
bool is_has_trailer = get_trailer_def_by_player(player_ptr, trailer_id, trailer_def_it);
params("v_id", vehicle_id); set_params(vehicle_def_it, params, "v_");
vehicle_curr_it = vehicles_state.find(vehicle_id);
if (is_has_trailer) {
params("t_id", trailer_id); set_params(trailer_def_it, params, "t_");
trailer_curr_it = vehicles_state.find(trailer_id);
}
garage_vals_t::const_iterator garage_vals_it = garage_vals.find(checkpoints::instance()->get_active_checkpoint(player_ptr));
if (garage_vals.end() == garage_vals_it) {
assert(false);
return cmd_arg_process_error;
}
garage_val_t const& garage_val = garage_vals_it->second;
params
("mod_garage_name", garage_val.mod_garage_ptr->name)
("mod_garage_sys_name", garage_val.mod_garage_ptr->sys_name)
("garage_sys_name", garage_val.garage_ptr->sys_name)
;
mods_groups_t mods_groups;
get_mods_groups(vehicle_def_it, mods_groups);
mods_groups_t::const_iterator mods_groups_it = mods_groups.find(group_name);
if (mods_groups.end() == mods_groups_it) {
pager("$(cmd_vehicle_modification_error_bad_group)");
return cmd_arg_process_error;
}
params
("group_name", mods_groups_it->first)
("id_max", mods_groups_it->second.size());
if (1 != mods_groups_it->second.size() && !is_has_id) {
// Если у нас более 1 компонента в группе, то необходимо явное указание индекса
pager("$(cmd_vehicle_modification_error_need_id)");
return cmd_arg_process_error;
}
if ((int)mods_groups_it->second.size() < id || 1 > id) {
pager("$(cmd_vehicle_modification_error_out_of_range)");
return cmd_arg_process_error;
}
mod_item_t mod_item;
{
mods_group_item_t::const_iterator component_it = mods_groups_it->second.begin();
for (int i = 1; i < id; ++i) {
++component_it;
}
mod_item = component_it->second;
}
params
("sys_name", mod_item.first)
("name", mod_item.second->name)
("money", mod_item.second->price)
("slot", mod_item.second->slot)
;
if (!player_ptr->get_item<player_money_item>()->can_take(mod_item.second->price)) {
pager("$(money_error_low_money)");
return cmd_arg_process_error;
}
// Истина, если не нужно проверять на дубликаты
bool is_ignore_duplicate = vehicle_component_ignore_duplicate.end() != vehicle_component_ignore_duplicate.find(mod_item.first);
bool is_need_mod_vehicle = false;
bool is_need_mod_trailer = false;
if (is_ignore_duplicate || vehicles_state.end() == vehicle_curr_it) {
is_need_mod_vehicle = true;
}
else {
vehicle_t::mods_t::const_iterator curr_slot = vehicle_curr_it->second.mods.find(mod_item.second->slot);
if (vehicle_curr_it->second.mods.end() == curr_slot || mod_item.first != curr_slot->second) {
vehicle_curr_it->second.mods[mod_item.second->slot] = mod_item.first;
is_need_mod_vehicle = true;
}
}
if (is_has_trailer && trailer_def_it->second.components.end() != trailer_def_it->second.components.find(mod_item.first)) {
// У нас есть прицеп, который может быть затюнены таким же компонетом
if (is_ignore_duplicate || vehicles_state.end() == trailer_curr_it) {
is_need_mod_trailer = true;
}
else {
vehicle_t::mods_t::const_iterator curr_trailer_slot = trailer_curr_it->second.mods.find(mod_item.second->slot);
if (trailer_curr_it->second.mods.end() == curr_trailer_slot || mod_item.first != curr_trailer_slot->second) {
trailer_curr_it->second.mods[mod_item.second->slot] = mod_item.first;
is_need_mod_trailer = true;
}
}
}
if (!is_need_mod_vehicle && !is_need_mod_trailer) {
pager("$(cmd_vehicle_modification_error_duplicate)");
return cmd_arg_process_error;
}
player_ptr->get_item<player_money_item>()->take(mod_item.second->price);
if (is_need_mod_vehicle) {
add_component(*mod_item.second, vehicle_id);
pager("$(cmd_vehicle_modification_done)");
sender("$(cmd_vehicle_modification_done_log)", msg_log);
}
if (is_need_mod_trailer) {
add_component(*mod_item.second, trailer_id);
pager("$(cmd_vehicle_modification_done_trailer)");
sender("$(cmd_vehicle_modification_done_trailer_log)", msg_log);
}
return cmd_arg_ok;
}
void vehicles::set_params(vehicle_defs_t::const_iterator const& def_it, messages_params& params, std::string const& prefix) {
params
(prefix + "model_id", def_it->first)
(prefix + "sys_name", def_it->second.sys_name)
(prefix + "name", def_it->second.name)
(prefix + "real_name", def_it->second.real_name)
;
}
void vehicles::set_params_colors(int index, messages_params& params, std::string const& prefix) {
vehicle_color_t& vehicle_color = vehicle_colors[index - 1];
params
(prefix + "id", index)
(prefix + "gtaid", vehicle_color.id)
(prefix + "name", vehicle_color.name)
(prefix + "raw", vehicle_color.color)
;
}
command_arguments_rezult vehicles::cmd_vehicle_modification_list(player_ptr_t const& player_ptr, std::string const& arguments, messages_pager& pager, messages_sender const& sender, messages_params& params) {
int vehicle_id;
vehicle_defs_t::const_iterator vehicle_def_it;
if (!get_vehicle_def_by_player(player_ptr, vehicle_id, vehicle_def_it)) return cmd_arg_process_error;
params("v_id", vehicle_id); set_params(vehicle_def_it, params, "v_");
mods_groups_t mods_groups;
get_mods_groups(vehicle_def_it, mods_groups);
pager.set_header_text(0, "$(cmd_vehicle_modification_list_header)");
BOOST_FOREACH(mods_groups_t::value_type const& mods_group, mods_groups) {
params("group_name", mods_group.first);
if (1 == mods_group.second.size()) {
// В группе у нас 1 элемент - обрабатывать его отдельно
params
("name", mods_group.second.begin()->first)
("price", mods_group.second.begin()->second.second->price)
;
pager("$(cmd_vehicle_modification_list_gp_single)");
}
else {
// В группе несколько элементов
pager.items_add("$(cmd_vehicle_modification_list_gp_header)");
int id = 1;
BOOST_FOREACH(mods_group_item_t::value_type const& mods_group_item, mods_group.second) {
params
("id", id++)
("name", mods_group_item.first)
("price", mods_group_item.second.second->price)
;
pager.items_add("$(cmd_vehicle_modification_list_item)");
}
pager.items_done();
}
}
return cmd_arg_auto;
}
command_arguments_rezult vehicles::cmd_vehicle_color_list(player_ptr_t const& player_ptr, std::string const& arguments, messages_pager& pager, messages_sender const& sender, messages_params& params) {
int vehicle_id, trailer_id;
vehicle_defs_t::const_iterator vehicle_def_it, trailer_def_it;
if (!get_vehicle_def_by_player(player_ptr, vehicle_id, vehicle_def_it)) return cmd_arg_process_error;
bool is_has_trailer = get_trailer_def_by_player(player_ptr, trailer_id, trailer_def_it);
int colors = vehicle_def_it->second.colors;
if (is_has_trailer) {
colors += trailer_def_it->second.colors;
}
params("v_id", vehicle_id); set_params(vehicle_def_it, params);
pager.set_header_text(0, "$(cmd_vehicle_color_list_header" + boost::lexical_cast<std::string>(colors) + ")");
for (std::size_t i = 0, size = vehicle_colors.size(); i < size; ++i) {
params
("id", i + 1)
("color", vehicle_colors[i].color)
("name", vehicle_colors[i].name);
pager("$(cmd_vehicle_color_list_item)");
}
return cmd_arg_auto;
}
void vehicles::get_mods_groups(vehicle_defs_t::const_iterator const& vehicle_def_it, mods_groups_t& mods_groups) {
BOOST_FOREACH(std::string const& mod_name, vehicle_def_it->second.components) {
vehicle_component_defs_t::const_iterator cmp_it = vehicle_component_defs.find(mod_name);
if (vehicle_component_defs.end() != cmp_it) {
mods_groups[cmp_it->second.group].insert(std::make_pair(cmp_it->second.name, std::make_pair(cmp_it->first, &cmp_it->second)));
}
}
}
void vehicles::add_component(vehicle_component_def_t const& component_def, int vehicle_id) {
std::for_each(component_def.ids.begin(), component_def.ids.end(), std::tr1::bind(&samp::api::add_vehicle_component, samp::api::instance(), vehicle_id, std::tr1::placeholders::_1));
}
void vehicles::remove_component(vehicle_component_def_t const& component_def, int vehicle_id) {
std::for_each(component_def.ids.begin(), component_def.ids.end(), std::tr1::bind(&samp::api::remove_vehicle_component, samp::api::instance(), vehicle_id, std::tr1::placeholders::_1));
}
void vehicles::mod_garages_create() {
BOOST_FOREACH(mod_garage_t const& mod_garage, mod_garages) {
BOOST_FOREACH(mod_garage_item_t const& garage, mod_garage.items) {
garage_val_t garage_val;
garage_val.mod_garage_ptr = &mod_garage;
garage_val.garage_ptr = &garage;
garage_val.mapicon_id = map_icons::instance()->add(garage.x, garage.y, garage.z, garage.interior, garage.world, garage.mapicon_radius, mod_garage.mapicon_marker_type);
garage_val.checkpoint_id = checkpoints::instance()->add(garage, std::tr1::bind(&vehicles::mod_garage_item_on_enter, this, std::tr1::placeholders::_1, std::tr1::placeholders::_2), std::tr1::bind(&vehicles::mod_garage_item_on_leave, this, std::tr1::placeholders::_1, std::tr1::placeholders::_2));
garage_vals.insert(std::make_pair(garage_val.checkpoint_id, garage_val));
}
}
}
void vehicles::mod_garages_destroy() {
BOOST_FOREACH(garage_vals_t::value_type const& garage_val_pair, garage_vals) {
map_icons::instance()->remove(garage_val_pair.second.mapicon_id);
checkpoints::instance()->remove(garage_val_pair.second.checkpoint_id);
}
garage_vals.clear();
}
void vehicles::mod_garage_item_on_enter(player_ptr_t const& player_ptr, int id) {
messages_item msg_item;
msg_item.get_params()
("checkpoint_id", id)
("player_name", player_ptr->name_get_full());
garage_vals_t::const_iterator garage_vals_it = garage_vals.find(id);
if (garage_vals.end() == garage_vals_it) {
assert(false);
return;
}
garage_val_t const& garage_val = garage_vals_it->second;
msg_item.get_params()
("mod_garage_name", garage_val.mod_garage_ptr->name)
("mod_garage_sys_name", garage_val.mod_garage_ptr->sys_name)
("garage_sys_name", garage_val.garage_ptr->sys_name)
;
int vehicle_id;
vehicle_defs_t::const_iterator vehicle_def_it;
bool vehicle_def_exhist = get_vehicle_def_by_player(player_ptr, vehicle_id, vehicle_def_it);
bool is_valid_vehicle = false;
if (vehicle_def_exhist) {
msg_item.get_params()("v_id", vehicle_id); set_params(vehicle_def_it, msg_item.get_params(), "v_");
is_valid_vehicle = garage_val.mod_garage_ptr->valid_vehicles.end() != garage_val.mod_garage_ptr->valid_vehicles.find(vehicle_def_it->second.sys_name);
}
std::string valid_cmd_list;
int cmd_count = 0;
if (is_valid_vehicle) {
if (cmd_vehicle_paintjob_access_checker_impl(player_ptr)) {
valid_cmd_list += "$(cmd_vehicle_paintjob_name) ";
++cmd_count;
}
if (cmd_vehicle_color_access_checker_impl(player_ptr)) {
valid_cmd_list += "$(cmd_vehicle_color_name) ";
++cmd_count;
}
if (cmd_vehicle_modification_access_checker_impl(player_ptr)) {
valid_cmd_list += "$(cmd_vehicle_modification_name) ";
++cmd_count;
}
boost::trim(valid_cmd_list);
}
msg_item.get_params()("valid_cmd_list", valid_cmd_list);
if (!vehicle_def_exhist) {
msg_item.get_sender()("$(on_modgarage_enter_foot)", msg_player(player_ptr));
if (is_trace_enter_leave_mod) {
msg_item.get_sender()("$(on_modgarage_enter_foot_log)", msg_debug);
}
}
else if (is_valid_vehicle && 0 != cmd_count) {
msg_item.get_sender()("$(on_modgarage_enter_valid)", msg_player(player_ptr));
if (is_trace_enter_leave_mod) {
msg_item.get_sender()("$(on_modgarage_enter_valid_log)", msg_debug);
}
}
else {
msg_item.get_sender()("$(on_modgarage_enter_invalid)", msg_player(player_ptr));
if (is_trace_enter_leave_mod) {
msg_item.get_sender()("$(on_modgarage_enter_invalid_log)", msg_debug);
}
}
}
void vehicles::mod_garage_item_on_leave(player_ptr_t const& player_ptr, int id) {
if (is_trace_enter_leave_mod) {
messages_item msg_item;
msg_item.get_params()
("checkpoint_id", id)
("player_name", player_ptr->name_get_full());
garage_vals_t::const_iterator garage_vals_it = garage_vals.find(id);
if (garage_vals.end() == garage_vals_it) {
assert(false);
return;
}
garage_val_t const& garage_val = garage_vals_it->second;
msg_item.get_params()
("mod_garage_name", garage_val.mod_garage_ptr->name)
("mod_garage_sys_name", garage_val.mod_garage_ptr->sys_name)
("garage_sys_name", garage_val.garage_ptr->sys_name)
;
msg_item.get_sender()("$(on_modgarage_leave_log)", msg_debug);
}
}
int vehicles::get_max_vehicle_id() const {
if (samp::server_ver_03a == samp::api::instance()->get_ver()) {
return samp::api::MAX_VEHICLES_v030;
}
return samp::api::MAX_VEHICLES;
}
pos4 vehicles::pos_get(int vehicle_id) const {
pos4 rezult;
samp::api::ptr api_ptr = samp::api::instance();
if (is_valid_vehicle_id(vehicle_id)) {
// Дописать интерьер
api_ptr->get_vehicle_pos(vehicle_id, rezult.x, rezult.y, rezult.z);
rezult.rz = api_ptr->get_vehicle_zangle(vehicle_id);
rezult.world = api_ptr->get_vehicle_virtual_world(vehicle_id);
}
return rezult;
}
bool vehicles::is_valid_vehicle_id(int vehicle_id) const {
return 0 != samp::api::instance()->get_vehicle_model(vehicle_id);
}
bool vehicles::is_vehicle_created_by_me(int vehicle_id) const {
return vehicles_state.end() != vehicles_state.find(vehicle_id);
}
bool vehicles::get_model_id_by_name(std::string const& gta_model_name, int& model_id) const {
BOOST_FOREACH(vehicle_defs_t::value_type const& vehicle_def, vehicle_defs) {
if (boost::iequals(gta_model_name, vehicle_def.second.sys_name)) {
model_id = vehicle_def.first;
return true;
}
}
return false;
}
bool vehicles::get_component_id_by_name(std::string const& gta_component_name, int& first_component_id) const {
vehicle_component_defs_t::const_iterator it = vehicle_component_defs.find(gta_component_name);
if (vehicle_component_defs.end() != it) {
if (!it->second.ids.empty()) {
first_component_id = it->second.ids[0];
return true;
}
}
return false;
}
std::string vehicles::get_component_name_by_id(int component_id) {
BOOST_FOREACH(vehicle_component_defs_t::value_type const& vehicle_component_def, vehicle_component_defs) {
if (vehicle_component_def.second.ids.end() != std::find(vehicle_component_def.second.ids.begin(), vehicle_component_def.second.ids.end(), component_id)) {
return vehicle_component_def.first;
}
}
return "no_name";
}
void vehicles::repair_garages_destroy() {
}
void vehicles::repair_garages_create() {
}
void vehicles::repair_garage_item_on_enter(player_ptr_t const& player_ptr, int id) {
}
void vehicles::repair_garage_item_on_leave(player_ptr_t const& player_ptr, int id) {
}
vehicle_ptr_t vehicles::get_vehicle(int vehicle_id) {
vehicles_state_t::iterator vehicle_curr_it = vehicles_state.find(vehicle_id);
if (vehicles_state.end() != vehicle_curr_it) {
return &vehicle_curr_it->second;
}
return 0;
}
void vehicles::dump_vehicles(vehiclesgame_t::update_t& vehicles) {
buffer::ptr buff(new buffer());
serialize(buff, serialization::make_nvp(vehicles, "vehicles"), serialization::make_def(&configuradable::configure, serialization::def_writing));
server_configuration::configure_use_buffer_debug_save(buff, PATH_VEHICLES_DUMP_FILENAME);
}
| [
"dimonml@19848965-7475-ded4-60a4-26152d85fbc5"
] | [
[
[
1,
1119
]
]
] |
dfa5a99c25afad3a23b7535132c7332f111d5789 | 28b0332fabba904ac0668630f185e0ecd292d2a1 | /src/Borland/CheckLabel.cpp | f6b1145b01b2e8a889a60d7bbb3ace867d520ee6 | [] | no_license | iplayfast/crylib | 57a507ba996d1abe020f93ea4a58f47f62b31434 | dbd435e14abc508c31d1f2f041f8254620e24dc0 | refs/heads/master | 2016-09-05T10:33:02.861605 | 2009-04-19T05:17:55 | 2009-04-19T05:17:55 | 35,353,897 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 738 | cpp | //---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "CheckLabel.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TCheckedLabel *CheckedLabel;
//---------------------------------------------------------------------------
__fastcall TCheckedLabel::TCheckedLabel(TComponent* Owner)
: TFrame(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TCheckedLabel::CheckBox1Click(TObject *Sender)
{
Edit1->Enabled = CheckBox1->Checked;
}
//---------------------------------------------------------------------------
| [
"cwbruner@f8ea3247-a519-0410-8bc2-439d413616df"
] | [
[
[
1,
21
]
]
] |
e76c8618218a5419319f02c45f2f9e1185806a3d | 60791ce953e9891f156b6862ad59ac4830a7cad2 | /CATL/Topology.cpp | b528db1ca7721c13fce75d1468fdb07e589d9de1 | [] | no_license | siavashmi/catl-code | 05283c6e24a1d3aa9652421a93f094c46c477014 | a668431b661c59f597c6f9408c371ec013bb9072 | refs/heads/master | 2021-01-10T03:17:38.898659 | 2011-06-30T10:27:35 | 2011-06-30T10:27:35 | 36,600,037 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 36,687 | cpp | #include "Topology.h"
#include <math.h> // For math routines (such as sqrt & trig).
#include <stdio.h>
#include <GL/glut.h> // OpenGL Graphics Utility Library
#include "common.h"
#include "assert.h"
#include <ctype.h>
#include "sensor.h"
float xrange = 120;
float yrange = 200;
float zrange = 50;
vector<Point> sensors;
int nSensors = 30000;
// The next global variable controls the animation's state and speed.
float RotateAngle = 0.0f; // Angle in degrees of rotation around y-axis
float Azimuth = 0.0; // Rotated up or down by this amount
float scale = 15;
float scalestepsize = 0.3f;
float AngleStepSize = 3.0f; // Step three degrees at a time
const float AngleStepMax = 10.0f;
const float AngleStepMin = 0.1f;
// The next global variable controls the animation's state and speed.
float CurrentAngle = 0.0f; // Angle in degrees
float AnimateStep = 0.5f; // Rotation step per update
int WireFrameOn = 1; // == 1 for wire frame mode
int displayMode=0;
// glutKeyboardFunc is called below to set this function to handle
// all "normal" key presses.
void myKeyboardFunc( unsigned char key, int x, int y )// what is the use of this function?
{
switch ( key ) {
case 'w':// in the main loop, every time input the key 'w', it will change, for the parameters WireFramOn is changed,
WireFrameOn = 1-WireFrameOn;
if ( WireFrameOn ) {
glPolygonMode ( GL_FRONT_AND_BACK, GL_LINE ); // Just show wireframes
}
else {
glPolygonMode ( GL_FRONT_AND_BACK, GL_FILL ); // Show solid polygons
}// the glpolygonmode : wire solid and point ; front and back views,
glutPostRedisplay();// window redisplayed,
break;
case 'R':
AngleStepSize *= 1.5;
if (AngleStepSize>AngleStepMax ) {
AngleStepSize = AngleStepMax;// what is the use of these parameters,
}
break;
case 'r':
AngleStepSize /= 1.5;
if (AngleStepSize<AngleStepMin ) {
AngleStepSize = AngleStepMin;
}
break;
case 'n':
changeDisplayMode();
break;
case 27: // Escape key
exit(1);
}
}
////////////////////////////////////////////////////////////////////////// the display functions need to be changed
//I need to display the nodes
void mySpecialKeyFunc( int key, int x, int y )// different views, with the arrow keys to control the angles to see the topology
{
switch ( key ) {
case GLUT_KEY_UP:
Azimuth += AngleStepSize;
if ( Azimuth>180.0f ) {
Azimuth -= 360.0f;
}
break;
case GLUT_KEY_DOWN:
Azimuth -= AngleStepSize;
if ( Azimuth < -180.0f ) {
Azimuth += 360.0f;
}
break;
case GLUT_KEY_LEFT:
RotateAngle += AngleStepSize;
if ( RotateAngle > 180.0f ) {
RotateAngle -= 360.0f;
}
break;
case GLUT_KEY_RIGHT:
RotateAngle -= AngleStepSize;
if ( RotateAngle < -180.0f ) {
RotateAngle += 360.0f;
}
break;
case GLUT_KEY_PAGE_UP:
scale += scalestepsize;
if(scale > 50) {
scale = 50;
}
break;
case GLUT_KEY_PAGE_DOWN:
scale -= scalestepsize;
if(scale < 0) {
scale = 0;
}
break;
}
glutPostRedisplay();
}
/*
* drawScene() handles the animation and the redrawing of the
* graphics window contents.
*/
void drawScene(void)
{
if(topologyIndex==0)// 8topology
drawPoint();
else
if(topologyIndex==1)
drawPointOfSmile();
else
if(topologyIndex==2)
drawPointOfS();
else
if(topologyIndex==3)
drawPointOfTorus();
}
// Initialize OpenGL's rendering modes
void initRendering()
{
glEnable( GL_DEPTH_TEST ); // Depth testing must be turned on
glEnable( GL_NORMALIZE );
glEnable( GL_BLEND );
glPointSize(2);//change the size of the node sensors,
glPolygonMode ( GL_FRONT_AND_BACK, GL_LINE );
// from the different views,
// Just show wireframes at first
}
// Called when the window is resized
// w, h - width and height of the window in pixels.
// how can we tell the window is resized?
void resizeWindow(int w, int h)
{
float aspectRatio;
glViewport( 0, 0, w, h ); // View port uses whole window
h = (h == 0) ? 1 : h;
aspectRatio = (float)w/(float)h;
// Set up the projection view matrix
glMatrixMode( GL_PROJECTION );// this is projection,
glLoadIdentity();
gluPerspective( 60.0, aspectRatio, 1.0, 30.0 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
// Move system 8 units away to be able to view from the origin.
glTranslatef(0.0, 0.0, -8.0);
// Tilt system 15 degrees downward in order to view from above
// the xy-plane.
glRotatef(15.0, 1.0,0.0,0.0);
}
void initSensors(const char* topoFile)
{
sensors.clear();
if(topoFile) {
FILE *fp;
fp = fopen(topoFile, "r");
char line[128];
if (!fp) {
fprintf(stderr, "no topo file %s found\n", topoFile);
exit(0);
}
do {
memset(line, 0, sizeof(line));
fgets(line, sizeof(line), fp);
if(!isspace(*line) && (*line)) {
Point s;
sscanf(line, "%lf %lf %lf", &s.x, &s.y, &s.z);
sensors.push_back(Point(s.x,s.y,s.z));
}
}while(!feof(fp));
fclose(fp);
}
}
///the initial is redundant
void drawPoint()
{
switch(displayMode)
{
case 0:
showOriginalOf8();
break;
case 1:
showLolizedOf8();
break;
case 2:
showTrasferedOf8();
break;
}
}
void changeDisplayMode(){
displayMode=(displayMode+1)%3;
}
void drawPointOfSmile()
{
if(displayMode==0)
{
showOriginalOfSmile();
}
if(displayMode==2)
{
showTrasferedOfSmile();
}
}
void drawPointOfS()
{
if(displayMode==0)
{
showOriginalOfS();
}
if(displayMode==1)
{
showTrasferedOfS();
}
}
void showOriginalOf8()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);// clear the color and the depth,
// Rotate the image
glMatrixMode( GL_MODELVIEW ); // what matrix are you changing , there are three matrix in all, the view,projection and the texture,
glLoadIdentity();
glTranslatef( 0, 0, -25); // at which view are you looking at the points,
//////////////////////////////////////////////////////////////////////////here add the parameter sent to this program,
glScalef(scale/X_RANGE,scale/Y_RANGE,scale/Z_RANGE);// scale,
glRotatef( RotateAngle, 0.0, 1.0, 0.0 ); // Rotate around y-axis
glRotatef( Azimuth, 1.0, 0.0, 0.0 ); // Set Azimuth angle
//rotate around the vector I just wrote.
glPushMatrix();// push the matrix, prevent the change of the original point,
glTranslatef( -xrange/2, -yrange/2, -zrange/2 );
// glRotatef( -90.0, 1.0, 0.0, 0.0 );
glColor4f( 1.0, 0.2, 0.2, 0.3 ); // Reddish color the last one is about the transparency
glBlendFunc(GL_SRC_ALPHA,GL_ONE);
glDisable( GL_DEPTH_TEST );
glBegin( GL_QUAD_STRIP );//
glVertex3f( 0.0, 0.0, 0.0 );
glVertex3f( 0.0, 0.0, zrange );
glVertex3f( 0.0, yrange, 0.0 );
glVertex3f( 0.0, yrange, zrange );
glVertex3f( xrange, yrange, 0.0 );
glVertex3f( xrange, yrange, zrange );
glVertex3f( xrange, 0.0, 0.0 );
glVertex3f( xrange, 0.0, zrange );
glVertex3f( 0.0, 0.0, 0.0 );
glVertex3f( 0.0, 0.0, zrange );
glEnd();// these form a closed graph~
// a cube does have four 8 points, but we need to close it, with the specified order,
glColor4f( 0.2, 1.0, 0.2, 0.3 ); // Greenish color
glBegin( GL_QUAD_STRIP );
glVertex3f( xrange/3, yrange/5, 0.0 );
glVertex3f( xrange/3, yrange/5, zrange );
glVertex3f( xrange/3, yrange/5*2, 0.0 );
glVertex3f( xrange/3, yrange/5*2, zrange );
glVertex3f( xrange/3*2, yrange/5*2, 0.0 );
glVertex3f( xrange/3*2, yrange/5*2, zrange );
glVertex3f( xrange/3*2, yrange/5, 0.0 );
glVertex3f( xrange/3*2, yrange/5, zrange );
glVertex3f( xrange/3, yrange/5, 0.0 );
glVertex3f( xrange/3, yrange/5, zrange );
glEnd();
glBegin( GL_QUAD_STRIP );
glVertex3f( xrange/3, yrange/5*3, 0.0 );
glVertex3f( xrange/3, yrange/5*3, zrange );
glVertex3f( xrange/3, yrange/5*4, 0.0 );
glVertex3f( xrange/3, yrange/5*4, zrange );
glVertex3f( xrange/3*2, yrange/5*4, 0.0 );
glVertex3f( xrange/3*2, yrange/5*4, zrange );
glVertex3f( xrange/3*2, yrange/5*3, 0.0 );
glVertex3f( xrange/3*2, yrange/5*3, zrange );
glVertex3f( xrange/3, yrange/5*3, 0.0 );
glVertex3f( xrange/3, yrange/5*3, zrange );
glEnd();
glPopMatrix();
glPushMatrix();
glColor3f( 1.0, 1.0, 1.0 );
glTranslatef( -xrange/2, -yrange/2, -zrange/2 );
for(int i = 0; i < globalField->nSensors; i++)
{
Sensor *s =globalField->sensorPool+i;
if(s->seed==true)
{
glColor3f( 1.0, 0.0, 0.0 );
glPointSize(5);
glBegin( GL_POINTS );
glVertex3f(s->location.x,s->location.y,s->location.z);
glEnd();
}
else
if(s->onEdge==true&&0)
{
glColor3f( 0.0, 1.0, 0.0 );
glPointSize(2);
glBegin( GL_POINTS );
glVertex3f(s->location.x,s->location.y,s->location.z);
glEnd();
}
else
if(s->initLandmark==true)
{
glColor3f( 0.0, 1.0, 0.0 );
glPointSize(3);
glBegin( GL_POINTS );
glVertex3f(s->location.x,s->location.y,s->location.z);
glEnd();
}
else
if(s->notchDegree>notchThreshold)
{
glColor3f( 1.0, 0.0, 0.0 );
glPointSize(2);
glBegin( GL_POINTS );
glVertex3f(s->location.x,s->location.y,s->location.z);
glEnd();
}
else
{
glColor3f( 1.0, 1.0, 1.0 );
glPointSize(2);
glBegin( GL_POINTS );
glVertex3f(s->location.x,s->location.y,s->location.z);
glEnd();
}
}
glPopMatrix();
glFlush();
glutSwapBuffers();
}
void showLolizedOf8()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);// clear the color and the depth,
// Rotate the image
glMatrixMode( GL_MODELVIEW ); // what matrix are you changing , there are three matrix in all, the view,projection and the texture,
glLoadIdentity();
glTranslatef( 0, 0, -7); // at which view are you looking at the points,
//////////////////////////////////////////////////////////////////////////here add the parameter sent to this program,
glScalef(scale/X_RANGE,scale/Y_RANGE,scale/Z_RANGE);// scale,
glRotatef( RotateAngle, 0.0, 1.0, 0.0 ); // Rotate around y-axis
glRotatef( Azimuth, 1.0, 0.0, 0.0 );
glPushMatrix();
glColor3f( 1.0, 1.0, 1.0 );
glTranslatef( -xrange/10, -yrange/10, -zrange/10 );
for(int i =0;i<globalField->nSensors;i++){
Sensor *s=globalField->sensorPool+i;
if(s->localizedPosition!=INVALID_POINT)
{
if(s->seed==true)
{
glColor3f( 1.0, 0, 0 );
glPointSize(5);
glBegin( GL_POINTS );
glVertex3f(s->localizedPosition.x,s->localizedPosition.y,s->localizedPosition.z);
glEnd();
}
else
if(s->onEdge==true){
glColor3f( 0.0, 1, 0 );
glPointSize(2);
glBegin( GL_POINTS );
glVertex3f(s->localizedPosition.x,s->localizedPosition.y,s->localizedPosition.z);
glEnd();
}
else if(s->initLandmark==true){
glColor3f( 1.0, 1, 0 );
glPointSize(3);
glBegin( GL_POINTS );
glVertex3f(s->localizedPosition.x,s->localizedPosition.y,s->localizedPosition.z);
glEnd();
}
else{
glColor3f( 1.0, 1, 1 );
glPointSize(2);
glBegin( GL_POINTS );
glVertex3f(s->localizedPosition.x,s->localizedPosition.y,s->localizedPosition.z);
glEnd();
}
}
}
glPopMatrix();
glFlush();
glutSwapBuffers();
}
void showTrasferedOf8()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);// clear the color and the depth,
// Rotate the image
glMatrixMode( GL_MODELVIEW ); // what matrix are you changing , there are three matrix in all, the view,projection and the texture,
glLoadIdentity();
glTranslatef( 0, 0, -25); // at which view are you looking at the points,
//////////////////////////////////////////////////////////////////////////here add the parameter sent to this program,
glScalef(scale/X_RANGE,scale/Y_RANGE,scale/Z_RANGE);// scale,
glRotatef( RotateAngle, 0.0, 1.0, 0.0 ); // Rotate around y-axis
glRotatef( Azimuth, 1.0, 0.0, 0.0 ); // Set Azimuth angle
//rotate around the vector I just wrote.
glPushMatrix();// push the matrix, prevent the change of the original point,
glTranslatef( -xrange/2, -yrange/2, -zrange/2 );
// glRotatef( -90.0, 1.0, 0.0, 0.0 );
glColor4f( 1.0, 0.2, 0.2, 0.3 ); // Reddish color the last one is about the transparency
glBlendFunc(GL_SRC_ALPHA,GL_ONE);
glDisable( GL_DEPTH_TEST );
glBegin( GL_QUAD_STRIP );//
glVertex3f( 0.0, 0.0, 0.0 );
glVertex3f( 0.0, 0.0, zrange );
glVertex3f( 0.0, yrange, 0.0 );
glVertex3f( 0.0, yrange, zrange );
glVertex3f( xrange, yrange, 0.0 );
glVertex3f( xrange, yrange, zrange );
glVertex3f( xrange, 0.0, 0.0 );
glVertex3f( xrange, 0.0, zrange );
glVertex3f( 0.0, 0.0, 0.0 );
glVertex3f( 0.0, 0.0, zrange );
glEnd();// these form a closed graph~
// a cube does have four 8 points, but we need to close it, with the specified order,
glColor4f( 0.2, 1.0, 0.2, 0.3 ); // Greenish color
glBegin( GL_QUAD_STRIP );
glVertex3f( xrange/3, yrange/5, 0.0 );
glVertex3f( xrange/3, yrange/5, zrange );
glVertex3f( xrange/3, yrange/5*2, 0.0 );
glVertex3f( xrange/3, yrange/5*2, zrange );
glVertex3f( xrange/3*2, yrange/5*2, 0.0 );
glVertex3f( xrange/3*2, yrange/5*2, zrange );
glVertex3f( xrange/3*2, yrange/5, 0.0 );
glVertex3f( xrange/3*2, yrange/5, zrange );
glVertex3f( xrange/3, yrange/5, 0.0 );
glVertex3f( xrange/3, yrange/5, zrange );
glEnd();
glBegin( GL_QUAD_STRIP );
glVertex3f( xrange/3, yrange/5*3, 0.0 );
glVertex3f( xrange/3, yrange/5*3, zrange );
glVertex3f( xrange/3, yrange/5*4, 0.0 );
glVertex3f( xrange/3, yrange/5*4, zrange );
glVertex3f( xrange/3*2, yrange/5*4, 0.0 );
glVertex3f( xrange/3*2, yrange/5*4, zrange );
glVertex3f( xrange/3*2, yrange/5*3, 0.0 );
glVertex3f( xrange/3*2, yrange/5*3, zrange );
glVertex3f( xrange/3, yrange/5*3, 0.0 );
glVertex3f( xrange/3, yrange/5*3, zrange );
glEnd();
glPopMatrix();
glPushMatrix();
glColor3f( 1.0, 1.0, 1.0 );
glTranslatef( -xrange/2, -yrange/2, -zrange/2 );
for(int i =0;i<globalField->nSensors;i++){
Sensor *s=globalField->sensorPool+i;
if(s->localizedPosition!=INVALID_POINT)
{
if(s->seed==true)
{
glColor3f( 1.0, 0, 0 );
glPointSize(5);
glBegin( GL_POINTS );
glVertex3f(s->finalLocalization.x,s->finalLocalization.y,s->finalLocalization.z);
glEnd();
}
else
if(s->onEdge==true){
glColor3f( 0.0, 1, 0 );
glPointSize(2);
glBegin( GL_POINTS );
glVertex3f(s->finalLocalization.x,s->finalLocalization.y,s->finalLocalization.z);
glEnd();
}
else if(s->initLandmark==true){
glColor3f( 1.0, 1, 0 );
glPointSize(3);
glBegin( GL_POINTS );
glVertex3f(s->finalLocalization.x,s->finalLocalization.y,s->finalLocalization.z);
glEnd();
}
else{
glColor3f( 1.0, 1, 1 );
glPointSize(2);
glBegin( GL_POINTS );
glVertex3f(s->finalLocalization.x,s->finalLocalization.y,s->finalLocalization.z);
glEnd();
}
}
}
glPopMatrix();
glFlush();
glutSwapBuffers();
}
void showOriginalOfSmile()
{
GLUquadricObj* myReusableQuadric = NULL;
xrange = 100;
xrange = 100;
yrange = 100;
zrange = 100;
float radius = xrange/2;
float H = 1.8;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if ( ! myReusableQuadric ) {
myReusableQuadric = gluNewQuadric();
// Should (but don't) check if pointer is still null --- to catch memory allocation errors.
gluQuadricNormals( myReusableQuadric, GL_TRUE );
}
// Rotate the image
glMatrixMode( GL_MODELVIEW ); // Current matrix affects objects positions
glLoadIdentity(); // Initialize to the identity
glTranslatef( 0.0, 0.0, -20.0 ); // Translate from origin (in front of viewer)
glScalef(scale/xrange,scale/yrange,scale/zrange);
glRotatef( RotateAngle, 0.0, 1.0, 0.0 ); // Rotate around y-axis
glRotatef( Azimuth, 1.0, 0.0, 0.0 ); // Set Azimuth angle
//Draw face
glPushMatrix();
// glTranslatef( -X_RANGE/2, -Y_RANGE/2, -Z_RANGE/2 );
glColor4f( 1.0, 0.2, 0.2, 0.0 ); // Reddish color
glBlendFunc(GL_SRC_ALPHA,GL_ONE);
glDisable( GL_DEPTH_TEST );
if(WireFrameOn)
glutWireSphere(radius, 20, 20);
else
glutSolidSphere(radius, 20, 20);
glPopMatrix();
//Draw left eye
glPushMatrix();
glColor4f( 0.2, 1.0, 0.2, 0.0 ); //Greenish color
glTranslatef( -radius/3, radius/3, -radius*H/2 );
gluCylinder(myReusableQuadric, radius/5, radius/5, radius*H, 20, 20);
glPopMatrix();
//Draw right eye
glPushMatrix();
glTranslatef( radius/3, radius/3, -radius*H/2 );
gluCylinder(myReusableQuadric, radius/5, radius/5, radius*H, 20, 20);
glPopMatrix();
//Draw glasses
glPushMatrix();
glColor4f( 0.2, 1.0, 0.2, 0.0 );
glTranslatef(radius/3, radius/3, radius*H/2);
gluDisk( myReusableQuadric, 0.0, radius/5, 20, 20 );
glPopMatrix();
glPushMatrix();
glTranslatef(radius/3, radius/3, -radius*H/2);
gluDisk( myReusableQuadric, 0.0, radius/5, 20, 20 );
glPopMatrix();
glPushMatrix();
glTranslatef(-radius/3, radius/3, radius*H/2);
gluDisk( myReusableQuadric, 0.0, radius/5, 20, 20 );
glPopMatrix();
glPushMatrix();
glTranslatef(-radius/3, radius/3, -radius*H/2);
gluDisk( myReusableQuadric, 0.0, radius/5, 20, 20 );
glPopMatrix();
//Draw mouth
glPushMatrix();
glColor4f( 0.2, 1.0, 0.2, 0.0 );
glTranslatef(-xrange/3/2, -yrange/6/2-radius/3, -zrange*0.9/2);
glBegin( GL_QUAD_STRIP );
glVertex3f( 0.0, 0.0, 0.0 );
glVertex3f( xrange/3, 0.0, 0.0 );
glVertex3f( 0.0, yrange/6, 0.0 );
glVertex3f( xrange/3, yrange/6, 0.0 );
glVertex3f( 0.0, yrange/6, zrange*0.9 );
glVertex3f( xrange/3, yrange/6, zrange*0.9 );
glVertex3f( 0.0, 0.0, zrange*0.9 );
glVertex3f( xrange/3, 0.0, zrange*0.9 );
glVertex3f( 0.0, 0.0, 0.0 );
glVertex3f( xrange/3, 0.0, 0.0 );
glEnd();
glPopMatrix();
glPushMatrix();
glColor3f( 1.0, 1.0, 1.0 );
// glTranslatef( -X_RANGE/2, -Y_RANGE/2, -Z_RANGE*0.75/2 );
for(int i =0;i<globalField->nSensors;i++)
{
Sensor *s=globalField->sensorPool+i;
if(s->seed==true)
{
glPointSize(9);
glColor3f(1,0,0);
glBegin( GL_POINTS );
glVertex3f(s->location.x-X_RANGE/2, s->location.y-Y_RANGE/2, s->location.z-Z_RANGE/2);
glEnd();
}
if(s->notchDegree>notchThreshold)
{
glPointSize(2);
glColor3f(1,0,0);
glBegin( GL_POINTS );
glVertex3f(s->location.x-X_RANGE/2, s->location.y-Y_RANGE/2, s->location.z-Z_RANGE/2);
glEnd();
}
else{
glPointSize(2);
glColor3f(1,1,1);
glBegin( GL_POINTS );
glVertex3f(s->location.x-X_RANGE/2, s->location.y-Y_RANGE/2, s->location.z-Z_RANGE/2);
glEnd();
}
}
glPopMatrix();
// Flush the pipeline, swap the buffers
glFlush();
glutSwapBuffers();
}
void showLolizedOfSmile()
{
// null at this time
}
void showTrasferedOfSmile()
{
xrange = 100;
xrange = 100;
yrange = 100;
zrange = 100;
float radius = xrange/2;
float H = 1.8;
GLUquadricObj* myReusableQuadric = NULL;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if ( ! myReusableQuadric ) {
myReusableQuadric = gluNewQuadric();
// Should (but don't) check if pointer is still null --- to catch memory allocation errors.
gluQuadricNormals( myReusableQuadric, GL_TRUE );
}
// Rotate the image
glMatrixMode( GL_MODELVIEW ); // Current matrix affects objects positions
glLoadIdentity(); // Initialize to the identity
glTranslatef( 0.0, 0.0, -20.0 ); // Translate from origin (in front of viewer)
glScalef(scale/xrange,scale/yrange,scale/zrange);
glRotatef( RotateAngle, 0.0, 1.0, 0.0 ); // Rotate around y-axis
glRotatef( Azimuth, 1.0, 0.0, 0.0 ); // Set Azimuth angle
//Draw face
glPushMatrix();
// glTranslatef( -X_RANGE/2, -Y_RANGE/2, -Z_RANGE/2 );
glColor4f( 1.0, 0.2, 0.2, 0.0 ); // Reddish color
glBlendFunc(GL_SRC_ALPHA,GL_ONE);
glDisable( GL_DEPTH_TEST );
if(WireFrameOn)
glutWireSphere(radius, 20, 20);
else
glutSolidSphere(radius, 20, 20);
glPopMatrix();
//Draw left eye
glPushMatrix();
glColor4f( 0.2, 1.0, 0.2, 0.0 ); //Greenish color
glTranslatef( -radius/3, radius/3, -radius*H/2 );
gluCylinder(myReusableQuadric, radius/5, radius/5, radius*H, 20, 20);
glPopMatrix();
//Draw right eye
glPushMatrix();
glTranslatef( radius/3, radius/3, -radius*H/2 );
gluCylinder(myReusableQuadric, radius/5, radius/5, radius*H, 20, 20);
glPopMatrix();
//Draw glasses
glPushMatrix();
glColor4f( 0.2, 1.0, 0.2, 0.0 );
glTranslatef(radius/3, radius/3, radius*H/2);
gluDisk( myReusableQuadric, 0.0, radius/5, 20, 20 );
glPopMatrix();
glPushMatrix();
glTranslatef(radius/3, radius/3, -radius*H/2);
gluDisk( myReusableQuadric, 0.0, radius/5, 20, 20 );
glPopMatrix();
glPushMatrix();
glTranslatef(-radius/3, radius/3, radius*H/2);
gluDisk( myReusableQuadric, 0.0, radius/5, 20, 20 );
glPopMatrix();
glPushMatrix();
glTranslatef(-radius/3, radius/3, -radius*H/2);
gluDisk( myReusableQuadric, 0.0, radius/5, 20, 20 );
glPopMatrix();
//Draw mouth
glPushMatrix();
glColor4f( 0.2, 1.0, 0.2, 0.0 );
glTranslatef(-xrange/3/2, -yrange/6/2-radius/3, -zrange*0.9/2);
glBegin( GL_QUAD_STRIP );
glVertex3f( 0.0, 0.0, 0.0 );
glVertex3f( xrange/3, 0.0, 0.0 );
glVertex3f( 0.0, yrange/6, 0.0 );
glVertex3f( xrange/3, yrange/6, 0.0 );
glVertex3f( 0.0, yrange/6, zrange*0.9 );
glVertex3f( xrange/3, yrange/6, zrange*0.9 );
glVertex3f( 0.0, 0.0, zrange*0.9 );
glVertex3f( xrange/3, 0.0, zrange*0.9 );
glVertex3f( 0.0, 0.0, 0.0 );
glVertex3f( xrange/3, 0.0, 0.0 );
glEnd();
glPopMatrix();
glPushMatrix();
glColor3f( 1.0, 1.0, 1.0 );
// glTranslatef( -X_RANGE/2, -Y_RANGE/2, -Z_RANGE*0.75/2 );
glBegin( GL_POINTS );
for(int i = 0; i < globalField->nSensors; i++)
{
Sensor *s=globalField->sensorPool+i;
glVertex3f(s->finalLocalization.x-X_RANGE/2, s->finalLocalization.y-Y_RANGE/2, s->finalLocalization.z-Z_RANGE/2);
}
glEnd();
glPopMatrix();
// Flush the pipeline, swap the buffers
glFlush();
glutSwapBuffers();
}
void showOriginalOfS()
{
float xrange = 200;
float yrange = 200;
float zrange = 100;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
scale=10;
// Rotate the image
glMatrixMode( GL_MODELVIEW ); // Current matrix affects objects positions
glLoadIdentity(); // Initialize to the identity
glTranslatef( 0.0, 0.0, -20.0 ); // Translate from origin (in front of viewer)
glScalef(scale/X_RANGE,scale/Y_RANGE,scale/Z_RANGE);
glRotatef( RotateAngle, 0.0, 1.0, 0.0 ); // Rotate around y-axis
glRotatef( Azimuth, 1.0, 0.0, 0.0 ); // Set Azimuth angle
glPushMatrix();
glTranslatef( -xrange/2, -yrange/2, -zrange/2 );
glColor4f( 1.0, 0.2, 0.2, 0.3 ); // Reddish color
glBlendFunc(GL_SRC_ALPHA,GL_ONE);
glDisable( GL_DEPTH_TEST );
glBegin( GL_QUAD_STRIP );
glVertex3f( 0.0, 0.0, 0.0 );
glVertex3f( 0.0, 0.0, zrange );
glVertex3f( 0.0, yrange/5, 0.0 );
glVertex3f( 0.0, yrange/5, zrange );
glVertex3f( xrange/5*3, yrange/5, 0.0 );
glVertex3f( xrange/5*3, yrange/5, zrange );
glVertex3f( xrange/5*3, yrange/5*2, 0.0 );
glVertex3f( xrange/5*3, yrange/5*2, zrange );
glVertex3f( 0.0, yrange/5*2, 0.0 );
glVertex3f( 0.0, yrange/5*2, zrange );
glVertex3f( 0.0, yrange, 0.0 );
glVertex3f( 0.0, yrange, zrange );
glVertex3f( xrange, yrange, 0.0 );
glVertex3f( xrange, yrange, zrange );
glVertex3f( xrange, yrange/5*4, 0.0 );
glVertex3f( xrange, yrange/5*4, zrange );
glVertex3f( xrange/5*2, yrange/5*4, 0.0 );
glVertex3f( xrange/5*2, yrange/5*4, zrange );
glVertex3f( xrange/5*2, yrange/5*3, 0.0 );
glVertex3f( xrange/5*2, yrange/5*3, zrange );
glVertex3f( xrange, yrange/5*3, 0.0 );
glVertex3f( xrange, yrange/5*3, zrange );
glVertex3f( xrange, 0.0, 0.0 );
glVertex3f( xrange, 0.0, zrange );
glVertex3f( 0.0, 0.0, 0.0 );
glVertex3f( 0.0, 0.0, zrange );
glVertex3f( 0.0, yrange/5, 0.0 );
glVertex3f( 0.0, yrange/5, zrange );
glEnd();
glPopMatrix();
glPushMatrix();
glColor3f( 1.0, 1.0, 1.0 );
glTranslatef( -xrange/2, -yrange/2, -zrange/2 );
for(int i =0;i<globalField->nSensors;i++)
{
Sensor *s=globalField->sensorPool+i;
if(s->seed==true)
{
glPointSize(9);
glColor3f(1,0,0);
glBegin(GL_POINTS);
glVertex3f(s->location.x,s->location.y,s->location.z);
glEnd();
}
else
if(s->notchDegree>notchThreshold){
glPointSize(3);
glColor3f(1,0,0);
glBegin(GL_POINTS);
glVertex3f(s->location.x,s->location.y,s->location.z);
glEnd();
}
else
{
glPointSize(2);
glColor3f(1,1,1);
glBegin(GL_POINTS);
glVertex3f(s->location.x,s->location.y,s->location.z);
glEnd();
}
}
glPopMatrix();
// Flush the pipeline, swap the buffers
glFlush();
glutSwapBuffers();
}
void showTrasferedOfS()
{
float xrange = 200;
float yrange = 200;
float zrange = 100;
scale=10;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Rotate the image
glMatrixMode( GL_MODELVIEW ); // Current matrix affects objects positions
glLoadIdentity(); // Initialize to the identity
glTranslatef( 0.0, 0.0, -20.0 ); // Translate from origin (in front of viewer)
glScalef(scale/X_RANGE,scale/Y_RANGE,scale/Z_RANGE);
glRotatef( RotateAngle, 0.0, 1.0, 0.0 ); // Rotate around y-axis
glRotatef( Azimuth, 1.0, 0.0, 0.0 ); // Set Azimuth angle
glPushMatrix();
glTranslatef( -xrange/2, -yrange/2, -zrange/2 );
glColor4f( 1.0, 0.2, 0.2, 0.3 ); // Reddish color
glBlendFunc(GL_SRC_ALPHA,GL_ONE);
glDisable( GL_DEPTH_TEST );
glBegin( GL_QUAD_STRIP );
glVertex3f( 0.0, 0.0, 0.0 );
glVertex3f( 0.0, 0.0, zrange );
glVertex3f( 0.0, yrange/5, 0.0 );
glVertex3f( 0.0, yrange/5, zrange );
glVertex3f( xrange/5*3, yrange/5, 0.0 );
glVertex3f( xrange/5*3, yrange/5, zrange );
glVertex3f( xrange/5*3, yrange/5*2, 0.0 );
glVertex3f( xrange/5*3, yrange/5*2, zrange );
glVertex3f( 0.0, yrange/5*2, 0.0 );
glVertex3f( 0.0, yrange/5*2, zrange );
glVertex3f( 0.0, yrange, 0.0 );
glVertex3f( 0.0, yrange, zrange );
glVertex3f( xrange, yrange, 0.0 );
glVertex3f( xrange, yrange, zrange );
glVertex3f( xrange, yrange/5*4, 0.0 );
glVertex3f( xrange, yrange/5*4, zrange );
glVertex3f( xrange/5*2, yrange/5*4, 0.0 );
glVertex3f( xrange/5*2, yrange/5*4, zrange );
glVertex3f( xrange/5*2, yrange/5*3, 0.0 );
glVertex3f( xrange/5*2, yrange/5*3, zrange );
glVertex3f( xrange, yrange/5*3, 0.0 );
glVertex3f( xrange, yrange/5*3, zrange );
glVertex3f( xrange, 0.0, 0.0 );
glVertex3f( xrange, 0.0, zrange );
glVertex3f( 0.0, 0.0, 0.0 );
glVertex3f( 0.0, 0.0, zrange );
glVertex3f( 0.0, yrange/5, 0.0 );
glVertex3f( 0.0, yrange/5, zrange );
glEnd();
glPopMatrix();
glPushMatrix();
glColor3f( 1.0, 1.0, 1.0 );
glTranslatef( -xrange/2, -yrange/2, -zrange/2 );
glBegin( GL_POINTS );
for(int i = 0; i < globalField->nSensors; i++)
{
Sensor *s=globalField->sensorPool+i;
glVertex3f(s->finalLocalization.x, s->finalLocalization.y, s->finalLocalization.z);
}
glEnd();
glPopMatrix();
// Flush the pipeline, swap the buffers
glFlush();
glutSwapBuffers();
}
void drawPointOfTorus()
{
if(displayMode==0)
showOriginalOfTorus();
if(displayMode==2)
showTrasferedOfTorus();
}
void putVert(int i, int j) {
float MajorRadius = 70;
float MinorRadius = 30;
int NumWraps = 40;
int NumPerWrap = 32;
float wrapFrac = (j%NumPerWrap)/(float)NumPerWrap;
float phi = PI*2*wrapFrac;
float theta = PI*2*(i%NumWraps+wrapFrac)/(float)NumWraps;
float sinphi = sin(phi);
float cosphi = cos(phi);
float sintheta = sin(theta);
float costheta = cos(theta);
float y = MinorRadius*sinphi;
float r = MajorRadius + MinorRadius*cosphi;
float x = sintheta*r;
float z = costheta*r;
glNormal3f(sintheta*cosphi, sinphi, costheta*cosphi);
glVertex3f(x,y,z);
}
void showOriginalOfTorus()
{
int i,j;
GLenum shadeModel = GL_SMOOTH;
GLenum polygonMode = GL_LINE;
GLenum LocalMode = GL_TRUE;
float scale = 8.0f;
float Noemit[4] = {0.0, 0.0, 0.0, 1.0};
float Matspec[4] = {1.0, 1.0, 1.0, 1.0};
float Matnonspec[4] = {0.8, 1.0, 1.0, 1.0};
float Matshiny = 16.0;
float RotX = 90.0f; // Rotational position around x-axis
float RotY = 0.0f;
int QuadMode = 1;
int NumWraps = 40;
int NumPerWrap = 32;
float MajorRadius = 70;
float MinorRadius = 30;
float PNoemit[4] = {0.0, 0.0, 0.0, 1.0};
float PMatspec[4] = {1.0, 1.0, 1.0, 1.0};
float PMatnonspec[4] = {1.0, 0.0, 0.0, 1.0};
float PMatshiny = 10.0;
// Clear the redering window
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glShadeModel( shadeModel ); // Set the shading to flat or smooth.
glPolygonMode(GL_FRONT_AND_BACK, polygonMode); // Set to be "wire" or "solid"
glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, LocalMode);
// Torus Materials
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, Matnonspec);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, Matspec);
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, Matshiny);
glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, Noemit);
glMatrixMode( GL_MODELVIEW ); // Current matrix affects objects positions
glLoadIdentity();
glTranslatef(0,0,-10);
glRotatef( RotateAngle, 0.0, 1.0, 0.0 );
glRotatef( Azimuth, 1.0, 0.0, 0.0 );
glPushMatrix(); // Save to use again next time.
glRotatef( RotX, 1.0, 0.0, 0.0);
glRotatef( RotY, 0.0, 1.0, 0.0);
// Draw the torus
glScalef( scale/X_RANGE, scale/Y_RANGE, scale/Z_RANGE );
glColor4f( 0.5, 1.0, 0.5, 1.0 );
// glutWireSphere(X_RANGE/2, 30, 30);
glBegin( QuadMode==1 ? GL_QUAD_STRIP : GL_TRIANGLE_STRIP );
for (i=0; i<NumWraps; i++ ) {
for (j=0; j<NumPerWrap; j++) {
putVert(i,j);
putVert(i+1,j);
}
}
putVert(0,0);
putVert(1,0);
glEnd();
// glPopMatrix();
// glPushMatrix();
// Draw the reference pyramid
glTranslatef( -MajorRadius-MinorRadius-MajorRadius/10.0, 0.0, 0.0);
glScalef( scale/4, scale/4, scale/4 );
glColor4f( 1.0f, 1.0f, 0.0f, 1.0f );
glBegin(GL_TRIANGLE_STRIP);
glVertex3f( -0.5, 0.0, sqrt(3.0)*0.5 );
glVertex3f( -0.5, 0.0, -sqrt(3.0)*0.5 );
glVertex3f( 1.0, 0.0, 0.0);
glVertex3f( 0.0, sqrt(2.0), 0.0);
glVertex3f( -0.5, 0.0, sqrt(3.0)*0.5 );
glVertex3f( -0.5, 0.0, -sqrt(3.0)*0.5 );
glEnd();
glPopMatrix(); // Restore to original matrix as set in resizeWindow()
//Points material
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, PMatnonspec);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, PMatspec);
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, PMatshiny);
glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, PNoemit);
/*
if ( runMode ) {
RotY += RotIncrementY;
if ( fabs(RotY)>360.0 ) {
RotY -= 360.0*((int)(RotY/360.0));
}
RotX += RotIncrementX;
if ( fabs(RotX)>360.0 ) {
RotX -= 360.0*((int)(RotX/360.0));
}
}
*/
// Set the orientation.
glRotatef( RotX, 1.0, 0.0, 0.0);
glRotatef( RotY, 0.0, 1.0, 0.0);
glColor4f( 0.0, 0.0, 0.0, 1.0 );
glScalef( scale/X_RANGE, scale/Y_RANGE, scale/Z_RANGE );
for(int i =0;i<globalField->nSensors;i++)
{
Sensor *s=globalField->sensorPool+i;
if(s->notchDegree>notchThreshold)
{
glPointSize(2);
glColor3f(1,0,0);
glBegin(GL_POINTS);
glVertex3f(s->location.x,s->location.y,s->location.z);
glEnd();
}
if(s->seed==true)
{
glPointSize(5);
glColor3f(1,0,0);
glBegin(GL_POINTS);
glVertex3f(s->location.x,s->location.y,s->location.z);
glEnd();
}
else
{
glPointSize(2);
glColor3f(1,1,1);
glBegin(GL_POINTS);
glVertex3f(s->location.x,s->location.y,s->location.z);
glEnd();
}
}
/*
//draw a ball
glPushMatrix();
glScalef( scale/X_RANGE, scale/Y_RANGE, scale/Z_RANGE );
glColor4f(0.5, 0.8, 0.0, 1.0);
glutWireSphere(X_RANGE/2, 20, 20);
glPopMatrix();
*/
// Flush the pipeline, swap the buffers
glFlush();
glutSwapBuffers();
}
void showTrasferedOfTorus()
{
int i,j;
GLenum shadeModel = GL_SMOOTH;
GLenum polygonMode = GL_LINE;
GLenum LocalMode = GL_TRUE;
float scale = 8.0f;
float Noemit[4] = {0.0, 0.0, 0.0, 1.0};
float Matspec[4] = {1.0, 1.0, 1.0, 1.0};
float Matnonspec[4] = {0.8, 1.0, 1.0, 1.0};
float Matshiny = 16.0;
float RotX = 90.0f; // Rotational position around x-axis
float RotY = 0.0f;
int QuadMode = 1;
int NumWraps = 40;
int NumPerWrap = 32;
float MajorRadius = 70;
float MinorRadius = 30;
float PNoemit[4] = {0.0, 0.0, 0.0, 1.0};
float PMatspec[4] = {1.0, 1.0, 1.0, 1.0};
float PMatnonspec[4] = {1.0, 0.0, 0.0, 1.0};
float PMatshiny = 10.0;
// Clear the redering window
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glShadeModel( shadeModel ); // Set the shading to flat or smooth.
glPolygonMode(GL_FRONT_AND_BACK, polygonMode); // Set to be "wire" or "solid"
glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, LocalMode);
// Torus Materials
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, Matnonspec);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, Matspec);
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, Matshiny);
glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, Noemit);
glMatrixMode( GL_MODELVIEW ); // Current matrix affects objects positions
glLoadIdentity();
glTranslatef(0,0,-10);
glRotatef( RotateAngle, 0.0, 1.0, 0.0 );
glRotatef( Azimuth, 1.0, 0.0, 0.0 );
glPushMatrix(); // Save to use again next time.
glRotatef( RotX, 1.0, 0.0, 0.0);
glRotatef( RotY, 0.0, 1.0, 0.0);
// Draw the torus
glScalef( scale/X_RANGE, scale/Y_RANGE, scale/Z_RANGE );
glColor4f( 0.5, 1.0, 0.5, 1.0 );
// glutWireSphere(X_RANGE/2, 30, 30);
/*
glBegin( QuadMode==1 ? GL_QUAD_STRIP : GL_TRIANGLE_STRIP );
for (i=0; i<NumWraps; i++ ) {
for (j=0; j<NumPerWrap; j++) {
putVert(i,j);
putVert(i+1,j);
}
}
putVert(0,0);
putVert(1,0);
glEnd();
*/
// glPopMatrix();
// glPushMatrix();
// Draw the reference pyramid
glTranslatef( -MajorRadius-MinorRadius-MajorRadius/10.0, 0.0, 0.0);
glScalef( scale/4, scale/4, scale/4 );
glColor4f( 1.0f, 1.0f, 0.0f, 1.0f );
glBegin(GL_TRIANGLE_STRIP);
glVertex3f( -0.5, 0.0, sqrt(3.0)*0.5 );
glVertex3f( -0.5, 0.0, -sqrt(3.0)*0.5 );
glVertex3f( 1.0, 0.0, 0.0);
glVertex3f( 0.0, sqrt(2.0), 0.0);
glVertex3f( -0.5, 0.0, sqrt(3.0)*0.5 );
glVertex3f( -0.5, 0.0, -sqrt(3.0)*0.5 );
glEnd();
glPopMatrix(); // Restore to original matrix as set in resizeWindow()
//Points material
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, PMatnonspec);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, PMatspec);
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, PMatshiny);
glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, PNoemit);
/*
if ( runMode ) {
RotY += RotIncrementY;
if ( fabs(RotY)>360.0 ) {
RotY -= 360.0*((int)(RotY/360.0));
}
RotX += RotIncrementX;
if ( fabs(RotX)>360.0 ) {
RotX -= 360.0*((int)(RotX/360.0));
}
}
*/
// Set the orientation.
glRotatef( RotX, 1.0, 0.0, 0.0);
glRotatef( RotY, 0.0, 1.0, 0.0);
glColor4f( 0.0, 0.0, 0.0, 1.0 );
glScalef( scale/X_RANGE, scale/Y_RANGE, scale/Z_RANGE );
for(int i =0;i<globalField->nSensors;i++)
{
Sensor *s=globalField->sensorPool+i;
if(s->notchDegree>notchThreshold)
{
glPointSize(2);
glColor3f(1,0,0);
glBegin(GL_POINTS);
glVertex3f(s->finalLocalization.x,s->finalLocalization.y,s->finalLocalization.z);
glEnd();
}
if(s->seed==true)
{
glPointSize(5);
glColor3f(1,0,0);
glBegin(GL_POINTS);
glVertex3f(s->finalLocalization.x,s->finalLocalization.y,s->finalLocalization.z);
glEnd();
}
else
{
glPointSize(2);
glColor3f(1,1,1);
glBegin(GL_POINTS);
glVertex3f(s->finalLocalization.x,s->finalLocalization.y,s->finalLocalization.z);
glEnd();
}
}
/*
//draw a ball
glPushMatrix();
glScalef( scale/X_RANGE, scale/Y_RANGE, scale/Z_RANGE );
glColor4f(0.5, 0.8, 0.0, 1.0);
glutWireSphere(X_RANGE/2, 20, 20);
glPopMatrix();
*/
// Flush the pipeline, swap the buffers
glFlush();
glutSwapBuffers();
} | [
"[email protected]"
] | [
[
[
1,
1310
]
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.