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
4d0390feec73412d2688d79f47b74efa84cc70c4
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/3rdParty/boost/libs/math/special_functions/special_functions_test.cpp
fc646dc4d5e9a3c67c9ea2058a9645d5cd7f8bee
[]
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
3,283
cpp
// test file for special functions. // (C) Copyright Hubert Holin 2003. // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <iomanip> #include <iostream> #include <functional> #include <boost/bind.hpp> #include <boost/function.hpp> #include <boost/test/unit_test_suite_ex.hpp> #include "sinc_test.hpp" #include "sinhc_test.hpp" #include "atanh_test.hpp" #include "asinh_test.hpp" #include "acosh_test.hpp" boost::unit_test_framework::test_suite * init_unit_test_suite(int, char *[]) { //::boost::unit_test_framework::unit_test_log::instance(). // set_log_threshold_level_by_name("messages"); boost::unit_test_framework::test_suite * test = BOOST_TEST_SUITE("special_functions_test"); #define BOOST_SPECIAL_FUNCTIONS_COMMON_GENERATOR(fct,type) \ test->add(BOOST_TEST_CASE(::boost::bind(static_cast \ < void (*) (const char *) >(&fct##_test<type>), #type))); #define BOOST_SPECIAL_FUNCTIONS_COMMON_TEST(type) \ BOOST_SPECIAL_FUNCTIONS_COMMON_GENERATOR(atanh,type) \ BOOST_SPECIAL_FUNCTIONS_COMMON_GENERATOR(asinh,type) \ BOOST_SPECIAL_FUNCTIONS_COMMON_GENERATOR(acosh,type) \ BOOST_SPECIAL_FUNCTIONS_COMMON_GENERATOR(sinc_pi,type) \ BOOST_SPECIAL_FUNCTIONS_COMMON_GENERATOR(sinhc_pi,type) #define BOOST_SPECIAL_FUNCTIONS_TEMPLATE_TEMPLATE_TEST(type) \ BOOST_SPECIAL_FUNCTIONS_COMMON_GENERATOR(sinc_pi_complex,type) \ BOOST_SPECIAL_FUNCTIONS_COMMON_GENERATOR(sinhc_pi_complex,type) #ifdef BOOST_NO_TEMPLATE_TEMPLATES #define BOOST_SPECIAL_FUNCTIONS_TEST(type) \ BOOST_SPECIAL_FUNCTIONS_COMMON_TEST(type) \ BOOST_MESSAGE("Warning: no template templates; curtailed functionality."); #else /* BOOST_NO_TEMPLATE_TEMPLATES */ #define BOOST_SPECIAL_FUNCTIONS_TEST(type) \ BOOST_SPECIAL_FUNCTIONS_COMMON_TEST(type) \ BOOST_SPECIAL_FUNCTIONS_TEMPLATE_TEMPLATE_TEST(type) #endif /* BOOST_NO_TEMPLATE_TEMPLATES */ BOOST_SPECIAL_FUNCTIONS_TEST(float) BOOST_SPECIAL_FUNCTIONS_TEST(double) BOOST_SPECIAL_FUNCTIONS_TEST(long double) #undef BOOST_SPECIAL_FUNCTIONS_TEST #undef BOOST_SPECIAL_FUNCTIONS_TEMPLATE_TEMPLATE_TEST #undef BOOST_SPECIAL_FUNCTIONS_COMMON_TEST #undef BOOST_SPECIAL_FUNCTIONS_COMMON_GENERATOR #ifdef BOOST_SPECIAL_FUNCTIONS_TEST_VERBOSE using ::std::numeric_limits; BOOST_MESSAGE("epsilon"); BOOST_MESSAGE( ::std::setw(15) << numeric_limits<float>::epsilon() << ::std::setw(15) << numeric_limits<double>::epsilon() << ::std::setw(15) << numeric_limits<long double>::epsilon()); BOOST_MESSAGE(" "); atanh_manual_check(); asinh_manual_check(); acosh_manual_check(); sinc_pi_manual_check(); sinhc_pi_manual_check(); #endif /* BOOST_SPECIAL_FUNCTIONS_TEST_VERBOSE */ return(test); }
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 106 ] ] ]
e24371489e639b14ceb50cf4b5dce2df74ec65d8
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/nebula2/src/gfx2/nd3d9mesh_main.cc
8278712d090f353c8548b8faaabf39281fd32216
[]
no_license
ugozapad/TheZombieEngine
832492930df28c28cd349673f79f3609b1fe7190
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
refs/heads/master
2020-04-30T11:35:36.258363
2011-02-24T14:18:43
2011-02-24T14:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,333
cc
//------------------------------------------------------------------------------ // nd3d9mesh_main.cc // (C) 2003 RadonLabs GmbH //------------------------------------------------------------------------------ #include "precompiled/pchndirect3d9.h" #include "gfx2/nd3d9mesh.h" #include "kernel/nlogclass.h" nNebulaClass(nD3D9Mesh, "nmesh2"); //------------------------------------------------------------------------------ /** */ nD3D9Mesh::nD3D9Mesh() : d3dVBLockFlags(0), d3dIBLockFlags(0), vertexBuffer(0), indexBuffer(0), vertexDeclaration(0), privVertexBuffer(0), privIndexBuffer(0) { // empty } //------------------------------------------------------------------------------ /** */ nD3D9Mesh::~nD3D9Mesh() { if (this->IsLoaded()) { this->Unload(); } } //------------------------------------------------------------------------------ /** nD3D9Mesh support asynchronous resource loading. */ bool nD3D9Mesh::CanLoadAsync() const { return true; } //------------------------------------------------------------------------------ /** This method is either called directly from the nResource::Load() method (in synchronous mode), or from the loader thread (in asynchronous mode). The method must try to validate its resources, set the valid and pending flags, and return a success code. This method may be called from a thread. */ bool nD3D9Mesh::LoadResource() { n_assert(!this->IsLoaded()); n_assert(0 == this->vertexBuffer); n_assert(0 == this->indexBuffer); bool success = nMesh2::LoadResource(); if (success) { // create the vertex declaration from the vertex component mask this->CreateVertexDeclaration(); } return success; } //------------------------------------------------------------------------------ /** Unload the d3d resources. Make sure that the resource are properly disconnected from the graphics server. This method is called from nResource::Unload() which serves as a wrapper for synchronous and asynchronous mode. This method will NEVER be called from a thread though. */ void nD3D9Mesh::UnloadResource() { n_assert(this->IsLoaded()); nMesh2::UnloadResource(); // release the d3d resource if (this->vertexBuffer) { this->vertexBuffer->Release(); this->vertexBuffer = 0; } if (this->indexBuffer) { this->indexBuffer->Release(); this->indexBuffer = 0; } if (this->vertexDeclaration) { this->vertexDeclaration->Release(); this->vertexDeclaration = 0; } // release private buffers (if this is a ReadOnly mesh) if (this->privVertexBuffer) { n_free(this->privVertexBuffer); this->privVertexBuffer = 0; } if (this->privIndexBuffer) { n_free(this->privIndexBuffer); this->privIndexBuffer = 0; } this->SetState(Unloaded); } //------------------------------------------------------------------------------ /** This method is called when the d3d device is lost. We only need to react if our vertex and index buffers are not in D3D's managed pool. In this case, we need to unload ourselves... */ void nD3D9Mesh::OnLost() { if ( (WriteOnly & this->vertexUsage) && (this->IsValid() || this->IsEmpty())) { this->UnloadResource(); this->SetState(Lost); } } //------------------------------------------------------------------------------ /** This method is called when the d3d device has been restored. If our buffers are in the D3D's default pool, we need to restore ourselves as well, Radon labs says: "and we need to set our state to empty, because the buffers contain no data." */ void nD3D9Mesh::OnRestored() { if (WriteOnly & this->vertexUsage) { this->SetState(Unloaded); this->LoadResource(); } } //------------------------------------------------------------------------------ /** Create a static d3d vertex buffer and validate the vertexBuffer member. - 27-Sep-04 floh DX7 compatibility fix: software processing meshes now created in system mem, and without the WRITEONLY flag */ void nD3D9Mesh::CreateVertexBuffer() { n_assert(this->vertexBufferByteSize > 0); n_assert(0 == this->privVertexBuffer); n_assert(0 == this->vertexBuffer); n_assert(this->vertexBufferByteSize > 0); if (ReadOnly & this->vertexUsage) { // this is a read-only mesh which will never be rendered // and only read-accessed by the CPU, allocate private // vertex buffer this->privVertexBuffer = n_malloc(this->vertexBufferByteSize); n_assert(this->privVertexBuffer); } else { nD3D9Server* gfxServer = (nD3D9Server*) nGfxServer2::Instance(); n_assert(gfxServer->d3d9Device); // this is either a WriteOnce or a WriteOnly vertex buffer, // in both cases we create a D3D vertex buffer object HRESULT hr; DWORD d3dUsage = D3DUSAGE_WRITEONLY; D3DPOOL d3dPool = D3DPOOL_MANAGED; this->d3dVBLockFlags = 0; if (WriteOnly & this->vertexUsage) { d3dUsage = (D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY); d3dPool = D3DPOOL_DEFAULT; this->d3dVBLockFlags = D3DLOCK_DISCARD; } if (ReadWrite & this->vertexUsage) { d3dUsage = D3DUSAGE_DYNAMIC; d3dPool = D3DPOOL_SYSTEMMEM; } if (RTPatch & this->vertexUsage) { d3dUsage |= D3DUSAGE_RTPATCHES; } if (PointSprite & this->vertexUsage) { d3dUsage |= D3DUSAGE_POINTS; } // create buffer with software processing flag // if the NeedsVertexShader hint is enabled, and the d3d device // has been created with software or mixed vertex processing if (gfxServer->AreVertexShadersEmulated() && (NeedsVertexShader & this->vertexUsage)) { d3dUsage |= D3DUSAGE_SOFTWAREPROCESSING; d3dUsage &= ~D3DUSAGE_WRITEONLY; d3dPool = D3DPOOL_SYSTEMMEM; } // create the vertex buffer hr = gfxServer->d3d9Device->CreateVertexBuffer( this->vertexBufferByteSize, d3dUsage, 0, d3dPool, &(this->vertexBuffer), NULL); n_dxtrace(hr, "CreateVertexBuffer() failed in nD3D9Mesh"); n_assert(this->vertexBuffer); } } //------------------------------------------------------------------------------ /** Create a static d3d index buffer and validate the index buffer member. - 27-Sep-04 floh DX7 compatibility fix: software processing meshes now created in system mem, and without the WRITEONLY flag */ void nD3D9Mesh::CreateIndexBuffer() { n_assert(this->indexBufferByteSize > 0); n_assert(0 == this->indexBuffer); n_assert(0 == this->privIndexBuffer); n_assert(this->indexBufferByteSize > 0); if (ReadOnly & this->indexUsage) { this->privIndexBuffer = n_malloc(this->indexBufferByteSize); n_assert(this->privIndexBuffer); } else { nD3D9Server* gfxServer = (nD3D9Server*) nGfxServer2::Instance(); n_assert(gfxServer->d3d9Device); HRESULT hr; DWORD d3dUsage = D3DUSAGE_WRITEONLY; D3DPOOL d3dPool = D3DPOOL_MANAGED; this->d3dIBLockFlags = 0; if (WriteOnly & this->indexUsage) { d3dUsage = (D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY); d3dPool = D3DPOOL_DEFAULT; this->d3dIBLockFlags = D3DLOCK_DISCARD; } if (ReadWrite & this->indexUsage) { d3dUsage = D3DUSAGE_DYNAMIC; d3dPool = D3DPOOL_SYSTEMMEM; } if (RTPatch & this->indexUsage) { d3dUsage |= D3DUSAGE_RTPATCHES; } if (PointSprite & this->indexUsage) { d3dUsage |= D3DUSAGE_POINTS; } // create buffer with software processing flag // if the NeedsVertexShader hint is enabled, and the d3d device // has been created with software or mixed vertex processing if (gfxServer->AreVertexShadersEmulated() && (NeedsVertexShader & this->vertexUsage)) { d3dUsage |= D3DUSAGE_SOFTWAREPROCESSING; d3dUsage &= ~D3DUSAGE_WRITEONLY; d3dPool = D3DPOOL_SYSTEMMEM; } hr = gfxServer->d3d9Device->CreateIndexBuffer( this->indexBufferByteSize, d3dUsage, D3DFMT_INDEX16, d3dPool, &(this->indexBuffer), NULL); n_dxtrace(hr, "CreateIndexBuffer failed in nD3D9Mesh"); n_assert(this->indexBuffer); } } //------------------------------------------------------------------------------ /** Create the d3d9 vertex declaration from the vertex component mask. */ void nD3D9Mesh::CreateVertexDeclaration() { n_assert(0 == this->vertexDeclaration); nD3D9Server* gfxServer = (nD3D9Server*) nGfxServer2::Instance(); n_assert(gfxServer->d3d9Device); this->vertexDeclaration = gfxServer->NewVertexDeclaration(this->vertexComponentMask); n_assert(this->vertexDeclaration); } //------------------------------------------------------------------------------ /** Lock the d3d vertex buffer and return pointer to it. */ float* nD3D9Mesh::LockVertices() { this->LockMutex(); n_assert(this->vertexBuffer || this->privVertexBuffer); float* retval = 0; if (this->vertexBuffer) { VOID* ptr; n_dxverify2( this->vertexBuffer->Lock(0, 0, &ptr, this->d3dVBLockFlags), "Lock() on vertex buffer failed in nD3D9Mesh()"); n_assert(ptr); retval = (float*) ptr; } else { retval = (float*) this->privVertexBuffer; } this->UnlockMutex(); return retval; } //------------------------------------------------------------------------------ /** Unlock the d3d vertex buffer locked by nD3D9Mesh::LockVertices(). */ void nD3D9Mesh::UnlockVertices() { this->LockMutex(); n_assert(this->vertexBuffer || this->privVertexBuffer); if (this->vertexBuffer) { HRESULT hr; hr = this->vertexBuffer->Unlock(); n_dxtrace(hr, "Unlock() on vertex buffer failed in nD3D9Mesh"); } this->UnlockMutex(); } //------------------------------------------------------------------------------ /** Lock the d3d index buffer and return pointer to it. */ ushort* nD3D9Mesh::LockIndices() { this->LockMutex(); n_assert(this->indexBuffer || this->privIndexBuffer); ushort* retval = 0; if (this->indexBuffer) { VOID* ptr; n_dxverify2( this->indexBuffer->Lock(0, 0, &ptr, this->d3dIBLockFlags), "Lock on index buffer failed in nD3D9Mesh" ); n_assert(ptr); retval = (ushort*) ptr; } else { retval = (ushort*) this->privIndexBuffer; } this->UnlockMutex(); return retval; } //------------------------------------------------------------------------------ /** Unlock the d3d index buffer locked by nD3D9Mesh::LockIndices(). */ void nD3D9Mesh::UnlockIndices() { this->LockMutex(); n_assert(this->indexBuffer || this->privIndexBuffer); if (this->indexBuffer) { n_dxverify2( this->indexBuffer->Unlock(), "Unlock() on index buffer failed in nD3D9Mesh" ); } this->UnlockMutex(); } //------------------------------------------------------------------------------ /** Compute the byte size of the mesh data */ int nD3D9Mesh::GetByteSize() { if (this->IsValid()) { int vertexBufferSize = this->GetNumVertices() * this->GetVertexWidth() * sizeof(float); int indexBufferSize = this->GetNumIndices() * sizeof(ushort); return vertexBufferSize + indexBufferSize + nMesh2::GetByteSize(); } else { return 0; } } //------------------------------------------------------------------------------ /** */ void nD3D9Mesh::TransformCoordArray(float* vb, int offsetComponent, const matrix44& matrix, int numVertices, bool normal) { const int stride = this->GetVertexWidth(); #if 0 //FIXME- D3DXVec3TransformNormalArray fails in AMD architecture const int strideBytes = stride * sizeof(float); D3DXVECTOR3* vector = (D3DXVECTOR3*) (vb + offsetComponent); if (normal) { D3DXVec3TransformNormalArray(vector, strideBytes, vector, strideBytes, (D3DXMATRIX*) matrix.m, numVertices); } else { D3DXVec3TransformCoordArray(vector, strideBytes, vector, strideBytes, (D3DXMATRIX*) matrix.m, numVertices); } #else vb += offsetComponent; if (normal) { for (int idx = 0; idx < numVertices; ++idx) { vector3* vec = (vector3*) vb; *vec = matrix.transform_norm(*vec); vb += stride; } } else { for (int idx = 0; idx < numVertices; ++idx) { vector3* vec = (vector3*) vb; *vec = matrix * (*vec); vb += stride; } } #endif } //------------------------------------------------------------------------------ /** */ void nD3D9Mesh::TransformTexCoordArray(float* vb, int offsetComponent, const matrix33& matrix, int numVertices) { const int stride = this->GetVertexWidth(); vb += offsetComponent; for (int idx = 0; idx < numVertices; ++idx) { vector2* vec = (vector2*) vb; *vec = matrix * (*vec); vb += stride; } } //------------------------------------------------------------------------------ /** */ bool nD3D9Mesh::Transform(float* vb, int idxBegin, int numVertices, const matrix44& matrix) { n_assert(vb); int stride = this->GetVertexWidth(); vb += (idxBegin*stride); if (this->vertexComponentMask & nMesh2::Coord) { int offset = this->GetVertexComponentOffset( nMesh2::Coord ); this->TransformCoordArray( vb, offset, matrix, numVertices, false); } int hasNormal = this->vertexComponentMask & nMesh2::Normal; int hasTan = this->vertexComponentMask & nMesh2::Tangent; int hasBin = this->vertexComponentMask & nMesh2::Binormal; if ( hasNormal || hasTan || hasBin) { matrix44 nor(matrix); nor.invert_simple(); nor.transpose(); if (hasNormal) { int offset = this->GetVertexComponentOffset( nMesh2::Normal ); this->TransformCoordArray( vb, offset, matrix, numVertices, true); } if (hasTan) { int offset = this->GetVertexComponentOffset( nMesh2::Tangent ); this->TransformCoordArray( vb, offset, matrix, numVertices, true); } if (hasBin) { int offset = this->GetVertexComponentOffset( nMesh2::Binormal); this->TransformCoordArray( vb, offset, matrix, numVertices, true); } } return true; } //------------------------------------------------------------------------------ /** */ bool nD3D9Mesh::TransformUv(int layer, float* vb, int idxBegin, int numVertices, const matrix33& matrix) { n_assert(layer < nGfxServer2::MaxTextureStages); uint uvMask[nGfxServer2::MaxTextureStages] = { nMesh2::Uv0, nMesh2::Uv1, nMesh2::Uv2, nMesh2::Uv3 }; n_assert(vb); vb += idxBegin * this->GetVertexWidth(); if (this->vertexComponentMask & uvMask[layer]) { int offset = this->GetVertexComponentOffset( nMesh2::Uv0 ); this->TransformTexCoordArray(vb, offset, matrix, numVertices); } return true; } //------------------------------------------------------------------------------ /** optimize faces to improve the post-tnl cache */ void nD3D9Mesh::OptimizeFaces(ushort* indices, int numFaces, int numVertices) { DWORD* pdwRemap = n_new_array(DWORD, numFaces); D3DXOptimizeFaces(indices, numFaces, numVertices, FALSE, pdwRemap); ushort* dstIndices = n_new_array(ushort, numFaces * 3); n_assert(dstIndices); memcpy(dstIndices, indices, numFaces * 6); // = 3 * sizeof(ushort) for (int i = 0; i < numFaces; ++i) { int newFace = (int) pdwRemap[i]; for (int j = 0; j < 3; ++j) { indices[newFace * 3 + j] = dstIndices[i * 3 + j]; } } n_delete_array(dstIndices); n_delete_array(pdwRemap); } //------------------------------------------------------------------------------ /** optimize vertices to improve the pre-tnl cache */ void nD3D9Mesh::OptimizeVertices(float* vertices, ushort* indices, int numVertices, int numFaces) { DWORD* pdwRemap = n_new_array(DWORD, numVertices); D3DXOptimizeVertices(indices, numFaces, numVertices, FALSE, pdwRemap); // remap vertices float* dstVertices = n_new_array(float, numVertices * this->GetVertexWidth()); n_assert(dstVertices); memcpy(dstVertices, vertices, numVertices * this->GetVertexWidth() * sizeof(float)); for (int i = 0; i < numVertices; ++i) { float* src = dstVertices + (i * this->GetVertexWidth()); float* dst = vertices + (pdwRemap[i] * this->GetVertexWidth()); memcpy(dst, src, this->GetVertexWidth() * sizeof(float)); } // remap triangles for (int faceIndex = 0; faceIndex < numFaces; ++faceIndex) { for (int index = 0; index < 3; ++index) { indices[faceIndex * 3 + index] = (ushort) pdwRemap[indices[faceIndex * 3 + index]]; } } n_delete_array(dstVertices); n_delete_array(pdwRemap); } //------------------------------------------------------------------------------ /** Optimizes the mesh indices and vertices - 27-Nov-06 mateu.batle created */ bool nD3D9Mesh::OptimizeMesh(OptimizationFlag flags, float * vertices, int numVertices, ushort * indices, int numIndices) { n_assert_return(vertices, false); n_assert_return(numVertices > 0, false); n_assert_return(indices, false); n_assert_return(numIndices > 0, false); // optimize faces to improve the post-TnL cache if (flags & nMesh2::Faces) { this->OptimizeFaces(indices, numIndices / 3, numVertices); } // optimize vertices to improve the pre-tnl cache if (flags & nMesh2::Vertices) { this->OptimizeVertices(vertices, indices, numVertices, numIndices / 3); } return true; }
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 644 ] ] ]
6b1e51fa72b7b119c5d957d624706c73ec87425a
faacd0003e0c749daea18398b064e16363ea8340
/3rdparty/phonon/medianode_p.h
069f1702a9e4d9d8ab8aaf458fd098b2133dbcb7
[]
no_license
yjfcool/lyxcar
355f7a4df7e4f19fea733d2cd4fee968ffdf65af
750be6c984de694d7c60b5a515c4eb02c3e8c723
refs/heads/master
2016-09-10T10:18:56.638922
2009-09-29T06:03:19
2009-09-29T06:03:19
42,575,701
0
0
null
null
null
null
UTF-8
C++
false
false
4,532
h
/* This file is part of the KDE project Copyright (C) 2007 Matthias Kretz <[email protected]> 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) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), Trolltech ASA (or its successors, if any) and the KDE Free Qt Foundation, which shall act as a proxy defined in Section 6 of version 3 of the license. 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, see <http://www.gnu.org/licenses/>. */ #ifndef PHONON_MEDIANODE_P_H #define PHONON_MEDIANODE_P_H #include <QtCore/QtGlobal> #include <QtCore/QList> #include <QtCore/QObject> #include "path.h" #include "phonon_export.h" QT_BEGIN_NAMESPACE class QObject; namespace Phonon { class MediaNode; class MediaNodeDestructionHandler; class PHONON_EXPORT MediaNodePrivate { Q_DECLARE_PUBLIC(MediaNode) friend class AudioOutputPrivate; friend class FactoryPrivate; protected: enum CastId { MediaNodePrivateType, AbstractAudioOutputPrivateType, AudioOutputType }; public: /** * Returns the backend object. If the object does not exist it tries to * create it before returning. * * \return the Iface object, might return \c 0 */ QObject *backendObject(); const CastId castId; protected: MediaNodePrivate(CastId _castId = MediaNodePrivateType); virtual ~MediaNodePrivate(); /** * \internal * This method cleanly deletes the Iface object. It is called on * destruction and before a backend change. */ void deleteBackendObject(); virtual bool aboutToDeleteBackendObject() = 0; /** * \internal * Creates the Iface object belonging to this class. For most cases the * implementation is * \code * Q_Q(ClassName); * m_iface = Factory::createClassName(this); * return m_iface; * \endcode * * This function should not be called except from slotCreateIface. * * \see slotCreateIface */ virtual void createBackendObject() = 0; public: /** * \internal * This class has its own destroyed signal since some cleanup calls * need the pointer to the backend object intact. The * QObject::destroyed signals comes after the backend object was * deleted. * * As this class cannot derive from QObject a simple handler * interface is used. */ void addDestructionHandler(MediaNodeDestructionHandler *handler); /** * \internal * This class has its own destroyed signal since some cleanup calls * need the pointer to the backend object intact. The * QObject::destroyed signals comes after the backend object was * deleted. * * As this class cannot derive from QObject a simple handler * interface is used. */ void removeDestructionHandler(MediaNodeDestructionHandler *handler); void addOutputPath(const Path &); void addInputPath(const Path &); void removeOutputPath(const Path &); void removeInputPath(const Path &); const QObject *qObject() const { return const_cast<MediaNodePrivate *>(this)->qObject(); } virtual QObject *qObject() { return 0; } protected: MediaNode *q_ptr; public: QObject *m_backendObject; protected: QList<Path> outputPaths; QList<Path> inputPaths; private: QList<MediaNodeDestructionHandler *> handlers; Q_DISABLE_COPY(MediaNodePrivate) }; } // namespace Phonon QT_END_NAMESPACE #endif // PHONON_MEDIANODE_P_H
[ "futurelink.vl@9e60f810-e830-11dd-9b7c-bbba4c9295f9" ]
[ [ [ 1, 145 ] ] ]
d4732ae8e294202e4c039c0ef3e7c116f3088ee1
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/LOGINSERVER/User.h
fcca64d77931708b54c17807bb8dd0b2410b6be3
[]
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,101
h
#ifndef __USER_H__ #define __USER_H__ #pragma once #include <DPlay.h> #include <map> #include <string> using namespace std; #include "MyMap.h" #include "mempooler.h" #include "ggsrv26.h" #include "dpmng.h" #define AUTH_PERIOD 300 class CUser { public: DPID m_dpid; DWORD m_dwTime; int m_nIndexOfCache; char m_pKey[MAX_ACCOUNT]; DWORD m_idPlayer; DWORD m_tPingRecvd; DWORD m_dwAuthKey; BOOL m_bIllegal; CCSAuth2 m_csa; time_t m_tAuth; int m_nWrite; int m_nRead; BOOL m_bAuth; public: // Constructions CUser( DPID dpid ); virtual ~CUser(); void SetExtra( const char* pKey, DWORD dwAuthKey ); void SetAuth( BOOL bAuth ) { m_bAuth = bAuth; } BOOL GetAuth() { return m_bAuth; } public: #ifndef __VM_0820 #ifndef __MEM_TRACE static MemPooler<CUser>* m_pPool; void* operator new( size_t nSize ) { return CUser::m_pPool->Alloc(); } void* operator new( size_t nSize, LPCSTR lpszFileName, int nLine ) { return CUser::m_pPool->Alloc(); } void operator delete( void* lpMem ) { CUser::m_pPool->Free( (CUser*)lpMem ); } void operator delete( void* lpMem, LPCSTR lpszFileName, int nLine ) { CUser::m_pPool->Free( (CUser*)lpMem ); } #endif // __MEM_TRACE #endif // __VM_0820 }; #ifdef __STL_0402 typedef map<DPID, CUser*> C2User; #else // __STL_0402 typedef CMyMap<CUser*> C2User; typedef CMyBucket<CUser*> CUserBucket; #endif // __STL_0402 class CUserMng { private: C2User m_dpid2User; map<string, CUser*> m_ac2User; u_long m_uCount; public: CMclCritSec m_AddRemoveLock; public: // Constructions CUserMng(); virtual ~CUserMng(); // Operations void Free( void ); BOOL AddUser( DPID dpid, CUser* pUser ); BOOL AddUser( const char* pKey, CUser* pUser ); BOOL RemoveUser( DPID dpid ); CUser* GetUser( const char* pKey ); CUser* GetUser( DPID dpid ); u_long GetCount( void ); void DestroyAbnormalPlayer( void ); void CheckAll(); }; inline u_long CUserMng::GetCount( void ) { CMclAutoLock Lock( m_AddRemoveLock ); return m_uCount; } #endif // __USER_H__
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 96 ] ] ]
d89ddbb1e1825eaf156a8701295d5dc30ef724a1
016774685beb74919bb4245d4d626708228e745e
/lib/Collide/ozcollide/aabbtree_poly.cpp
15ca18faf745381346b8d31276d1165d319a7e68
[]
no_license
sutuglon/Motor
10ec08954d45565675c9b53f642f52f404cb5d4d
16f667b181b1516dc83adc0710f8f5a63b00cc75
refs/heads/master
2020-12-24T16:59:23.348677
2011-12-20T20:44:19
2011-12-20T20:44:19
1,925,770
1
0
null
null
null
null
UTF-8
C++
false
false
19,846
cpp
/* OZCollide - Collision Detection Library Copyright (C) 2006 Igor Kravtchenko 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 Contact the author: [email protected] */ #include <ozcollide/ozcollide.h> #ifndef OZCOLLIDE_PCH #include <ozcollide/aabbtree_poly.h> #include <ozcollide/dataio.h> #include <ozcollide/intr_boxbox.h> #include <ozcollide/intr_spherebox.h> #include <ozcollide/intr_tribox.h> #include <ozcollide/intr_spheretri.h> #include <ozcollide/intr_linebox.h> #include <ozcollide/intr_segmenttri.h> #endif #include "aabbtreepoly_io.cpp" ENTER_NAMESPACE_OZCOLLIDE AABBTreePoly::AABBTreePoly(int _leafDepth) : AABBTree(AABBTREE_LEAFTYPE_POLYGON, _leafDepth) { points_ = NULL; leafs_ = NULL; bufEdges_ = NULL; offBufEdges_ = 0; bufPols_ = NULL; offBufPols_ = 0; } AABBTreePoly::~AABBTreePoly() { SAFE_ARRAYDELETE(points_); SAFE_ARRAYDELETE(leafs_); } void AABBTreePoly::final() { int i, j; for (i = 0; i < nbLeafs_; i++) { AABBTreePolygonLeaf *leaf = &leafs_[i]; for (j = 0; j < leaf->nbPolys; j++) { Polygon &pol = (Polygon&) leaf->polys[j]; int rel1 = pol.getIndex(0); int rel2 = pol.getIndex(1); int rel3 = pol.getIndex(pol.getNbIndices() - 1); Vec3f vec1 = points_[rel2] - points_[rel1]; Vec3f vec2 = points_[rel3] - points_[rel1]; Vec3f normal = vec1 | vec2; normal.normalize(); pol.setNormal(normal); } } } int AABBTreePoly::getNbPoints() const { return nbPoints_; } const Vec3f* AABBTreePoly::getPointsList() const { return points_; } int AABBTreePoly::getMemoryConsumption() const { int size = 0; size += getNbNodes() * sizeof(AABBTreeNode); size += getNbLeafs() * sizeof(AABBTreePolygonLeaf); int t = sizeof *points_; size += nbPoints_ * t; size += sizeof *this; return size; } // BOX bool AABBTreePoly::isCollideWithBox(const Box &_box) { nbColls_ = 0; box_ = _box; boxColRes_ = NULL; return isCollideWithBox(*root_); } bool AABBTreePoly::isCollideWithBox(const Box &_box, BoxColResult &_cr) { if (bUseTemporalCoherence_ && _cr.polys_.size() != 0) { bool res = testIntersectionTriBox(*_cr.polys_[0], points_, _box); if (res == true) { nbColls_ = 1; return true; } } nbColls_ = 0; box_ = _box; boxColRes_ = &_cr; boxColRes_->boxQuery_ = _box; boxColRes_->polys_.resize(0); return isCollideWithBox(*root_); } void AABBTreePoly::collideWithBox(const Box &_box, BoxColResult &_cr) { if (bUseTemporalCoherence_ == true) { if (_box.isInside(_cr.boxQuery_)) { nbColls_ = _cr.polys_.size(); return; } // Too bad, will do normal query with an inflated volume box_ = _box; box_.extent *= coefVolInflater_; } else { box_ = _box; } _cr.boxQuery_ = box_; callback_ = NULL; boxColRes_ = &_cr; _cr.polys_.resize(0); nbColls_ = 0; collideWithBox(*root_); } void AABBTreePoly::collideWithBox(const Box &_box, AABBCDPoly_callback *_callback, void *_userCallback) { if (!_callback) return; callback_ = _callback; userCallback_ = _userCallback; boxColRes_ = NULL; nbColls_ = 0; box_ = _box; collideWithBox(*root_); } // OBB bool AABBTreePoly::isCollideWithOBB(const OBB &_obb) { nbColls_ = 0; obb_ = _obb; obbColRes_ = NULL; return isCollideWithOBB(*root_); } bool AABBTreePoly::isCollideWithOBB(const OBB &_obb, OBBColResult &_cr) { /* if (bUseTemporalCoherence_ && cr.polys_.size() != 0) { ozbool res = testIntersectionTriBox(*cr.polys_[0], points_, box); if (res == OZTRUE) { nbColls_ = 1; return OZTRUE; } } */ nbColls_ = 0; obb_ = _obb; obbColRes_ = &_cr; obbColRes_->obbQuery_ = _obb; obbColRes_->polys_.resize(0); return isCollideWithOBB(*root_); } void AABBTreePoly::collideWithOBB(const OBB &_obb, OBBColResult &_cr) { /* if (bUseTemporalCoherence_ == OZTRUE) { if (box.isInside(cr.boxQuery_)) { nbColls_ = cr.polys_.size(); return; } // Too bad, will do normal query with an inflated volume box_ = box; box_.extent *= coefVolInflater_; } else { */ obb_ = _obb; // } _cr.obbQuery_ = obb_; callback_ = NULL; obbColRes_ = &_cr; _cr.polys_.resize(0); nbColls_ = 0; collideWithOBB(*root_); } void AABBTreePoly::collideWithOBB(const OBB &_obb, AABBCDPoly_callback *_callback, void *_userCallback) { if (!_callback) return; callback_ = _callback; userCallback_ = _userCallback; obbColRes_ = NULL; nbColls_ = 0; obb_ = _obb; collideWithBox(*root_); } // SPHERE bool AABBTreePoly::isCollideWithSphere(const Sphere &_sphere) { sphereColRes_ = NULL; nbColls_ = 0; sphere_ = _sphere; return isCollideWithSphere(*root_); } void AABBTreePoly::collideWithSphere(const Sphere &_sphere, AABBCDPoly_callback *_callback, void *_userCallback) { if (!_callback) return; sphereColRes_ = NULL; callback_ = _callback; userCallback_ = _userCallback; nbColls_ = 0; sphere_ = _sphere; collideWithSphere(*root_); } void AABBTreePoly::collideWithSphere(const Sphere &_sphere, SphereColResult &_cr) { if (bUseTemporalCoherence_ == true) { if (_sphere.isCollide(_cr.sphereQuery_)) { nbColls_ = _cr.polys_.size(); return; } // Too bad, will do normal query with an inflated volume sphere_ = _sphere; sphere_.radius *= coefVolInflater_; } else { sphere_ = _sphere; } _cr.sphereQuery_ = sphere_; callback_ = NULL; sphereColRes_ = &_cr; _cr.polys_.resize(0); nbColls_ = 0; collideWithSphere(*root_); } // ELLIPSOID bool AABBTreePoly::isCollideWithEllipsoid(const Ellipsoid &_ellip) { ellipColRes_ = NULL; nbColls_ = 0; ellip_ = _ellip; return isCollideWithEllipsoid(*root_); } void AABBTreePoly::collideWithEllipsoid(const Ellipsoid &_ellip, AABBCDPoly_callback *_callback, void *_userCallback) { if (!_callback) return; ellipColRes_ = NULL; callback_ = _callback; userCallback_ = _userCallback; nbColls_ = 0; ellip_ = _ellip; collideWithEllipsoid(*root_); } void AABBTreePoly::collideWithEllipsoid(const Ellipsoid &_ellip, EllipsoidColResult &_cr) { // if (bUseTemporalCoherence_ == OZTRUE) { // if (sphere.isCollide(cr.sphereQuery_)) { // nbColls_ = cr.polys_.size(); // return; // } // Too bad, will do normal query with an inflated volume // sphere_ = sphere; // sphere_.radius *= coefVolInflater_; // } // else { ellip_ = _ellip; // sphere_.center = ellip.pos; // sphere_.radius = ellip.radii.x; // } // invRadii_.x = 1.0f / ellip.radii.x; // invRadii_.y = 1.0f / ellip.radii.y; // invRadii_.z = 1.0f / ellip.radii.z; _cr.ellipsoidQuery_ = ellip_; callback_ = NULL; ellipColRes_ = &_cr; _cr.polys_.resize(0); nbColls_ = 0; collideWithEllipsoid(*root_); } // SEGMENT bool AABBTreePoly::isCollideWithSegment(const Vec3f &_seg_pt0, const Vec3f &_seg_pt1) { nbColls_ = 0; seg_pt0_ = _seg_pt0; seg_pt1_ = _seg_pt1; segmentColRes_ = NULL; return isCollideWithSegment(*root_); } bool AABBTreePoly::isCollideWithSegment(const Vec3f &_seg_pt0, const Vec3f &_seg_pt1, SegmentColResult &_cr) { nbColls_ = 0; seg_pt0_ = _seg_pt0; seg_pt1_ = _seg_pt1; segmentColRes_ = &_cr; segmentColRes_->segmentPt0_ = _seg_pt0; segmentColRes_->segmentPt1_ = _seg_pt1; segmentColRes_->polys_.resize(0); return isCollideWithSegment(*root_); } void AABBTreePoly::collideWithSegment(const Vec3f &seg_pt0, const Vec3f &seg_pt1, AABBCDPoly_callback *callback, void *userCallback) { if (!callback) return; segmentColRes_ = NULL; callback_ = callback; userCallback_ = userCallback; nbColls_ = 0; seg_pt0_ = seg_pt0; seg_pt1_ = seg_pt1; collideWithSegment(*root_); } void AABBTreePoly::collideWithSegment(const Vec3f &seg_pt0, const Vec3f &seg_pt1, SegmentColResult &cr) { cr.segmentPt0_ = seg_pt0; cr.segmentPt1_ = seg_pt1; seg_pt0_ = seg_pt0; seg_pt1_ = seg_pt1; callback_ = NULL; segmentColRes_ = &cr; cr.polys_.resize(0); nbColls_ = 0; collideWithSegment(*root_); } // int AABBTreePoly::getNbCollidedPrimitives() const { return nbColls_; } // // // BOX bool AABBTreePoly::isCollideWithBox(const AABBTreeNode &_node) { if (_node.aabb.isOverlap(box_) == true) { if (!_node.left && !_node.right) { // reach a leaf const AABBTreePolygonLeaf &pl = (AABBTreePolygonLeaf&) _node; int nbPols = pl.nbPolys; for (int i = 0; i < nbPols; i++) { const Polygon *pol = &pl.polys[i]; bool res = testIntersectionTriBox(*pol, points_, box_); if (res) { nbColls_++; if (boxColRes_) { int user = 0; if (pl.users) user = pl.users[i]; boxColRes_->polys_.add( pol ); boxColRes_->users_.add( user ); } return res; } } } else { if (_node.left) { if (isCollideWithBox(*_node.left) == true) return true; } if (_node.right) { if (isCollideWithBox(*_node.right) == true) return true; } } } return false; } void AABBTreePoly::collideWithBox(const AABBTreeNode &_node) { if (_node.aabb.isOverlap(box_) == true) { if (!_node.left && !_node.right) { // reach a leaf const AABBTreePolygonLeaf &pl = (AABBTreePolygonLeaf&) _node; int nbPols = pl.nbPolys; for (int i = 0; i < nbPols; i++) { const Polygon *pol = &pl.polys[i]; int user = 0; if (pl.users) user = pl.users[i]; bool res = testIntersectionTriBox(*pol, points_, box_); if (res == true) { nbColls_++; if (callback_) callback_(*this, *pol, user, _node.aabb, userCallback_); else { boxColRes_->polys_.add(pol); boxColRes_->users_.add(user); } } } } else { if (_node.left) collideWithBox(*_node.left); if (_node.right) collideWithBox(*_node.right); } } } // // // OBB bool AABBTreePoly::isCollideWithOBB(const AABBTreeNode &_node) { if (testIntersectionAABB_OBB(_node.aabb, obb_) == true) { if (!_node.left && !_node.right) { // reach a leaf const AABBTreePolygonLeaf &pl = (AABBTreePolygonLeaf&) _node; int nbPols = pl.nbPolys; for (int i = 0; i < nbPols; i++) { const Polygon *pol = &pl.polys[i]; bool res = testIntersectionTriOBB(*pol, points_, obb_); if (res) { nbColls_++; if (obbColRes_) { int user = 0; if (pl.users) user = pl.users[i]; obbColRes_->polys_.add( pol ); obbColRes_->users_.add( user ); } return res; } } } else { if (_node.left) { if (isCollideWithOBB(*_node.left) == true) return true; } if (_node.right) { if (isCollideWithOBB(*_node.right) == true) return true; } } } return false; } void AABBTreePoly::collideWithOBB(const AABBTreeNode &_node) { if (testIntersectionAABB_OBB(_node.aabb, obb_) == true) { if (!_node.left && !_node.right) { // reach a leaf const AABBTreePolygonLeaf &pl = (AABBTreePolygonLeaf&) _node; int nbPols = pl.nbPolys; for (int i = 0; i < nbPols; i++) { const Polygon *pol = &pl.polys[i]; int user = 0; if (user) user = pl.users[i]; bool res = testIntersectionTriOBB(*pol, points_, obb_); if (res == true) { nbColls_++; if (callback_) callback_(*this, *pol, user, _node.aabb, userCallback_); else { obbColRes_->polys_.add(pol); obbColRes_->users_.add(user); } } } } else { if (_node.left) collideWithOBB(*_node.left); if (_node.right) collideWithOBB(*_node.right); } } } // SPHERE bool AABBTreePoly::isCollideWithSphere(const AABBTreeNode &_node) { if (testIntersectionSphereBox(sphere_, _node.aabb) == true) { if (!_node.left && !_node.right) { // reach a leaf const AABBTreePolygonLeaf &pl = (AABBTreePolygonLeaf&) _node; int nbPols = pl.nbPolys; for (int i = 0; i < nbPols; i++) { const Polygon *pol = &pl.polys[i]; int i0 = pol->getIndex(0); int i1 = pol->getIndex(1); int i2 = pol->getIndex(2); bool res = magic_testIntersectionSphereTriangle(sphere_.center, sphere_.radius, points_[i0], points_[i1], points_[i2]); if (res) { if (sphereColRes_) { int user = 0; if (pl.users) user = pl.users[i]; sphereColRes_->polys_.add( pol ); sphereColRes_->users_.add( user ); } nbColls_++; return res; } } } else { if (_node.left) { if (isCollideWithSphere(*_node.left) == true) return true; } if (_node.right) { if (isCollideWithSphere(*_node.right) == true) return true; } } } return false; } void AABBTreePoly::collideWithSphere(const AABBTreeNode &_node) { if (testIntersectionSphereBox(sphere_, _node.aabb) == true) { if (!_node.left && !_node.right) { // reach a leaf const AABBTreePolygonLeaf &pl = (AABBTreePolygonLeaf&) _node; int nbPols = pl.nbPolys; for (int i = 0; i < nbPols; i++) { const Polygon *pol = &pl.polys[i]; int user = 0; if (user) user = pl.users[i]; int i0 = pol->getIndex(0); int i1 = pol->getIndex(1); int i2 = pol->getIndex(2); bool res = magic_testIntersectionSphereTriangle( sphere_.center, sphere_.radius, points_[i0], points_[i1], points_[i2]); if (res) { nbColls_++; if (callback_) callback_(*this, *pol, user, _node.aabb, userCallback_); else { sphereColRes_->polys_.add(pol); sphereColRes_->users_.add(user); } } } } else { if (_node.left) collideWithSphere(*_node.left); if (_node.right) collideWithSphere(*_node.right); } } } // ELLIPSOID bool AABBTreePoly::isCollideWithEllipsoid(const AABBTreeNode &_node) { if (testIntersectionEllipsoidBox(ellip_, _node.aabb) == true) { if (!_node.left && !_node.right) { // reach a leaf const AABBTreePolygonLeaf &pl = (AABBTreePolygonLeaf&) _node; int nbPols = pl.nbPolys; for (int i = 0; i < nbPols; i++) { const Polygon *pol = &pl.polys[i]; int i0 = pol->getIndex(0); int i1 = pol->getIndex(1); int i2 = pol->getIndex(2); Vec3f pt1 = points_[i0] * ellip_.getInvRadii(); Vec3f pt2 = points_[i1] * ellip_.getInvRadii(); Vec3f pt3 = points_[i2] * ellip_.getInvRadii(); Vec3f center = ellip_.getCenter() * ellip_.getInvRadii(); bool res = magic_testIntersectionSphereTriangle(center, 1, pt1, pt2, pt3); if (res) { if (ellipColRes_) { int user = 0; if (pl.users) user = pl.users[i]; ellipColRes_->polys_.add( pol ); ellipColRes_->users_.add( user ); } nbColls_++; return res; } } } else { if (_node.left) { if (isCollideWithEllipsoid(*_node.left) == true) return true; } if (_node.right) { if (isCollideWithEllipsoid(*_node.right) == true) return true; } } } return false; } void AABBTreePoly::collideWithEllipsoid(const AABBTreeNode &_node) { if (testIntersectionEllipsoidBox(ellip_, _node.aabb) == true) { if (!_node.left && !_node.right) { // reach a leaf const AABBTreePolygonLeaf &pl = (AABBTreePolygonLeaf&) _node; int nbPols = pl.nbPolys; for (int i = 0; i < nbPols; i++) { const Polygon *pol = &pl.polys[i]; int user = 0; if (user) user = pl.users[i]; int i0 = pol->getIndex(0); int i1 = pol->getIndex(1); int i2 = pol->getIndex(2); Vec3f pt1 = points_[i0] * ellip_.getInvRadii(); Vec3f pt2 = points_[i1] * ellip_.getInvRadii(); Vec3f pt3 = points_[i2] * ellip_.getInvRadii(); Vec3f center = ellip_.getCenter() * ellip_.getInvRadii(); bool res = magic_testIntersectionSphereTriangle(center, 1, pt1, pt2, pt3); if (res) { nbColls_++; if (callback_) callback_(*this, *pol, user, _node.aabb, userCallback_); else { ellipColRes_->polys_.add( pol ); ellipColRes_->users_.add( user ); } } } } else { if (_node.left) collideWithEllipsoid(*_node.left); if (_node.right) collideWithEllipsoid(*_node.right); } } } // SEGMENT bool AABBTreePoly::isCollideWithSegment(const AABBTreeNode &_node) { if (testIntersectionSegmentBox(seg_pt0_, seg_pt1_, _node.aabb) == true) { if (!_node.left && !_node.right) { // reach a leaf const AABBTreePolygonLeaf &pl = (AABBTreePolygonLeaf&) _node; int nbPols = pl.nbPolys; for (int i = 0; i < nbPols; i++) { const Polygon *pol = &pl.polys[i]; int i0 = pol->getIndex(0); int i1 = pol->getIndex(1); int i2 = pol->getIndex(2); bool res = testIntersectionSegmentTri(seg_pt0_, seg_pt1_, points_[i0], points_[i1], points_[i2]); if (res) { nbColls_++; if (segmentColRes_) { int user = 0; if (pl.users) user = pl.users[i]; segmentColRes_->polys_.add( pol ); segmentColRes_->users_.add( user ); } return res; } } } else { if (_node.left) { if (isCollideWithSegment(*_node.left) == true) return true; } if (_node.right) { if (isCollideWithSegment(*_node.right) == true) return true; } } } return false; } void AABBTreePoly::collideWithSegment(const AABBTreeNode &_node) { if (testIntersectionSegmentBox(seg_pt0_, seg_pt1_, _node.aabb) == true) { if (!_node.left && !_node.right) { // reach a leaf const AABBTreePolygonLeaf &pl = (AABBTreePolygonLeaf&) _node; int nbPols = pl.nbPolys; for (int i = 0; i < nbPols; i++) { const Polygon *pol = &pl.polys[i]; int user = 0; if (pl.users) user = pl.users[i]; int i0 = pol->getIndex(0); int i1 = pol->getIndex(1); int i2 = pol->getIndex(2); bool res = testIntersectionSegmentTri(seg_pt0_, seg_pt1_, points_[i0], points_[i1], points_[i2]); if (res) { nbColls_++; if (callback_) callback_(*this, *pol, user, _node.aabb, userCallback_); else { segmentColRes_->polys_.add(pol); segmentColRes_->users_.add(user); } } } } else { if (_node.left) collideWithSegment(*_node.left); if (_node.right) collideWithSegment(*_node.right); } } } // void AABBTreePoly::scale(float _scale) { int i; int nbPoints = nbPoints_; for (i = 0; i < nbPoints; i++) points_[i] *= _scale; for (i = 0; i < nbNodes_; i++) { AABBTreeNode *node = &root_[i]; node->aabb.center *= _scale; node->aabb.extent *= _scale; } for (i = 0; i < nbLeafs_; i++) { AABBTreePolygonLeaf *leaf = &leafs_[i]; leaf->aabb.center *= _scale; leaf->aabb.extent *= _scale; } } LEAVE_NAMESPACE
[ [ [ 1, 841 ] ] ]
c556ff30c3f089e21ba53d831de7098d878618bf
0bfae28f3c10720e1451b78abbe3105108d1c073
/src/MathLib/Vector.h
e146eb78713476b517075031e8ff43f43872e723
[]
no_license
bloom1123/SEDSros
aae5ada7c8c6658b95418cc7d9f93eb1ebd37461
11b726dc376f58cd5b59f62d7b561962fd56cfb4
refs/heads/master
2021-12-02T08:47:33.660287
2011-11-11T17:12:04
2011-11-11T17:12:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
29,710
h
/* * Copyright (C) 2010 Learning Algorithms and Systems Laboratory, EPFL, Switzerland * Author: Eric Sauser * email: [email protected] * website: lasa.epfl.ch * * Permission is granted to copy, distribute, and/or modify this program * under the terms of the GNU General Public License, version 2 or any * later version published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General * Public License for more details */ #ifndef VECTOR_H #define VECTOR_H #include "MathLibCommon.h" #include "Macros.h" #include <assert.h> #include <math.h> #include <iostream> #include <vector> using namespace std; #ifndef NULL #define NULL 0 #endif #ifdef USE_MATHLIB_NAMESPACE namespace MathLib { #endif #ifdef USE_T_EXTENSIONS template<unsigned int ROW> class TVector; #endif typedef vector<unsigned int> IndicesVector; /** * \defgroup MathLib MathLib * * \brief A mathematical library for doing various things such as * matrix manipulation */ /** * \class Vector * * \ingroup MathLib * * \brief The basic vector class * * This vector class can be used for doing various vector manipulation. * This should be combined with the Matrix class for doing almost anything * you ever dreamt of. */ class Matrix; class Vector { friend class Matrix; #ifdef USE_T_EXTENSIONS template<unsigned int ROW> friend class TVector; #endif protected: static REALTYPE undef; ///< The default value returned when a vector out-of-bound is reached unsigned int row; ///< The size of the vector REALTYPE *_; ///< The data array. public: /// Create an empty vector inline Vector() { row = 0; _ = NULL; } /// The destructor inline virtual ~Vector(){ Release(); } /// The copy constructor inline Vector(const Vector &vector){ row = 0; _ = NULL; Set(vector); } /** * \brief Create a sized vector * \param size The size * \param clear Tell if the vector sould be set to 0 */ inline Vector(unsigned int size, bool clear = true){ row = 0; _ = NULL; Resize(size,false); if(clear) Zero(); } /** * \brief Create a vector by copying a memory area * \param array The array of REALTYPE to be copied * \param size The size */ inline Vector(const REALTYPE *array, unsigned int size){ row = 0; _ = NULL; Set(array,size); } #ifdef USE_T_EXTENSIONS /// Copy Contructor of a template Vector (see TVector) template<unsigned int ROW> inline Vector(const TVector<ROW> &vector){ row = 0; _ = NULL; Set(vector._,ROW); } #endif /// An assignment function inline Vector& Set(const Vector &vector){ Resize(vector.row,false); memcpy(_,vector._,row*sizeof(REALTYPE)); return *this; } /// An assignment function inline Vector& Set(const REALTYPE * array, unsigned int size){ Resize(size,false); if((row)&&(array)) memcpy(_,array,size*sizeof(REALTYPE)); return *this; } /// Set all values to 0 inline Vector& Zero(){ if(row) memset(_,0,row*sizeof(REALTYPE)); return *this; } /// Set all values to 1 inline Vector& One(){ REALTYPE *src = _; unsigned int len = row; while(len--) *(src++) = R_ONE; return *this; } /// Set random values uniformly distributed between 0 and 1 inline Vector& Random(){ REALTYPE *src = _; unsigned int len = row; while(len--){ *(src++) = RND(R_ONE); } return *this; } /// Get the size of the vector inline unsigned int Size() const{ return row; } /// Get the data pointer inline REALTYPE *Array() const{ return _; } /** * \brief Get the reference to a vector value * \param row The row number (starting from 0) * \return The corresponding value */ inline REALTYPE& operator[] (const unsigned int row){ if(row<this->row) return _[row]; return undef; } inline REALTYPE& operator() (const unsigned int row){ if(row<this->row) return _[row]; return undef; } inline REALTYPE& Ref(const unsigned int row){ if(row<this->row) return _[row]; return undef; } inline REALTYPE& RefNoCheck(const unsigned int row){ return _[row]; } /** * \brief Get a vector value * \param row The row number (starting from 0) * \return The corresponding value */ inline REALTYPE At(const unsigned int row) const { if(row<this->row) return _[row]; return undef; } inline REALTYPE AtNoCheck(const unsigned int row) const { return _[row]; } inline Vector& operator = (const Vector &vector){ return Set(vector); } inline Vector& operator = (const REALTYPE val){ REALTYPE *src = _; unsigned int len = row; while(len--) *(src++) = val; return *this; } /** * \brief The - operator * \return A new vector */ inline Vector operator - () const{ Vector result; REALTYPE *src = _; REALTYPE *dst = result._; unsigned int len = row; while(len--) *(dst++) = -(*(src++)); return result; } inline Vector& SMinus() { REALTYPE *src = _; unsigned int len = row; while(len--){ *(src) = -(*(src)); src++; } return *this; } inline Vector& operator += (const Vector &vector){ REALTYPE *src = _; REALTYPE *dst = vector._; unsigned int len = (row<=vector.row?row:vector.row); while(len--) *(src++) += *(dst++); return *this; } inline Vector& operator -= (const Vector &vector){ REALTYPE *src = _; REALTYPE *dst = vector._; unsigned int len = (row<=vector.row?row:vector.row); while(len--) *(src++) -= *(dst++); return *this; } /// Element-wise multiplication inline Vector& operator ^= (const Vector &vector){ REALTYPE *src = _; REALTYPE *dst = vector._; unsigned int len = (row<=vector.row?row:vector.row); while(len--) *(src++) *= *(dst++); return *this; } /// Element-wise division inline Vector& operator /= (const Vector &vector){ REALTYPE *src = _; REALTYPE *dst = vector._; unsigned int len = (row<=vector.row?row:vector.row); while(len--) *(src++) /= *(dst++); return *this; } inline Vector& operator += (REALTYPE scalar){ REALTYPE *src = _; unsigned int len = row; while(len--) *(src++) += scalar; return *this; } inline Vector& operator -= (REALTYPE scalar){ REALTYPE *src = _; unsigned int len = row; while(len--) *(src++) -= scalar; return *this; } inline Vector& operator *= (REALTYPE scalar){ REALTYPE *src = _; unsigned int len = row; while(len--) *(src++) *= scalar; return *this; } inline Vector& operator /= (REALTYPE scalar){ scalar = R_ONE / scalar; REALTYPE *src = _; unsigned int len = row; while(len--) *(src++) *= scalar; return *this; } inline Vector operator + (const Vector &vector) const{ Vector result; return Add(vector,result); } inline Vector operator - (const Vector &vector) const{ Vector result; return Sub(vector,result); } /// Element-wise multiplication inline Vector operator ^ (const Vector &vector) const{ Vector result; return PMult(vector,result); } /// Element-wise division inline Vector operator / (const Vector &vector) const{ Vector result; return PDiv(vector,result); } inline REALTYPE operator * (const Vector &vector) const{ return Dot(vector); } inline Vector operator + (REALTYPE scalar) const{ Vector result; return Add(scalar,result); } inline Vector operator - (REALTYPE scalar) const{ Vector result; return Sub(scalar,result); } inline Vector operator * (REALTYPE scalar) const{ Vector result; return Mult(scalar,result); } inline Vector operator / (REALTYPE scalar) const{ Vector result; return Div(scalar,result); } inline bool operator == (const Vector& vector) const{ if(row!=vector.row) return false; REALTYPE *src = _; REALTYPE *dst = vector._; unsigned int len = row; while(len--) if(*(src++) != *(dst++)) return false; return true; } inline bool operator != (const Vector& vector) const{ return !(*this == vector); } inline Vector& ScaleAddTo(REALTYPE scale, Vector &result) const { REALTYPE *src = _; REALTYPE *dst = result._; unsigned int len = (row<=result.row?row:result.row); while(len--) *(dst++) += *(src++) * scale; return result; } /** * \brief Sum two vector in a faster way than using the + operator * \param vector The second vector to be summed up * \param result The result * \return The result vector */ inline Vector& Add(const Vector &vector, Vector& result) const{ result.Resize(row,false); REALTYPE *src0 = _; REALTYPE *src = vector._; REALTYPE *dst = result._; if(row<=vector.row){ unsigned int len = row; while(len--) *(dst++) = *(src0++) + *(src++); }else{ unsigned int len = vector.row; while(len--) *(dst++) = *(src0++) + *(src++); len = row - vector.row; while(len--) *(dst++) = *(src0++); } return result; } /** * \brief Substract two vector in a faster way than using the + operator * \param vector The substracting vector * \param result The result * \return The result vector */ inline Vector& Sub(const Vector &vector, Vector& result) const{ result.Resize(row,false); REALTYPE *src0 = _; REALTYPE *src = vector._; REALTYPE *dst = result._; if(row<=vector.row){ unsigned int len = row; while(len--) *(dst++) = *(src0++) - *(src++); }else{ unsigned int len = vector.row; while(len--) *(dst++) = *(src0++) - *(src++); len = row - vector.row; while(len--) *(dst++) = *(src0++); } return result; } /// Element-wise multiplication inline Vector& PMult(const Vector &vector, Vector& result) const{ result.Resize(row,false); REALTYPE *src0 = _; REALTYPE *src = vector._; REALTYPE *dst = result._; if(row<=vector.row){ unsigned int len = row; while(len--) *(dst++) = *(src0++) * *(src++); }else{ unsigned int len = vector.row; while(len--) *(dst++) = *(src0++) * *(src++); len = row - vector.row; while(len--) *(dst++) = *(src0++); } return result; } /// Element-wise division inline Vector& PDiv(const Vector &vector, Vector& result) const{ result.Resize(row,false); REALTYPE *src0 = _; REALTYPE *src = vector._; REALTYPE *dst = result._; if(row<=vector.row){ unsigned int len = row; while(len--) *(dst++) = *(src0++) / *(src++); }else{ unsigned int len = vector.row; while(len--) *(dst++) = *(src0++) / *(src++); len = row - vector.row; while(len--) *(dst++) = *(src0++); } return result; } /// Scalar summation inline Vector& Add(REALTYPE scalar, Vector& result) const{ result.Resize(row,false); REALTYPE *src = _; REALTYPE *dst = result._; unsigned int len = row; while(len--) *(dst++) = *(src++) + scalar; return result; } /// Scalar substraction inline Vector& Sub(REALTYPE scalar, Vector& result) const{ result.Resize(row,false); REALTYPE *src = _; REALTYPE *dst = result._; unsigned int len = row; while(len--) *(dst++) = *(src++) - scalar; return result; } /// Scalar multiplication inline Vector& Mult(REALTYPE scalar, Vector& result) const{ result.Resize(row,false); REALTYPE *src = _; REALTYPE *dst = result._; unsigned int len = row; while(len--) *(dst++) = *(src++) * scalar; return result; } /// Scalar division inline Vector& Div(REALTYPE scalar, Vector& result) const{ scalar = R_ONE/scalar; result.Resize(row,false); REALTYPE *src = _; REALTYPE *dst = result._; unsigned int len = row; while(len--) *(dst++) = *(src++) * scalar; return result; } Matrix& MultTranspose(const Vector & vec, Matrix& result); Matrix MultTranspose(const Vector & vec); /// Sum up all elements of the vector inline REALTYPE Sum() const { REALTYPE result = R_ZERO; REALTYPE *src = _; unsigned int len = row; while(len--) result += *(src++); return result; } /// The norm of the vector inline REALTYPE Norm() const { #ifdef MATHLIB_USE_DOUBLE_AS_REAL return sqrt(Norm2()); #else return sqrtf(Norm2()); #endif } /// The squared norm of the vector inline REALTYPE Norm2() const { REALTYPE result = R_ZERO; REALTYPE *src = _; unsigned int len = row; while(len--){ result += *(src) * (*(src)); src++; } return result; } /// Normalize the vector to 1 inline void Normalize(){ REALTYPE norm = Norm(); if(norm>EPSILON){ REALTYPE scalar = R_ONE / Norm(); (*this) *= scalar; }else{ Zero(); } } /// The distance between two vectors inline REALTYPE Distance(const Vector &vector) const{ return (*this-vector).Norm(); } /// The squared distance between two vectors inline REALTYPE Distance2(const Vector &vector) const{ return (*this-vector).Norm2(); } /// The dot product with another vector inline REALTYPE Dot(const Vector &vector) const{ unsigned int k = (row<=vector.row?row:vector.row); REALTYPE result = R_ZERO; REALTYPE *src = _; REALTYPE *dst = vector._; while(k--) result += (*(src++)) * (*(dst++)); return result; } /// The maximum value of the vector inline REALTYPE Max(unsigned int *index=NULL){ if(row==0){ if(index) *index = 0; return R_ZERO; } REALTYPE *src =_; REALTYPE res =*(src++); if(index){ *index = 0; for(unsigned int i=1;i<row;i++){ if(*src>res){ res = *src; *index = i; } src++; } }else{ for(unsigned int i=1;i<row;i++){ if(*src>res) res = *src; src++; } } return res; } /// The minimum value of the vector inline REALTYPE Min(unsigned int *index=NULL){ if(row==0){ if(index) *index = 0; return R_ZERO; } REALTYPE *src =_; REALTYPE res =*(src++); if(index){ *index = 0; for(unsigned int i=1;i<row;i++){ if(*src<res){ res = *src; *index = i; } src++; } }else{ for(unsigned int i=1;i<row;i++){ if(*src<res) res = *src; src++; } } return res; } /// The index of the maximum value of the vector inline int MaxId(){ unsigned int res; Max(&res); return res; } /// The index of the minimum value of the vector inline int MinId(){ unsigned int res; Min(&res); return res; } /// The maximum value of two vector inline Vector& Max(const Vector& v0,const Vector& v1){ const unsigned int kmin = (v0.row<v1.row?v0.row:v1.row); const unsigned int kmax = (v0.row<v1.row?v1.row:v0.row); Resize(kmax,false); for(unsigned int i=0;i<kmin;i++){ _[i] = (v0._[i]>v1._[i]?v0._[i]:v1._[i]); } if(kmin<kmax){ if(v0.row<v1.row){ for(unsigned int i=kmin;i<kmax;i++){ _[i] = v1._[i]; } }else{ for(unsigned int i=kmin;i<kmax;i++){ _[i] = v0._[i]; } } } return *this; } /// The minimum value of two vector inline Vector& Min(const Vector& v0,const Vector& v1){ const unsigned int kmin = (v0.row<v1.row?v0.row:v1.row); const unsigned int kmax = (v0.row<v1.row?v1.row:v0.row); Resize(kmax,false); for(unsigned int i=0;i<kmin;i++){ _[i] = (v0._[i]<v1._[i]?v0._[i]:v1._[i]); } if(kmin<kmax){ if(v0.row<v1.row){ for(unsigned int i=kmin;i<kmax;i++){ _[i] = v1._[i]; } }else{ for(unsigned int i=kmin;i<kmax;i++){ _[i] = v0._[i]; } } } return *this; } /// Return the absolute value of the vector inline Vector Abs(){ Vector result; return Abs(result); } /// Set the result to the absolute value of the vector inline Vector& Abs(Vector &result) const{ result.Resize(row,false); REALTYPE *src = _; REALTYPE *dst = result._; unsigned int len = row; while(len--) *(dst++) = fabs(*(src++)); return result; } /// Absolute value of the vector inline Vector& SAbs() { REALTYPE *src = _; unsigned int len = row; while(len--){ *src = fabs(*src); src++; } return *this; } inline Vector& Sort(IndicesVector * indices=NULL){ if(indices){ indices->resize(row); for(unsigned int i=0;i<row;i++) indices->at(i)=i; } REALTYPE cmax; unsigned int maxId; for(unsigned int i=0;i<row-1;i++){ cmax = _[i]; maxId = i; for(unsigned int j=i+1;j<row;j++){ if(cmax<_[j]){ cmax = _[j]; maxId = j; } } if(maxId!=i){ REALTYPE tmp = _[i]; _[i] = _[maxId]; _[maxId] = tmp; if(indices){ unsigned int idx = indices->at(i); indices->at(i) = indices->at(maxId); indices->at(maxId) = idx; } } } return *this; } inline Vector& AbsSort(IndicesVector * indices=NULL){ if(indices){ indices->resize(row); for(unsigned int i=0;i<row;i++) indices->at(i)=i; } REALTYPE cmax; unsigned int maxId; for(unsigned int i=0;i<row-1;i++){ cmax = fabs(_[i]); maxId = i; for(unsigned int j=i+1;j<row;j++){ if(cmax<fabs(_[j])){ cmax = fabs(_[j]); maxId = j; } } if(maxId!=i){ REALTYPE tmp = _[i]; _[i] = _[maxId]; _[maxId] = tmp; if(indices){ unsigned int idx = indices->at(i); indices->at(i) = indices->at(maxId); indices->at(maxId) = idx; } } } return *this; } /** * \brief Set the value of another vector into the current vector * \param startPos The index starting from which the data of the passed vector will be copied * \param vector The input vector */ inline Vector& SetSubVector(unsigned int startPos, const Vector &vector) { if(startPos<row){ const unsigned int k = (row-startPos<=vector.row?row-startPos:vector.row); for (unsigned int i = 0; i < k; i++){ _[startPos+i] = vector._[i]; } } return *this; } /** * \brief Get a vector containing some of the vector values * \param startPos The starting index * \param len The length of data to be copied */ inline Vector GetSubVector(unsigned int startPos, unsigned int len) const { Vector result(len,false); return GetSubVector(startPos,len,result); } /** * \brief Get a vector containing some of the vector values * \param startPos The starting index * \param len The length of data to be copied * \param result The output vector */ inline Vector& GetSubVector(unsigned int startPos, unsigned int len, Vector &result) const { result.Resize(len,false); if(startPos<row){ const unsigned int k = (row-startPos<=len?row-startPos:len); for (unsigned int i = 0; i < k; i++){ result[i] = _[startPos+i]; } for (unsigned int i = k; i < len; i++){ result[i] = R_ZERO; } }else{ result.Zero(); } return result; } inline Vector& GetSubVector(const Vector& ids, Vector &result) const { int s = ids.Size(); IndicesVector id; for(int i=0;i<s;i++) id.push_back(int(ROUND(ids.At(i)))); return GetSubVector(id,result); } /** * \brief Get a vector containing the vector values a given indices * \param ids A vecotr containing the indices * \param result The output vector */ inline Vector& GetSubVector(const IndicesVector& ids, Vector &result) const { const unsigned int k=ids.size(); result.Resize(k); for(unsigned int i=0;i<k;i++){ const unsigned int g = ids[i]; if(g<row){ result._[i] = _[g]; }else{ result._[i] = R_ZERO; } } return result; } /** * \brief Set at given indices a given vector values * \param ids The indices * \param result The vector */ inline Vector& SetSubVector(const IndicesVector& ids, const Vector &source) { const unsigned int j=ids.size(); const unsigned int k= (source.row<j?source.row:j); for(unsigned int i=0;i<k;i++){ const unsigned int g = ids[i]; if(g<row){ _[g] = source._[i]; } } return *this; } inline Vector& InsertSubVector(unsigned int start, const Vector& vector, unsigned int vectorStart, unsigned int vectorLength){ if(vectorStart >= vector.row) return *this; if(start >= row) return *this; if(vectorStart+vectorLength > vector.row) vectorLength = vector.row-vectorStart; if(start+vectorLength > row) vectorLength = row-start; unsigned int rowOffset = start; unsigned int vectorRowOffset = vectorStart; for(unsigned int j=0;j<vectorLength;j++){ _[rowOffset] = vector._[vectorRowOffset]; rowOffset++; vectorRowOffset++; } return *this; } /// Shift the value to the right (rightmost value is set to the left) inline Vector& ShiftRight(){ if(row>1){ REALTYPE *src = _ + row-1; REALTYPE zero = *src; unsigned int len = row-1; while(len--){ *src = *(src-1); src--; } *src = zero; } return *this; } /// Shift the value toi the left (leftmost value is set to the right) inline Vector& ShiftLeft(){ if(row>1){ REALTYPE *src = _; REALTYPE zero = *src; unsigned int len = row-1; while(len--){ *src = *(src+1); src++; } *src = zero; } return *this; } inline Vector& Trunc(const Vector& min, const Vector& max){ unsigned int k = MIN(min.row,max.row); unsigned int len = MIN(row,k); REALTYPE *dst = _; REALTYPE *v1 = min._; REALTYPE *v2 = max._; while(len--){ *dst = TRUNC((*dst),(*(v1)),(*(v2))); v1++; v2++; dst++; } if(row>k){ unsigned int len = row-k; while(len--) *(dst++) = R_ZERO; } return *this; } inline Vector& Trunc(const REALTYPE min, const REALTYPE max){ REALTYPE *dst = _; unsigned int len = row; while(len--){ *dst = TRUNC((*dst),min,max); dst++; } return *this; } /// Print the vector to stdout void Print() const; void Print(string name) const; /*{ std::cout << "Vector " <<row<<std::endl;; for (unsigned int i = 0; i < row; i++) std::cout << _[i] <<" "; std::cout << std::endl; }*/ /// Print the vector to stdout friend std::ostream & operator<<(std::ostream& out, const Vector & a){ PRINT_BEGIN(out); for (unsigned int i = 0; i < a.Size(); i++){ out.width(PRINT_WIDTH); out<< a.AtNoCheck(i)<<" " ; } PRINT_END(out); return out; } int PrintToString(char * str, int maxsize=0){ int cIndex = 0; str[0] = 0; if(maxsize<=0){ for (unsigned int i = 0; i < row; i++){ cIndex += sprintf(str+cIndex,"%1.12f ",_[i]); } }else{ for (unsigned int i = 0; i < row; i++){ int nb = snprintf(str+cIndex,maxsize-cIndex,"%1.12f ",_[i]); if(nb>=maxsize-cIndex) break; cIndex += nb; } } return cIndex; } protected: inline void Release(){ if(_!=NULL) delete [] _; row = 0; _ = NULL; } public: /** * \brief Resize the vector * \param size The new size * \param copy Should keep the original data or just resize. */ inline virtual Vector& Resize(unsigned int size, bool copy = true){ if(row!=size){ if(size){ REALTYPE *arr = new REALTYPE[size]; if(copy){ unsigned int len = (row<size?row:size); memcpy(arr,_,len*sizeof(REALTYPE)); if(len<size){ memset(arr+len,0,(size-len)*sizeof(REALTYPE)); } } if(_!=NULL) delete [] _; _ = arr; row = size; }else{ Release(); } } return *this; } }; class SharedVector : public Vector { protected: unsigned int maxMemorySize; public: inline SharedVector():Vector(){} inline SharedVector(REALTYPE *array, unsigned int rowSize):Vector(){ SetSharedPtr(array,rowSize); } inline SharedVector(const Vector & vector):Vector(){ SetSharedPtr(vector.Array(),vector.Size()); } #ifdef USE_T_EXTENSIONS /// Copy Contructor of a template Vector (see TVector) template<unsigned int ROW> inline SharedVector(const TVector<ROW> &vector):Vector(){ SetSharedPtr(vector.Array(),ROW); } #endif inline virtual ~SharedVector(){ Release(); } inline SharedVector& SetSharedPtr(REALTYPE *array, unsigned int size){ row = size; maxMemorySize = size; _ = array; return *this; } protected: inline virtual void Release(){ _ = NULL; } public: inline virtual SharedVector& Resize(unsigned int rowSize, bool copy = true){ assert(rowSize<=maxMemorySize); row = rowSize; return *this; } }; #ifdef USE_MATHLIB_NAMESPACE } #endif #endif
[ "stober@laptop.(none)" ]
[ [ [ 1, 1087 ] ] ]
386ad2d0c044c2a4fb23989f1f3e7c5dd647921f
b84a38aad619acf34c22ed6e6caa0f7b00ebfa0a
/Code/TootleAudio/IPad/IPadAudio.cpp
52cf29bc33011392aca16de4a0e9b9cf5d8a87b2
[]
no_license
SoylentGraham/Tootle
4ae4e8352f3e778e3743e9167e9b59664d83b9cb
17002da0936a7af1f9b8d1699d6f3e41bab05137
refs/heads/master
2021-01-24T22:44:04.484538
2010-11-03T22:53:17
2010-11-03T22:53:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,513
cpp
/* * IPadAudio.cpp * TootleAudio * * Created by Duane Bradbury on 15/12/2009. * Copyright 2009 Tootle. All rights reserved. * */ #include "IPadAudio.h" #include "IPadAudioOpenAL.h" #include <TootleAsset/TAsset.h> #include <TootleAsset/TAudio.h> using namespace TLAudio; SyncBool Platform::Init() { return OpenAL::Init(); } SyncBool Platform::Update() { return OpenAL::Update(); } SyncBool Platform::Shutdown() { return OpenAL::Shutdown(); } Bool Platform::CreateSource(TRefRef AudioSourceRef) { if(!OpenAL::CreateSource(AudioSourceRef)) { TLDebug_Print("Failed to create source for audio"); return FALSE; } return TRUE; } Bool Platform::RemoveSource(TRefRef AudioSourceRef) { // Release the platform specific buffer data if(!Platform::OpenAL::ReleaseSource(AudioSourceRef)) { // Failed? No low level buffer? TLDebug_Print("Failed to release low level audio source"); return FALSE; } return TRUE; } Bool Platform::CreateBuffer(TLAsset::TAudio& AudioAsset) { if(!OpenAL::CreateBuffer(AudioAsset)) { TLDebug_Print("Failed to create buffer for audio"); return FALSE; } return TRUE; } Bool Platform::RemoveBuffer(TRefRef AudioAssetRef) { // Release the platform specific buffer data if(!Platform::OpenAL::ReleaseBuffer(AudioAssetRef)) { // Failed? No low level buffer? TLDebug_Print("Failed to release low level audio buffer"); return FALSE; } return TRUE; } Bool Platform::HasBuffer(TRefRef AudioAssetRef) { return OpenAL::HasBuffer(AudioAssetRef); } Bool Platform::HasSource(TRefRef AudioSourceRef) { return OpenAL::HasSource(AudioSourceRef); } Bool Platform::StartAudio(TRefRef AudioSourceRef) { // Play the source return OpenAL::StartAudio(AudioSourceRef); } Bool Platform::StopAudio(TRefRef AudioSourceRef) { // Stop the source return OpenAL::StopAudio(AudioSourceRef); } Bool Platform::PauseAudio(TRefRef AudioSourceRef) { // Pause the source return OpenAL::PauseAudio(AudioSourceRef); } Bool Platform::SetPitch(TRefRef AudioSourceRef, const float fPitch) { return OpenAL::SetPitch(AudioSourceRef, fPitch); } Bool Platform::GetPitch(TRefRef AudioSourceRef, float& fPitch) { return OpenAL::GetPitch(AudioSourceRef, fPitch); } Bool Platform::SetVolume(TRefRef AudioSourceRef, const float fVolume) { return OpenAL::SetVolume(AudioSourceRef, fVolume); } Bool Platform::GetVolume(TRefRef AudioSourceRef, float& fVolume) { return OpenAL::GetVolume(AudioSourceRef, fVolume); } Bool Platform::SetLooping(TRefRef AudioSourceRef, const Bool bLooping) { return OpenAL::SetLooping(AudioSourceRef, bLooping); } Bool Platform::GetIsLooping(TRefRef AudioSourceRef, Bool& bLooping) { return OpenAL::GetIsLooping(AudioSourceRef, bLooping); } Bool Platform::SetRelative(TRefRef AudioSourceRef, const Bool bRelative) { return OpenAL::SetRelative(AudioSourceRef, bRelative); } Bool Platform::GetIsRelative(TRefRef AudioSourceRef, Bool& bRelative) { return OpenAL::GetIsLooping(AudioSourceRef, bRelative); } Bool Platform::SetPosition(TRefRef AudioSourceRef, const float3 vPosition) { return OpenAL::SetPosition(AudioSourceRef, vPosition); } Bool Platform::GetPosition(TRefRef AudioSourceRef, float3& vPosition) { return OpenAL::GetPosition(AudioSourceRef, vPosition); } Bool Platform::SetVelocity(TRefRef AudioSourceRef, const float3 vVelocity) { return OpenAL::SetVelocity(AudioSourceRef, vVelocity); } Bool Platform::GetVelocity(TRefRef AudioSourceRef, float3& vVelocity) { return OpenAL::GetVelocity(AudioSourceRef, vVelocity); } Bool Platform::SetMinRange(TRefRef AudioSourceRef, const float fDistance) { return OpenAL::SetReferenceDistance(AudioSourceRef, fDistance); } Bool Platform::SetMaxRange(TRefRef AudioSourceRef, const float fDistance) { return OpenAL::SetMaxDistance(AudioSourceRef, fDistance); } Bool Platform::SetRateOfDecay(TRefRef AudioSourceRef, const float fRateOfDecay) { return OpenAL::SetRollOffFactor(AudioSourceRef, fRateOfDecay); } Bool Platform::AttachSourceToBuffer(TRefRef AudioSourceRef, TRefRef AudioAssetRef, Bool bStreaming) { // Get the buffer and source OpenAL ID's ALuint uBuffer, uSource; if(!OpenAL::GetBufferID(AudioAssetRef, uBuffer)) { TLDebug_Print("Failed to find audio buffer ID"); return FALSE; } if(!OpenAL::GetSourceID(AudioSourceRef, uSource)) { TLDebug_Print("Failed to find audio source ID"); return FALSE; } // Got both buffer and source ID // Now attach the source ot the buffer return OpenAL::AttachSourceToBuffer(uSource, uBuffer, bStreaming); } Bool Platform::DetermineFinishedAudio(TArray<TRef>& refArray) { return OpenAL::DetermineFinishedAudio(refArray); } void Platform::SetListener(const TListenerProperties& Props) { OpenAL::SetListener(Props); } Bool Platform::Enable() { return OpenAL::Enable(); } Bool Platform::Disable() { return OpenAL::Disable(); } Bool Platform::Activate() { return OpenAL::Activate(); } Bool Platform::Deactivate() { return OpenAL::Deactivate(); } Bool Platform::SetDistanceModel(TLAudio::DistanceModel uDistanceModel) { return OpenAL::SetDistanceModel(uDistanceModel); } Bool Platform::SetDopplerEffect(float fFactor, float fVelocity) { return OpenAL::SetDopplerEffect(fFactor, fVelocity); }
[ [ [ 1, 258 ] ] ]
c54d4575cc28ee9ea7a1283385117721cf0dbc27
1bc2f450f157ce39cbd92d0549e1459368a76e94
/lib/cppunit-1.12.1/include/cppunit/plugin/PlugInManager.h
a205d0e1f0417d4b1a23be12a6af6728439adcae
[]
no_license
mirror/odin
168267277386d6c07c006cb196fec3bb208f5e3c
63b4633a87b03a924df612271c2d6310c34834a8
refs/heads/master
2023-09-01T13:28:38.392325
2011-10-09T15:38:02
2011-10-09T15:38:02
9,256,124
5
4
null
null
null
null
UTF-8
C++
false
false
3,137
h
#ifndef CPPUNIT_PLUGIN_PLUGINMANAGER_H #define CPPUNIT_PLUGIN_PLUGINMANAGER_H #include <cppunit/Portability.h> #if !defined(CPPUNIT_NO_TESTPLUGIN) #if CPPUNIT_NEED_DLL_DECL #pragma warning( push ) #pragma warning( disable: 4251 ) // X needs to have dll-interface to be used by clients of class Z #endif #include <cppunit/plugin/PlugInParameters.h> struct CppUnitTestPlugIn; CPPUNIT_NS_BEGIN class DynamicLibraryManager; class TestResult; class XmlOutputter; /*! \brief Manges TestPlugIn. */ class CPPUNIT_API PlugInManager { public: /*! Constructs a PlugInManager object. */ PlugInManager(); /// Destructor. virtual ~PlugInManager(); /*! \brief Loads the specified plug-in. * * After being loaded, the CppUnitTestPlugIn::initialize() is called. * * \param libraryFileName Name of the file that contains the TestPlugIn. * \param parameters List of string passed to the plug-in. * \return Pointer on the DynamicLibraryManager associated to the library. * Valid until the library is unloaded. Never \c NULL. * \exception DynamicLibraryManagerException is thrown if an error occurs during loading. */ void load( const std::string &libraryFileName, const PlugInParameters &parameters = PlugInParameters() ); /*! \brief Unloads the specified plug-in. * \param libraryFileName Name of the file that contains the TestPlugIn passed * to a previous call to load(). */ void unload( const std::string &libraryFileName ); /*! \brief Gives a chance to each loaded plug-in to register TestListener. * * For each plug-in, call CppUnitTestPlugIn::addListener(). */ void addListener( TestResult *eventManager ); /*! \brief Gives a chance to each loaded plug-in to unregister TestListener. * For each plug-in, call CppUnitTestPlugIn::removeListener(). */ void removeListener( TestResult *eventManager ); /*! \brief Provides a way for the plug-in to register some XmlOutputterHook. */ void addXmlOutputterHooks( XmlOutputter *outputter ); /*! \brief Called when the XmlOutputter is destroyed. * * Can be used to free some resources allocated by addXmlOutputterHooks(). */ void removeXmlOutputterHooks(); protected: /*! \brief (INTERNAL) Information about a specific plug-in. */ struct PlugInInfo { std::string m_fileName; DynamicLibraryManager *m_manager; CppUnitTestPlugIn *m_interface; }; /*! Unloads the specified plug-in. * \param plugIn Information about the plug-in. */ void unload( PlugInInfo &plugIn ); private: /// Prevents the use of the copy constructor. PlugInManager( const PlugInManager &copy ); /// Prevents the use of the copy operator. void operator =( const PlugInManager &copy ); private: typedef CppUnitDeque<PlugInInfo> PlugIns; PlugIns m_plugIns; }; CPPUNIT_NS_END #if CPPUNIT_NEED_DLL_DECL #pragma warning( pop ) #endif #endif // !defined(CPPUNIT_NO_TESTPLUGIN) #endif // CPPUNIT_PLUGIN_PLUGINMANAGER_H
[ "kaltduscher65@b91d169b-bf28-450c-9b59-d70c078a1df8" ]
[ [ [ 1, 113 ] ] ]
fe655ac720dd0db053e5a2e422f63d670c336834
fc4946d917dc2ea50798a03981b0274e403eb9b7
/gentleman/gentleman/WindowsAPICodePack/WindowsAPICodePack/DirectX/DirectX/DirectUnknown.h
d64a97b80af4f5bd0b9ad7b4682ab4c4609d96f0
[]
no_license
midnite8177/phever
f9a55a545322c9aff0c7d0c45be3d3ddd6088c97
45529e80ebf707e7299887165821ca360aa1907d
refs/heads/master
2020-05-16T21:59:24.201346
2010-07-12T23:51:53
2010-07-12T23:51:53
34,965,829
3
2
null
null
null
null
UTF-8
C++
false
false
1,085
h
// Copyright (c) Microsoft Corporation. All rights reserved. #pragma once namespace Microsoft { namespace WindowsAPICodePack { namespace DirectX { /// <summary> /// Base class for all classes supporting internal IUnknown interfaces /// </summary> public ref class DirectUnknown abstract { internal: template <typename T> T* GetInterface() { return static_cast<T*>(nativeUnknown.Get()); } void Attach(IUnknown* _right); void Attach(IUnknown* _right, bool _deletable); DirectUnknown(IUnknown* _iUnknown); DirectUnknown(IUnknown* _iUnknown, bool _deletable); DirectUnknown() ; public: /// <summary> /// Get the internal native pointer for the wrapped IUnknown Interface /// </summary> /// <returns> /// A pointer to the wrapped native IUnknown. /// </returns> property IntPtr NativeInterface { IntPtr get() { return IntPtr(nativeUnknown.Get()); } } private: AutoIUnknown<IUnknown> nativeUnknown; }; } } }
[ "lucemia@9e708c16-f4dd-11de-aa3c-59de0406b4f5" ]
[ [ [ 1, 47 ] ] ]
0862c1e139000611f3e0a8ce878a1273ee3c1b54
c1a2953285f2a6ac7d903059b7ea6480a7e2228e
/deitel/ch11/Fig11_17_18/Fig11_18.cpp
ab90a27643263d657b2d225edd1ebf145b354a68
[]
no_license
tecmilenio/computacion2
728ac47299c1a4066b6140cebc9668bf1121053a
a1387e0f7f11c767574fcba608d94e5d61b7f36c
refs/heads/master
2016-09-06T19:17:29.842053
2008-09-28T04:27:56
2008-09-28T04:27:56
50,540
4
3
null
null
null
null
WINDOWS-1258
C++
false
false
1,813
cpp
// Fig. 11.18: Fig11_18.cpp // Driver for simple class Array. #include <iostream> using std::cout; using std::endl; #include "Array.h" void outputArray( const Array & ); // prototype int main() { Array integers1( 7 ); // 7-element array outputArray( integers1 ); // output Array integers1 outputArray( 3 ); // convert 3 to an Array and output Array’s contents outputArray( Array( 3 ) ); // explicit single-argument constructor call return 0; } // end main // print array contents void outputArray( const Array &arrayToOutput ) { cout << "The Array received has " << arrayToOutput.getSize() << " elements. The contents are:\n" << arrayToOutput << endl; } // end outputArray /************************************************************************** * (C) Copyright 1992-2008 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * **************************************************************************/
[ [ [ 1, 41 ] ] ]
5823b92c69546e6e90323f4c88ddc395b00a5eab
8b3186e126ac2d19675dc19dd473785de97068d2
/bmt_prod/util/color3.h
437b2a61b816ef55eb5587350fed5f064fee27ca
[]
no_license
leavittx/revenge
e1fd7d6cd1f4a1fb1f7a98de5d16817a0c93da47
3389148f82e6434f0619df47c076c60c8647ed86
refs/heads/master
2021-01-01T17:28:26.539974
2011-08-25T20:25:14
2011-08-25T20:25:14
618,159
2
0
null
null
null
null
UTF-8
C++
false
false
809
h
#pragma once #include <math.h> /* A simple RGB color class. */ class Color3 { public: Color3(); Color3(float r, float g, float b); Color3(const class Color3 &v) { this->r = v.r; this->g = v.g; this->b = v.b; } Color3(unsigned int rgb); ~Color3(); Color3 operator + (Color3 const &col); Color3 operator - (Color3 const &col); Color3 operator += (Color3 const &col); Color3 operator -= (Color3 const &col); Color3 operator * (const float &value); Color3 operator *= (float const &value); void operator = (Color3 const &col); Color3 normalize(); void use(); void useWithAlpha(float alpha = 1.0f); void useModulated(float modulation = 1.0f); void useWithAlphaModulated(float alpha = 1.0f, float modulation = 1.0f); float r, g, b; private: };
[ [ [ 1, 39 ] ] ]
6e1b75345ba7e875ae908d7645e8c93d589fcf82
463c3b62132d215e245a097a921859ecb498f723
/lib/dlib/test/serialize.cpp
df0f442ed060de791b812aa8d191710007ff500d
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
athulan/cppagent
58f078cee55b68c08297acdf04a5424c2308cfdc
9027ec4e32647e10c38276e12bcfed526a7e27dd
refs/heads/master
2021-01-18T23:34:34.691846
2009-05-05T00:19:54
2009-05-05T00:19:54
197,038
4
1
null
null
null
null
UTF-8
C++
false
false
16,055
cpp
// Copyright (C) 2008 Davis E. King ([email protected]) // License: Boost Software License See LICENSE.txt for the full license. #include <iostream> #include <fstream> #include <sstream> #include <dlib/compress_stream.h> #include <dlib/base64.h> #include <string> #include <cstdlib> #include <ctime> #include <dlib/serialize.h> #include "tester.h" namespace { // ---------------------------------------------------------------------------------------- using namespace test; using namespace dlib; using namespace std; struct test_object { signed char i1; signed short i2; signed long i3; unsigned char i4; unsigned short i5; unsigned long i6; uint64 i7; signed char i1_0; signed short i2_0; signed long i3_0; unsigned char i4_0; unsigned short i5_0; unsigned long i6_0; uint64 i7_0; signed char i1_n; signed short i2_n; signed long i3_n; float f1; double f2; long double f3; float f1_inf; double f2_inf; long double f3_inf; float f1_ninf; double f2_ninf; long double f3_ninf; float f1_qnan; double f2_qnan; long double f3_qnan; float f1_snan; double f2_snan; long double f3_snan; std::string s1; std::wstring s2; int array[10]; bool b_true; bool b_false; void set_state_1( ) { i1 = 1; i2 = 2; i3 = 3; i4 = 4; i5 = 5; i6 = 6; i7 = 7; i1_0 = 0; i2_0 = 0; i3_0 = 0; i4_0 = 0; i5_0 = 0; i6_0 = 0; i7_0 = 0; i1_n = -1; i2_n = -2; i3_n = -3; f1 = 123.456f; f2 = 543.341; f3 = 5234234.23; f1_inf = numeric_limits<float>::infinity(); f2_inf = numeric_limits<double>::infinity(); f3_inf = numeric_limits<long double>::infinity(); f1_ninf = -numeric_limits<float>::infinity(); f2_ninf = -numeric_limits<double>::infinity(); f3_ninf = -numeric_limits<long double>::infinity(); f1_qnan = numeric_limits<float>::quiet_NaN(); f2_qnan = numeric_limits<double>::quiet_NaN(); f3_qnan = numeric_limits<long double>::quiet_NaN(); f1_snan = numeric_limits<float>::signaling_NaN(); f2_snan = numeric_limits<double>::signaling_NaN(); f3_snan = numeric_limits<long double>::signaling_NaN(); s1 = "davis"; s2 = L"yo yo yo"; for (int i = 0; i < 10; ++i) array[i] = i; b_true = true; b_false = false; } void set_state_2( ) { i1 = 10; i2 = 20; i3 = 30; i4 = 40; i5 = 50; i6 = 60; i7 = 70; i1_0 = 5; i2_0 = 6; i3_0 = 7; i4_0 = 8; i5_0 = 9; i6_0 = 10; i7_0 = 11; i1_n = -13; i2_n = -25; i3_n = -12; f1 = 45.3f; f2 = 0.001; f3 = 2.332; f1_inf = f1; f2_inf = f2; f3_inf = f3; f1_ninf = f1; f2_ninf = f2; f3_ninf = f3; f1_qnan = f1; f2_qnan = f2; f3_qnan = f3; f1_snan = f1; f2_snan = f2; f3_snan = f3; s1 = ""; s2 = L""; for (int i = 0; i < 10; ++i) array[i] = 10-i; b_true = false; b_false = true; } void assert_in_state_1 ( ) { DLIB_CASSERT (i1 == 1,""); DLIB_CASSERT (i2 == 2,""); DLIB_CASSERT (i3 == 3,""); DLIB_CASSERT (i4 == 4,""); DLIB_CASSERT (i5 == 5,""); DLIB_CASSERT (i6 == 6,""); DLIB_CASSERT (i7 == 7,""); DLIB_CASSERT (i1_0 == 0,""); DLIB_CASSERT (i2_0 == 0,""); DLIB_CASSERT (i3_0 == 0,""); DLIB_CASSERT (i4_0 == 0,""); DLIB_CASSERT (i5_0 == 0,""); DLIB_CASSERT (i6_0 == 0,""); DLIB_CASSERT (i7_0 == 0,""); DLIB_CASSERT (i1_n == -1,""); DLIB_CASSERT (i2_n == -2,""); DLIB_CASSERT (i3_n == -3,""); DLIB_CASSERT (abs(f1 -123.456) < 1e-5,""); DLIB_CASSERT (abs(f2 - 543.341) < 1e-10,""); DLIB_CASSERT (abs(f3 - 5234234.23) < 1e-10,""); DLIB_CASSERT (f1_inf == numeric_limits<float>::infinity(),""); DLIB_CASSERT (f2_inf == numeric_limits<double>::infinity(),""); DLIB_CASSERT (f3_inf == numeric_limits<long double>::infinity(),""); DLIB_CASSERT (f1_ninf == -numeric_limits<float>::infinity(),""); DLIB_CASSERT (f2_ninf == -numeric_limits<double>::infinity(),""); DLIB_CASSERT (f3_ninf == -numeric_limits<long double>::infinity(),""); DLIB_CASSERT (!(f1_qnan <= numeric_limits<float>::infinity() && f1_qnan >= -numeric_limits<float>::infinity() ),""); DLIB_CASSERT (!(f2_qnan <= numeric_limits<double>::infinity() && f1_qnan >= -numeric_limits<double>::infinity() ),""); DLIB_CASSERT (!(f3_qnan <= numeric_limits<long double>::infinity() && f1_qnan >= -numeric_limits<long double>::infinity() ),""); DLIB_CASSERT (!(f1_snan <= numeric_limits<float>::infinity() && f1_qnan >= -numeric_limits<float>::infinity() ),""); DLIB_CASSERT (!(f2_snan <= numeric_limits<double>::infinity() && f1_qnan >= -numeric_limits<double>::infinity() ),""); DLIB_CASSERT (!(f3_snan <= numeric_limits<long double>::infinity() && f1_qnan >= -numeric_limits<long double>::infinity() ),""); DLIB_CASSERT (s1 == "davis",""); DLIB_CASSERT (s2 == L"yo yo yo",""); for (int i = 0; i < 10; ++i) { DLIB_CASSERT (array[i] == i,""); } DLIB_CASSERT (b_true == true,""); DLIB_CASSERT (b_false == false,""); } void assert_in_state_2 ( ) { DLIB_CASSERT (i1 == 10,""); DLIB_CASSERT (i2 == 20,""); DLIB_CASSERT (i3 == 30,""); DLIB_CASSERT (i4 == 40,""); DLIB_CASSERT (i5 == 50,""); DLIB_CASSERT (i6 == 60,""); DLIB_CASSERT (i7 == 70,""); DLIB_CASSERT (i1_0 == 5,""); DLIB_CASSERT (i2_0 == 6,""); DLIB_CASSERT (i3_0 == 7,""); DLIB_CASSERT (i4_0 == 8,""); DLIB_CASSERT (i5_0 == 9,""); DLIB_CASSERT (i6_0 == 10,""); DLIB_CASSERT (i7_0 == 11,""); DLIB_CASSERT (i1_n == -13,""); DLIB_CASSERT (i2_n == -25,""); DLIB_CASSERT (i3_n == -12,""); DLIB_CASSERT (abs(f1 - 45.3) < 1e-5,""); DLIB_CASSERT (abs(f2 - 0.001) < 1e-10,""); DLIB_CASSERT (abs(f3 - 2.332) < 1e-10,""); DLIB_CASSERT (abs(f1_inf - 45.3) < 1e-5,""); DLIB_CASSERT (abs(f2_inf - 0.001) < 1e-10,""); DLIB_CASSERT (abs(f3_inf - 2.332) < 1e-10,""); DLIB_CASSERT (abs(f1_ninf - 45.3) < 1e-5,""); DLIB_CASSERT (abs(f2_ninf - 0.001) < 1e-10,""); DLIB_CASSERT (abs(f3_ninf - 2.332) < 1e-10,""); DLIB_CASSERT (abs(f1_qnan - 45.3) < 1e-5,""); DLIB_CASSERT (abs(f2_qnan - 0.001) < 1e-10,""); DLIB_CASSERT (abs(f3_qnan - 2.332) < 1e-10,""); DLIB_CASSERT (abs(f1_snan - 45.3) < 1e-5,""); DLIB_CASSERT (abs(f2_snan - 0.001) < 1e-10,""); DLIB_CASSERT (abs(f3_snan - 2.332) < 1e-10,""); DLIB_CASSERT (s1 == "",""); DLIB_CASSERT (s2 == L"",""); for (int i = 0; i < 10; ++i) { DLIB_CASSERT (array[i] == 10-i,""); } DLIB_CASSERT (b_true == false,""); DLIB_CASSERT (b_false == true,""); } }; // ---------------------------------------------------------------------------------------- void serialize ( const test_object& item, std::ostream& out ) { dlib::serialize(item.i1,out); dlib::serialize(item.i2,out); dlib::serialize(item.i3,out); dlib::serialize(item.i4,out); dlib::serialize(item.i5,out); dlib::serialize(item.i6,out); dlib::serialize(item.i7,out); dlib::serialize(item.i1_0,out); dlib::serialize(item.i2_0,out); dlib::serialize(item.i3_0,out); dlib::serialize(item.i4_0,out); dlib::serialize(item.i5_0,out); dlib::serialize(item.i6_0,out); dlib::serialize(item.i7_0,out); dlib::serialize(item.i1_n,out); dlib::serialize(item.i2_n,out); dlib::serialize(item.i3_n,out); dlib::serialize(item.f1,out); dlib::serialize(item.f2,out); dlib::serialize(item.f3,out); dlib::serialize(item.f1_inf,out); dlib::serialize(item.f2_inf,out); dlib::serialize(item.f3_inf,out); dlib::serialize(item.f1_ninf,out); dlib::serialize(item.f2_ninf,out); dlib::serialize(item.f3_ninf,out); dlib::serialize(item.f1_qnan,out); dlib::serialize(item.f2_qnan,out); dlib::serialize(item.f3_qnan,out); dlib::serialize(item.f1_snan,out); dlib::serialize(item.f2_snan,out); dlib::serialize(item.f3_snan,out); dlib::serialize(item.s1,out); dlib::serialize(item.s2,out); dlib::serialize(item.array,out); dlib::serialize(item.b_true,out); dlib::serialize(item.b_false,out); } // ---------------------------------------------------------------------------------------- void deserialize ( test_object& item, std::istream& in ) { dlib::deserialize(item.i1,in); dlib::deserialize(item.i2,in); dlib::deserialize(item.i3,in); dlib::deserialize(item.i4,in); dlib::deserialize(item.i5,in); dlib::deserialize(item.i6,in); dlib::deserialize(item.i7,in); dlib::deserialize(item.i1_0,in); dlib::deserialize(item.i2_0,in); dlib::deserialize(item.i3_0,in); dlib::deserialize(item.i4_0,in); dlib::deserialize(item.i5_0,in); dlib::deserialize(item.i6_0,in); dlib::deserialize(item.i7_0,in); dlib::deserialize(item.i1_n,in); dlib::deserialize(item.i2_n,in); dlib::deserialize(item.i3_n,in); dlib::deserialize(item.f1,in); dlib::deserialize(item.f2,in); dlib::deserialize(item.f3,in); dlib::deserialize(item.f1_inf,in); dlib::deserialize(item.f2_inf,in); dlib::deserialize(item.f3_inf,in); dlib::deserialize(item.f1_ninf,in); dlib::deserialize(item.f2_ninf,in); dlib::deserialize(item.f3_ninf,in); dlib::deserialize(item.f1_qnan,in); dlib::deserialize(item.f2_qnan,in); dlib::deserialize(item.f3_qnan,in); dlib::deserialize(item.f1_snan,in); dlib::deserialize(item.f2_snan,in); dlib::deserialize(item.f3_snan,in); dlib::deserialize(item.s1,in); dlib::deserialize(item.s2,in); dlib::deserialize(item.array,in); dlib::deserialize(item.b_true,in); dlib::deserialize(item.b_false,in); } // ---------------------------------------------------------------------------------------- // This function returns the contents of the file 'stuff.bin' const std::string get_decoded_string() { dlib::base64::kernel_1a base64_coder; dlib::compress_stream::kernel_1ea compressor; std::ostringstream sout; std::istringstream sin; // The base64 encoded data from the file 'stuff.bin' we want to decode and return. sout << "AVaifX9zEbXbpgarAlucU9BNkSZXOyTKOGxr7taGvaQqrWOaCnaFVnAkSoI4sZ3Va8+I4DqkUa10"; sout << "6im2LoQqVlfhtRzCgI93x19uWen15Lk+zylZTc34P6aBwSuYMo957IjLhCcBsxIqIbXnWN/7zQSv"; sout << "c7Anq5STW+yvKzSohWor56pGXDTtZrm9bFTsaztlavtnauYvgn7RZkp4a9MrbgnDzdzmzAnE7+w1"; sout << "hl94IKktATHIBtMUJsrENvx+np3m01ygEPIftRmEa4KpW1JkZORjqUR/j211oUweh+LYIMR+s4cX"; sout << "0L7bwPBmULwA"; // Put the data into the istream sin sin.str(sout.str()); sout.str(""); // Decode the base64 text into its compressed binary form base64_coder.decode(sin,sout); sin.clear(); sin.str(sout.str()); sout.str(""); // Decompress the data into its original form compressor.decompress(sin,sout); // Return the decoded and decompressed data return sout.str(); } // ---------------------------------------------------------------------------------------- // Declare the logger we will use in this test. The name of the tester // should start with "test." logger dlog("test.serialize"); void serialize_test ( ) /*! ensures - runs tests on the serialization code for compliance with the specs !*/ { print_spinner(); ostringstream sout; test_object obj; obj.set_state_1(); obj.assert_in_state_1(); serialize(obj, sout); obj.assert_in_state_1(); obj.set_state_2(); obj.assert_in_state_2(); serialize(obj, sout); obj.assert_in_state_2(); istringstream sin(sout.str()); deserialize(obj,sin); obj.assert_in_state_1(); deserialize(obj,sin); obj.assert_in_state_2(); // now do the same thing as above but deserialize from some stored binary // data to make sure the serialized values are portable between different // machines sin.clear(); sin.str(get_decoded_string()); deserialize(obj,sin); obj.assert_in_state_1(); deserialize(obj,sin); obj.assert_in_state_2(); /* // This is the code that produced the encoded data stored in the get_decoded_string() function ofstream fout("stuff.bin",ios::binary); obj.set_state_1(); obj.assert_in_state_1(); serialize(obj, fout); obj.assert_in_state_1(); obj.set_state_2(); obj.assert_in_state_2(); serialize(obj, fout); obj.assert_in_state_2(); */ } class serialize_tester : public tester { /*! WHAT THIS OBJECT REPRESENTS This object represents a test for the serialization . When it is constructed it adds itself into the testing framework. The command line switch is specified as test_serialize by passing that string to the tester constructor. !*/ public: serialize_tester ( ) : tester ("test_serialize", "Runs tests on the serialization code.") {} void perform_test ( ) { serialize_test(); } } a; }
[ "jimmy@DGJ3X3B1.(none)" ]
[ [ [ 1, 521 ] ] ]
b4b41901dca1405bc986b50dc27021b2771486d8
50e7a87a6bf57bf0ebfb52e885cea94a92043d40
/heig-boy/interface/RefreshManager.h
b21320b9493d3b9e9e2a28790065b98f6abadc8f
[]
no_license
dragon2snow/Heig-Boy-
88ec3bef310448de6c86b916cabcec141704a3e6
dee7e02bc245b50aaabb572d8fe1b9360f393b11
refs/heads/master
2020-04-22T15:17:19.324636
2010-01-20T23:58:56
2010-01-20T23:58:56
170,473,048
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,425
h
/** Classe de gestion de l'émulation. Gère l'ouverture d'une ROM puis de l'affichage de la partie. */ #pragma once #include "wx/wx.h" class RefreshManager : public wxThread { friend class MainWindow; MainWindow *frame; #ifdef WIN32 unsigned long long frequency; #else #endif unsigned long long lastTime; bool romLoaded; wxMutex mutexRomLoaded; bool pauseActive; wxMutex mutexPause; bool fin; public: wxMutex mutexInFrame; bool fastMode; /** Mettre la partie en pause \param active Pour activer ou désactiver la pause */ void pause(bool active); /** Mode turbo on/off \param active Pour activer ou désactiver le turbo */ void turbo(bool active); /** Constructeur \param frame La fenêtre mère */ RefreshManager(MainWindow *frame); /** Initialisation de la synchro, platform specifique. */ void synchroInit(); /** Obtient la valeur du temps courant. */ unsigned long long getTime(); /** Synchronize @ 60 fps. Retourne vrai si on est en retard. \return vrai si on est en retard. */ bool synchroDo(); /** Permet de charger un jeu */ void loadRom(); /** Permet de savoir s'il on est entrain de jouer */ bool isPlaying(); /** Met fin au thread proprement */ void endGame(); /** Point d'entrée du thread */ virtual void *Entry(); };
[ "gabranth@bfddfde6-68e7-4156-9405-ca205172725d" ]
[ [ [ 1, 87 ] ] ]
38e81af85ce559c84cf6508b3e29a5eddc3e892c
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/trunk/engine/ui/include/InfoPopup.h
4429aa4347385d783b7faf7b40b6ad2c483e4353
[ "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,746
h
/* This source file is part of Rastullahs Lockenpracht. * Copyright (C) 2003-2008 Team Pantheon. http://www.team-pantheon.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the Clarified Artistic License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not you can get it here * http://www.jpaulmorrison.com/fbp/artistic2.htm. */ #include "UiPrerequisites.h" #include <vector> #include "AbstractWindow.h" #include "QuestListener.h" namespace rl { class _RlUiExport InfoPopup : public AbstractWindow, public QuestListener { public: InfoPopup(); ~InfoPopup(); void showError(); void showQuestBookChange(); void windowHid(); void setVisible(bool visible, bool destroyAfterHide = false); void questStateChanged(QuestEvent* anEvent); void questPartsDoneChanged(QuestEvent* anEvent); void questKnownChanged(QuestEvent* anEvent); void questSubquestAdded(QuestEvent* anEvent); void journalEntryAdded(JournalEvent* anEvent); void journalEntryDeleted(JournalEvent* anEvent); private: static const int ICON_SPACING = 5; void showMessageIcon(CEGUI::Window* image); std::vector<CEGUI::Window*> mActiveIcons; CEGUI::Window* mErrorIcon; CEGUI::Window* mQuestIcon; }; }
[ "blakharaz@4c79e8ff-cfd4-0310-af45-a38c79f83013", "tanis@4c79e8ff-cfd4-0310-af45-a38c79f83013", "timm@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 25 ], [ 30, 30 ], [ 33, 33 ], [ 35, 35 ], [ 37, 42 ], [ 47, 47 ], [ 49, 49 ], [ 54, 55 ] ], [ [ 26, 29 ], [ 31, 32 ], [ 34, 34 ], [ 36, 36 ], [ 43, 43 ], [ 45, 46 ], [ 48, 48 ], [ 50, 53 ] ], [ [ 44, 44 ] ] ]
616033d91db08593d489424dcb7136345e01fdda
1193b8d2ab6bb40ce2adbf9ada5b3d1124f1abb3
/branches/mapmodule/modules/genericmapmodule/src/GenericMapWalkmeshSubManager.cpp
992862a52a912101bab19412cd96b0362cf7f7d7
[]
no_license
sonetto/legacy
46bb60ef8641af618d22c08ea198195fd597240b
e94a91950c309fc03f9f52e6bc3293007c3a0bd1
refs/heads/master
2021-01-01T16:45:02.531831
2009-09-10T21:50:42
2009-09-10T21:50:42
32,183,635
0
2
null
null
null
null
UTF-8
C++
false
false
23,303
cpp
/*----------------------------------------------------------------------------- This source file is part of Sonetto RPG Engine. Copyright (C) 2007,2008 Arthur Carvalho de Souza Lima, Guilherme Prá Vieira Sonetto RPG Engine is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Sonetto RPG Engine 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 or go to http://www.gnu.org/copyleft/lesser.txt -----------------------------------------------------------------------------*/ #include <OgreSceneNode.h> #include <SonettoMath.h> #include "GenericMapWalkmeshSubManager.h" #include "GenericMapWalkmesh.h" namespace GenericMapModule { //------------------------------------------------------------------------- // GenericMapModule::WalkmeshSubManager implementation. //------------------------------------------------------------------------- void WalkmeshSubManager::setWalkmesh(const Walkmesh *walkmesh) { if (!mEvents.empty()) { SONETTO_THROW("Walkmesh is not empty of events"); } mWalkmesh = walkmesh; } //------------------------------------------------------------------------- void WalkmeshSubManager::registerEvent(Event *evt) { // Checks if it was not already registered if (std::find(mEvents.begin(),mEvents.end(),evt) != mEvents.end()) { SONETTO_THROW("Event already registered with walkmesh"); } mEvents.push_back(evt); } //------------------------------------------------------------------------- void WalkmeshSubManager::unregisterEvent(Event *evt) { EventVector::iterator i = std::find(mEvents.begin(), mEvents.end(),evt); // Checks if it is not registered yet if (i == mEvents.end()) { SONETTO_THROW("Event not registered with walkmesh"); } // Unregisters event mEvents.erase(i); } //------------------------------------------------------------------------- bool WalkmeshSubManager::walkmeshBorderCross(Event *evt, Ogre::Vector3 &position,float *slideFactor) { uint32 curTri = evt->getCurrentTriangle(); Ogre::Vector3 direction = position - evt->getSceneNode()-> getPosition(); direction.normalise(); while (true) { uint32 nextTri = 0; // Gets current triangle's vertex coordinates const Ogre::Vector3 &vA = mWalkmesh->getTriangleVertex(curTri,0); const Ogre::Vector3 &vB = mWalkmesh->getTriangleVertex(curTri,1); const Ogre::Vector3 &vC = mWalkmesh->getTriangleVertex(curTri,2); // Checks what borders were crossed float sign1 = Sonetto::Math::sideOfVector(position,vB,vA); float sign2 = Sonetto::Math::sideOfVector(position,vC,vB); float sign3 = Sonetto::Math::sideOfVector(position,vA,vC); if (sign1 < 0) { nextTri = mWalkmesh->getEdgeLink(curTri,0); if (slideFactor) { Ogre::Vector3 border = vB - vA; float angle; border.normalise(); Ogre::Quaternion quat; quat.FromAngleAxis(Ogre::Radian(Ogre::Degree(90.0f)), Ogre::Vector3::UNIT_Y); border = quat * border; angle = Ogre::Math::ACos(border.dotProduct(direction)). valueDegrees(); *slideFactor = Sonetto::Math::clamp(angle / 180.0f, 0.0f,1.0f); } } else if (sign2 < 0) { nextTri = mWalkmesh->getEdgeLink(curTri,1); if (slideFactor) { Ogre::Vector3 border = vC - vB; float angle; border.normalise(); Ogre::Quaternion quat; quat.FromAngleAxis(Ogre::Radian(Ogre::Degree(90.0f)), Ogre::Vector3::UNIT_Y); border = quat * border; angle = Ogre::Math::ACos(border.dotProduct(direction)). valueDegrees(); *slideFactor = Sonetto::Math::clamp(angle / 180.0f, 0.0f,1.0f); } } else if (sign3 < 0) { nextTri = mWalkmesh->getEdgeLink(curTri,2); if (slideFactor) { Ogre::Vector3 border = vA - vC; float angle; border.normalise(); Ogre::Quaternion quat; quat.FromAngleAxis(Ogre::Radian(Ogre::Degree(90.0f)), Ogre::Vector3::UNIT_Y); border = quat * border; angle = Ogre::Math::ACos(border.dotProduct(direction)). valueDegrees(); *slideFactor = Sonetto::Math::clamp(angle / 180.0f, 0.0f,1.0f); } } else { // Not crossing any borders // Gets destination elevation and saves current triangle position.y = Sonetto::Math::pointElevation(position,vA,vB,vC); evt->setCurrentTriangle(curTri); // No borders were crossed, so our slide factor is 1.0f /*if (slideFactor) { *slideFactor = 1.0f; }*/ // false == No borders crossed return false; } if (nextTri > 0) { curTri = nextTri; continue; } position.y = Sonetto::Math::pointElevation(position,vA,vB,vC); evt->setCurrentTriangle(curTri); return true; } } //------------------------------------------------------------------------- bool WalkmeshSubManager::checkCollisions(Event *evt, Ogre::Vector3 &position) { // If we have our ignore collisions flag set, we should return false /*if (evt->getIgnoreCollision() == true) { return false; } // Loops through all registered events inside this walkmesh manager for (WalkmeshEventInfoMap::iterator i = mEventInfo.begin(); i != mEventInfo.end();++i) { const EventObject *evt2 = i->first; // Skips if this event (`evt2') is the same as inputed (`evt') // or if its ignore collisions flag is set if (evt2 == evt || evt2->getIgnoreCollision() == true) { continue; } // Gets event's position and collision radius Ogre::Vector3 pos2 = evt2->getPosition(); float colRadius = evt2->getColRadius(); // The height we need to check depends on which event is below which float height; if (pos2.y >= position.y) { height = evt->getHeight(); } else { height = evt2->getHeight(); } // Check if the two events potentially intersect given their distance // on the Y axis and the height chosen up there if (( pos2.y - position.y + height < height * 2 ) && ( pos2.y - position.y + height >= 0 ) ) { // Squares colRadius to avoid needing to square root the distance colRadius *= colRadius; float distance = ( (pos2.x - position.x) * (pos2.x - position.x) ) + ( (pos2.z - position.z) * (pos2.z - position.z) ); // If the squared distance is smaller than the squared radius, then // the cylinders intersect, in which case we return true if (distance < colRadius) { return true; } } } // Returns false if our event's cylinder didn't intersect with any // other events*/ return false; } //------------------------------------------------------------------------- void WalkmeshSubManager::moveEvent(Event *evt, const Ogre::Vector3 &moveVector) { // <todo> Move the event freely when evt->isFlying() is true // Checks whether the event is registered or not if (std::find(mEvents.begin(),mEvents.end(),evt) == mEvents.end()) { SONETTO_THROW("Event not registered with walkmesh"); } // Gets this event's current triangle uint32 curTri = evt->getCurrentTriangle(); // Checks whether this event was positioned on the walkmesh or not if (curTri == 0) { SONETTO_THROW("Event position not set in walkmesh"); } // Gets this event's current position Ogre::Vector3 startPoint(evt->getSceneNode()->getPosition()); // This `direction' vector will be modified later // That's why it is copied to a local variable instead of being used // directly by accessing `moveVector' Ogre::Vector3 direction(moveVector); // Do not move if the move vector has a length of 0.0f if (direction.x == 0.0f && direction.z == 0.0f) { return; } // Gets event collision radius float colRadius = evt->getRadius(); // Used to rotate vectors Ogre::Quaternion q1(0.0f,0.0f, 0.0f,1.0f); // Calculates final desired destination on the XZ plane Ogre::Vector3 endPoint( startPoint + (direction * evt->getWalkSpeed()) ); // Collision check flags bool first_triangle_check = false; bool second_triangle_check = false; bool third_triangle_check = false; bool last_triangle_check = false; bool first_entity_check = false; bool second_entity_check = false; bool third_entity_check = false; // Gets current triangle's vertex coordinates const Ogre::Vector3 &vA = mWalkmesh->getTriangleVertex(curTri,0); const Ogre::Vector3 &vB = mWalkmesh->getTriangleVertex(curTri,1); const Ogre::Vector3 &vC = mWalkmesh->getTriangleVertex(curTri,2); // Gets the Y elevation based on the destination // coordinates on the XZ plane endPoint.y = Sonetto::Math::pointElevation(endPoint,vA,vB,vC); // Gets a vector that begins on the start point and ends on // the end point, taking into account the Y-axis elevation difference // between them, and normalises it Ogre::Vector3 xyzMoveVector = endPoint - startPoint; xyzMoveVector.normalise(); // Scales the XYZ move vector to the length of the XZ move vector // This will make the XYZ move vector have the same length as the // inputed moveVector, resulting in the same move speed xyzMoveVector *= direction.length(); // Gets final direction back from the xyzMoveVector // They are changed now, since xyzMoveVector cares about elevation direction.x = xyzMoveVector.x; direction.z = xyzMoveVector.z; for (int i = 0; i < 17; ++i) { float scaleDirection,slideFactor = 1.0f,finalSlideFactor = 1.0f; Ogre::Vector3 rotatedDirection(0.0f, 0.0f, 0.0f); Ogre::Vector3 rotatedEndPoint(0.0f,0.0f,0.0f); // Sets new end point based on `direction' endPoint = startPoint + (direction * evt->getWalkSpeed()); // 1st check // Rotates direction by +45 degrees on the Y axis q1.FromAngleAxis(Ogre::Radian(Ogre::Degree(45.0f)), Ogre::Vector3::UNIT_Y); rotatedDirection = q1 * direction; // Scale the rotated direction so that it lengths the same as before // plus the collision radius of this event scaleDirection = rotatedDirection.normalise() + colRadius; rotatedDirection *= scaleDirection; // Calculates rotated end point rotatedEndPoint = endPoint + rotatedDirection; // Checks rotated end point against the walkmesh and restores // current triangle event information (it is changed by // walkmeshBorderCross()) first_triangle_check = walkmeshBorderCross(evt,rotatedEndPoint, &slideFactor); evt->setCurrentTriangle(curTri); if (first_triangle_check) { finalSlideFactor = slideFactor; } // Checks rotated end point against other events first_entity_check = checkCollisions(evt,rotatedEndPoint); // 2nd check // Rotates direction by -45 degrees on the Y axis q1.FromAngleAxis(Ogre::Radian(Ogre::Degree(-45.0f)), Ogre::Vector3::UNIT_Y); rotatedDirection = q1 * direction; // Scale the rotated direction so that it lengths the same as before // plus the collision radius of this event scaleDirection = rotatedDirection.normalise() + colRadius; rotatedDirection *= scaleDirection; // Calculates rotated end point rotatedEndPoint = endPoint + rotatedDirection; // Checks rotated end point against the walkmesh and restores // current triangle event information (it is changed by // walkmeshBorderCross()) second_triangle_check = walkmeshBorderCross(evt,rotatedEndPoint, &slideFactor); evt->setCurrentTriangle(curTri); if (second_triangle_check && slideFactor < finalSlideFactor) { finalSlideFactor = slideFactor; } // Checks rotated end point against other events second_entity_check = checkCollisions(evt,rotatedEndPoint); // 3rd check // The third check doesn't rotate the direction vector // It is the check responsible for checking whether there is a // collision directly to the front of our move vector rotatedDirection = direction; rotatedEndPoint = endPoint + rotatedDirection; // Scale the rotated direction so that it lengths the same as before // plus the collision radius of this event scaleDirection = rotatedDirection.normalise() + colRadius; rotatedDirection *= scaleDirection; // Checks end point against the walkmesh and restores // current triangle event information (it is changed by // walkmeshBorderCross()) third_triangle_check = walkmeshBorderCross(evt,rotatedEndPoint, &slideFactor); evt->setCurrentTriangle(curTri); if (third_triangle_check && slideFactor < finalSlideFactor) { finalSlideFactor = slideFactor; } // Checks end point against other events third_entity_check = checkCollisions(evt,rotatedEndPoint); // Apply slide factor direction *= finalSlideFactor; // Checks collision flags and modify `direction' vector accordingly, // and then rechecking // <todo> Do we really need to check whether no event collision is // happening? It doesn't make sense! if (first_triangle_check == true || second_triangle_check == true || third_triangle_check == true ) { // <todo> From here on I can't make heads or tails of this code // if not both left and right check was fail if (first_triangle_check == false || second_triangle_check == false) { if ( (first_triangle_check == false && first_entity_check == true ) || (first_triangle_check == true && second_triangle_check == false) ) { q1.FromAngleAxis(Ogre::Radian(Ogre::Degree(-11.25f)), Ogre::Vector3::UNIT_Y); direction = q1 * direction; } if ( first_triangle_check == false && first_entity_check == false && (second_triangle_check == true || second_entity_check == true) ) { q1.FromAngleAxis(Ogre::Radian(Ogre::Degree(11.25f)), Ogre::Vector3::UNIT_Y); direction = q1 * direction; } continue; } break; } } // Checks whether our final position is free last_triangle_check = walkmeshBorderCross(evt,endPoint); // Only sets final event position if no collide flags are // still set to true if (first_triangle_check == false && second_triangle_check == false && third_triangle_check == false && last_triangle_check == false && first_entity_check == false && second_entity_check == false && third_entity_check == false ) { evt->getSceneNode()->setPosition(endPoint); } } //------------------------------------------------------------------------- bool WalkmeshSubManager::setEventPosition(Event *evt, const Ogre::Vector3 &pos) { EventVector::iterator i = std::find(mEvents.begin(),mEvents.end(),evt); // Checks whether the event is registered or not if (i == mEvents.end()) { SONETTO_THROW("Event not registered with walkmesh"); } uint32 tri = 0; // Current nearest triangle found bool firstFound = true; // Flagged false when the first triangle is found float yNearest; // Y coordinate of the nearest triangle found Ogre::Vector3 vA,vB,vC; // Current nearest triangle vertices // Loops through each triangle in the walkmesh searching for the nearest // triangle from the given pos.y for (size_t i = 1;i <= mWalkmesh->triangles.size();++i) { // Gets the iterated triangle vertex coordinates const Ogre::Vector3 &vAtmp = mWalkmesh->getTriangleVertex(i,0); const Ogre::Vector3 &vBtmp = mWalkmesh->getTriangleVertex(i,1); const Ogre::Vector3 &vCtmp = mWalkmesh->getTriangleVertex(i,2); // If the given position `pos' is inside the iterated triangle, // we procceed with our tests if (Sonetto::Math::sideOfVector(pos,vBtmp,vAtmp) > 0.0f && Sonetto::Math::sideOfVector(pos,vCtmp,vBtmp) > 0.0f && Sonetto::Math::sideOfVector(pos,vAtmp,vCtmp) > 0.0f ) { // Gets the medium Y coordinate of this triangle float yCenter = (vAtmp.y + vBtmp.y + vCtmp.y) / 3; // If this is the first triangle found, we just set the // variables to describe it // Elsewise we need to check whether this new triangle is more // near to the event than the last one found if (firstFound) { yNearest = yCenter; vA = vAtmp; vB = vBtmp; vC = vCtmp; tri = i; firstFound = false; } else { // Gets distances between the event Y position and the iterated // triangle, and between the event Y position and the last triangle // position that was deemed to be the nearest to the event position float yDistance = pos.y - yCenter; float yOldDistance = pos.y - yNearest; // If this iterated triangle is more near to the event position than // the last one, we pick it to check against others if (fabs(yDistance) < fabs(yOldDistance)) { yNearest = yCenter; vA = vAtmp; vB = vBtmp; vC = vCtmp; tri = i; } } } } // If we have found a triangle (i.e. the event is effectively over the // walkmesh), we need to get the Y elevation on the desired XZ plane and // set the event position to these new coordinates if (tri != 0) { Ogre::Vector3 finalPos(pos); finalPos.y = Sonetto::Math::pointElevation(pos,vA,vB,vC); evt->getSceneNode()->setPosition(finalPos); evt->setCurrentTriangle(tri); // Returns true: Yes, the new position is set return true; } // Otherwise, returns false: Could not set position because the desired // position on the XZ plane was outside the walkmesh return false; } //------------------------------------------------------------------------- bool WalkmeshSubManager::isEventOverTriangle(Event *evt,uint32 triangleID) { const Ogre::Vector3 &vA = mWalkmesh->getTriangleVertex(triangleID,0); const Ogre::Vector3 &vB = mWalkmesh->getTriangleVertex(triangleID,1); const Ogre::Vector3 &vC = mWalkmesh->getTriangleVertex(triangleID,2); if (Sonetto::Math::sideOfVector(evt->getSceneNode()->getPosition(), vB,vA) > 0.0f && Sonetto::Math::sideOfVector(evt->getSceneNode()->getPosition(), vC,vB) > 0.0f && Sonetto::Math::sideOfVector(evt->getSceneNode()->getPosition(), vA,vC) > 0.0f ) { return true; } return false; } } // namespace
[ [ [ 1, 563 ] ] ]
7f597d98bbf3afa1e8c8364c0c35508ea9e99b04
cfcd2a448c91b249ea61d0d0d747129900e9e97f
/thirdparty/OpenCOLLADA/COLLADAFramework/include/COLLADAFWValueType.h
7d3ef0f6ea53e9963a59d3dd2a284b86829dfe0b
[]
no_license
fire-archive/OgreCollada
b1686b1b84b512ffee65baddb290503fb1ebac9c
49114208f176eb695b525dca4f79fc0cfd40e9de
refs/heads/master
2020-04-10T10:04:15.187350
2009-05-31T15:33:15
2009-05-31T15:33:15
268,046
0
0
null
null
null
null
UTF-8
C++
false
false
6,899
h
/* Copyright (c) 2008 NetAllied Systems GmbH This file is part of COLLADAFramework. Licensed under the MIT Open Source License, for details please see LICENSE file or the website http://www.opensource.org/licenses/mit-license.php */ #ifndef __COLLADAFW_VALUE_TYPE_H__ #define __COLLADAFW_VALUE_TYPE_H__ #include "COLLADAFWPrerequisites.h" #include "COLLADAFWConstants.h" #include "COLLADABUUtils.h" namespace COLLADAFW { /** Valid type elements are: bool, bool2, bool3, bool4, int, int2, int3, int4, float, float2, float3, float4, float2x2, float3x3, float4x4, string */ class ValueType { public: /** The datatype of the param's value. */ enum ColladaType { BOOL, BOOL2, BOOL3, BOOL4, INT, INT2, INT3, INT4, FLOAT, FLOAT2, FLOAT3, FLOAT4, FLOAT2x2, FLOAT3x3, FLOAT4x4, STRING, SURFACE, SAMPLER_1D, SAMPLER_2D, SAMPLER_3D, SAMPLER_CUBE, SAMPLER_RECT, SAMPLER_DEPTH, VALUE_TYPE_UNSPECIFIED }; public: /** Constructor. */ ValueType () {} /** Destructor. */ ~ValueType () {} /** Returns the param value type as string. */ static const String& getValueTypeAsString ( ColladaType colladaValueType ) { switch ( colladaValueType ) { case ValueType::BOOL: return Constants::VALUE_TYPE_BOOL; case ValueType::BOOL2: return Constants::VALUE_TYPE_BOOL2; case ValueType::BOOL3: return Constants::VALUE_TYPE_BOOL3; case ValueType::BOOL4: return Constants::VALUE_TYPE_BOOL4; case ValueType::INT: return Constants::VALUE_TYPE_INT; case ValueType::INT2: return Constants::VALUE_TYPE_INT2; case ValueType::INT3: return Constants::VALUE_TYPE_INT3; case ValueType::INT4: return Constants::VALUE_TYPE_INT4; case ValueType::FLOAT: return Constants::VALUE_TYPE_FLOAT; case ValueType::FLOAT2: return Constants::VALUE_TYPE_FLOAT2; case ValueType::FLOAT3: return Constants::VALUE_TYPE_FLOAT3; case ValueType::FLOAT4: return Constants::VALUE_TYPE_FLOAT4; case ValueType::FLOAT2x2: return Constants::VALUE_TYPE_FLOAT2x2; case ValueType::FLOAT3x3: return Constants::VALUE_TYPE_FLOAT3x3; case ValueType::FLOAT4x4: return Constants::VALUE_TYPE_FLOAT4x4; case ValueType::STRING: return Constants::VALUE_TYPE_STRING; case ValueType::SURFACE: return Constants::VALUE_TYPE_SURFACE; case ValueType::SAMPLER_1D: return Constants::VALUE_TYPE_SAMPLER_1D; case ValueType::SAMPLER_2D: return Constants::VALUE_TYPE_SAMPLER_2D; case ValueType::SAMPLER_3D: return Constants::VALUE_TYPE_SAMPLER_3D; case ValueType::SAMPLER_CUBE: return Constants::VALUE_TYPE_SAMPLER_CUBE; case ValueType::SAMPLER_RECT: return Constants::VALUE_TYPE_SAMPLER_RECT; case ValueType::SAMPLER_DEPTH: return Constants::VALUE_TYPE_SAMPLER_DEPTH; case ValueType::VALUE_TYPE_UNSPECIFIED: default: return Constants::EMPTY_STRING; } } static const ColladaType getValueTypeFromString ( const String& valueType ) { if ( COLLADABU::Utils::equalsIgnoreCase ( valueType, Constants::VALUE_TYPE_BOOL ) ) return ValueType::BOOL; if ( COLLADABU::Utils::equalsIgnoreCase ( valueType, Constants::VALUE_TYPE_BOOL2 ) ) return ValueType::BOOL2; if ( COLLADABU::Utils::equalsIgnoreCase ( valueType, Constants::VALUE_TYPE_BOOL3 ) ) return ValueType::BOOL3; if ( COLLADABU::Utils::equalsIgnoreCase ( valueType, Constants::VALUE_TYPE_BOOL4 ) ) return ValueType::BOOL4; if ( COLLADABU::Utils::equalsIgnoreCase ( valueType, Constants::VALUE_TYPE_INT ) ) return ValueType::INT; if ( COLLADABU::Utils::equalsIgnoreCase ( valueType, Constants::VALUE_TYPE_INT2 ) ) return ValueType::INT2; if ( COLLADABU::Utils::equalsIgnoreCase ( valueType, Constants::VALUE_TYPE_INT3 ) ) return ValueType::INT3; if ( COLLADABU::Utils::equalsIgnoreCase ( valueType, Constants::VALUE_TYPE_INT4 ) ) return ValueType::INT4; if ( COLLADABU::Utils::equalsIgnoreCase ( valueType, Constants::VALUE_TYPE_FLOAT ) ) return ValueType::FLOAT; if ( COLLADABU::Utils::equalsIgnoreCase ( valueType, Constants::VALUE_TYPE_FLOAT2 ) ) return ValueType::FLOAT2; if ( COLLADABU::Utils::equalsIgnoreCase ( valueType, Constants::VALUE_TYPE_FLOAT3 ) ) return ValueType::FLOAT3; if ( COLLADABU::Utils::equalsIgnoreCase ( valueType, Constants::VALUE_TYPE_FLOAT4 ) ) return ValueType::FLOAT4; if ( COLLADABU::Utils::equalsIgnoreCase ( valueType, Constants::VALUE_TYPE_FLOAT2x2 ) ) return ValueType::FLOAT2x2; if ( COLLADABU::Utils::equalsIgnoreCase ( valueType, Constants::VALUE_TYPE_FLOAT3x3 ) ) return ValueType::FLOAT3x3; if ( COLLADABU::Utils::equalsIgnoreCase ( valueType, Constants::VALUE_TYPE_FLOAT4x4 ) ) return ValueType::FLOAT4x4; if ( COLLADABU::Utils::equalsIgnoreCase ( valueType, Constants::VALUE_TYPE_STRING ) ) return ValueType::STRING; if ( COLLADABU::Utils::equalsIgnoreCase ( valueType, Constants::VALUE_TYPE_SURFACE ) ) return ValueType::SURFACE; if ( COLLADABU::Utils::equalsIgnoreCase ( valueType, Constants::VALUE_TYPE_SAMPLER_1D ) ) return ValueType::SAMPLER_1D; if ( COLLADABU::Utils::equalsIgnoreCase ( valueType, Constants::VALUE_TYPE_SAMPLER_2D ) ) return ValueType::SAMPLER_2D; if ( COLLADABU::Utils::equalsIgnoreCase ( valueType, Constants::VALUE_TYPE_SAMPLER_3D ) ) return ValueType::SAMPLER_3D; if ( COLLADABU::Utils::equalsIgnoreCase ( valueType, Constants::VALUE_TYPE_SAMPLER_CUBE ) ) return ValueType::SAMPLER_CUBE; if ( COLLADABU::Utils::equalsIgnoreCase ( valueType, Constants::VALUE_TYPE_SAMPLER_RECT ) ) return ValueType::SAMPLER_RECT; if ( COLLADABU::Utils::equalsIgnoreCase ( valueType, Constants::VALUE_TYPE_SAMPLER_DEPTH ) ) return ValueType::SAMPLER_DEPTH; return ValueType::VALUE_TYPE_UNSPECIFIED; } }; } #endif // __COLLADAFW_VALUE_TYPE_H__
[ [ [ 1, 139 ] ] ]
72b2fd7129e3e8ea04539fc359bb2f18ee1994e8
5d3c1be292f6153480f3a372befea4172c683180
/trunk/Event Heap/c++/Windows/include/idk_ne_InetAddress.h
fa56661ba2e9fa42b4beb8ec8cab4b228aa7dfda
[ "Artistic-2.0" ]
permissive
BackupTheBerlios/istuff-svn
5f47aa73dd74ecf5c55f83765a5c50daa28fa508
d0bb9963b899259695553ccd2b01b35be5fb83db
refs/heads/master
2016-09-06T04:54:24.129060
2008-05-02T22:33:26
2008-05-02T22:33:26
40,820,013
0
0
null
null
null
null
UTF-8
C++
false
false
2,523
h
/* Copyright (c) 2003 The Board of Trustees of The Leland Stanford Junior * University. All Rights Reserved. * * See the file LICENSE.txt for information on redistributing this software. */ /* $Id: idk_ne_InetAddress.h,v 1.5 2003/06/02 08:03:40 tomoto Exp $ */ #ifndef _IDK_NE_INETADDRESS_H_ #define _IDK_NE_INETADDRESS_H_ #include <idk_ne_Types.h> #include <idk_ut_TProxyObject.h> /** @file Definition of idk_ne_InetAddress class. */ class idki_ne_InetAddress; // impl /** This class represents an Internet address. Only supports IPv4. */ class IDK_DECL idk_ne_InetAddress : public idk_ut_TProxyObject<idki_ne_InetAddress> { private: friend class idki_ne_InetAddress; idk_ne_InetAddress(idki_ne_InetAddress* impl); public: ~idk_ne_InetAddress(); /** Creates an InetAddress object by host name. @param hostName Host name @returns New InetAddress object representing the specified host. @throws idk_ne_NetSystemException Network subsystem failure. @throws idk_ne_UnknownHostException Cannot resolve the host name. @throws idk_io_InterruptedIOException The operation was interrupted by a signal. */ static idk_ne_InetAddressPtr cs_createByName(const char* hostName); /** Creates an InetAddress object representing the localhost. @returns New InetAddress object representing the localhost. @throws idk_ne_NetSystemException Network subsystem failure. @throws idk_ut_UnknownHostException Cannot resolve the host name. @throws idk_io_InterruptedIOException The operation was interrupted by a signal. */ static idk_ne_InetAddressPtr cs_createLocalHost(); /** Clones the object. */ idk_ne_InetAddressPtr clone() const; /** Gets in_addr structure. This would not be useful in normal usage. @returns in_addr structure in the object. */ const in_addr& getAddress() const; /** Gets the host address in a string format like "192.168.0.1". @return a string representing the host address. */ const char* getHostAddress() const; /** Gets the host name. @return Host name. Not canonicalized. */ const char* getHostName() const; /** Returns the hash value of the object. */ int hashCode() const; /** Returns non-zero if the object is identical with the given object. Two InetAddress objects are identical when they holds the same IP address even if the host names are different. */ int equals(const idk_ne_InetAddress* other) const; }; #endif
[ "ballagas@2a53cb5c-8ff1-0310-8b75-b3ec22923d26" ]
[ [ [ 1, 90 ] ] ]
0aa9440018fbef65b222e6e089f26e68498cd7ec
fac8de123987842827a68da1b580f1361926ab67
/src/transporter/utilities/updateListenerMgr.cpp
b2c91da547a55a486d840ab3fd7952362093f2f5
[]
no_license
blockspacer/transporter-game
23496e1651b3c19f6727712a5652f8e49c45c076
083ae2ee48fcab2c7d8a68670a71be4d09954428
refs/heads/master
2021-05-31T04:06:07.101459
2009-02-19T20:59:59
2009-02-19T20:59:59
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,761
cpp
#include "transporter.h" static UpdateListenerMgr* volatile updateListenerMgr; void UpdateListenerMgr::destroyUpdateListenerMgr() { if(updateListenerMgr) { delete updateListenerMgr; updateListenerMgr = NULL; } } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 UpdateListenerMgr::UpdateListenerMgr() { InitializeCriticalSection(&lock); } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 UpdateListenerMgr::~UpdateListenerMgr() { EnterCriticalSection(&lock); listeners.clear(); LeaveCriticalSection(&lock); DeleteCriticalSection(&lock); } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 UpdateListenerMgr* UpdateListenerMgr::getInstance() { static UpdateListenerMgr* volatile selfPtr; if( selfPtr == NULL) { UpdateListenerMgr* newUpdateListenerMgr = new UpdateListenerMgr; LONG value = InterlockedCompareExchange((LONG*)&selfPtr,(LONG)newUpdateListenerMgr,NULL); if( value != NULL ) { delete newUpdateListenerMgr; } else { updateListenerMgr = selfPtr; atexit(destroyUpdateListenerMgr); } } return selfPtr; } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 void UpdateListenerMgr::addListener( UpdateListener* listener ) { EnterCriticalSection(&lock); std::vector<UpdateListener*>::iterator it = listeners.begin(); for(it ; it!=listeners.end() ; it++) { if(*it == listener) { LeaveCriticalSection(&lock); return; } } listeners.push_back(listener); LeaveCriticalSection(&lock); } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 void UpdateListenerMgr::removeListener( UpdateListener* listener ) { EnterCriticalSection(&lock); std::vector<UpdateListener*>::iterator it = listeners.begin(); for(it ; it!=listeners.end() ; it++) { if(*it == listener) { listeners.erase(it); break; } } LeaveCriticalSection(&lock); } //覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧 void UpdateListenerMgr::update( u32 evId,u32 param ) { EnterCriticalSection(&lock); std::vector<UpdateListener*>::iterator it = listeners.begin(); for(it ; it!=listeners.end() ; it++) { UpdateListener* listener = *it; listener->update(evId,param); } LeaveCriticalSection(&lock); }
[ "uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4" ]
[ [ [ 1, 100 ] ] ]
a9000b8ecd6f6d19063910b750338d9b470dad67
677f7dc99f7c3f2c6aed68f41c50fd31f90c1a1f
/SolidSBCTestLib/SolidSBCNetTcpResult.cpp
8a4f012d6cbcba6a822d2547a05e4e07535bbbad
[]
no_license
M0WA/SolidSBC
0d743c71ec7c6f8cfe78bd201d0eb59c2a8fc419
3e9682e90a22650e12338785c368ed69a9cac18b
refs/heads/master
2020-04-19T14:40:36.625222
2011-12-02T01:50:05
2011-12-02T01:50:05
168,250,374
0
0
null
null
null
null
UTF-8
C++
false
false
384
cpp
#include "StdAfx.h" #include "SolidSBCNetTcpResult.h" CSolidSBCNetTcpResult::CSolidSBCNetTcpResult(void) : CSolidSBCTestResult("testLib_NetTCPResults") { RegisterAttributeDataType("handshake_duration", DB_DOUBLE); } DOUBLE CSolidSBCNetTcpResult::GetDuration(void) { DOUBLE dValue = 0.0; GetKeyValue( "handshake_duration", dValue , (DOUBLE) 0.0 ); return dValue; }
[ "admin@bd7e3521-35e9-406e-9279-390287f868d3" ]
[ [ [ 1, 15 ] ] ]
84e33a4c4169bb8ecb1a2718b6e337451d8965cb
a86ab590320fbbf2c3d8cac5cea9622bef28944b
/include/imgCreator.hpp
a75a031fc67d0a22a189f04df506e098b9bba5c4
[]
no_license
wumingbo/itunes-habit
c6318344f8fa9ceded030a7b2bb7cbae36fb9032
79670b45ad253ab3f5d2c5c07547844ca49d283b
refs/heads/master
2021-01-22T15:21:37.165310
2010-06-30T06:15:48
2010-06-30T06:15:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
786
hpp
#pragma once #include <tchar.h> #include <map> #include <string> #include <vector> #include <iostream> using namespace std; #include <xercesc/dom/DOMElement.hpp> XERCES_CPP_NAMESPACE_USE class Creator { public: Creator() { cout << __FUNCTION__ << "\n"; } ~Creator() { cout << __FUNCTION__ << "\n"; } void createLastPlayedChart( const vector<const DOMElement *> & arr, LPCTSTR file, LPSTR font, int size) const; void createArtistGraph( const map<wstring, int> & i, const basic_string<TCHAR> & file ) const; void createDynaLastPlayed( const vector<const DOMElement *> & arr, const basic_string<TCHAR> & file ) const; private: };
[ "colin.diesh@37d2c1db-bb2f-0410-a901-09a4849b322f", "[email protected]", "Colin Diesh@Colin_Dell.(none)" ]
[ [ [ 1, 6 ], [ 8, 8 ], [ 10, 18 ], [ 21, 22 ], [ 26, 28 ], [ 31, 33 ], [ 36, 40 ] ], [ [ 7, 7 ], [ 9, 9 ], [ 19, 20 ], [ 23, 23 ], [ 29, 30 ], [ 34, 35 ] ], [ [ 24, 25 ] ] ]
4a5617b48f0bb62d4184f685109f9752192f1cca
9a48be80edc7692df4918c0222a1640545384dbb
/Libraries/Boost1.40/libs/filesystem/src/operations.cpp
9a9cc8df42b4329ffd7e7fb2e8f2682721fa194e
[ "BSL-1.0" ]
permissive
fcrick/RepSnapper
05e4fb1157f634acad575fffa2029f7f655b7940
a5809843f37b7162f19765e852b968648b33b694
refs/heads/master
2021-01-17T21:42:29.537504
2010-06-07T05:38:05
2010-06-07T05:38:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
50,832
cpp
// operations.cpp ----------------------------------------------------------// // Copyright 2002-2005 Beman Dawes // Copyright 2001 Dietmar Kuehl // Use, modification, and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy // at http://www.boost.org/LICENSE_1_0.txt) // See library home page at http://www.boost.org/libs/filesystem //----------------------------------------------------------------------------// // define BOOST_FILESYSTEM_SOURCE so that <boost/filesystem/config.hpp> knows // the library is being built (possibly exporting rather than importing code) #define BOOST_FILESYSTEM_SOURCE #define _POSIX_PTHREAD_SEMANTICS // Sun readdir_r() needs this // enable the XPG-compliant version of readdir_r() on AIX #if defined(_AIX) # define _LINUX_SOURCE_COMPAT #endif #if !(defined(__HP_aCC) && defined(_ILP32) && \ !defined(_STATVFS_ACPP_PROBLEMS_FIXED)) #define _FILE_OFFSET_BITS 64 // at worst, these defines may have no effect, #endif #define __USE_FILE_OFFSET64 // but that is harmless on Windows and on POSIX // 64-bit systems or on 32-bit systems which don't have files larger // than can be represented by a traditional POSIX/UNIX off_t type. // OTOH, defining them should kick in 64-bit off_t's (and thus // st_size) on 32-bit systems that provide the Large File // Support (LFS) interface, such as Linux, Solaris, and IRIX. // The defines are given before any headers are included to // ensure that they are available to all included headers. // That is required at least on Solaris, and possibly on other // systems as well. // for some compilers (CodeWarrior, for example), windows.h // is getting included by some other boost header, so do this early: #if !defined(_WIN32_WINNT) #define _WIN32_WINNT 0x0500 // Default to Windows 2K or later #endif #include <boost/filesystem/operations.hpp> #include <boost/scoped_array.hpp> #include <boost/throw_exception.hpp> #include <boost/detail/workaround.hpp> namespace fs = boost::filesystem; using boost::system::error_code; using boost::system::system_category; # if defined(BOOST_WINDOWS_API) # include <windows.h> # include <ctime> // for time_t # else // BOOST_POSIX_API # include <sys/types.h> # if !defined(__APPLE__) && !defined(__OpenBSD__) # include <sys/statvfs.h> # define BOOST_STATVFS statvfs # define BOOST_STATVFS_F_FRSIZE vfs.f_frsize # else #ifdef __OpenBSD__ # include <sys/param.h> #endif # include <sys/mount.h> # define BOOST_STATVFS statfs # define BOOST_STATVFS_F_FRSIZE static_cast<boost::uintmax_t>( vfs.f_bsize ) # endif # include <dirent.h> # include <unistd.h> # include <fcntl.h> # include <utime.h> # include "limits.h" # endif // BOOST_FILESYSTEM_STATUS_CACHE enables file_status cache in // dir_itr_increment. The config tests are placed here because some of the // macros being tested come from dirent.h. // // TODO: find out what macros indicate dirent::d_type present in more libraries # if defined(BOOST_WINDOWS_API) \ || (defined(_DIRENT_HAVE_D_TYPE) /* defined by GNU C library if d_type present */ \ && !(defined(__SUNPRO_CC) && !defined(__sun))) // _DIRENT_HAVE_D_TYPE wrong for Sun compiler on Linux # define BOOST_FILESYSTEM_STATUS_CACHE # endif #include <sys/stat.h> // even on Windows some functions use stat() #include <string> #include <cstring> #include <cstdio> // for remove, rename #include <cerrno> #include <cassert> // #include <iostream> // for debugging only; comment out when not in use #ifdef BOOST_NO_STDC_NAMESPACE namespace std { using ::strcmp; using ::remove; using ::rename; } #endif // helpers -----------------------------------------------------------------// namespace { const error_code ok; bool is_empty_directory( const std::string & dir_path ) { static const fs::directory_iterator end_itr; return fs::directory_iterator(fs::path(dir_path)) == end_itr; } #ifdef BOOST_WINDOWS_API // For Windows, the xxxA form of various function names is used to avoid // inadvertently getting wide forms of the functions. (The undecorated // forms are actually macros, so can misfire if the user has various // other macros defined. There was a bug report of this happening.) inline DWORD get_file_attributes( const char * ph ) { return ::GetFileAttributesA( ph ); } # ifndef BOOST_FILESYSTEM_NARROW_ONLY inline DWORD get_file_attributes( const wchar_t * ph ) { return ::GetFileAttributesW( ph ); } bool is_empty_directory( const std::wstring & dir_path ) { static const fs::wdirectory_iterator wend_itr; return fs::wdirectory_iterator(fs::wpath(dir_path)) == wend_itr; } inline BOOL get_file_attributes_ex( const wchar_t * ph, WIN32_FILE_ATTRIBUTE_DATA & fad ) { return ::GetFileAttributesExW( ph, ::GetFileExInfoStandard, &fad ); } HANDLE create_file( const wchar_t * ph, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile ) { return ::CreateFileW( ph, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile ); } inline DWORD get_current_directory( DWORD sz, wchar_t * buf ) { return ::GetCurrentDirectoryW( sz, buf ); } inline bool set_current_directory( const wchar_t * buf ) { return ::SetCurrentDirectoryW( buf ) != 0 ; } inline bool get_free_disk_space( const std::wstring & ph, PULARGE_INTEGER avail, PULARGE_INTEGER total, PULARGE_INTEGER free ) { return ::GetDiskFreeSpaceExW( ph.c_str(), avail, total, free ) != 0; } inline std::size_t get_full_path_name( const std::wstring & ph, std::size_t len, wchar_t * buf, wchar_t ** p ) { return static_cast<std::size_t>( ::GetFullPathNameW( ph.c_str(), static_cast<DWORD>(len), buf, p )); } inline bool remove_directory( const std::wstring & ph ) { return ::RemoveDirectoryW( ph.c_str() ) != 0; } inline bool delete_file( const std::wstring & ph ) { return ::DeleteFileW( ph.c_str() ) != 0; } inline bool create_directory( const std::wstring & dir ) { return ::CreateDirectoryW( dir.c_str(), 0 ) != 0; } #if _WIN32_WINNT >= 0x500 inline bool create_hard_link( const std::wstring & to_ph, const std::wstring & from_ph ) { return ::CreateHardLinkW( from_ph.c_str(), to_ph.c_str(), 0 ) != 0; } #endif # endif // ifndef BOOST_FILESYSTEM_NARROW_ONLY template< class String > fs::file_status status_template( const String & ph, error_code & ec ) { DWORD attr( get_file_attributes( ph.c_str() ) ); if ( attr == 0xFFFFFFFF ) { ec = error_code( ::GetLastError(), system_category ); if ((ec.value() == ERROR_FILE_NOT_FOUND) || (ec.value() == ERROR_PATH_NOT_FOUND) || (ec.value() == ERROR_INVALID_NAME) // "tools/jam/src/:sys:stat.h", "//foo" || (ec.value() == ERROR_INVALID_DRIVE) // USB card reader with no card inserted || (ec.value() == ERROR_INVALID_PARAMETER) // ":sys:stat.h" || (ec.value() == ERROR_BAD_PATHNAME) // "//nosuch" on Win64 || (ec.value() == ERROR_BAD_NETPATH)) // "//nosuch" on Win32 { ec = ok; // these are not considered errors; // the status is considered not found return fs::file_status( fs::file_not_found ); } else if ((ec.value() == ERROR_SHARING_VIOLATION)) { ec = ok; // these are not considered errors; // the file exists but the type is not known return fs::file_status( fs::type_unknown ); } return fs::file_status( fs::status_unknown ); } ec = ok;; return (attr & FILE_ATTRIBUTE_DIRECTORY) ? fs::file_status( fs::directory_file ) : fs::file_status( fs::regular_file ); } BOOL get_file_attributes_ex( const char * ph, WIN32_FILE_ATTRIBUTE_DATA & fad ) { return ::GetFileAttributesExA( ph, ::GetFileExInfoStandard, &fad ); } template< class String > boost::filesystem::detail::query_pair is_empty_template( const String & ph ) { WIN32_FILE_ATTRIBUTE_DATA fad; if ( get_file_attributes_ex( ph.c_str(), fad ) == 0 ) return std::make_pair( error_code( ::GetLastError(), system_category ), false ); return std::make_pair( ok, ( fad.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) ? is_empty_directory( ph ) :( !fad.nFileSizeHigh && !fad.nFileSizeLow ) ); } HANDLE create_file( const char * ph, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile ) { return ::CreateFileA( ph, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile ); } // Thanks to Jeremy Maitin-Shepard for much help and for permission to // base the equivalent() implementation on portions of his // file-equivalence-win32.cpp experimental code. struct handle_wrapper { HANDLE handle; handle_wrapper( HANDLE h ) : handle(h) {} ~handle_wrapper() { if ( handle != INVALID_HANDLE_VALUE ) ::CloseHandle(handle); } }; template< class String > boost::filesystem::detail::query_pair equivalent_template( const String & ph1, const String & ph2 ) { // Note well: Physical location on external media is part of the // equivalence criteria. If there are no open handles, physical location // can change due to defragmentation or other relocations. Thus handles // must be held open until location information for both paths has // been retrieved. handle_wrapper p1( create_file( ph1.c_str(), 0, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0 ) ); int error1(0); // save error code in case we have to throw if ( p1.handle == INVALID_HANDLE_VALUE ) error1 = ::GetLastError(); handle_wrapper p2( create_file( ph2.c_str(), 0, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0 ) ); if ( p1.handle == INVALID_HANDLE_VALUE || p2.handle == INVALID_HANDLE_VALUE ) { if ( p1.handle != INVALID_HANDLE_VALUE || p2.handle != INVALID_HANDLE_VALUE ) { return std::make_pair( ok, false ); } assert( p1.handle == INVALID_HANDLE_VALUE && p2.handle == INVALID_HANDLE_VALUE ); { return std::make_pair( error_code( error1, system_category), false ); } } // at this point, both handles are known to be valid BY_HANDLE_FILE_INFORMATION info1, info2; if ( !::GetFileInformationByHandle( p1.handle, &info1 ) ) { return std::make_pair( error_code( ::GetLastError(), system_category ), false ); } if ( !::GetFileInformationByHandle( p2.handle, &info2 ) ) { return std::make_pair( error_code( ::GetLastError(), system_category ), false ); } // In theory, volume serial numbers are sufficient to distinguish between // devices, but in practice VSN's are sometimes duplicated, so last write // time and file size are also checked. return std::make_pair( ok, info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber && info1.nFileIndexHigh == info2.nFileIndexHigh && info1.nFileIndexLow == info2.nFileIndexLow && info1.nFileSizeHigh == info2.nFileSizeHigh && info1.nFileSizeLow == info2.nFileSizeLow && info1.ftLastWriteTime.dwLowDateTime == info2.ftLastWriteTime.dwLowDateTime && info1.ftLastWriteTime.dwHighDateTime == info2.ftLastWriteTime.dwHighDateTime ); } template< class String > boost::filesystem::detail::uintmax_pair file_size_template( const String & ph ) { WIN32_FILE_ATTRIBUTE_DATA fad; // by now, intmax_t is 64-bits on all Windows compilers if ( get_file_attributes_ex( ph.c_str(), fad ) == 0 ) return std::make_pair( error_code( ::GetLastError(), system_category ), 0 ); if ( (fad.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) !=0 ) return std::make_pair( error_code( ERROR_FILE_NOT_FOUND, system_category), 0 ); return std::make_pair( ok, (static_cast<boost::uintmax_t>(fad.nFileSizeHigh) << (sizeof(fad.nFileSizeLow)*8)) + fad.nFileSizeLow ); } inline bool get_free_disk_space( const std::string & ph, PULARGE_INTEGER avail, PULARGE_INTEGER total, PULARGE_INTEGER free ) { return ::GetDiskFreeSpaceExA( ph.c_str(), avail, total, free ) != 0; } template< class String > boost::filesystem::detail::space_pair space_template( String & ph ) { ULARGE_INTEGER avail, total, free; boost::filesystem::detail::space_pair result; if ( get_free_disk_space( ph, &avail, &total, &free ) ) { result.first = ok; result.second.capacity = (static_cast<boost::uintmax_t>(total.HighPart) << 32) + total.LowPart; result.second.free = (static_cast<boost::uintmax_t>(free.HighPart) << 32) + free.LowPart; result.second.available = (static_cast<boost::uintmax_t>(avail.HighPart) << 32) + avail.LowPart; } else { result.first = error_code( ::GetLastError(), system_category ); result.second.capacity = result.second.free = result.second.available = 0; } return result; } inline DWORD get_current_directory( DWORD sz, char * buf ) { return ::GetCurrentDirectoryA( sz, buf ); } template< class String > error_code get_current_path_template( String & ph ) { DWORD sz; if ( (sz = get_current_directory( 0, static_cast<typename String::value_type*>(0) )) == 0 ) { sz = 1; } typedef typename String::value_type value_type; boost::scoped_array<value_type> buf( new value_type[sz] ); if ( get_current_directory( sz, buf.get() ) == 0 ) return error_code( ::GetLastError(), system_category ); ph = buf.get(); return ok; } inline bool set_current_directory( const char * buf ) { return ::SetCurrentDirectoryA( buf ) != 0; } template< class String > error_code set_current_path_template( const String & ph ) { return error_code( set_current_directory( ph.c_str() ) ? 0 : ::GetLastError(), system_category ); } inline std::size_t get_full_path_name( const std::string & ph, std::size_t len, char * buf, char ** p ) { return static_cast<std::size_t>( ::GetFullPathNameA( ph.c_str(), static_cast<DWORD>(len), buf, p )); } const std::size_t buf_size( 128 ); template<class String> error_code get_full_path_name_template( const String & ph, String & target ) { typename String::value_type buf[buf_size]; typename String::value_type * pfn; std::size_t len = get_full_path_name( ph, buf_size , buf, &pfn ); if ( len == 0 ) return error_code( ::GetLastError(), system_category ); if ( len > buf_size ) { typedef typename String::value_type value_type; boost::scoped_array<value_type> big_buf( new value_type[len] ); if ( (len=get_full_path_name( ph, len , big_buf.get(), &pfn )) == 0 ) return error_code( ::GetLastError(), system_category ); big_buf[len] = '\0'; target = big_buf.get(); return ok; } buf[len] = '\0'; target = buf; return ok; } template<class String> error_code get_file_write_time( const String & ph, FILETIME & last_write_time ) { handle_wrapper hw( create_file( ph.c_str(), 0, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0 ) ); if ( hw.handle == INVALID_HANDLE_VALUE ) return error_code( ::GetLastError(), system_category ); return error_code( ::GetFileTime( hw.handle, 0, 0, &last_write_time ) != 0 ? 0 : ::GetLastError(), system_category ); } template<class String> error_code set_file_write_time( const String & ph, const FILETIME & last_write_time ) { handle_wrapper hw( create_file( ph.c_str(), FILE_WRITE_ATTRIBUTES, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0 ) ); if ( hw.handle == INVALID_HANDLE_VALUE ) return error_code( ::GetLastError(), system_category ); return error_code( ::SetFileTime( hw.handle, 0, 0, &last_write_time ) != 0 ? 0 : ::GetLastError(), system_category ); } // these constants come from inspecting some Microsoft sample code std::time_t to_time_t( const FILETIME & ft ) { __int64 t = (static_cast<__int64>( ft.dwHighDateTime ) << 32) + ft.dwLowDateTime; # if !defined( BOOST_MSVC ) || BOOST_MSVC > 1300 // > VC++ 7.0 t -= 116444736000000000LL; # else t -= 116444736000000000; # endif t /= 10000000; return static_cast<std::time_t>( t ); } void to_FILETIME( std::time_t t, FILETIME & ft ) { __int64 temp = t; temp *= 10000000; # if !defined( BOOST_MSVC ) || BOOST_MSVC > 1300 // > VC++ 7.0 temp += 116444736000000000LL; # else temp += 116444736000000000; # endif ft.dwLowDateTime = static_cast<DWORD>( temp ); ft.dwHighDateTime = static_cast<DWORD>( temp >> 32 ); } template<class String> boost::filesystem::detail::time_pair last_write_time_template( const String & ph ) { FILETIME lwt; error_code ec( get_file_write_time( ph, lwt ) ); return std::make_pair( ec, to_time_t( lwt ) ); } template<class String> error_code last_write_time_template( const String & ph, const std::time_t new_time ) { FILETIME lwt; to_FILETIME( new_time, lwt ); return set_file_write_time( ph, lwt ); } bool remove_directory( const std::string & ph ) { return ::RemoveDirectoryA( ph.c_str() ) != 0; } bool delete_file( const std::string & ph ) { return ::DeleteFileA( ph.c_str() ) != 0; } template<class String> error_code remove_template( const String & ph ) { // TODO: test this code in the presence of Vista symlinks, // including dangling, self-referal, and cyclic symlinks error_code ec; fs::file_status sf( fs::detail::status_api( ph, ec ) ); if ( ec ) return ec; if ( sf.type() == fs::file_not_found ) return ok; if ( fs::is_directory( sf ) ) { if ( !remove_directory( ph ) ) return error_code(::GetLastError(), system_category); } else { if ( !delete_file( ph ) ) return error_code(::GetLastError(), system_category); } return ok; } inline bool create_directory( const std::string & dir ) { return ::CreateDirectoryA( dir.c_str(), 0 ) != 0; } template<class String> boost::filesystem::detail::query_pair create_directory_template( const String & dir_ph ) { error_code error, dummy; if ( create_directory( dir_ph ) ) return std::make_pair( error, true ); error = error_code( ::GetLastError(), system_category ); // an error here may simply mean the postcondition is already met if ( error.value() == ERROR_ALREADY_EXISTS && fs::is_directory( fs::detail::status_api( dir_ph, dummy ) ) ) return std::make_pair( ok, false ); return std::make_pair( error, false ); } #if _WIN32_WINNT >= 0x500 inline bool create_hard_link( const std::string & to_ph, const std::string & from_ph ) { return ::CreateHardLinkA( from_ph.c_str(), to_ph.c_str(), 0 ) != 0; } #endif #if _WIN32_WINNT >= 0x500 template<class String> error_code create_hard_link_template( const String & to_ph, const String & from_ph ) { return error_code( create_hard_link( to_ph.c_str(), from_ph.c_str() ) ? 0 : ::GetLastError(), system_category ); } #endif #else // BOOST_POSIX_API int posix_remove( const char * p ) { # if defined(__QNXNTO__) || (defined(__MSL__) && (defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__))) // Some Metrowerks C library versions fail on directories because of a // known Metrowerks coding error in ::remove. Workaround is to call // rmdir() or unlink() as indicated. // Same bug also reported for QNX, with the same fix. int err = ::unlink( p ); if ( err == 0 || errno != EPERM ) return err; return ::rmdir( p ); # else return std::remove( p ); # endif } #endif } // unnamed namespace namespace boost { namespace filesystem { namespace detail { BOOST_FILESYSTEM_DECL system::error_code throws; // free functions ----------------------------------------------------------// BOOST_FILESYSTEM_DECL error_code not_found_error() { # ifdef BOOST_WINDOWS_API return error_code(ERROR_PATH_NOT_FOUND, system_category); # else return error_code(ENOENT, system_category); # endif } BOOST_FILESYSTEM_DECL bool possible_large_file_size_support() { # ifdef BOOST_POSIX_API struct stat lcl_stat; return sizeof( lcl_stat.st_size ) > 4; # else return true; # endif } # ifdef BOOST_WINDOWS_API BOOST_FILESYSTEM_DECL fs::file_status status_api( const std::string & ph, error_code & ec ) { return status_template( ph, ec ); } # ifndef BOOST_FILESYSTEM_NARROW_ONLY BOOST_FILESYSTEM_DECL fs::file_status status_api( const std::wstring & ph, error_code & ec ) { return status_template( ph, ec ); } BOOST_FILESYSTEM_DECL bool symbolic_link_exists_api( const std::wstring & ) { return false; } BOOST_FILESYSTEM_DECL fs::detail::query_pair is_empty_api( const std::wstring & ph ) { return is_empty_template( ph ); } BOOST_FILESYSTEM_DECL fs::detail::query_pair equivalent_api( const std::wstring & ph1, const std::wstring & ph2 ) { return equivalent_template( ph1, ph2 ); } BOOST_FILESYSTEM_DECL fs::detail::uintmax_pair file_size_api( const std::wstring & ph ) { return file_size_template( ph ); } BOOST_FILESYSTEM_DECL fs::detail::space_pair space_api( const std::wstring & ph ) { return space_template( ph ); } BOOST_FILESYSTEM_DECL error_code get_current_path_api( std::wstring & ph ) { return get_current_path_template( ph ); } BOOST_FILESYSTEM_DECL error_code set_current_path_api( const std::wstring & ph ) { return set_current_path_template( ph ); } BOOST_FILESYSTEM_DECL error_code get_full_path_name_api( const std::wstring & ph, std::wstring & target ) { return get_full_path_name_template( ph, target ); } BOOST_FILESYSTEM_DECL time_pair last_write_time_api( const std::wstring & ph ) { return last_write_time_template( ph ); } BOOST_FILESYSTEM_DECL error_code last_write_time_api( const std::wstring & ph, std::time_t new_value ) { return last_write_time_template( ph, new_value ); } BOOST_FILESYSTEM_DECL fs::detail::query_pair create_directory_api( const std::wstring & ph ) { return create_directory_template( ph ); } #if _WIN32_WINNT >= 0x500 BOOST_FILESYSTEM_DECL error_code create_hard_link_api( const std::wstring & to_ph, const std::wstring & from_ph ) { return create_hard_link_template( to_ph, from_ph ); } #endif BOOST_FILESYSTEM_DECL error_code create_symlink_api( const std::wstring & /*to_ph*/, const std::wstring & /*from_ph*/ ) { return error_code( ERROR_NOT_SUPPORTED, system_category ); } BOOST_FILESYSTEM_DECL error_code remove_api( const std::wstring & ph ) { return remove_template( ph ); } BOOST_FILESYSTEM_DECL error_code rename_api( const std::wstring & from, const std::wstring & to ) { return error_code( ::MoveFileW( from.c_str(), to.c_str() ) ? 0 : ::GetLastError(), system_category ); } BOOST_FILESYSTEM_DECL error_code copy_file_api( const std::wstring & from, const std::wstring & to, bool fail_if_exists ) { return error_code( ::CopyFileW( from.c_str(), to.c_str(), fail_if_exists ) ? 0 : ::GetLastError(), system_category ); } BOOST_FILESYSTEM_DECL bool create_file_api( const std::wstring & ph, std::ios_base::openmode mode ) // true if succeeds { DWORD access( ((mode & std::ios_base::in) == 0 ? 0 : GENERIC_READ) | ((mode & std::ios_base::out) == 0 ? 0 : GENERIC_WRITE) ); DWORD disposition(0); // see 27.8.1.3 Table 92 if ( (mode&~std::ios_base::binary) == (std::ios_base::out|std::ios_base::app) ) disposition = OPEN_ALWAYS; else if ( (mode&~(std::ios_base::binary|std::ios_base::out)) == std::ios_base::in ) disposition = OPEN_EXISTING; else if ( ((mode&~(std::ios_base::binary|std::ios_base::trunc)) == std::ios_base::out ) || ((mode&~std::ios_base::binary) == (std::ios_base::in|std::ios_base::out|std::ios_base::trunc)) ) disposition = CREATE_ALWAYS; else assert( 0 && "invalid mode argument" ); HANDLE handle ( ::CreateFileW( ph.c_str(), access, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, 0, disposition, (mode &std::ios_base::out) != 0 ? FILE_ATTRIBUTE_ARCHIVE : FILE_ATTRIBUTE_NORMAL, 0 ) ); if ( handle == INVALID_HANDLE_VALUE ) return false; ::CloseHandle( handle ); return true; } BOOST_FILESYSTEM_DECL std::string narrow_path_api( const std::wstring & ph ) // return is empty if fails { std::string narrow_short_form; std::wstring short_form; for ( DWORD buf_sz( static_cast<DWORD>( ph.size()+1 ));; ) { boost::scoped_array<wchar_t> buf( new wchar_t[buf_sz] ); DWORD sz( ::GetShortPathNameW( ph.c_str(), buf.get(), buf_sz ) ); if ( sz == 0 ) return narrow_short_form; if ( sz <= buf_sz ) { short_form += buf.get(); break; } buf_sz = sz + 1; } // contributed by Takeshi Mouri: int narrow_sz( ::WideCharToMultiByte( CP_ACP, 0, short_form.c_str(), static_cast<int>(short_form.size()), 0, 0, 0, 0 ) ); boost::scoped_array<char> narrow_buf( new char[narrow_sz] ); ::WideCharToMultiByte( CP_ACP, 0, short_form.c_str(), static_cast<int>(short_form.size()), narrow_buf.get(), narrow_sz, 0, 0 ); narrow_short_form.assign(narrow_buf.get(), narrow_sz); return narrow_short_form; } BOOST_FILESYSTEM_DECL error_code dir_itr_first( void *& handle, const std::wstring & dir, std::wstring & target, file_status & sf, file_status & symlink_sf ) { // use a form of search Sebastian Martel reports will work with Win98 std::wstring dirpath( dir ); dirpath += (dirpath.empty() || dirpath[dirpath.size()-1] != L'\\') ? L"\\*" : L"*"; WIN32_FIND_DATAW data; if ( (handle = ::FindFirstFileW( dirpath.c_str(), &data )) == INVALID_HANDLE_VALUE ) { handle = 0; return error_code( ::GetLastError() == ERROR_FILE_NOT_FOUND ? 0 : ::GetLastError(), system_category ); } target = data.cFileName; if ( data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) { sf.type( directory_file ); symlink_sf.type( directory_file ); } else { sf.type( regular_file ); symlink_sf.type( regular_file ); } return ok; } BOOST_FILESYSTEM_DECL error_code dir_itr_increment( void *& handle, std::wstring & target, file_status & sf, file_status & symlink_sf ) { WIN32_FIND_DATAW data; if ( ::FindNextFileW( handle, &data ) == 0 ) // fails { int error = ::GetLastError(); dir_itr_close( handle ); return error_code( error == ERROR_NO_MORE_FILES ? 0 : error, system_category ); } target = data.cFileName; if ( data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) { sf.type( directory_file ); symlink_sf.type( directory_file ); } else { sf.type( regular_file ); symlink_sf.type( regular_file ); } return ok; } # endif // ifndef BOOST_FILESYSTEM_NARROW_ONLY // suggested by Walter Landry BOOST_FILESYSTEM_DECL bool symbolic_link_exists_api( const std::string & ) { return false; } BOOST_FILESYSTEM_DECL fs::detail::query_pair is_empty_api( const std::string & ph ) { return is_empty_template( ph ); } BOOST_FILESYSTEM_DECL fs::detail::query_pair equivalent_api( const std::string & ph1, const std::string & ph2 ) { return equivalent_template( ph1, ph2 ); } BOOST_FILESYSTEM_DECL fs::detail::uintmax_pair file_size_api( const std::string & ph ) { return file_size_template( ph ); } BOOST_FILESYSTEM_DECL fs::detail::space_pair space_api( const std::string & ph ) { return space_template( ph ); } BOOST_FILESYSTEM_DECL error_code get_current_path_api( std::string & ph ) { return get_current_path_template( ph ); } BOOST_FILESYSTEM_DECL error_code set_current_path_api( const std::string & ph ) { return set_current_path_template( ph ); } BOOST_FILESYSTEM_DECL error_code get_full_path_name_api( const std::string & ph, std::string & target ) { return get_full_path_name_template( ph, target ); } BOOST_FILESYSTEM_DECL time_pair last_write_time_api( const std::string & ph ) { return last_write_time_template( ph ); } BOOST_FILESYSTEM_DECL error_code last_write_time_api( const std::string & ph, std::time_t new_value ) { return last_write_time_template( ph, new_value ); } BOOST_FILESYSTEM_DECL fs::detail::query_pair create_directory_api( const std::string & ph ) { return create_directory_template( ph ); } #if _WIN32_WINNT >= 0x500 BOOST_FILESYSTEM_DECL error_code create_hard_link_api( const std::string & to_ph, const std::string & from_ph ) { return create_hard_link_template( to_ph, from_ph ); } #endif BOOST_FILESYSTEM_DECL error_code create_symlink_api( const std::string & /*to_ph*/, const std::string & /*from_ph*/ ) { return error_code( ERROR_NOT_SUPPORTED, system_category ); } BOOST_FILESYSTEM_DECL error_code remove_api( const std::string & ph ) { return remove_template( ph ); } BOOST_FILESYSTEM_DECL error_code rename_api( const std::string & from, const std::string & to ) { return error_code( ::MoveFileA( from.c_str(), to.c_str() ) ? 0 : ::GetLastError(), system_category ); } BOOST_FILESYSTEM_DECL error_code copy_file_api( const std::string & from, const std::string & to, bool fail_if_exists ) { return error_code( ::CopyFileA( from.c_str(), to.c_str(), fail_if_exists ) ? 0 : ::GetLastError(), system_category ); } BOOST_FILESYSTEM_DECL error_code dir_itr_first( void *& handle, const std::string & dir, std::string & target, file_status & sf, file_status & symlink_sf ) // Note: an empty root directory has no "." or ".." entries, so this // causes a ERROR_FILE_NOT_FOUND error which we do not considered an // error. It is treated as eof instead. { // use a form of search Sebastian Martel reports will work with Win98 std::string dirpath( dir ); dirpath += (dirpath.empty() || (dirpath[dirpath.size()-1] != '\\' && dirpath[dirpath.size()-1] != ':')) ? "\\*" : "*"; WIN32_FIND_DATAA data; if ( (handle = ::FindFirstFileA( dirpath.c_str(), &data )) == INVALID_HANDLE_VALUE ) { handle = 0; return error_code( ::GetLastError() == ERROR_FILE_NOT_FOUND ? 0 : ::GetLastError(), system_category ); } target = data.cFileName; if ( data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) { sf.type( directory_file ); symlink_sf.type( directory_file ); } else { sf.type( regular_file ); symlink_sf.type( regular_file ); } return ok; } BOOST_FILESYSTEM_DECL error_code dir_itr_close( void *& handle ) { if ( handle != 0 ) { bool ok = ::FindClose( handle ) != 0; handle = 0; return error_code( ok ? 0 : ::GetLastError(), system_category ); } return ok; } BOOST_FILESYSTEM_DECL error_code dir_itr_increment( void *& handle, std::string & target, file_status & sf, file_status & symlink_sf ) { WIN32_FIND_DATAA data; if ( ::FindNextFileA( handle, &data ) == 0 ) // fails { int error = ::GetLastError(); dir_itr_close( handle ); return error_code( error == ERROR_NO_MORE_FILES ? 0 : error, system_category ); } target = data.cFileName; if ( data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) { sf.type( directory_file ); symlink_sf.type( directory_file ); } else { sf.type( regular_file ); symlink_sf.type( regular_file ); } return ok; } # else // BOOST_POSIX_API BOOST_FILESYSTEM_DECL fs::file_status status_api( const std::string & ph, error_code & ec ) { struct stat path_stat; if ( ::stat( ph.c_str(), &path_stat ) != 0 ) { if ( errno == ENOENT || errno == ENOTDIR ) { ec = ok; return fs::file_status( fs::file_not_found ); } ec = error_code( errno, system_category ); return fs::file_status( fs::status_unknown ); } ec = ok; if ( S_ISDIR( path_stat.st_mode ) ) return fs::file_status( fs::directory_file ); if ( S_ISREG( path_stat.st_mode ) ) return fs::file_status( fs::regular_file ); if ( S_ISBLK( path_stat.st_mode ) ) return fs::file_status( fs::block_file ); if ( S_ISCHR( path_stat.st_mode ) ) return fs::file_status( fs::character_file ); if ( S_ISFIFO( path_stat.st_mode ) ) return fs::file_status( fs::fifo_file ); if ( S_ISSOCK( path_stat.st_mode ) ) return fs::file_status( fs::socket_file ); return fs::file_status( fs::type_unknown ); } BOOST_FILESYSTEM_DECL fs::file_status symlink_status_api( const std::string & ph, error_code & ec ) { struct stat path_stat; if ( ::lstat( ph.c_str(), &path_stat ) != 0 ) { if ( errno == ENOENT || errno == ENOTDIR ) { ec = ok; return fs::file_status( fs::file_not_found ); } ec = error_code( errno, system_category ); return fs::file_status( fs::status_unknown ); } ec = ok; if ( S_ISREG( path_stat.st_mode ) ) return fs::file_status( fs::regular_file ); if ( S_ISDIR( path_stat.st_mode ) ) return fs::file_status( fs::directory_file ); if ( S_ISLNK( path_stat.st_mode ) ) return fs::file_status( fs::symlink_file ); if ( S_ISBLK( path_stat.st_mode ) ) return fs::file_status( fs::block_file ); if ( S_ISCHR( path_stat.st_mode ) ) return fs::file_status( fs::character_file ); if ( S_ISFIFO( path_stat.st_mode ) ) return fs::file_status( fs::fifo_file ); if ( S_ISSOCK( path_stat.st_mode ) ) return fs::file_status( fs::socket_file ); return fs::file_status( fs::type_unknown ); } // suggested by Walter Landry BOOST_FILESYSTEM_DECL bool symbolic_link_exists_api( const std::string & ph ) { struct stat path_stat; return ::lstat( ph.c_str(), &path_stat ) == 0 && S_ISLNK( path_stat.st_mode ); } BOOST_FILESYSTEM_DECL query_pair is_empty_api( const std::string & ph ) { struct stat path_stat; if ( (::stat( ph.c_str(), &path_stat )) != 0 ) return std::make_pair( error_code( errno, system_category ), false ); return std::make_pair( ok, S_ISDIR( path_stat.st_mode ) ? is_empty_directory( ph ) : path_stat.st_size == 0 ); } BOOST_FILESYSTEM_DECL query_pair equivalent_api( const std::string & ph1, const std::string & ph2 ) { struct stat s2; int e2( ::stat( ph2.c_str(), &s2 ) ); struct stat s1; int e1( ::stat( ph1.c_str(), &s1 ) ); if ( e1 != 0 || e2 != 0 ) return std::make_pair( error_code( e1 != 0 && e2 != 0 ? errno : 0, system_category ), false ); // at this point, both stats are known to be valid return std::make_pair( ok, s1.st_dev == s2.st_dev && s1.st_ino == s2.st_ino // According to the POSIX stat specs, "The st_ino and st_dev fields // taken together uniquely identify the file within the system." // Just to be sure, size and mod time are also checked. && s1.st_size == s2.st_size && s1.st_mtime == s2.st_mtime ); } BOOST_FILESYSTEM_DECL uintmax_pair file_size_api( const std::string & ph ) { struct stat path_stat; if ( ::stat( ph.c_str(), &path_stat ) != 0 ) return std::make_pair( error_code( errno, system_category ), 0 ); if ( !S_ISREG( path_stat.st_mode ) ) return std::make_pair( error_code( EPERM, system_category ), 0 ); return std::make_pair( ok, static_cast<boost::uintmax_t>(path_stat.st_size) ); } BOOST_FILESYSTEM_DECL space_pair space_api( const std::string & ph ) { struct BOOST_STATVFS vfs; space_pair result; if ( ::BOOST_STATVFS( ph.c_str(), &vfs ) != 0 ) { result.first = error_code( errno, system_category ); result.second.capacity = result.second.free = result.second.available = 0; } else { result.first = ok; result.second.capacity = static_cast<boost::uintmax_t>(vfs.f_blocks) * BOOST_STATVFS_F_FRSIZE; result.second.free = static_cast<boost::uintmax_t>(vfs.f_bfree) * BOOST_STATVFS_F_FRSIZE; result.second.available = static_cast<boost::uintmax_t>(vfs.f_bavail) * BOOST_STATVFS_F_FRSIZE; } return result; } BOOST_FILESYSTEM_DECL time_pair last_write_time_api( const std::string & ph ) { struct stat path_stat; if ( ::stat( ph.c_str(), &path_stat ) != 0 ) return std::make_pair( error_code( errno, system_category ), 0 ); return std::make_pair( ok, path_stat.st_mtime ); } BOOST_FILESYSTEM_DECL error_code last_write_time_api( const std::string & ph, std::time_t new_value ) { struct stat path_stat; if ( ::stat( ph.c_str(), &path_stat ) != 0 ) return error_code( errno, system_category ); ::utimbuf buf; buf.actime = path_stat.st_atime; // utime() updates access time too:-( buf.modtime = new_value; return error_code( ::utime( ph.c_str(), &buf ) != 0 ? errno : 0, system_category ); } BOOST_FILESYSTEM_DECL error_code get_current_path_api( std::string & ph ) { for ( long path_max = 32;; path_max *=2 ) // loop 'til buffer large enough { boost::scoped_array<char> buf( new char[static_cast<std::size_t>(path_max)] ); if ( ::getcwd( buf.get(), static_cast<std::size_t>(path_max) ) == 0 ) { if ( errno != ERANGE // bug in some versions of the Metrowerks C lib on the Mac: wrong errno set # if defined(__MSL__) && (defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__)) && errno != 0 # endif ) return error_code( errno, system_category ); } else { ph = buf.get(); break; } } return ok; } BOOST_FILESYSTEM_DECL error_code set_current_path_api( const std::string & ph ) { return error_code( ::chdir( ph.c_str() ) ? errno : 0, system_category ); } BOOST_FILESYSTEM_DECL fs::detail::query_pair create_directory_api( const std::string & ph ) { if ( ::mkdir( ph.c_str(), S_IRWXU|S_IRWXG|S_IRWXO ) == 0 ) { return std::make_pair( ok, true ); } int ec=errno; error_code dummy; if ( ec != EEXIST || !fs::is_directory( status_api( ph, dummy ) ) ) { return std::make_pair( error_code( ec, system_category ), false ); } return std::make_pair( ok, false ); } BOOST_FILESYSTEM_DECL error_code create_hard_link_api( const std::string & to_ph, const std::string & from_ph ) { return error_code( ::link( to_ph.c_str(), from_ph.c_str() ) == 0 ? 0 : errno, system_category ); } BOOST_FILESYSTEM_DECL error_code create_symlink_api( const std::string & to_ph, const std::string & from_ph ) { return error_code( ::symlink( to_ph.c_str(), from_ph.c_str() ) == 0 ? 0 : errno, system_category ); } BOOST_FILESYSTEM_DECL error_code remove_api( const std::string & ph ) { if ( posix_remove( ph.c_str() ) == 0 ) return ok; int error = errno; // POSIX says "If the directory is not an empty directory, rmdir() // shall fail and set errno to EEXIST or ENOTEMPTY." // Linux uses ENOTEMPTY, Solaris uses EEXIST. if ( error == EEXIST ) error = ENOTEMPTY; error_code ec; // ignore errors if post-condition satisfied return status_api(ph, ec).type() == file_not_found ? ok : error_code( error, system_category ) ; } BOOST_FILESYSTEM_DECL error_code rename_api( const std::string & from, const std::string & to ) { // POSIX is too permissive so must check error_code dummy; if ( fs::exists( status_api( to, dummy ) ) ) return error_code( EEXIST, system_category ); return error_code( std::rename( from.c_str(), to.c_str() ) != 0 ? errno : 0, system_category ); } BOOST_FILESYSTEM_DECL error_code copy_file_api( const std::string & from_file_ph, const std::string & to_file_ph, bool fail_if_exists ) { const std::size_t buf_sz = 32768; boost::scoped_array<char> buf( new char [buf_sz] ); int infile=-1, outfile=-1; // -1 means not open // bug fixed: code previously did a stat() on the from_file first, but that // introduced a gratuitous race condition; the stat() is now done after the open() if ( (infile = ::open( from_file_ph.c_str(), O_RDONLY )) < 0 ) { return error_code( errno, system_category ); } struct stat from_stat; if ( ::stat( from_file_ph.c_str(), &from_stat ) != 0 ) { return error_code( errno, system_category ); } int oflag = O_CREAT | O_WRONLY; if ( fail_if_exists ) oflag |= O_EXCL; if ( (outfile = ::open( to_file_ph.c_str(), oflag, from_stat.st_mode )) < 0 ) { int open_errno = errno; BOOST_ASSERT( infile >= 0 ); ::close( infile ); return error_code( open_errno, system_category ); } ssize_t sz, sz_read=1, sz_write; while ( sz_read > 0 && (sz_read = ::read( infile, buf.get(), buf_sz )) > 0 ) { // Allow for partial writes - see Advanced Unix Programming (2nd Ed.), // Marc Rochkind, Addison-Wesley, 2004, page 94 sz_write = 0; do { if ( (sz = ::write( outfile, buf.get() + sz_write, sz_read - sz_write )) < 0 ) { sz_read = sz; // cause read loop termination break; // and error to be thrown after closes } sz_write += sz; } while ( sz_write < sz_read ); } if ( ::close( infile) < 0 ) sz_read = -1; if ( ::close( outfile) < 0 ) sz_read = -1; return error_code( sz_read < 0 ? errno : 0, system_category ); } // this code is based on Stevens and Rago, Advanced Programming in the // UNIX envirnment, 2nd Ed., ISBN 0-201-43307-9, page 49 error_code path_max( std::size_t & result ) { # ifdef PATH_MAX static std::size_t max = PATH_MAX; # else static std::size_t max = 0; # endif if ( max == 0 ) { errno = 0; long tmp = ::pathconf( "/", _PC_NAME_MAX ); if ( tmp < 0 ) { if ( errno == 0 ) // indeterminate max = 4096; // guess else return error_code( errno, system_category ); } else max = static_cast<std::size_t>( tmp + 1 ); // relative root } result = max; return ok; } BOOST_FILESYSTEM_DECL error_code dir_itr_first( void *& handle, void *& buffer, const std::string & dir, std::string & target, file_status &, file_status & ) { if ( (handle = ::opendir( dir.c_str() )) == 0 ) return error_code( errno, system_category ); target = std::string( "." ); // string was static but caused trouble // when iteration called from dtor, after // static had already been destroyed std::size_t path_size; error_code ec = path_max( path_size ); if ( ec ) return ec; dirent de; buffer = std::malloc( (sizeof(dirent) - sizeof(de.d_name)) + path_size + 1 ); // + 1 for "/0" return ok; } BOOST_FILESYSTEM_DECL error_code dir_itr_close( void *& handle, void*& buffer ) { std::free( buffer ); buffer = 0; if ( handle == 0 ) return ok; DIR * h( static_cast<DIR*>(handle) ); handle = 0; return error_code( ::closedir( h ) == 0 ? 0 : errno, system_category ); } // warning: the only dirent member updated is d_name inline int readdir_r_simulator( DIR * dirp, struct dirent * entry, struct dirent ** result ) // *result set to 0 on end of directory { errno = 0; # if !defined(__CYGWIN__) \ && defined(_POSIX_THREAD_SAFE_FUNCTIONS) \ && defined(_SC_THREAD_SAFE_FUNCTIONS) \ && (_POSIX_THREAD_SAFE_FUNCTIONS+0 >= 0) \ && (!defined(__hpux) || (defined(__hpux) && defined(_REENTRANT))) if ( ::sysconf( _SC_THREAD_SAFE_FUNCTIONS ) >= 0 ) { return ::readdir_r( dirp, entry, result ); } # endif struct dirent * p; *result = 0; if ( (p = ::readdir( dirp )) == 0 ) return errno; std::strcpy( entry->d_name, p->d_name ); *result = entry; return 0; } BOOST_FILESYSTEM_DECL error_code dir_itr_increment( void *& handle, void *& buffer, std::string & target, file_status & sf, file_status & symlink_sf ) { BOOST_ASSERT( buffer != 0 ); dirent * entry( static_cast<dirent *>(buffer) ); dirent * result; int return_code; if ( (return_code = readdir_r_simulator( static_cast<DIR*>(handle), entry, &result )) != 0 ) return error_code( errno, system_category ); if ( result == 0 ) return dir_itr_close( handle, buffer ); target = entry->d_name; # ifdef BOOST_FILESYSTEM_STATUS_CACHE if ( entry->d_type == DT_UNKNOWN ) // filesystem does not supply d_type value { sf = symlink_sf = fs::file_status(fs::status_unknown); } else // filesystem supplies d_type value { if ( entry->d_type == DT_DIR ) sf = symlink_sf = fs::file_status( fs::directory_file ); else if ( entry->d_type == DT_REG ) sf = symlink_sf = fs::file_status( fs::regular_file ); else if ( entry->d_type == DT_LNK ) { sf = fs::file_status( fs::status_unknown ); symlink_sf = fs::file_status( fs::symlink_file ); } else sf = symlink_sf = fs::file_status( fs::status_unknown ); } # else sf = symlink_sf = fs::file_status( fs::status_unknown ); # endif return ok; } # endif } // namespace detail } // namespace filesystem } // namespace boost
[ "metrix@Blended.(none)" ]
[ [ [ 1, 1368 ] ] ]
0f5b89301ae15aec01a78048dcb57ed99c9fb405
f2b4a9d938244916aa4377d4d15e0e2a6f65a345
/Game/Dlg_CapArt.cpp
97896e6525777e173d9c33631020c1dddb4a805a
[ "Apache-2.0" ]
permissive
notpushkin/palm-heroes
d4523798c813b6d1f872be2c88282161cb9bee0b
9313ea9a2948526eaed7a4d0c8ed2292a90a4966
refs/heads/master
2021-05-31T19:10:39.270939
2010-07-25T12:25:00
2010-07-25T12:25:00
62,046,865
2
1
null
null
null
null
UTF-8
C++
false
false
3,052
cpp
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "stdafx.h" #include "ArtifactList.h" #include "Dlg_CapArt.h" const sint32 acW = 32; const sint32 acH = 32; iDlg_CapArt::iDlg_CapArt(iViewMgr* pViewMgr, const iHero* pHero, const iArtList& artList) : iBaseGameDlg(pViewMgr,pHero->Owner()->PlayerId()), m_pHero(pHero), m_artList(artList) { m_bSingle = artList.GetSize() == 1; if (!m_bSingle) m_Title.Setf(gTextMgr[TRID_MSG_CAP_ARTS],m_artList.GetSize()); else m_Title = gTextMgr[TRID_MSG_CAP_ART]; } void iDlg_CapArt::OnCreateDlg() { iRect clRect = ClientRect(); if (!m_bSingle) { iArtListCtrl* pArtCtrl = new iArtListCtrl(m_pMgr, this, m_artList, iPoint(20,clRect.y2()-60), iSize(acW,acH), 6, iArtBackPackCtrl::Horizontal, 101); AddChild(pArtCtrl); } AddChild(new iTextButton(m_pMgr,this,iRect(clRect.x+(clRect.w/2-20),clRect.y2()-DEF_BTN_HEIGHT,40,DEF_BTN_HEIGHT),TRID_OK, DRC_OK)); } void iDlg_CapArt::DoCompose(const iRect& clRect) { iRect rc(clRect); sint32 th = gTextComposer.TextBoxOut(dlgfc_topic, gApp.Surface(), m_Title, iRect(rc.x+5,rc.y,rc.w-10,30)); if (m_bSingle) { BlitIcon(gApp.Surface(), gGame.ItemMgr().m_artMgr[m_artList[0]].Sprite(), iRect(rc.x,rc.y+th,rc.w, 32)); th += 32; gTextComposer.TextOut(dlgfc_topic, gApp.Surface(), iPoint(), gTextMgr[gGame.ItemMgr().m_artMgr[m_artList[0]].NameKey(m_pHero)], iRect(rc.x+5,rc.y+th,rc.w-10,30), AlignTop); th += 15; th += gTextComposer.TextBoxOut(dlgfc_plain, gApp.Surface(), gTextMgr[gGame.ItemMgr().m_artMgr[m_artList[0]].DescKey(m_pHero)], iRect(rc.x+5,rc.y+th,rc.w-10,30)); } } iSize iDlg_CapArt::ClientSize() const { sint32 w = (m_bSingle)?200:250; sint32 h = 0; // title h += gTextComposer.GetTextBoxSize(m_Title, w-10, dlgfc_topic).h + 5; if (m_bSingle) { // Artifact icon h += 32; // Artifact name h += 15; // Artifact description h += gTextComposer.GetTextBoxSize(gTextMgr[gGame.ItemMgr().m_artMgr[m_artList[0]].DescKey(m_pHero)], w-10, dlgfc_plain).h; } else { // Artifact list h += 40; } // ok button h += DEF_BTN_HEIGHT + 15; return iSize(w,h); } void iDlg_CapArt::iCMDH_ControlCommand(iView* pView, CTRL_CMD_ID cmd, sint32 param) { if (cmd == CCI_BTNCLICK) { EndDialog(pView->GetUID()); } }
[ "palmheroesteam@2c21ad19-eed7-4c86-9350-8a7669309276" ]
[ [ [ 1, 95 ] ] ]
5ec3737776846edf73b2054f07e32dbfd459cd06
62207628c4869e289975cc56be76339a31525c5d
/Source/Star Foxes Skeleton/standardShipClass.h
b00f8bc99a8de3697d9b3369340f50247eaad5a1
[]
no_license
dieno/star-foxes
f596e5c6b548fa5bb4f5d716b73df6285b2ce10e
eb6a12c827167fd2b7dd63ce19a1f15d7b7763f8
refs/heads/master
2021-01-01T16:39:47.800555
2011-05-29T03:51:35
2011-05-29T03:51:35
32,129,303
0
0
null
null
null
null
UTF-8
C++
false
false
769
h
#ifndef STANDARDSHIPCLASS_H #define STANDARDSHIPCLASS_H #include "mainShipClass.h" class StandardShipClass : public MainShipClass { public: StandardShipClass(LPD3DXMESH mesh, D3DMATERIAL9* meshMat, LPDIRECT3DTEXTURE9* meshTex, DWORD meshNumMat, LPDIRECT3DDEVICE9 newg_pDevice) :MainShipClass(mesh, meshMat, meshTex, meshNumMat, newg_pDevice){ setDamagePerShot(1); setMaxHealth(120); setCurrentHealth(120); } StandardShipClass(PMESHSTRUCT meshStruct, LPDIRECT3DDEVICE9 newg_pDevice) :MainShipClass(meshStruct, newg_pDevice){ setDamagePerShot(1); setMaxHealth(120); setCurrentHealth(120); } static float getAfterburnerSpeed() { return afterburnerSpeed_; } private: static float afterburnerSpeed_; }; #endif
[ "[email protected]@2f9817a0-ed27-d5fb-3aa2-4a2bb642cc6a", "[email protected]@2f9817a0-ed27-d5fb-3aa2-4a2bb642cc6a" ]
[ [ [ 1, 9 ], [ 11, 16 ], [ 18, 29 ] ], [ [ 10, 10 ], [ 17, 17 ] ] ]
024d805a35d120bb249ab315e8b19905ef95cab5
c70941413b8f7bf90173533115c148411c868bad
/core/src/vtxKeyframe.cpp
6ea5aef70314f3ccd76e5063b29d9ef4949b2721
[]
no_license
cnsuhao/vektrix
ac6e028dca066aad4f942b8d9eb73665853fbbbe
9b8c5fa7119ff7f3dc80fb05b7cdba335cf02c1a
refs/heads/master
2021-06-23T11:28:34.907098
2011-03-27T17:39:37
2011-03-27T17:39:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,725
cpp
/* ----------------------------------------------------------------------------- This source file is part of "vektrix" (the rich media and vector graphics rendering library) For the latest info, see http://www.fuse-software.com/ Copyright (c) 2009-2010 Fuse-Software (tm) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "vtxKeyframe.h" #include "vtxFrameEvent.h" namespace vtx { //----------------------------------------------------------------------- Keyframe::Keyframe() : mIndex(0) { } //----------------------------------------------------------------------- Keyframe::~Keyframe() { } //----------------------------------------------------------------------- Keyframe* Keyframe::clone(DisplayObjectContainer* container) { Keyframe* clonedKeyframe = new Keyframe; clonedKeyframe->mIndex = mIndex; EventContainer::EventList::iterator it = mEvents.begin(); for( ; it != mEvents.end(); ++it) { FrameEvent* event = (*it)->clone(container); clonedKeyframe->mEvents.push_back(event); } return clonedKeyframe; } //----------------------------------------------------------------------- bool Keyframe::operator<(const Keyframe& keyframe) const { return (mIndex < keyframe.mIndex); } //----------------------------------------------------------------------- void Keyframe::setIndex(const uint& index) { mIndex = index; } //----------------------------------------------------------------------- const uint& Keyframe::getIndex() { return mIndex; } //----------------------------------------------------------------------- }
[ "stonecold_@9773a11d-1121-4470-82d2-da89bd4a628a" ]
[ [ [ 1, 78 ] ] ]
0b97cfc666bc4cf6736c8939807975ead49b3049
ed8cbdeb94cdc3364586c6e73d48427eab3dd624
/benchmarks/win32/Programming Projects/Columbia/VC/testEvent/testEvent.cpp
f9e08ea8eae22d3f0c7224f08baa9b9d5d09625f
[]
no_license
Programming-Systems-Lab/archived-events
3b5281b1f3013cc4a3943e52cfd616d2daeba6f2
61d521b39996393ad7ad6d9430dbcdab4b2b36c6
refs/heads/master
2020-09-17T23:37:34.037734
2002-12-20T15:45:08
2002-12-20T15:45:08
67,139,857
0
0
null
null
null
null
UTF-8
C++
false
false
2,571
cpp
// testEvent.cpp : Implementation of DLL Exports. // Note: Proxy/Stub Information // To build a separate proxy/stub DLL, // run nmake -f testEventps.mk in the project directory. #include "stdafx.h" #include "resource.h" #include <initguid.h> #include "testEvent.h" #include "testEvent_i.c" #include "AMTSTest.h" CComModule _Module; BEGIN_OBJECT_MAP(ObjectMap) OBJECT_ENTRY(CLSID_AMTSTest, AMTSTest) END_OBJECT_MAP() class CTestEventApp : public CWinApp { public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CTestEventApp) public: virtual BOOL InitInstance(); virtual int ExitInstance(); //}}AFX_VIRTUAL //{{AFX_MSG(CTestEventApp) // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP() }; BEGIN_MESSAGE_MAP(CTestEventApp, CWinApp) //{{AFX_MSG_MAP(CTestEventApp) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG_MAP END_MESSAGE_MAP() CTestEventApp theApp; BOOL CTestEventApp::InitInstance() { _Module.Init(ObjectMap, m_hInstance, &LIBID_TESTEVENTLib); return CWinApp::InitInstance(); } int CTestEventApp::ExitInstance() { _Module.Term(); return CWinApp::ExitInstance(); } ///////////////////////////////////////////////////////////////////////////// // Used to determine whether the DLL can be unloaded by OLE STDAPI DllCanUnloadNow(void) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); return (AfxDllCanUnloadNow()==S_OK && _Module.GetLockCount()==0) ? S_OK : S_FALSE; } ///////////////////////////////////////////////////////////////////////////// // Returns a class factory to create an object of the requested type STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv) { return _Module.GetClassObject(rclsid, riid, ppv); } ///////////////////////////////////////////////////////////////////////////// // DllRegisterServer - Adds entries to the system registry STDAPI DllRegisterServer(void) { // registers object, typelib and all interfaces in typelib return _Module.RegisterServer(TRUE); } ///////////////////////////////////////////////////////////////////////////// // DllUnregisterServer - Removes entries from the system registry STDAPI DllUnregisterServer(void) { return _Module.UnregisterServer(TRUE); }
[ "jjp32" ]
[ [ [ 1, 97 ] ] ]
46b55d006a59f457e1d40b5d8524f2f328651b57
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Common/Scd/RegexWrap/RegexWrap.cpp
8a3121e09d69b09be1415d540848c3014aaba2b2
[]
no_license
abcweizhuo/Test3
0f3379e528a543c0d43aad09489b2444a2e0f86d
128a4edcf9a93d36a45e5585b70dee75e4502db4
refs/heads/master
2021-01-17T01:59:39.357645
2008-08-20T00:00:29
2008-08-20T00:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,420
cpp
//////////////////////////////////////////////////////////////// // MSDN Magazine -- June 2006 // If this code works, it was written by Paul DiLascia. // If not, I don't know who wrote it. // Compiles with Visual Studio 2005 (VC8) on Windows XP. Tab size=3. // #include "stdafx.h" #include "RegexWrap.h" #define S(s) (gcnew String(s)) //////////////// Capture //////////////// IMPLEMENT_WRAPPER(Capture, Object) int CMCapture::Index() const { return (*this)->Index; } int CMCapture::Length() const { return (*this)->Length; } CString CMCapture::Value() const { return (*this)->Value; } //////////////// CaptureCollection //////////////// IMPLEMENT_COLLECTION(CaptureCollection, Object) CMCapture CMCaptureCollection::operator[](int i) { try { return (*this)->default[i]; } catch (ArgumentException^ e) { throw CMArgumentException(e); } catch (Exception^ e) { throw CMException(e); } } //////////////// Group //////////////// IMPLEMENT_WRAPPER(Group, Capture) bool CMGroup::Success() const { return (*this)->Success; } CMCaptureCollection CMGroup::Captures() const { return (*this)->Captures; } //////////////// GroupCollection //////////////// IMPLEMENT_COLLECTION(GroupCollection, Object) CMGroup CMGroupCollection::operator[](int i) { return (*this)->default[i]; } CMGroup CMGroupCollection::operator[](LPCTSTR name) { return (*this)->default[S(name)]; } //////////////// Match //////////////// IMPLEMENT_WRAPPER(Match, Group) #pragma warning( push ) #pragma warning( disable : 4835 ) // one-and-only Empty object WREXPORT const CMMatch CMMatch::Empty(Match::Empty); #pragma warning( pop ) CMMatch CMMatch::NextMatch() const { return (*this)->NextMatch(); } CString CMMatch::Result(CString sReplace) const { return (*this)->Result(gcnew String(sReplace)); } CMGroupCollection CMMatch::Groups() const { return (*this)->Groups; } ////////////////// // This class implements a MatchEvaluator delegate that calls an ordinary C++ // callback. The static Create function returns a new instance initialized // with a given C++ callback fn and void* param. // ref class WrapMatchEvaluator { protected: CMMatch::evaluator _pfn; // native callback fn void* _param; // native param public: WrapMatchEvaluator(CMMatch::evaluator pfn, void* param) : _pfn(pfn),_param(param) { } String^ callback(Match^ m) { return _pfn ? gcnew String((_pfn)(CMMatch(m),_param)) : m->Value; } static MatchEvaluator^ Create(CMMatch::evaluator pfn, void* param) { WrapMatchEvaluator^ me = gcnew WrapMatchEvaluator(pfn, param); return gcnew MatchEvaluator(me, &WrapMatchEvaluator::callback); } }; //////////////// MatchCollection //////////////// IMPLEMENT_COLLECTION(MatchCollection, Object) CMMatch CMMatchCollection::operator[](int i) { try { return (*this)->default[i]; } catch (Exception^ e) { throw CMException(e); } } //////////////// Regex //////////////// IMPLEMENT_WRAPPER(Regex, Object) ////////////////// // Wrap construction of Regex object in try/catch to wrap any exception before // re-throwing it. Regex throws an ArgumentException if the regex is // ill-formed. // Regex^ NewRegex(LPCTSTR s) { try { return gcnew Regex(gcnew String(s)); } catch (Exception^ e) { throw CMException(e); } } CMRegex::CMRegex(LPCTSTR s) : CMObject(NewRegex(s)) { } Regex^ NewRegex(LPCTSTR s, CMRegex::Options opt) { try { return gcnew Regex(gcnew String(s), static_cast<RegexOptions>(opt)); } catch (Exception^ e) { throw CMException(e); } } CMRegex::CMRegex(LPCTSTR s, Options opt) : CMObject(NewRegex(s, opt)) { } //////////////// // Below are all the wrapper fns. They're so brainless you could write them // in your sleep. // CMMatch CMRegex::Match(LPCTSTR input) { return (*this)->Match(S(input)); } CMMatch CMRegex::Match(LPCTSTR input, int beg) { return (*this)->Match(S(input), beg); } CMMatch CMRegex::Match(LPCTSTR input, int beg, int len) { return (*this)->Match(S(input), beg, len); } CMMatch CMRegex::Match(LPCTSTR input, LPCTSTR pattern) { return Regex::Match(S(input), S(pattern)); } CMMatch CMRegex::Match(LPCTSTR input, LPCTSTR pattern, Options opt) { return Regex::Match(S(input), S(pattern), static_cast<RegexOptions>(opt)); } bool CMRegex::IsMatch(LPCTSTR input) { return (*this)->IsMatch(S(input)); } bool CMRegex::IsMatch(LPCTSTR input, int beg) { return (*this)->IsMatch(S(input), beg); } bool CMRegex::IsMatch(LPCTSTR input, LPCTSTR pattern) { return Regex::IsMatch(S(input), S(pattern)); } CMMatchCollection CMRegex::Matches(LPCTSTR input) { return (*this)->Matches(S(input)); } CMMatchCollection CMRegex::Matches(LPCTSTR input, int beg) { return (*this)->Matches(S(input), beg); } CMMatchCollection CMRegex::Matches(LPCTSTR input, LPCTSTR pattern) { return Regex::Matches(S(input), S(pattern)); } vector<CString> CMRegex::Split(LPCTSTR input) { return wrap_array<CString,String>((*this)->Split(S(input))); } vector<CString> CMRegex::Split(LPCTSTR input, int n) { return wrap_array<CString,String>((*this)->Split(S(input), n)); } vector<CString> CMRegex::Split(LPCTSTR input, LPCTSTR pattern) { return wrap_array<CString,String>(Regex::Split(S(input), S(pattern))); } vector<CString> CMRegex::Split(LPCTSTR input, LPCTSTR pattern, Options opt) { return wrap_array<CString,String>(Regex::Split(S(input), S(pattern), static_cast<RegexOptions>(opt))); } CString CMRegex::Escape(CString s) { return Regex::Escape(S(s)); } CString CMRegex::Replace(LPCTSTR input, LPCTSTR replace) { return (*this)->Replace(S(input), S(replace)); } CString CMRegex::Replace(LPCTSTR input, LPCTSTR replace, int n) { return (*this)->Replace(S(input), S(replace), n); } CString CMRegex::Replace(LPCTSTR input, LPCTSTR pattern, LPCTSTR replace) { return Regex::Replace(S(input), S(pattern), S(replace)); } CString CMRegex::Replace(LPCTSTR input, LPCTSTR pattern, LPCTSTR replace, Options opt) { return Regex::Replace(S(input), S(pattern), S(replace), static_cast<RegexOptions>(opt)); } CString CMRegex::Replace(LPCTSTR input, CMMatch::evaluator me, void* lp) { return (*this)->Replace(S(input), WrapMatchEvaluator::Create(me, lp)); } CString CMRegex::Replace(LPCTSTR input, CMMatch::evaluator me, void* lp, int n) { return (*this)->Replace(S(input), WrapMatchEvaluator::Create(me, lp), n); } CString CMRegex::Replace(LPCTSTR input, LPCTSTR pattern, CMMatch::evaluator me, void* lp) { return Regex::Replace(S(input), S(pattern), WrapMatchEvaluator::Create(me, lp)); } CString CMRegex::Replace(LPCTSTR input, LPCTSTR pattern, CMMatch::evaluator me, void* lp, Options opt) { return Regex::Replace(S(input), S(pattern), WrapMatchEvaluator::Create(me, lp), static_cast<RegexOptions>(opt)); } vector<CString> CMRegex::GetGroupNames() { return wrap_array<CString,String>((*this)->GetGroupNames()); } vector<int> CMRegex::GetGroupNumbers() { return wrap_array<int>((*this)->GetGroupNumbers()); } CString CMRegex::GroupNameFromNumber(int i) { return (*this)->GroupNameFromNumber(i); } int CMRegex::GroupNumberFromName(CString s) { return (*this)->GroupNumberFromName(S(s)); }
[ [ [ 1, 320 ] ] ]
fa766ce20e4ee4929eb4b3ff90310f131a073764
602ca72f508609f21e22bf03125e55b6631c1e80
/KinectSign/I4C3DSocketCommunication.cpp
92aba3c45238de89f2bac17ccebe5efd1c18b24f
[]
no_license
chanpi/KinectSign
f5717b4f37f584d85349f76ce80138abfff0ff69
4c28f735aa24c22938acd20d1be8374521a30a2a
refs/heads/master
2021-01-18T14:46:12.107209
2011-08-09T08:16:43
2011-08-09T08:16:43
2,172,210
1
0
null
null
null
null
UTF-8
C++
false
false
694
cpp
#include "StdAfx.h" #include "I4C3DSocketCommunication.h" #include "KinectSign.h" I4C3DSocketCommunication::I4C3DSocketCommunication(HWND hMainWnd) { m_socketHandler = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); m_addr.sin_family = AF_INET; m_addr.sin_port = htons(22202); m_addr.sin_addr.S_un.S_addr = INADDR_ANY; bind(m_socketHandler, (const SOCKADDR*)&m_addr, sizeof(m_addr)); if (WSAAsyncSelect(m_socketHandler, hMainWnd, WSOCK_SELECT, FD_READ) == SOCKET_ERROR) { MessageBox(hMainWnd, _T("[ERROR] WSAAsyncSelect()"), _T("KinectSign"), MB_ICONERROR | MB_OK); } } I4C3DSocketCommunication::~I4C3DSocketCommunication(void) { closesocket(m_socketHandler); }
[ [ [ 1, 23 ] ] ]
0dcfc1a044f246c2d7b1c44a4fd59ac793e7db3e
1585c7e187eec165138edbc5f1b5f01d3343232f
/parallel/parallel/stdafx.cpp
61a03351afae866b78a19047e163e6eb8772f62f
[]
no_license
a-27m/vssdb
c8885f479a709dd59adbb888267a03fb3b0c3afb
d86944d4d93fd722e9c27cb134256da16842f279
refs/heads/master
2022-08-05T06:50:12.743300
2011-06-23T08:35:44
2011-06-23T08:35:44
82,612,001
1
0
null
2021-03-29T08:05:33
2017-02-20T23:07:03
C#
UTF-8
C++
false
false
210
cpp
// stdafx.cpp : source file that includes just the standard includes // parallel.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
[ "Axell@bf672a44-3a04-1d4a-850b-c2a239875c8c" ]
[ [ [ 1, 8 ] ] ]
4a9e5c93ac3ac23f231c916ef3dcb4bcb811f56d
4a99fa98abd0285bc3b5671f237b932114123340
/physics/BulletCollision/CollisionDispatch/btCollisionWorld.h
71ffb00fc40dec75c8f25b0a99419c9b280c0881
[]
no_license
automenta/crittergod1.5
937cd925a4ba57b3e8cfa4899a81ba24fe3e4138
4786fe9d621c0e61cdd43ca3a363bfce6510e3c0
refs/heads/master
2020-12-24T16:58:32.854270
2010-04-12T03:25:39
2010-04-12T03:25:39
520,917
1
0
null
null
null
null
UTF-8
C++
false
false
15,330
h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://bulletphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /** * @mainpage Bullet Documentation * * @section intro_sec Introduction * Bullet Collision Detection & Physics SDK * * Bullet is a Collision Detection and Rigid Body Dynamics Library. The Library is Open Source and free for commercial use, under the ZLib license ( http://opensource.org/licenses/zlib-license.php ). * * There is the Physics Forum for feedback and general Collision Detection and Physics discussions. * Please visit http://www.bulletphysics.com * * @section install_sec Installation * * @subsection step1 Step 1: Download * You can download the Bullet Physics Library from the Google Code repository: http://code.google.com/p/bullet/downloads/list * @subsection step2 Step 2: Building * Bullet comes with autogenerated Project Files for Microsoft Visual Studio 6, 7, 7.1 and 8. * The main Workspace/Solution is located in Bullet/msvc/8/wksbullet.sln (replace 8 with your version). * * Under other platforms, like Linux or Mac OS-X, Bullet can be build using either using make, cmake, http://www.cmake.org , or jam, http://www.perforce.com/jam/jam.html . cmake can autogenerate Xcode, KDevelop, MSVC and other build systems. just run cmake . in the root of Bullet. * So if you are not using MSVC or cmake, you can run ./autogen.sh ./configure to create both Makefile and Jamfile and then run make or jam. * Jam is a build system that can build the library, demos and also autogenerate the MSVC Project Files. * If you don't have jam installed, you can make jam from the included jam-2.5 sources, or download jam from ftp://ftp.perforce.com/jam * * @subsection step3 Step 3: Testing demos * Try to run and experiment with BasicDemo executable as a starting point. * Bullet can be used in several ways, as Full Rigid Body simulation, as Collision Detector Library or Low Level / Snippets like the GJK Closest Point calculation. * The Dependencies can be seen in this documentation under Directories * * @subsection step4 Step 4: Integrating in your application, full Rigid Body and Soft Body simulation * Check out BasicDemo how to create a btDynamicsWorld, btRigidBody and btCollisionShape, Stepping the simulation and synchronizing your graphics object transform. * Check out SoftDemo how to use soft body dynamics, using btSoftRigidDynamicsWorld. * @subsection step5 Step 5 : Integrate the Collision Detection Library (without Dynamics and other Extras) * Bullet Collision Detection can also be used without the Dynamics/Extras. * Check out btCollisionWorld and btCollisionObject, and the CollisionInterfaceDemo. * @subsection step6 Step 6 : Use Snippets like the GJK Closest Point calculation. * Bullet has been designed in a modular way keeping dependencies to a minimum. The ConvexHullDistance demo demonstrates direct use of btGjkPairDetector. * * @section copyright Copyright * Copyright (C) 2005-2008 Erwin Coumans, some contributions Copyright Gino van den Bergen, Christer Ericson, Simon Hobbs, Ricardo Padrela, F Richter(res), Stephane Redon * Special thanks to all visitors of the Bullet Physics forum, and in particular above contributors, John McCutchan, Nathanael Presson, Dave Eberle, Dirk Gregorius, Erin Catto, Dave Eberle, Adam Moravanszky, * Pierre Terdiman, Kenny Erleben, Russell Smith, Oliver Strunk, Jan Paul van Waveren, Marten Svanfeldt. * */ #ifndef COLLISION_WORLD_H #define COLLISION_WORLD_H class btStackAlloc; class btCollisionShape; class btConvexShape; class btBroadphaseInterface; #include "LinearMath/btVector3.h" #include "LinearMath/btTransform.h" #include "btCollisionObject.h" #include "btCollisionDispatcher.h" #include "BulletCollision/BroadphaseCollision/btOverlappingPairCache.h" #include "LinearMath/btAlignedObjectArray.h" ///CollisionWorld is interface and container for the collision detection class btCollisionWorld { protected: btAlignedObjectArray<btCollisionObject*> m_collisionObjects; btDispatcher* m_dispatcher1; btDispatcherInfo m_dispatchInfo; btStackAlloc* m_stackAlloc; btBroadphaseInterface* m_broadphasePairCache; btIDebugDraw* m_debugDrawer; ///m_forceUpdateAllAabbs can be set to false as an optimization to only update active object AABBs ///it is true by default, because it is error-prone (setting the position of static objects wouldn't update their AABB) bool m_forceUpdateAllAabbs; public: //this constructor doesn't own the dispatcher and paircache/broadphase btCollisionWorld(btDispatcher* dispatcher,btBroadphaseInterface* broadphasePairCache, btCollisionConfiguration* collisionConfiguration); virtual ~btCollisionWorld(); void setBroadphase(btBroadphaseInterface* pairCache) { m_broadphasePairCache = pairCache; } const btBroadphaseInterface* getBroadphase() const { return m_broadphasePairCache; } btBroadphaseInterface* getBroadphase() { return m_broadphasePairCache; } btOverlappingPairCache* getPairCache() { return m_broadphasePairCache->getOverlappingPairCache(); } btDispatcher* getDispatcher() { return m_dispatcher1; } const btDispatcher* getDispatcher() const { return m_dispatcher1; } void updateSingleAabb(btCollisionObject* colObj); virtual void updateAabbs(); virtual void setDebugDrawer(btIDebugDraw* debugDrawer) { m_debugDrawer = debugDrawer; } virtual btIDebugDraw* getDebugDrawer() { return m_debugDrawer; } virtual void debugDrawWorld(); virtual void debugDrawObject(const btTransform& worldTransform, const btCollisionShape* shape, const btVector3& color); void debugDrawSphere(btScalar radius, const btTransform& transform, const btVector3& color); ///LocalShapeInfo gives extra information for complex shapes ///Currently, only btTriangleMeshShape is available, so it just contains triangleIndex and subpart struct LocalShapeInfo { int m_shapePart; int m_triangleIndex; //const btCollisionShape* m_shapeTemp; //const btTransform* m_shapeLocalTransform; }; struct LocalRayResult { LocalRayResult(btCollisionObject* collisionObject, LocalShapeInfo* localShapeInfo, const btVector3& hitNormalLocal, btScalar hitFraction) :m_collisionObject(collisionObject), m_localShapeInfo(localShapeInfo), m_hitNormalLocal(hitNormalLocal), m_hitFraction(hitFraction) { } btCollisionObject* m_collisionObject; LocalShapeInfo* m_localShapeInfo; btVector3 m_hitNormalLocal; btScalar m_hitFraction; }; ///RayResultCallback is used to report new raycast results struct RayResultCallback { btScalar m_closestHitFraction; btCollisionObject* m_collisionObject; short int m_collisionFilterGroup; short int m_collisionFilterMask; //@BP Mod - Custom flags, currently used to enable backface culling on tri-meshes, see btRaycastCallback unsigned int m_flags; virtual ~RayResultCallback() { } bool hasHit() const { return (m_collisionObject != 0); } RayResultCallback() :m_closestHitFraction(btScalar(1.)), m_collisionObject(0), m_collisionFilterGroup(btBroadphaseProxy::DefaultFilter), m_collisionFilterMask(btBroadphaseProxy::AllFilter), //@BP Mod m_flags(0) { } virtual bool needsCollision(btBroadphaseProxy* proxy0) const { bool collides = (proxy0->m_collisionFilterGroup & m_collisionFilterMask) != 0; collides = collides && (m_collisionFilterGroup & proxy0->m_collisionFilterMask); return collides; } virtual btScalar addSingleResult(LocalRayResult& rayResult,bool normalInWorldSpace) = 0; }; struct ClosestRayResultCallback : public RayResultCallback { ClosestRayResultCallback(const btVector3& rayFromWorld,const btVector3& rayToWorld) :m_rayFromWorld(rayFromWorld), m_rayToWorld(rayToWorld) { } btVector3 m_rayFromWorld;//used to calculate hitPointWorld from hitFraction btVector3 m_rayToWorld; btVector3 m_hitNormalWorld; btVector3 m_hitPointWorld; virtual btScalar addSingleResult(LocalRayResult& rayResult,bool normalInWorldSpace) { //caller already does the filter on the m_closestHitFraction btAssert(rayResult.m_hitFraction <= m_closestHitFraction); m_closestHitFraction = rayResult.m_hitFraction; m_collisionObject = rayResult.m_collisionObject; if (normalInWorldSpace) { m_hitNormalWorld = rayResult.m_hitNormalLocal; } else { ///need to transform normal into worldspace m_hitNormalWorld = m_collisionObject->getWorldTransform().getBasis()*rayResult.m_hitNormalLocal; } m_hitPointWorld.setInterpolate3(m_rayFromWorld,m_rayToWorld,rayResult.m_hitFraction); return rayResult.m_hitFraction; } }; struct LocalConvexResult { LocalConvexResult(btCollisionObject* hitCollisionObject, LocalShapeInfo* localShapeInfo, const btVector3& hitNormalLocal, const btVector3& hitPointLocal, btScalar hitFraction ) :m_hitCollisionObject(hitCollisionObject), m_localShapeInfo(localShapeInfo), m_hitNormalLocal(hitNormalLocal), m_hitPointLocal(hitPointLocal), m_hitFraction(hitFraction) { } btCollisionObject* m_hitCollisionObject; LocalShapeInfo* m_localShapeInfo; btVector3 m_hitNormalLocal; btVector3 m_hitPointLocal; btScalar m_hitFraction; }; ///RayResultCallback is used to report new raycast results struct ConvexResultCallback { btScalar m_closestHitFraction; short int m_collisionFilterGroup; short int m_collisionFilterMask; ConvexResultCallback() :m_closestHitFraction(btScalar(1.)), m_collisionFilterGroup(btBroadphaseProxy::DefaultFilter), m_collisionFilterMask(btBroadphaseProxy::AllFilter) { } virtual ~ConvexResultCallback() { } bool hasHit() const { return (m_closestHitFraction < btScalar(1.)); } virtual bool needsCollision(btBroadphaseProxy* proxy0) const { bool collides = (proxy0->m_collisionFilterGroup & m_collisionFilterMask) != 0; collides = collides && (m_collisionFilterGroup & proxy0->m_collisionFilterMask); return collides; } virtual btScalar addSingleResult(LocalConvexResult& convexResult,bool normalInWorldSpace) = 0; }; struct ClosestConvexResultCallback : public ConvexResultCallback { ClosestConvexResultCallback(const btVector3& convexFromWorld,const btVector3& convexToWorld) :m_convexFromWorld(convexFromWorld), m_convexToWorld(convexToWorld), m_hitCollisionObject(0) { } btVector3 m_convexFromWorld;//used to calculate hitPointWorld from hitFraction btVector3 m_convexToWorld; btVector3 m_hitNormalWorld; btVector3 m_hitPointWorld; btCollisionObject* m_hitCollisionObject; virtual btScalar addSingleResult(LocalConvexResult& convexResult,bool normalInWorldSpace) { //caller already does the filter on the m_closestHitFraction btAssert(convexResult.m_hitFraction <= m_closestHitFraction); m_closestHitFraction = convexResult.m_hitFraction; m_hitCollisionObject = convexResult.m_hitCollisionObject; if (normalInWorldSpace) { m_hitNormalWorld = convexResult.m_hitNormalLocal; } else { ///need to transform normal into worldspace m_hitNormalWorld = m_hitCollisionObject->getWorldTransform().getBasis()*convexResult.m_hitNormalLocal; } m_hitPointWorld = convexResult.m_hitPointLocal; return convexResult.m_hitFraction; } }; int getNumCollisionObjects() const { return int(m_collisionObjects.size()); } /// rayTest performs a raycast on all objects in the btCollisionWorld, and calls the resultCallback /// This allows for several queries: first hit, all hits, any hit, dependent on the value returned by the callback. void rayTest(const btVector3& rayFromWorld, const btVector3& rayToWorld, RayResultCallback& resultCallback) const; // convexTest performs a swept convex cast on all objects in the btCollisionWorld, and calls the resultCallback // This allows for several queries: first hit, all hits, any hit, dependent on the value return by the callback. void convexSweepTest (const btConvexShape* castShape, const btTransform& from, const btTransform& to, ConvexResultCallback& resultCallback, btScalar allowedCcdPenetration = btScalar(0.)) const; /// rayTestSingle performs a raycast call and calls the resultCallback. It is used internally by rayTest. /// In a future implementation, we consider moving the ray test as a virtual method in btCollisionShape. /// This allows more customization. static void rayTestSingle(const btTransform& rayFromTrans,const btTransform& rayToTrans, btCollisionObject* collisionObject, const btCollisionShape* collisionShape, const btTransform& colObjWorldTransform, RayResultCallback& resultCallback); /// objectQuerySingle performs a collision detection query and calls the resultCallback. It is used internally by rayTest. static void objectQuerySingle(const btConvexShape* castShape, const btTransform& rayFromTrans,const btTransform& rayToTrans, btCollisionObject* collisionObject, const btCollisionShape* collisionShape, const btTransform& colObjWorldTransform, ConvexResultCallback& resultCallback, btScalar allowedPenetration); virtual void addCollisionObject(btCollisionObject* collisionObject,short int collisionFilterGroup=btBroadphaseProxy::DefaultFilter,short int collisionFilterMask=btBroadphaseProxy::AllFilter); btCollisionObjectArray& getCollisionObjectArray() { return m_collisionObjects; } const btCollisionObjectArray& getCollisionObjectArray() const { return m_collisionObjects; } virtual void removeCollisionObject(btCollisionObject* collisionObject); virtual void performDiscreteCollisionDetection(); btDispatcherInfo& getDispatchInfo() { return m_dispatchInfo; } const btDispatcherInfo& getDispatchInfo() const { return m_dispatchInfo; } bool getForceUpdateAllAabbs() const { return m_forceUpdateAllAabbs; } void setForceUpdateAllAabbs( bool forceUpdateAllAabbs) { m_forceUpdateAllAabbs = forceUpdateAllAabbs; } }; #endif //COLLISION_WORLD_H
[ [ [ 1, 428 ] ] ]
b435ea4f30819381e43e15788593405da07cced8
9a48be80edc7692df4918c0222a1640545384dbb
/Libraries/Boost1.40/libs/asio/example/serialization/server.cpp
9a55ac723b69e30984fd8ada3879d7c67f79e166
[ "BSL-1.0" ]
permissive
fcrick/RepSnapper
05e4fb1157f634acad575fffa2029f7f655b7940
a5809843f37b7162f19765e852b968648b33b694
refs/heads/master
2021-01-17T21:42:29.537504
2010-06-07T05:38:05
2010-06-07T05:38:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,971
cpp
// // server.cpp // ~~~~~~~~~~ // // Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio.hpp> #include <boost/bind.hpp> #include <boost/lexical_cast.hpp> #include <iostream> #include <vector> #include "connection.hpp" // Must come before boost/serialization headers. #include <boost/serialization/vector.hpp> #include "stock.hpp" namespace s11n_example { /// Serves stock quote information to any client that connects to it. class server { public: /// Constructor opens the acceptor and starts waiting for the first incoming /// connection. server(boost::asio::io_service& io_service, unsigned short port) : acceptor_(io_service, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port)) { // Create the data to be sent to each client. stock s; s.code = "ABC"; s.name = "A Big Company"; s.open_price = 4.56; s.high_price = 5.12; s.low_price = 4.33; s.last_price = 4.98; s.buy_price = 4.96; s.buy_quantity = 1000; s.sell_price = 4.99; s.sell_quantity = 2000; stocks_.push_back(s); s.code = "DEF"; s.name = "Developer Entertainment Firm"; s.open_price = 20.24; s.high_price = 22.88; s.low_price = 19.50; s.last_price = 19.76; s.buy_price = 19.72; s.buy_quantity = 34000; s.sell_price = 19.85; s.sell_quantity = 45000; stocks_.push_back(s); // Start an accept operation for a new connection. connection_ptr new_conn(new connection(acceptor_.io_service())); acceptor_.async_accept(new_conn->socket(), boost::bind(&server::handle_accept, this, boost::asio::placeholders::error, new_conn)); } /// Handle completion of a accept operation. void handle_accept(const boost::system::error_code& e, connection_ptr conn) { if (!e) { // Successfully accepted a new connection. Send the list of stocks to the // client. The connection::async_write() function will automatically // serialize the data structure for us. conn->async_write(stocks_, boost::bind(&server::handle_write, this, boost::asio::placeholders::error, conn)); // Start an accept operation for a new connection. connection_ptr new_conn(new connection(acceptor_.io_service())); acceptor_.async_accept(new_conn->socket(), boost::bind(&server::handle_accept, this, boost::asio::placeholders::error, new_conn)); } else { // An error occurred. Log it and return. Since we are not starting a new // accept operation the io_service will run out of work to do and the // server will exit. std::cerr << e.message() << std::endl; } } /// Handle completion of a write operation. void handle_write(const boost::system::error_code& e, connection_ptr conn) { // Nothing to do. The socket will be closed automatically when the last // reference to the connection object goes away. } private: /// The acceptor object used to accept incoming socket connections. boost::asio::ip::tcp::acceptor acceptor_; /// The data to be sent to each client. std::vector<stock> stocks_; }; } // namespace s11n_example int main(int argc, char* argv[]) { try { // Check command line arguments. if (argc != 2) { std::cerr << "Usage: server <port>" << std::endl; return 1; } unsigned short port = boost::lexical_cast<unsigned short>(argv[1]); boost::asio::io_service io_service; s11n_example::server server(io_service, port); io_service.run(); } catch (std::exception& e) { std::cerr << e.what() << std::endl; } return 0; }
[ "metrix@Blended.(none)" ]
[ [ [ 1, 130 ] ] ]
a55f81d58b732dd5913ca06a033d199ee87dbdb1
6bdb3508ed5a220c0d11193df174d8c215eb1fce
/Codes/Halak/SpatialObject.cpp
45c12fb827a13626cef68ec1a1c437b1052618d8
[]
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
1,571
cpp
#include <Halak/PCH.h> #include <Halak/SpatialObject.h> namespace Halak { SpatialObject::SpatialObject() : position(Vector3::Zero), rotation(Quaternion::Identity), scale(1.0f), revision(1) { } SpatialObject::SpatialObject(Vector3 position) : position(position), rotation(Quaternion::Identity), scale(1.0f), revision(1) { } SpatialObject::SpatialObject(Vector3 position, Quaternion rotation, float scale) : position(position), rotation(rotation), scale(scale), revision(1) { } SpatialObject::~SpatialObject() { } Vector3 SpatialObject::GetPosition() { return position; } void SpatialObject::SetPosition(Vector3 value) { if (position != value) { position = value; revision++; } } Quaternion SpatialObject::GetRotation() { return rotation; } void SpatialObject::SetRotation(Quaternion value) { if (rotation != value) { rotation = value; revision++; } } float SpatialObject::GetScale() { return scale; } void SpatialObject::SetScale(float value) { if (scale != value) { scale = value; revision++; } } uint SpatialObject::GetRevision() const { return revision; } }
[ [ [ 1, 80 ] ] ]
a404436a7f0c4e8918b01b280599f4edb0d39b06
3276915b349aec4d26b466d48d9c8022a909ec16
/c++小作品/小程序/成绩评定.cpp
f87c16b2de91c67d970e77eb4af01f730a56b235
[]
no_license
flyskyosg/3dvc
c10720b1a7abf9cf4fa1a66ef9fc583d23e54b82
0279b1a7ae097b9028cc7e4aa2dcb67025f096b9
refs/heads/master
2021-01-10T11:39:45.352471
2009-07-31T13:13:50
2009-07-31T13:13:50
48,670,844
0
0
null
null
null
null
GB18030
C++
false
false
838
cpp
#include<iostream.h> #include<iomanip.h> #define N 10 void input(int a[][3],int n) { int i,j; for(i=0,j=0;i<n;i++) { cout<<"输入学号"; cin>>a[i][j]; cout<<"输入成绩"; cin>>a[i][j+1]; a[i][j+2]=0; cout<<endl; } } void comp(int a[][3],int n) { int i;int k,sum=0; for(i=0;i<n;i++) sum+=a[i][1]; k=sum/n; for(i=0;i<n;i++) { if(a[i][1]>=((1+0.2)*k)) a[i][2]=1; else if(a[i][1]>=((1+0.15)*k)) a[i][2]=2; else if(a[i][1]>=((1+0.1)*k)) a[i][2]=3; else a[i][2]=0; } } void output(int a[][3],int n) { int i,j; cout<<"学号"<<"成绩"<<"级别"<<endl; for(i=0;i<n;i++) { for(j=0;j<=2;j++) cout<<setw(4)<<a[i][j]; cout<<endl; } } void main() { int a[N][3],n=N; input(a,n); comp(a,n); output(a,n); cin>>n; }
[ [ [ 1, 55 ] ] ]
e45429e98e4984dcd838ca3e633dcf2df87ed3d8
4b30b09448549ffbe73c2346447e249713c1a463
/Sources/inetsock/email.h
4f6669d0d859bbfdef57419b0d7c1a7f95235ab8
[]
no_license
dblock/agnes
551fba6af6fcccfe863a1a36aad9fb066a2eaeae
3b3608eba8e7ee6a731f0d5a3191eceb0c012dd5
refs/heads/master
2023-09-05T22:32:10.661399
2009-10-29T11:23:28
2009-10-29T11:23:28
1,998,777
1
1
null
null
null
null
UTF-8
C++
false
false
541
h
#ifndef email_h #define email_h #include "../cstring/cstring.h" #include "inetsock.h" class CEmail{ public: CString from; CString to; CString name; CString subject; CString contents; CEmail(void); ~CEmail(void); void Send(const CString&); void Send(inetSocket& mail_sock); void expect110_ok(inetSocket&); void expect25_ok(inetSocket&, int code); void send25_ok(inetSocket&, const CString& string, int code); void send110_ok(inetSocket&, const CString& string); CString conversation; }; #endif
[ [ [ 1, 28 ] ] ]
a77e308cdfa265f13480ad6239a3f720c8f41a25
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/dom/DOMNodeList.hpp
8bf71b68047b6f80976ff795967a7803dede5245
[ "Apache-2.0" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
3,730
hpp
#ifndef DOMNodeList_HEADER_GUARD_ #define DOMNodeList_HEADER_GUARD_ /* * Copyright 2001-2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: DOMNodeList.hpp,v 1.9 2004/09/08 13:55:39 peiyongz Exp $ */ #include <xercesc/util/XercesDefs.hpp> XERCES_CPP_NAMESPACE_BEGIN class DOMNode; /** * The <code>DOMNodeList</code> interface provides the abstraction of an ordered * collection of nodes. DOMNodeLists are created by DOMDocument::getElementsByTagName(), * DOMNode::getChildNodes(), * * <p>The items in the <code>DOMNodeList</code> are accessible via an integral * index, starting from 0. * * DOMNodeLists are "live", in that any changes to the document tree are immediately * reflected in any DOMNodeLists that may have been created for that tree. */ class CDOM_EXPORT DOMNodeList { protected: // ----------------------------------------------------------------------- // Hidden constructors // ----------------------------------------------------------------------- /** @name Hidden constructors */ //@{ DOMNodeList() {}; //@} private: // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- /** @name Unimplemented constructors and operators */ //@{ DOMNodeList(const DOMNodeList &); DOMNodeList & operator = (const DOMNodeList &); //@} public: // ----------------------------------------------------------------------- // All constructors are hidden, just the destructor is available // ----------------------------------------------------------------------- /** @name Destructor */ //@{ /** * Destructor * */ virtual ~DOMNodeList() {}; //@} // ----------------------------------------------------------------------- // Virtual DOMNodeList interface // ----------------------------------------------------------------------- /** @name Functions introduced in DOM Level 1 */ //@{ // ----------------------------------------------------------------------- // Getter methods // ----------------------------------------------------------------------- /** * Returns the <code>index</code> item in the collection. * * If <code>index</code> is greater than or equal to the number of nodes in * the list, this returns <code>null</code>. * * @param index Index into the collection. * @return The node at the <code>index</code>th position in the * <code>DOMNodeList</code>, or <code>null</code> if that is not a valid * index. * @since DOM Level 1 */ virtual DOMNode *item(XMLSize_t index) const = 0; /** * Returns the number of nodes in the list. * * The range of valid child node indices is 0 to <code>length-1</code> inclusive. * @since DOM Level 1 */ virtual XMLSize_t getLength() const = 0; //@} }; XERCES_CPP_NAMESPACE_END #endif
[ [ [ 1, 113 ] ] ]
5eba17f617e8f39a14ab7a69d80b062c43d93eb4
d115cf7a1b374d857f6b094d4b4ccd8e9b1ac189
/tags/pyplusplus_dev_0.9.5/unittests/data/pointer_as_arg_to_be_exported.hpp
6b5901568ff9916c0a3f9e923c4197119fd710f9
[ "BSL-1.0" ]
permissive
gatoatigrado/pyplusplusclone
30af9065fb6ac3dcce527c79ed5151aade6a742f
a64dc9aeeb718b2f30bd6a5ff8dcd8bfb1cd2ede
refs/heads/master
2016-09-05T23:32:08.595261
2010-05-16T10:53:45
2010-05-16T10:53:45
700,369
4
2
null
null
null
null
UTF-8
C++
false
false
494
hpp
// Copyright 2004-2008 Roman Yakovenko. // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef __pointer_as_arg_to_be_exported_hpp__ #define __pointer_as_arg_to_be_exported_hpp__ #include <string> namespace pointer_as_arg{ struct data{}; inline int test_for_null( data* d=0 ){ return d ? 1 : 0; } } #endif//__pointer_as_arg_to_be_exported_hpp__
[ "roman_yakovenko@dc5859f9-2512-0410-ae5c-dd123cda1f76" ]
[ [ [ 1, 22 ] ] ]
4473d62048061fd8bd37233fa454e83aa0ad0cc9
1de7bc93ba6d2e2000683eaf97277b35679ab873
/SecureIM/commonheaders.cpp
aa6c45496328c77b64f2e58e49aa19268b0b391f
[]
no_license
mohamadpk/secureimplugin
b184642095e24b623b618d02cc7c946fc9bed6bf
6ebfa5477b1aa8baaccea3f86f402f6d7f808de1
refs/heads/master
2021-03-12T23:50:12.141449
2010-04-28T06:54:37
2010-04-28T06:54:37
37,033,105
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
8,182
cpp
#include "commonheaders.h" HINSTANCE g_hInst, g_hIconInst; PLUGINLINK *pluginLink; MM_INTERFACE mmi = {0}; MUUID interfaces[] = {MIID_SECUREIM, MIID_LAST}; LPCSTR szModuleName = MODULENAME; LPCSTR szVersionStr = MODULENAME" DLL ("__VERSION_STRING")"; char TEMP[MAX_PATH]; int TEMP_SIZE = 0; HANDLE g_hEvent[2], g_hMenu[15], g_hCLIcon=0, g_hFolders=0; HANDLE *g_hService=NULL; HANDLE *g_hHook=NULL; int iService=0; int iHook=0; HICON g_hICO[ICO_CNT], g_hPOP[POP_CNT], g_hIEC[1+IEC_CNT*MODE_CNT] = {0}; IconExtraColumn g_IEC[1+IEC_CNT*MODE_CNT]; int iBmpDepth; BOOL bCoreUnicode = false, bMetaContacts = false, bPopupExists = false, bPopupUnicode = false; BOOL bPGPloaded = false, bPGPkeyrings = false, bUseKeyrings = false, bPGPprivkey = false; BOOL bGPGloaded = false, bGPGkeyrings = false, bSavePass = false; BOOL bSFT, bSOM, bASI, bMCD, bSCM, bDGP, bAIP, bNOL, bAAK, bMCM; BYTE bADV, bPGP, bGPG; DWORD iCoreVersion = 0; CRITICAL_SECTION localQueueMutex; PLUGININFO pluginInfo = { sizeof(PLUGININFO), MODULENAME" (2in1)", __VERSION_DWORD, MODULENAME" plugin for Miranda IM ("__DATE__")", "Johell, Ghost, Nightwish, __alex, Baloo", "[email protected], [email protected]", "© 2003 Johell, © 2005-09 Baloo", "http://addons.miranda-im.org/details.php?action=viewfile&id=2445", 0, 0 }; PLUGININFOEX pluginInfoEx = { sizeof(PLUGININFOEX), MODULENAME" (2in1)", __VERSION_DWORD, MODULENAME" plugin for Miranda IM ("__DATE__")", "Johell, Ghost, Nightwish, __alex, Baloo", "[email protected], [email protected]", "© 2003 Johell, © 2005-09 Baloo", "http://addons.miranda-im.org/details.php?action=viewfile&id=2445", 0, 0, MIID_SECUREIM }; LPSTR myDBGetString(HANDLE hContact,const char *szModule,const char *szSetting) { char *val=NULL; DBVARIANT dbv; dbv.type = DBVT_ASCIIZ; DBGetContactSetting(hContact,szModule,szSetting,&dbv); if( dbv.pszVal && (dbv.type==DBVT_ASCIIZ || dbv.type==DBVT_UTF8 || dbv.type==DBVT_WCHAR) ) val = mir_strdup(dbv.pszVal); DBFreeVariant(&dbv); return val; } LPSTR myDBGetStringDecode(HANDLE hContact,const char *szModule,const char *szSetting) { char *val = myDBGetString(hContact,szModule,szSetting); if(!val) return NULL; int len = strlen(val)+64; char *buf = (LPSTR)mir_alloc(len); strncpy(buf,val,len); mir_free(val); CallService(MS_DB_CRYPT_DECODESTRING,(WPARAM)len,(LPARAM)buf); return buf; } int myDBWriteStringEncode(HANDLE hContact,const char *szModule,const char *szSetting,const char *val) { int len = strlen(val)+64; char *buf = (LPSTR)alloca(len); strncpy(buf,val,len); CallService(MS_DB_CRYPT_ENCODESTRING,(WPARAM)len,(LPARAM)buf); int ret = DBWriteContactSettingString(hContact,szModule,szSetting,buf); return ret; } /* int DBWriteString(HANDLE hContact,const char *szModule,const char *szSetting,const char *val) { return DBWriteContactSettingString(hContact,szModule,szSetting,val); } int DBGetByte(HANDLE hContact,const char *szModule,const char *szSetting,int errorValue) { return DBGetContactSettingByte(hContact,szModule,szSetting,errorValue); } int DBWriteByte(HANDLE hContact,const char *szModule,const char *szSetting,BYTE val) { return DBWriteContactSettingByte(hContact,szModule,szSetting,val); } int DBGetWord(HANDLE hContact,const char *szModule,const char *szSetting,int errorValue) { return DBGetContactSettingWord(hContact,szModule,szSetting,errorValue); } int DBWriteWord(HANDLE hContact,const char *szModule,const char *szSetting,WORD val) { return DBWriteContactSettingWord(hContact,szModule,szSetting,val); } */ void GetFlags() { bSFT = DBGetContactSettingByte(0,szModuleName,"sft",0); bSOM = DBGetContactSettingByte(0,szModuleName,"som",0); bASI = DBGetContactSettingByte(0,szModuleName,"asi",0); bMCD = DBGetContactSettingByte(0,szModuleName,"mcd",0); bSCM = DBGetContactSettingByte(0,szModuleName,"scm",0); bDGP = DBGetContactSettingByte(0,szModuleName,"dgp",0); bAIP = DBGetContactSettingByte(0,szModuleName,"aip",0); bADV = DBGetContactSettingByte(0,szModuleName,"adv",0); bNOL = DBGetContactSettingByte(0,szModuleName,"nol",0); bAAK = DBGetContactSettingByte(0,szModuleName,"aak",0); bMCM = DBGetContactSettingByte(0,szModuleName,"mcm",0); } void SetFlags() { DBWriteContactSettingByte(0,szModuleName,"sft",bSFT); DBWriteContactSettingByte(0,szModuleName,"som",bSOM); DBWriteContactSettingByte(0,szModuleName,"asi",bASI); DBWriteContactSettingByte(0,szModuleName,"mcd",bMCD); DBWriteContactSettingByte(0,szModuleName,"scm",bSCM); DBWriteContactSettingByte(0,szModuleName,"dgp",bDGP); DBWriteContactSettingByte(0,szModuleName,"aip",bAIP); DBWriteContactSettingByte(0,szModuleName,"adv",bADV); DBWriteContactSettingByte(0,szModuleName,"nol",bNOL); DBWriteContactSettingByte(0,szModuleName,"aak",bAAK); DBWriteContactSettingByte(0,szModuleName,"mcm",bMCM); } /*-----------------------------------------------------*/ /* LPSTR u2a( LPCWSTR src ) { int codepage = ServiceExists(MS_LANGPACK_GETCODEPAGE)?CallService( MS_LANGPACK_GETCODEPAGE, 0, 0 ):CP_ACP; int cbLen = WideCharToMultiByte( codepage, 0, src, -1, NULL, 0, NULL, NULL ); LPSTR result = (LPSTR) mir_alloc( cbLen+1 ); if ( result == NULL ) return NULL; WideCharToMultiByte( codepage, 0, src, -1, result, cbLen, NULL, NULL ); result[ cbLen ] = 0; return result; } LPWSTR a2u( LPCSTR src ) { int codepage = ServiceExists(MS_LANGPACK_GETCODEPAGE)?CallService( MS_LANGPACK_GETCODEPAGE, 0, 0 ):CP_ACP; int cbLen = MultiByteToWideChar( codepage, 0, src, -1, NULL, 0 ); LPWSTR result = (LPWSTR) mir_alloc( sizeof(WCHAR)*(cbLen+1)); if ( result == NULL ) return NULL; MultiByteToWideChar( codepage, 0, src, -1, result, cbLen ); result[ cbLen ] = 0; return result; } */ struct A2U { LPSTR a; LPSTR u; }; typedef A2U* pA2U; pA2U pa2u; int ca2u=0; LPSTR TranslateU( LPCSTR lpText ) { int i; for(i=0;i<ca2u;i++) { if( pa2u[i].a == lpText ) { return pa2u[i].u; } } ca2u++; pa2u = (pA2U) mir_realloc(pa2u,sizeof(A2U)*ca2u); pa2u[i].a = (LPSTR) lpText; if( bCoreUnicode ) { LPWSTR lpwText = mir_a2u(lpText); LPWSTR lpwTran = TranslateW(lpwText); mir_free(lpwText); pa2u[i].u = mir_strdup(exp->utf8encode(lpwTran)); } else { LPSTR lpTran = Translate(lpText); LPWSTR lpwTran = mir_a2u(lpTran); lpTran = exp->utf8encode(lpwTran); mir_free(lpwTran); pa2u[i].u = mir_strdup(lpTran); } return pa2u[i].u; } int msgbox( HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT uType) { if( bCoreUnicode ) { LPWSTR lpwText = mir_a2u(lpText); LPWSTR lpwCaption = mir_a2u(lpCaption); int r = MessageBoxW(hWnd,TranslateW(lpwText),TranslateW(lpwCaption),uType); mir_free(lpwCaption); mir_free(lpwText); return r; } return MessageBoxA(hWnd,Translate(lpText),Translate(lpCaption),uType); } void CopyToClipboard(HWND hwnd,LPSTR msg) { HGLOBAL hglbCopy; LPSTR lpstrCopy; hglbCopy = GlobalAlloc(GMEM_MOVEABLE, lstrlenA(msg)+1); lpstrCopy = (LPSTR)GlobalLock(hglbCopy); lstrcpyA(lpstrCopy, msg); GlobalUnlock(hglbCopy); OpenClipboard(NULL); EmptyClipboard(); SetClipboardData(CF_TEXT, hglbCopy); CloseClipboard(); } #if defined(_DEBUG) || defined(NETLIB_LOG) HANDLE hNetlibUser; void InitNetlib() { NETLIBUSER nl_user; memset(&nl_user,0,sizeof(nl_user)); nl_user.cbSize = sizeof(nl_user); nl_user.szSettingsModule = (LPSTR)szModuleName; nl_user.szDescriptiveName = (LPSTR)szModuleName; nl_user.flags = NUF_NOOPTIONS; hNetlibUser = (HANDLE)CallService(MS_NETLIB_REGISTERUSER, 0, (LPARAM)&nl_user); } void DeinitNetlib() { if(hNetlibUser) CallService(MS_NETLIB_CLOSEHANDLE, (WPARAM)hNetlibUser, 0); } int Sent_NetLog(const char *fmt,...) { va_list va; char szText[1024]; va_start(va,fmt); mir_vsnprintf(szText,sizeof(szText),fmt,va); va_end(va); return CallService(MS_NETLIB_LOG,(WPARAM)hNetlibUser,(LPARAM)szText); } #endif // EOF
[ "balookrd@d641cd86-4a32-0410-994c-055de1cff029" ]
[ [ [ 1, 273 ] ] ]
183b36a25d787b07a1cb1082b7870d2fd82c36ef
77d0b0ac21a9afdf667099c3cad0f9bbb483dc25
/include/iglu/tlistbox.h
c1d32ebc6976edbfefbf2a21830671d9d110d268
[]
no_license
martinribelotta/oneshot
21e218bbdfc310bad4a531dcd401ad28625ead75
81bde2718b6dac147282cce8a1c945187b0b2ccf
refs/heads/master
2021-05-27T23:29:43.732068
2010-05-24T04:36:10
2010-05-24T04:36:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,917
h
/* * IGLU Iterfaz Grafica Libre del Usuario. * Copyright (C) 2005 Martin Alejandro Ribelotta * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef _igluTListBox_h #define _igluTListBox_h #include <iglu/tview.h> #include <iglu/tbutton.h> #include <iglu/tlist.h> #include <iglu/tscroll.h> class TListBox: public TView { protected: TList *list; TScroll *bar; int topitem, bottomitem, flags; void calculateparams (); void drawitems (); void drawdecorate (); void dodrawitems (); void dodrawdecorate (); public: int pos, height_item; void (*onSelect) (TPoint& pos, TListBox *list); TListBox (TRect& r); ~TListBox (); void selectn (int n); inline int nitems () { return list->count; } virtual void Draw (); virtual void HandleEvent (TEvent& e); virtual void moverel(int dx, int dy); virtual void RecuestAlign (TRect& o, TRect& n); virtual void getClientArea (TRect& r, int absolute); virtual void GotFocus (); virtual void LostFocus (); void additem (char *name, TObject *obj=NULL); int finditem (char *name); char *getn(int n) { return list->getname (n); } void clearlist (); }; #endif /* _igluTListBox_h */
[ [ [ 1, 67 ] ] ]
2b875268bdaa8374091d5c76f09d6e549e5c5ce1
b63cad17af550bc7150431b7b0d639a46a129d82
/crypto.cpp
a335530896aadbbd46bc905bf71949934685b2d8
[]
no_license
cjus/msgCourier
90463028b5e6222dd5c804215fa43bc518c4a539
075ff724316fd28c21d842726b694806d82bf53b
refs/heads/master
2021-01-10T19:41:02.306930
2010-09-05T18:47:24
2010-09-05T18:47:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,286
cpp
/* crypto.h Copyright (C) 2005 Carlos Justiniano [email protected], [email protected], [email protected] crypto.cpp 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. crypto.cpp was developed by Carlos Justiniano for use on the msgCourier project and the ChessBrain Project and is now 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 crypto.cpp; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* #include "cryptopp/crc.h" #include "cryptopp/adler32.h" #include "cryptopp/md2.h" #include "cryptopp/md5.h" #include "cryptopp/md5mac.h" #include "cryptopp/sha.h" #include "cryptopp/haval.h" #include "cryptopp/tiger.h" #include "cryptopp/ripemd.h" #include "cryptopp/panama.h" #include "cryptopp/whrlpool.h" #include "cryptopp/idea.h" #include "cryptopp/des.h" #include "cryptopp/rc2.h" #include "cryptopp/arc4.h" #include "cryptopp/rc5.h" #include "cryptopp/blowfish.h" #include "cryptopp/wake.h" #include "cryptopp/3way.h" #include "cryptopp/safer.h" #include "cryptopp/gost.h" #include "cryptopp/shark.h" #include "cryptopp/cast.h" #include "cryptopp/square.h" #include "cryptopp/skipjack.h" #include "cryptopp/seal.h" #include "cryptopp/rc6.h" #include "cryptopp/mars.h" #include "cryptopp/rijndael.h" #include "cryptopp/twofish.h" #include "cryptopp/serpent.h" #include "cryptopp/shacal2.h" #include "cryptopp/camellia.h" #include "cryptopp/hmac.h" #include "cryptopp/xormac.h" #include "cryptopp/cbcmac.h" #include "cryptopp/dmac.h" #include "cryptopp/ttmac.h" #include "cryptopp/blumshub.h" #include "cryptopp/rng.h" #include "cryptopp/files.h" #include "cryptopp/hex.h" #include "cryptopp/modes.h" #include "cryptopp/mdc.h" #include "cryptopp/lubyrack.h" #include "cryptopp/tea.h" #include "cryptopp/randpool.h" #include "cryptopp/rsa.h" #include "cryptopp/base64.h" */ #include <iostream> #include "crypto.h" using namespace std; //using namespace CryptoPP; void cCrypto::CreateSHA(const char *pData, int len, string &shaoutput) { /* byte shahash[SHA::DIGESTSIZE]; SHA().CalculateDigest(shahash, (const byte*)pData, len); byte buffer[1 + 2 * SHA::DIGESTSIZE]; HexEncoder hex; hex.Put(shahash, SHA::DIGESTSIZE); hex.MessageEnd(); hex.Get(buffer, 2*SHA::DIGESTSIZE); buffer[2 * SHA::DIGESTSIZE] = 0; shaoutput = (const char *)buffer; */ } void cCrypto::GenerateCerts() { /* //Print("Generation of public/private key certificates is a time consuming task.\nPlease be patient..."); try { //unsigned int keyLength, const char *privFilename, const char *pubFilename, const char *seed unsigned int keyLength = 4096; const char *privFilename = "msgCourier.prv"; const char *pubFilename = "msgCourier.pub"; // generate seed char timestring[20]; sprintf(timestring, "%x", time(0)); byte shahash[SHA::DIGESTSIZE]; SHA().CalculateDigest(shahash, (const byte*)timestring, strlen(timestring)); byte seed[1 + 2 * SHA::DIGESTSIZE]; HexEncoder hex; hex.Put(shahash, SHA::DIGESTSIZE); hex.MessageEnd(); hex.Get(seed, 2*SHA::DIGESTSIZE); seed[2 * SHA::DIGESTSIZE] = 0; // create certificates RandomPool randPool; randPool.Put((byte*)seed, strlen((char*)seed)); RSAES_OAEP_SHA_Decryptor priv(randPool, keyLength); HexEncoder privFile(new FileSink(privFilename)); priv.DEREncode(privFile); privFile.MessageEnd(); RSAES_OAEP_SHA_Encryptor pub(priv); HexEncoder pubFile(new FileSink(pubFilename)); pub.DEREncode(pubFile); pubFile.MessageEnd(); //Print("\nGeneration of public/private key certificates succeeded.\nThe files msgCourier.prv and msgCourier.pub have been created.\n"); } catch (...) { //Print("\nGeneration of public/private key certificates failed.\n"); } */ }
[ [ [ 1, 143 ] ] ]
07f71e4092da79217b1c9a52e9d874fc695200cd
14a00dfaf0619eb57f1f04bb784edd3126e10658
/Lab3/SupportCode/ColorMap.cpp
f5397d6b49633e504fd5b9426ac86a0fe5126b35
[]
no_license
SHINOTECH/modanimation
89f842262b1f552f1044d4aafb3d5a2ce4b587bd
43d0fde55cf75df9d9a28a7681eddeb77460f97c
refs/heads/master
2021-01-21T09:34:18.032922
2010-04-07T12:23:13
2010-04-07T12:23:13
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,997
cpp
/************************************************************************************************* * * Modeling and animation (TNM079) 2007 * Code base for lab assignments. Copyright: * Gunnar Johansson ([email protected]) * Ken Museth ([email protected]) * Michael Bang Nielsen ([email protected]) * Ola Nilsson ([email protected]) * Andreas Söderström ([email protected]) * *************************************************************************************************/ #include "ColorMap.h" //----------------------------------------------------------------------------- ColorMap::ColorMap() { /* % A matlab script to export colormaps function f=pcmap(cmap) s = size(cmap); for i=1:s(1,1) fprintf(1, 'colors.push_back(Vector3<float>(%f, %f, %f));\n', cmap(i,1), cmap(i,2), cmap(i,3)); end */ // run the above script with for example the colormap jet: pcmap(jet) // and paste the result below to change colormap // A simple red-black-blue colormap colors.push_back(Vector3<float>(1, 0, 0)); colors.push_back(Vector3<float>(0, 0, 0)); colors.push_back(Vector3<float>(0, 0, 1)); } //----------------------------------------------------------------------------- Vector3<float> ColorMap::map(float val, float low, float high) const { float h = switch1(val, low, high); h = clamp(h, 0.f, 1.f); float pos = h*(colors.size()-1); float t = pos - floorf(pos); unsigned int index = (unsigned int) floorf(pos); // linear interpolation return colors[index]*(1-t) + colors[index+1]*t; } //----------------------------------------------------------------------------- Vector3<float> ColorMap::map(Vector3<float> vec, float low, float high) const { return Vector3<float>(switch1(vec.x(), low, high),switch1(vec.y(), low, high),switch1(vec.z(), low, high)); } //-----------------------------------------------------------------------------
[ "jpjorge@da195381-492e-0410-b4d9-ef7979db4686" ]
[ [ [ 1, 46 ] ] ]
887124fd0860bd9cb1c0ebab9e13da88a2901ae7
22b6d8a368ecfa96cb182437b7b391e408ba8730
/engine/include/qvHashFunctions.h
a7fdf53c7112757bc4db33b53d6c6453508689ba
[ "MIT" ]
permissive
drr00t/quanticvortex
2d69a3e62d1850b8d3074ec97232e08c349e23c2
b780b0f547cf19bd48198dc43329588d023a9ad9
refs/heads/master
2021-01-22T22:16:50.370688
2010-12-18T12:06:33
2010-12-18T12:06:33
85,525,059
0
0
null
null
null
null
UTF-8
C++
false
false
2,334
h
/************************************************************************************************** //This code is part of QuanticVortex for latest information, see http://www.quanticvortex.org // //Copyright (c) 2009-2010 QuanticMinds Software Ltda. // //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: // //The above copyright notice and this permission notice shall be included in //all copies or substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //THE SOFTWARE. **************************************************************************************************/ #ifndef __HASH_FUNCTIONS_H_ #define __HASH_FUNCTIONS_H_ #include "qvCompileConfig.h" #include "qvTypes.h" namespace qv { //----------------------------------------------------------------------------- /*// MurmurHash2, by Austin Appleby from http://sites.google.com/site/murmurhash/ // Note - This code makes a few assumptions about how your machine behaves - // 1. We can read a 4-byte value from any address without crashing // 2. sizeof(int) == 4 // And it has a few limitations - // 1. It will not work incrementally. // 2. It will not produce the same results on little-endian and big-endian // machines. // All code is released to the public domain. For business purposes, Murmurhash is // under the MIT license. */ extern "C" _QUANTICVORTEX_API_ u32 QUANTICVORTEX_CALLCONV createMurmurHash2 ( const void * key, u32 len, u32 seed = 0); } #endif
[ [ [ 1, 56 ] ] ]
fa6ccb8725adb717e65ba1a1985ac4a403f7f426
619941b532c6d2987c0f4e92b73549c6c945c7e5
/Stellar_/code/Foundation/math/d3dx9/d3dx9_scalar.h
44be4f17877df72638b321258a6fd68a8cd9676e
[]
no_license
dzw/stellarengine
2b70ddefc2827be4f44ec6082201c955788a8a16
2a0a7db2e43c7c3519e79afa56db247f9708bc26
refs/heads/master
2016-09-01T21:12:36.888921
2008-12-12T12:40:37
2008-12-12T12:40:37
36,939,169
0
0
null
null
null
null
UTF-8
C++
false
false
6,493
h
#pragma once #ifndef MATH_D3DX9_SCALAR_H #define MATH_D3DX9_SCALAR_H //------------------------------------------------------------------------------ /** @file math/d3dx9/scalar.h Scalar typedef and math functions for D3DX9 math functions. (C) 2007 Radon Labs GmbH */ #include "core/types.h" namespace Math { typedef float scalar; #ifndef PI #define PI (3.1415926535897932384626433832795028841971693993751f) #endif #define S_PI PI #ifndef TINY #define TINY (0.0000001f) #endif #define S_TINY TINY #define s_max(a,b) (((a) > (b)) ? (a) : (b)) #define s_min(a,b) (((a) < (b)) ? (a) : (b)) #define s_abs(a) (((a)<0.0f) ? (-(a)) : (a)) #define s_sgn(a) (((a)<0.0f) ? (-1) : (1)) #define s_max(a,b) (((a) > (b)) ? (a) : (b)) #define s_min(a,b) (((a) < (b)) ? (a) : (b)) #define s_abs(a) (((a)<0.0f) ? (-(a)) : (a)) #define s_sgn(a) (((a)<0.0f) ? (-1) : (1)) #define s_deg2rad(d) (((d)*PI)/180.0f) #define s_rad2deg(r) (((r)*180.0f)/PI) const scalar LN_2 = 0.693147180559945f; //------------------------------------------------------------------------------ /** */ __forceinline scalar s_sin(scalar x) { return sinf(x); } //------------------------------------------------------------------------------ /** */ __forceinline scalar s_cos(scalar x) { return cosf(x); } //------------------------------------------------------------------------------ /** */ __forceinline scalar s_asin(scalar x) { return asinf(x); } //------------------------------------------------------------------------------ /** */ __forceinline scalar s_acos(scalar x) { return acosf(x); } //------------------------------------------------------------------------------ /** log2() function. */ __forceinline scalar s_log2(scalar f) { return logf(f) / LN_2; } //------------------------------------------------------------------------------ /** Integer clamping. */ __forceinline int s_iclamp(int val, int minVal, int maxVal) { if (val < minVal) return minVal; else if (val > maxVal) return maxVal; else return val; } //------------------------------------------------------------------------------ /** Safe sqrt. */ __forceinline scalar s_sqrt(scalar x) { return sqrtf(x); } //------------------------------------------------------------------------------ /** A fuzzy floating point equality check */ __forceinline bool s_fequal(scalar f0, scalar f1, scalar tol) { scalar f = f0 - f1; return ((f > (-tol)) && (f < tol)); } //------------------------------------------------------------------------------ /** A fuzzy floating point less-then check. */ __forceinline bool s_fless(scalar f0, scalar f1, scalar tol) { return ((f0 - f1) < tol); } //------------------------------------------------------------------------------ /** A fuzzy floating point greater-then check. */ __forceinline bool s_fgreater(scalar f0, scalar f1, scalar tol) { return ((f0 - f1) > tol); } //------------------------------------------------------------------------------ /** Smooth a new value towards an old value using a change value. */ __forceinline scalar s_smooth(scalar newVal, scalar curVal, scalar maxChange) { scalar diff = newVal - curVal; if (fabs(diff) > maxChange) { if (diff > 0.0f) { curVal += maxChange; if (curVal > newVal) { curVal = newVal; } } else if (diff < 0.0f) { curVal -= maxChange; if (curVal < newVal) { curVal = newVal; } } } else { curVal = newVal; } return curVal; } //------------------------------------------------------------------------------ /** Clamp a value against lower und upper boundary. */ __forceinline scalar s_clamp(scalar val, scalar lower, scalar upper) { if (val < lower) return lower; else if (val > upper) return upper; else return val; } //------------------------------------------------------------------------------ /** Saturate a value (clamps between 0.0f and 1.0f) */ __forceinline scalar s_saturate(scalar val) { if (val < 0.0f) return 0.0f; else if (val > 1.0f) return 1.0f; else return val; } //------------------------------------------------------------------------------ /** Return a pseudo random number between 0 and 1. */ __forceinline scalar s_rand() { return scalar(rand()) / scalar(RAND_MAX); } //------------------------------------------------------------------------------ /** Return a pseudo random number between min and max. */ __forceinline scalar s_rand(scalar min, scalar max) { scalar unit = scalar(rand()) / RAND_MAX; scalar diff = max - min; return min + unit * diff; } //------------------------------------------------------------------------------ /** Chop float to int. */ __forceinline int s_fchop(scalar f) { /// @todo type cast to int is slow! return int(f); } //------------------------------------------------------------------------------ /** Round float to integer. */ __forceinline int s_frnd(scalar f) { return s_fchop(floorf(f + 0.5f)); } //------------------------------------------------------------------------------ /** Linearly interpolate between 2 values: ret = x + l * (y - x) */ __forceinline float s_lerp(scalar x, scalar y, scalar l) { return x + l * (y - x); } //------------------------------------------------------------------------------ /** */ __forceinline scalar s_fmod(scalar x, scalar y) { return fmodf(x, y); } //------------------------------------------------------------------------------ /** Normalize an angular value into the range rad(0) to rad(360). */ __forceinline scalar s_modangle(scalar a) { // FIXME: hmm... while(a < 0.0f) { a += s_deg2rad(360.0f); } if (a >= s_deg2rad(360.0f)) { a = s_fmod(a, s_deg2rad(360.0f)); } return a; } } // namespace Math //------------------------------------------------------------------------------ #endif
[ "ctuoMail@5f320639-c338-0410-82ad-c55551ec1e38" ]
[ [ [ 1, 286 ] ] ]
82bbb1b550cc37c452669b317ec6969895957e66
e02fa80eef98834bf8a042a09d7cb7fe6bf768ba
/TestPlugin/src/TestPluginDLL.cpp
b9fb7912f7757b831ec33987df15918d97c9d79b
[]
no_license
MyGUI/mygui-historical
fcd3edede9f6cb694c544b402149abb68c538673
4886073fd4813de80c22eded0b2033a5ba7f425f
refs/heads/master
2021-01-23T16:40:19.477150
2008-03-06T22:19:12
2008-03-06T22:19:12
22,805,225
2
0
null
null
null
null
UTF-8
C++
false
false
372
cpp
#include "TestPlugin.h" #include "MyGUI_PluginManager.h" TestPlugin *plugin = 0; extern "C" void _MyGUIExport dllStartPlugin(void) { plugin = new TestPlugin(); MyGUI::PluginManager::getInstance().installPlugin(plugin); } extern "C" void _MyGUIExport dllStopPlugin(void) { MyGUI::PluginManager::getInstance().uninstallPlugin(plugin); delete plugin; }
[ [ [ 1, 1 ], [ 3, 8 ], [ 10, 13 ], [ 15, 16 ] ], [ [ 2, 2 ], [ 9, 9 ], [ 14, 14 ] ] ]
44048d652018b5d0f19894cb2216e2a2c8743b3d
6b3fa487428d3e2c66376572fd3c6dd3501b282c
/sapien190/trunk/source/Sandbox/Sapien/rpy/Continuous.h
7fddfef603bbb4165c19a4755a0c7cd5362fa72e
[]
no_license
kimbjerge/iirtsf10grp5
8626a10b23ee5cdde9944280c3cd06833e326adb
3cbdd2ded74369d2cd455f63691abc834edfb95c
refs/heads/master
2021-01-25T06:36:48.487881
2010-06-03T09:26:19
2010-06-03T09:26:19
32,920,746
0
0
null
null
null
null
UTF-8
C++
false
false
2,221
h
/********************************************************************* Rhapsody : 7.5 Login : KBE Component : DefaultComponent Configuration : DefaultConfig Model Element : Continuous //! Generated Date : Fri, 30, Apr 2010 File Path : DefaultComponent/DefaultConfig/Continuous.h *********************************************************************/ #ifndef Continuous_H #define Continuous_H //#[ ignore #ifdef _MSC_VER // disable Microsoft compiler warning (debug information truncated) #pragma warning(disable: 4786) #endif //#] //## auto_generated #include <oxf/oxf.h> //## auto_generated #include <string> //## auto_generated #include <algorithm> //## auto_generated #include "math.h" //## auto_generated #include "Application.h" //## classInstance itsECGCalculate class ECGCalculate; //## classInstance itsEDRCalculate class EDRCalculate; //## auto_generated class Filter; //## auto_generated class Generator; //## auto_generated class InfECGCalculate; //## auto_generated class InfusionGenerator; //## auto_generated class Medicine; //## classInstance itsNormalGenerator class NormalGenerator; //## auto_generated class PatientModel; //## classInstance itsPulseCalculate class PulseCalculate; //## auto_generated class Record; //## auto_generated class RecordFile; //## auto_generated class RecordIterator; //## auto_generated class RecordProxy; //## auto_generated class RecordSimulate; //## auto_generated class TestContinous; //## package Application::Continuous //## type SampleType typedef int SampleType; //## auto_generated void Continuous_initRelations(); //## classInstance itsECGCalculate extern ECGCalculate itsECGCalculate; //## classInstance itsEDRCalculate extern EDRCalculate itsEDRCalculate; //## classInstance itsNormalGenerator extern NormalGenerator itsNormalGenerator; //## classInstance itsPulseCalculate extern PulseCalculate itsPulseCalculate; #endif /********************************************************************* File Path : DefaultComponent/DefaultConfig/Continuous.h *********************************************************************/
[ "bjergekim@49e60964-1571-11df-9d2a-2365f6df44e6" ]
[ [ [ 1, 103 ] ] ]
07796131fec9a7ef6919792f211a625a304da239
e88830a2981a792c91776bf1188c7d15edc6dea0
/HaploBuilder.cpp
1aec7d82f51dddb37696e396ff3d79f4565d3c1d
[]
no_license
Wu-Lab/HMC
9d848582cddae4a2d6cbb5f492bca51fde923918
5f5c0e22fcbc007e2dae2eb2dfe53e1b78a964ef
refs/heads/master
2020-07-09T08:55:22.057596
2010-12-29T21:48:38
2010-12-29T21:48:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,423
cpp
#include "HaploBuilder.h" #include "HaploPair.h" #include "GenoData.h" #include "MemLeak.h" HaploBuilder::HaploBuilder() : m_patterns(*this), m_sample_size(1) { } HaploBuilder::~HaploBuilder() { for_each(m_haplopairs.begin(), m_haplopairs.end(), DeleteAll_Clear()); } void HaploBuilder::setGenoData(GenoData &genos) { m_genos = &genos; m_samples.clear(); } void HaploBuilder::initialize() { for_each(m_haplopairs.begin(), m_haplopairs.end(), DeleteAll_Clear()); m_haplopairs.resize(genotype_len()+1); m_best_pair.resize(pattern_num()); for (int i=0; i<pattern_num(); ++i) { m_best_pair[i].clear(); } } double HaploBuilder::resolve(const Genotype &genotype, Genotype &resolution, vector<Genotype> &res_list, int sample_size) { int pn = pattern_num(); int head_len = m_patterns.head_len(); int i, j, k, n; Allele a, b; double total_likelihood, coverage; vector<HaploPairLink> res_link; vector<HaploPair*>::iterator i_hp; m_sample_size = sample_size > 1 ? sample_size : 1; initialize(); initHeadList(genotype); for (i=head_len; i<genotype_len(); ++i) { if (genotype.isMissing(i)) { for (j=0; j<m_genos->allele_num(i); ++j) { if (m_genos->allele_frequency(i, j) > 0) { for (k=j; k<m_genos->allele_num(i); ++k) { if (m_genos->allele_frequency(i, k) > 0) { a = m_genos->allele_symbol(i, j); b = m_genos->allele_symbol(i, k); extendAll(i, a, b); } } } } } else if (genotype(0)[i].isMissing()) { for (j=0; j<m_genos->allele_num(i); ++j) { if (m_genos->allele_frequency(i, j) > 0) { a = m_genos->allele_symbol(i, j); extendAll(i, a, genotype(1)[i]); } } } else if (genotype(1)[i].isMissing()) { for (j=0; j<m_genos->allele_num(i); ++j) { if (m_genos->allele_frequency(i, j) > 0) { a = m_genos->allele_symbol(i, j); extendAll(i, a, genotype(0)[i]); } } } else { extendAll(i, genotype(0)[i], genotype(1)[i]); } if (m_haplopairs[i+1].size() <= 0) { break; } else { for_each(m_haplopairs[i+1].begin(), m_haplopairs[i+1].end(), HaploPair::pack_size()); } } if (m_haplopairs[genotype_len()].size() > 0) { total_likelihood = 0; res_link.clear(); for (i_hp = m_haplopairs[genotype_len()].begin(); i_hp != m_haplopairs[genotype_len()].end(); ++i_hp) { total_likelihood += (*i_hp)->forward_likelihood(); k = res_link.size(); n = (*i_hp)->best_links().size(); res_link.insert(res_link.end(), (*i_hp)->best_links().begin(), (*i_hp)->best_links().end()); for (i=k; i<k+n; ++i) { res_link[i].link = (*i_hp); res_link[i].index = i-k; if (!res_link[i].homozygous) res_link[i].likelihood *= 2.0; } if (res_link.size() > m_sample_size) { nth_element(res_link.begin(), res_link.begin()+m_sample_size-1, res_link.end(), greater<HaploPairLink>()); res_link.resize(m_sample_size); } } sort(res_link.begin(), res_link.end(), greater<HaploPairLink>()); coverage = 0; res_list.clear(); n = res_link.size(); for (i=0; i<n; ++i) { res_list.push_back(res_link[i].link->getGenotype(res_link[i].index)); res_list[i].setPosteriorProbability(res_list[i].prior_probability() / total_likelihood); res_list[i].setGenotypeProbability(total_likelihood); coverage += res_list[i].posterior_probability(); } resolution = res_list.front(); } else { coverage = 0; res_list.clear(); resolution = genotype; resolution.setPriorProbability(0); resolution.setPosteriorProbability(0); resolution.setGenotypeProbability(0); } return coverage; } double HaploBuilder::getLikelihood(const Haplotype &haplotype) { int head_len = m_patterns.head_len(); const BackwardPatternTree *pattern_tree = m_patterns.pattern_tree(); int i; HaploPattern *hp; double likelihood = 1.0; for (i=head_len; i<=genotype_len(); ++i) { hp = pattern_tree->findLongestMatchPattern(i, &haplotype); if (hp) { likelihood *= hp->transition_prob(); } else { likelihood = 0; break; } } return likelihood; } double HaploBuilder::getLikelihood(const Genotype &genotype) { return getLikelihood(genotype(0)) * getLikelihood(genotype(1)); } void HaploBuilder::initHeadList(const Genotype &genotype) { int head_len = m_patterns.head_len(); const vector<HaploPattern*> &head_list = m_patterns.head_list(); const BackwardPatternTree *pattern_tree = m_patterns.pattern_tree(); vector<AlleleSequence*> new_list, last_list; vector<AlleleSequence*>::iterator i_as; vector<HaploPattern*>::const_iterator head; for (head = head_list.begin(); head != head_list.end(); ++head) { if ((*head)->isMatch(genotype)) { last_list.push_back(new AlleleSequence); for (int j=0; j<head_len; ++j) { i_as = last_list.begin(); if (genotype.isMissing(j) || (genotype.hasMissing(j) && genotype.hasAllele(j, (**head)[j]))) { while (i_as != last_list.end()) { AlleleSequence *as = *i_as; for (int k=0; k<m_genos->allele_num(j); ++k) { if (m_genos->allele_frequency(j, k) > 0) { AlleleSequence *new_as = new AlleleSequence; new_as->assign(*as, m_genos->allele_symbol(j, k)); new_list.push_back(new_as); } } ++i_as; } } else if (genotype.isHeterozygous(j)) { while (i_as != last_list.end()) { AlleleSequence *as = *i_as; AlleleSequence *new_as = new AlleleSequence; if ((**head)[j] == genotype(0)[j]) { new_as->assign(*as, genotype(1)[j]); } else { new_as->assign(*as, genotype(0)[j]); } new_list.push_back(new_as); ++i_as; } } else { while (i_as != last_list.end()) { AlleleSequence *as = *i_as; AlleleSequence *new_as = new AlleleSequence; new_as->assign(*as, genotype(0)[j]); new_list.push_back(new_as); ++i_as; } } DeleteAll_Clear()(last_list); last_list.swap(new_list); } i_as = last_list.begin(); while (i_as != last_list.end()) { HaploPattern *hp = pattern_tree->findLongestMatchPattern(head_len, *i_as); if (hp && hp->start() == 0) { if (hp->id() >= (*head)->id()) { HaploPair *new_hp = new HaploPair(*head, hp); m_haplopairs[head_len].push_back(new_hp); m_best_pair[new_hp->id_a()].insert(make_pair(new_hp->id_b(), m_haplopairs[head_len].size())); } } else { Logger::error("Can not find matching pattern!"); exit(1); } ++i_as; } DeleteAll_Clear()(last_list); } } } void HaploBuilder::extendAll(int i, Allele a1, Allele a2) { vector<HaploPair*>::iterator i_hp; for (i_hp = m_haplopairs[i].begin(); i_hp != m_haplopairs[i].end(); ++i_hp) { extend(*i_hp, a1, a2); if (a1 != a2) extend(*i_hp, a2, a1); } } void HaploBuilder::extend(HaploPair *hp, Allele a1, Allele a2) { if (hp->forward_likelihood() <= 0) return; const HaploPattern *hpa, *hpb; hpa = hp->successor_a(a1); hpb = hp->successor_b(a2); if (hpa && hpb) { addHaploPair(hp, hpa, hpb); } } void HaploBuilder::addHaploPair(HaploPair *hp, const HaploPattern *hpa, const HaploPattern *hpb) { bool reversed = false; if (hpa->id() > hpb->id()) { reversed = true; swap(hpa, hpb); } map<int, int>::iterator i = m_best_pair[hpa->id()].lower_bound(hpb->id()); if (i == m_best_pair[hpa->id()].end() || (*i).first != hpb->id()) { m_haplopairs[hp->end()+1].push_back(new HaploPair(hpa, hpb, hp, reversed)); m_best_pair[hpa->id()].insert(i, make_pair(hpb->id(), m_haplopairs[hp->end()+1].size())); } else { m_haplopairs[hp->end()+1][(*i).second-1]->add(hp, reversed, m_sample_size); } } void HaploBuilder::calcBackwardLikelihood() { int head_len = m_patterns.head_len(); vector<HaploPair*>::iterator i_hp; for (int i=genotype_len()-1; i>=head_len; --i) { for (i_hp=m_haplopairs[i].begin(); i_hp!=m_haplopairs[i].end(); ++i_hp) { (*i_hp)->calcBackwardLikelihood(); } } } void HaploBuilder::estimateFrequency(vector<HaploPattern*> &patterns) { int i, n; int start, geno; Genotype res; vector<Genotype> res_list; ForwardPatternTree tree(*m_genos); map<HaploPair*, double> match_list[3]; n = patterns.size(); for (i=0; i<n; ++i) { HaploPattern *hp = patterns[i]; tree.addPattern(hp); hp->setFrequency(0); hp->setPrefixFreq(0); } for (geno=0; geno<genotype_num(); ++geno) { resolve((*m_genos)[geno], res, res_list); calcBackwardLikelihood(); m_current_genotype_probability = (*m_genos)[geno].genotype_probability(); for (start=0; start<genotype_len(); ++start) { match_list[0].clear(); match_list[1].clear(); int end = max(start, m_patterns.head_len()); n = m_haplopairs[end].size(); for (i=0; i<n; ++i) { HaploPair *hp = m_haplopairs[end][i]; match_list[0][hp] = hp->forward_likelihood(); } PatternNode *node = tree.root(start); n = node->size(); for (i=0; i<node->size(); ++i) { if (node->getChild(i)) { estimateFrequency(node->getChild(i), start, m_genos->allele_symbol(start, i), 1.0, match_list); } } } } n = patterns.size(); for (i=0; i<n; ++i) { HaploPattern *hp = patterns[i]; double freq = min(hp->frequency(), genotype_num()); double prefix_freq = min(hp->prefix_freq(), genotype_num()); freq = min(freq, prefix_freq); hp->setFrequency(freq / genotype_num()); hp->setPrefixFreq(prefix_freq / genotype_num()); if (prefix_freq > 0) { hp->setTransitionProb(freq / prefix_freq); } else { hp->setTransitionProb(freq / genotype_num()); } } } double HaploBuilder::estimateFrequency(PatternNode *node, int locus, const Allele &a, double last_freq, const map<HaploPair*, double> last_match[3]) { map<HaploPair*, double> match_list[3]; map<HaploPair*, double>::const_iterator i_mp; vector<HaploPair*>::const_iterator i_link; HaploPair *last_hp, *hp; double weight; int i; if (locus < m_patterns.head_len()) { for (i_mp=last_match[0].begin(); i_mp!=last_match[0].end(); ++i_mp) { hp = (*i_mp).first; weight = (*i_mp).second; if (hp->pattern_a()[locus] == a) { if (hp->pattern_b()[locus] == a) { match_list[0][hp] += weight; } else { match_list[1][hp] += weight * 0.5; } } else if (hp->pattern_b()[locus] == a) { match_list[2][hp] += weight * 0.5; } } for (i_mp=last_match[1].begin(); i_mp!=last_match[1].end(); ++i_mp) { hp = (*i_mp).first; weight = (*i_mp).second; if (hp->pattern_a()[locus] == a) { match_list[1][hp] += weight; } } for (i_mp=last_match[2].begin(); i_mp!=last_match[2].end(); ++i_mp) { hp = (*i_mp).first; weight = (*i_mp).second; if (hp->pattern_b()[locus] == a) { match_list[2][hp] += weight; } } } else { for (i_mp=last_match[0].begin(); i_mp!=last_match[0].end(); ++i_mp) { last_hp = (*i_mp).first; weight = (*i_mp).second; for (i=0; i<2; ++i) { for (i_link=last_hp->forward_links(i).begin(); i_link!=last_hp->forward_links(i).end(); ++i_link) { hp = *i_link; if (hp->allele_a() == a) { if (hp->allele_b() == a) { match_list[0][hp] += weight * hp->transition_prob(); } else { match_list[1][hp] += weight * hp->transition_prob() * 0.5; } } else if (hp->allele_b() == a) { match_list[2][hp] += weight * hp->transition_prob() * 0.5; } } } } for (i_mp=last_match[1].begin(); i_mp!=last_match[1].end(); ++i_mp) { last_hp = (*i_mp).first; weight = (*i_mp).second; for (i_link=last_hp->forward_links(0).begin(); i_link!=last_hp->forward_links(0).end(); ++i_link) { hp = *i_link; if (hp->allele_a() == a) { match_list[1][hp] += weight * hp->transition_prob(); } } for (i_link=last_hp->forward_links(1).begin(); i_link!=last_hp->forward_links(1).end(); ++i_link) { hp = *i_link; if (hp->allele_b() == a) { match_list[2][hp] += weight * hp->transition_prob(); } } } for (i_mp=last_match[2].begin(); i_mp!=last_match[2].end(); ++i_mp) { last_hp = (*i_mp).first; weight = (*i_mp).second; for (i_link=last_hp->forward_links(0).begin(); i_link!=last_hp->forward_links(0).end(); ++i_link) { hp = *i_link; if (hp->allele_b() == a) { match_list[2][hp] += weight * hp->transition_prob(); } } for (i_link=last_hp->forward_links(1).begin(); i_link!=last_hp->forward_links(1).end(); ++i_link) { hp = *i_link; if (hp->allele_a() == a) { match_list[1][hp] += weight * hp->transition_prob(); } } } } double freq = 0; for (i=0; i<3; ++i) { for (i_mp=match_list[i].begin(); i_mp!=match_list[i].end(); ++i_mp) { freq += (*i_mp).second * (*i_mp).first->backward_likelihood(); } } freq /= m_current_genotype_probability; if (node->data()) { HaploPattern *hp = node->data(); hp->setFrequency(hp->frequency() + freq); hp->setPrefixFreq(hp->prefix_freq() + last_freq); } for (i=0; i<node->size(); ++i) { if (node->getChild(i)) { estimateFrequency(node->getChild(i), locus+1, m_genos->allele_symbol(locus+1, i), freq, match_list); } } return freq; }
[ "wulingyun@localhost" ]
[ [ [ 1, 450 ] ] ]
4ed977978f26a919a278a18dea24c6e56b183a33
f177993b13e97f9fecfc0e751602153824dfef7e
/ImProSln/ARToolKitPlus_2.1.1/src/CameraFactory.cxx
8539edff2330eb64aee7c042b3f426a3a77c30a9
[]
no_license
svn2github/imtophooksln
7bd7412947d6368ce394810f479ebab1557ef356
bacd7f29002135806d0f5047ae47cbad4c03f90e
refs/heads/master
2020-05-20T04:00:56.564124
2010-09-24T09:10:51
2010-09-24T09:10:51
11,787,598
1
0
null
null
null
null
UTF-8
C++
false
false
2,757
cxx
/* ======================================================================== * PROJECT: ARToolKitPlus * ======================================================================== * This work is based on the original ARToolKit developed by * Hirokazu Kato * Mark Billinghurst * HITLab, University of Washington, Seattle * http://www.hitl.washington.edu/artoolkit/ * * Copyright of the derived and new portions of this work * (C) 2006 Graz University of Technology * * This framework 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 framework 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 framework; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * For further information please contact * Dieter Schmalstieg * <[email protected]> * Graz University of Technology, * Institut for Computer Graphics and Vision, * Inffeldgasse 16a, 8010 Graz, Austria. * ======================================================================== ** @author Thomas Pintaric * * $Id: CameraFactory.cxx 162 2006-04-19 21:28:10Z grabner $ * @file * ======================================================================== */ #include <ARToolKitPlus/CameraFactory.h> #include <ARToolKitPlus/CameraImpl.h> #include <ARToolKitPlus/CameraAdvImpl.h> namespace ARToolKitPlus { Camera* CameraFactory:: createCamera(const char* filename) { CameraAdvImpl *c_ptr = new CameraAdvImpl(); if(c_ptr->loadFromFile(filename)) return((Camera*)c_ptr); else delete c_ptr; CameraImpl *c2_ptr = new CameraImpl(); if(c2_ptr->loadFromFile(filename)) return((Camera*)c2_ptr); else delete c2_ptr; return(NULL); } Camera* CameraFactory::createCamera(int xsize, int ysize, double* mat, double* dist_factor) { CameraImpl *c_ptr = new CameraImpl(); c_ptr->xsize = xsize; c_ptr->ysize = ysize; if (mat == NULL) { return NULL; } for(int i=0; i<3; i++) { for(int j=0; j<4; j++) { c_ptr->mat[i][j] = (ARFloat) mat[4*i + j]; } } if (dist_factor == NULL) { return NULL; } for (int i = 0; i < 4; i++) { c_ptr->dist_factor[i] = dist_factor[i]; } return c_ptr; } } // namespace ARToolKitPlus
[ "ndhumuscle@fa729b96-8d43-11de-b54f-137c5e29c83a" ]
[ [ [ 1, 87 ] ] ]
78ed2017bf0758319f45c87e5a87515ce44f2ffe
6e4f9952ef7a3a47330a707aa993247afde65597
/PROJECTS_ROOT/WireKeys/WP_SoundCtrl/SmartWires/Soundutils/SimpleMixer.h
04ef5a14050fb606905e1fb9b8bd5c001d2b8c57
[]
no_license
meiercn/wiredplane-wintools
b35422570e2c4b486c3aa6e73200ea7035e9b232
134db644e4271079d631776cffcedc51b5456442
refs/heads/master
2021-01-19T07:50:42.622687
2009-07-07T03:34:11
2009-07-07T03:34:11
34,017,037
2
1
null
null
null
null
UTF-8
C++
false
false
1,035
h
// SimpleMixer.h: interface for the CSimpleMixer class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_SIMPLEMIXER_H__12A45D24_96E0_11D5_93A8_BDF05C053B6A__INCLUDED_) #define AFX_SIMPLEMIXER_H__12A45D24_96E0_11D5_93A8_BDF05C053B6A__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "Mmsystem.h" class CSimpleMixer { private: HMIXER m_hMixer; public: BOOL isOpened(){return (m_hMixer!=NULL);}; DWORD m_dwVolumeCtrlID; DWORD m_dwMuteCtrlID; CSimpleMixer(); virtual ~CSimpleMixer(); BOOL Open(UINT mixerID, HWND hNotificationReciever = NULL, DWORD dwCompType = MIXERLINE_COMPONENTTYPE_DST_SPEAKERS); BOOL Close(); BOOL GetMuteCtrlValue() const; void SetMuteCtrlValue(BOOL bValue); UINT GetVolumeCtrlValue() const; void SetVolumeCtrlValue(UINT uValue); static UINT GetMixerNumber() { return mixerGetNumDevs(); } }; #endif // !defined(AFX_SIMPLEMIXER_H__12A45D24_96E0_11D5_93A8_BDF05C053B6A__INCLUDED_)
[ "wplabs@3fb49600-69e0-11de-a8c1-9da277d31688" ]
[ [ [ 1, 39 ] ] ]
e87295a8470c9c8c9ba9e0171d75b5c7214d8f6a
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ClientShellDLL/ClientShellShared/HeadBobMgr.cpp
2fc55e2f7838e87036a1912fa1e627eda0808c86
[]
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
12,994
cpp
// ----------------------------------------------------------------------- // // // MODULE : HeadBobMgr.cpp // // PURPOSE : Head Bob Mgr - Implementation // // CREATED : 01/09/00 // // (c) 2000-2002 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #include "stdafx.h" #include "HeadBobMgr.h" #include "GameClientShell.h" #include "SurfaceFunctions.h" #include "VarTrack.h" #include "CharacterFX.h" #include "VehicleMgr.h" #include "ClientWeaponBase.h" #include "CMoveMgr.h" CHeadBobMgr* g_pHeadBobMgr = LTNULL; extern VarTrack g_vtMaxVehicleYawDiff; extern SurfaceType g_eClientLastSurfaceType; VarTrack g_vtVehicleHeadCantUpRate; VarTrack g_vtVehicleHeadCantDownRate; VarTrack g_vtMaxVehicleHeadCant; VarTrack g_vtVehiclePaceAdjust; VarTrack g_vtRunPaceAdjust; VarTrack g_vtWalkPaceAdjust; VarTrack g_vtBobDecayTime; VarTrack g_vtBobV; VarTrack g_vtSwayH; VarTrack g_vtSwayV; VarTrack g_vtMaxBobAmp; VarTrack g_vtRollAdjust; VarTrack g_vtHeadBobAdjust; VarTrack g_vtWeaponSway; static LTFLOAT s_fBobDecayStartTime = -1.0f; static LTFLOAT s_fBobStartTime = -1.0f; static LTBOOL s_bCanDoLeftFootstep = LTTRUE; static LTBOOL s_bCanDoRightFootstep = LTFALSE; // --------------------------------------------------------------------------- // // // ROUTINE: CHeadBobMgr::CHeadBobMgr // // PURPOSE: Constructor // // --------------------------------------------------------------------------- // CHeadBobMgr::CHeadBobMgr() { g_pHeadBobMgr = this; m_fBobHeight = 0.0f; m_fBobAmp = 0.0f; m_fBobPhase = 0.0f; m_fSwayPhase = 0.0f; } // --------------------------------------------------------------------------- // // // ROUTINE: CHeadBobMgr::Init // // PURPOSE: Init // // --------------------------------------------------------------------------- // LTBOOL CHeadBobMgr::Init() { g_vtVehicleHeadCantUpRate.Init(g_pLTClient, "VehicleHeadCantUpRate", NULL, 1.0f); g_vtVehicleHeadCantDownRate.Init(g_pLTClient, "VehicleHeadCantDownRate", NULL, 1.0f); g_vtMaxVehicleHeadCant.Init(g_pLTClient, "VehicleMaxHeadCant", NULL, 20.0f); g_vtVehiclePaceAdjust.Init(g_pLTClient, "BobSwayVehiclePaceAdjust", NULL, 0.0f); g_vtRunPaceAdjust.Init(g_pLTClient, "BobSwayRunPaceAdjust", NULL, 1.5f); g_vtWalkPaceAdjust.Init(g_pLTClient, "BobSwayWalkPaceAdjust", NULL, 1.0f); g_vtBobDecayTime.Init(g_pLTClient, "BobDecayTime", NULL, 0.1f); g_vtBobV.Init(g_pLTClient, "BobV", NULL, 0.45f); g_vtSwayH.Init(g_pLTClient, "SwayH", NULL, 0.005f); g_vtSwayV.Init(g_pLTClient, "SwayV", NULL, 0.002f); g_vtMaxBobAmp.Init(g_pLTClient, "MaxBobAmp", NULL, 10.0f); g_vtRollAdjust.Init(g_pLTClient, "BobRollAdjust", NULL, 0.005f); g_vtHeadBobAdjust.Init(g_pLTClient, "HeadBob", NULL, 1.0f); g_vtWeaponSway.Init(g_pLTClient, "WeaponSway", NULL, 1.0f); return LTTRUE; } // --------------------------------------------------------------------------- // // // ROUTINE: CHeadBobMgr::Update // // PURPOSE: Update all variables // // --------------------------------------------------------------------------- // void CHeadBobMgr::Update() { // Don't allow head bobbing or canting to update when paused... if( g_pGameClientShell->IsGamePaused() ) return; CMoveMgr* pMoveMgr = g_pPlayerMgr->GetMoveMgr(); if (!pMoveMgr) return; // We check CanDoFootstep instead of on ground since CanDoFootstep // handles stairs much better... if ( (!g_pPlayerMgr->IsSpectatorMode() && g_pPlayerMgr->IsFirstPerson() && pMoveMgr->CanDoFootstep() && g_pPlayerMgr->IsPlayerMovementAllowed() && pMoveMgr->GetAllowMovement()) || pMoveMgr->GetVehicleMgr()->IsVehiclePhysics() ) { UpdateHeadBob(); UpdateHeadCant(); } } // --------------------------------------------------------------------------- // // // ROUTINE: CHeadBobMgr::UpdateHeadBob // // PURPOSE: Adjusts the head bobbing & swaying // // --------------------------------------------------------------------------- // void CHeadBobMgr::UpdateHeadBob() { CMoveMgr* pMoveMgr = g_pPlayerMgr->GetMoveMgr(); if (!pMoveMgr) return; LTBOOL bZoomed = g_pPlayerMgr->IsZoomed(); uint32 dwPlayerFlags = g_pPlayerMgr->GetPlayerFlags(); // This frame time is used since unlike ClientDE::GetFrameTime() the // max value is controlled by the game... LTFLOAT fFrameTime = g_pGameClientShell->GetFrameTime(); LTFLOAT fTime = g_pLTClient->GetTime(); LTBOOL bRunning = (LTBOOL) !!(dwPlayerFlags & BC_CFLG_RUN); LTFLOAT fMoveDist = pMoveMgr->GetVelocity().Mag() * fFrameTime; LTBOOL bFootstep = LTFALSE; LTBOOL bLeftFoot = LTFALSE; LTFLOAT fPace = 0.0f; if (pMoveMgr->GetVehicleMgr()->IsVehiclePhysics()) { fPace = MATH_CIRCLE * g_vtVehiclePaceAdjust.GetFloat(); } else if (bRunning) { fPace = MATH_CIRCLE * g_vtRunPaceAdjust.GetFloat(); } else { fPace = MATH_CIRCLE * g_vtWalkPaceAdjust.GetFloat(); } // Make sure bob phase and sway phase start at the right values... if (m_fBobAmp == 0.0f) { m_fBobPhase = 0.0f; m_fSwayPhase = 0.0f; } else // Normal processing... { // Bob phase should be between MATH_PI and MATH_CIRCLE so that the // sin(m_fBobPhase) is always between -1 and 0... m_fBobPhase += (fFrameTime * fPace); if (m_fBobPhase > MATH_CIRCLE) { m_fBobPhase -= MATH_PI; } else if (m_fBobPhase < MATH_PI) { m_fBobPhase += MATH_PI; } m_fSwayPhase += (fFrameTime * fPace); if (m_fSwayPhase > MATH_CIRCLE) { m_fSwayPhase -= MATH_CIRCLE; } } // See if it is time to play a footstep sound... if ((m_fSwayPhase > MATH_CIRCLE * 0.25f) && (m_fSwayPhase <= MATH_CIRCLE * 0.75f)) { if (s_bCanDoLeftFootstep) { bLeftFoot = LTFALSE; bFootstep = LTTRUE; s_bCanDoLeftFootstep = LTFALSE; s_bCanDoRightFootstep = LTTRUE; } } else if (m_fSwayPhase > MATH_CIRCLE * 0.75f) { if (s_bCanDoRightFootstep) { bLeftFoot = LTTRUE; bFootstep = LTTRUE; s_bCanDoLeftFootstep = LTTRUE; s_bCanDoRightFootstep = LTFALSE; } } LTBOOL bMoving = LTFALSE; LTFLOAT t; uint32 dwTestFlags = (BC_CFLG_MOVING); // | BC_CFLG_DUCK); if (fMoveDist > 0.1f) { bMoving = !!(dwPlayerFlags & dwTestFlags); } // If we're not moving, decay the head bob... if (!bMoving) { s_fBobStartTime = -1.0f; if (s_fBobDecayStartTime < 0.0f) { // Calculate what the current bobamp percent is... t = (1.0f - m_fBobAmp / g_vtMaxBobAmp.GetFloat()); s_fBobDecayStartTime = fTime - (g_vtBobDecayTime.GetFloat() * t); } LTFLOAT fDur = (fTime - s_fBobDecayStartTime); if (fDur <= g_vtBobDecayTime.GetFloat()) { t = fDur / g_vtBobDecayTime.GetFloat(); // 0 to 1 t = WaveFn_SlowOff(t); t = 1.0f - t; // 1 to 0 m_fBobAmp = t * g_vtMaxBobAmp.GetFloat(); if (m_fBobAmp < 0.0f) { m_fBobAmp = 0.0f; } } else { m_fBobAmp = 0.0f; } } else // We're moving... { s_fBobDecayStartTime = -1.0f; // If we just started bobing, ramp up the bob... if (s_fBobStartTime < 0.0f) { // Calculate what the current bobamp percent is... t = m_fBobAmp / g_vtMaxBobAmp.GetFloat(); s_fBobStartTime = fTime - (g_vtBobDecayTime.GetFloat() * t); } LTFLOAT fDur = (fTime - s_fBobStartTime); if (fDur <= g_vtBobDecayTime.GetFloat()) { t = fDur / g_vtBobDecayTime.GetFloat(); // 0 to 1 t = WaveFn_SlowOn(t); m_fBobAmp = t * g_vtMaxBobAmp.GetFloat(); if (m_fBobAmp > g_vtMaxBobAmp.GetFloat()) { m_fBobAmp = g_vtMaxBobAmp.GetFloat(); } } else { m_fBobAmp = g_vtMaxBobAmp.GetFloat(); } } // Update the bob... if (!bZoomed) { m_fBobHeight = g_vtBobV.GetFloat() * m_fBobAmp * (float)sin(m_fBobPhase); } // Update the weapon model bobbing... IClientWeaponBase *pClientWeapon = g_pPlayerMgr->GetCurrentClientWeapon(); if ( pClientWeapon && !bZoomed ) { LTFLOAT fSwayHeight = g_vtSwayV.GetFloat() * m_fBobAmp * (float)sin(m_fSwayPhase * 2); LTFLOAT fSwayWidth = g_vtSwayH.GetFloat() * m_fBobAmp * (float)sin(m_fSwayPhase - (MATH_PI/3)); // No weapon bob if vehicle mode... if (pMoveMgr->GetVehicleMgr()->IsVehiclePhysics()) { fSwayWidth = fSwayHeight = 0.0f; } fSwayHeight *= g_vtWeaponSway.GetFloat(); fSwayWidth *= g_vtWeaponSway.GetFloat(); pClientWeapon->UpdateBob(fSwayWidth, fSwayHeight); } // Update the head cant... if (!bZoomed && !pMoveMgr->GetVehicleMgr()->IsVehiclePhysics()) { LTFLOAT fRollAdjust = g_vtRollAdjust.GetFloat() * (float)sin(m_fSwayPhase); // Turn head bob up/down... fRollAdjust *= g_vtHeadBobAdjust.GetFloat(); if (m_fBobAmp == 0.0f) { fRollAdjust = 0.0f; } g_pPlayerMgr->SetRoll(fRollAdjust); } // Play foot step sounds at the appropriate time... if (bMoving && bFootstep) { CCharacterFX* pCharFX = pMoveMgr->GetCharacterFX(); if (pCharFX) { SurfaceType eSurf = pMoveMgr->GetStandingOnSurface(); eSurf = (eSurf == ST_UNKNOWN ? pCharFX->GetLastSurface() : eSurf); LTVector vPos; g_pLTClient->GetObjectPos(pMoveMgr->GetObject(), &vPos); pCharFX->PlayMovementSound(vPos, eSurf, bLeftFoot); } } } // ----------------------------------------------------------------------- // // // ROUTINE: CHeadBobMgr::AdjustCameraPos() // // PURPOSE: Adjust the camera's bob position... // // ----------------------------------------------------------------------- // void CHeadBobMgr::AdjustCameraPos(LTVector &vPos) { vPos.y += m_fBobHeight * g_vtHeadBobAdjust.GetFloat(); } // Limits the angle to a -PI to PI range. static inline float LimitToPosNegPi( float fAngle ) { // Copy the angle and make sure it's under 2 pi. float fNewAngle = ( float )fmod( fAngle, MATH_CIRCLE ); if( fNewAngle > MATH_PI ) fNewAngle = fNewAngle - MATH_CIRCLE; else if( fNewAngle < -MATH_PI ) fNewAngle = fNewAngle + MATH_CIRCLE; return fNewAngle; } // ----------------------------------------------------------------------- // // // ROUTINE: CHeadBobMgr::UpdateHeadCant() // // PURPOSE: Update head tilt when strafing // // ----------------------------------------------------------------------- // void CHeadBobMgr::UpdateHeadCant() { CMoveMgr* pMoveMgr = g_pPlayerMgr->GetMoveMgr(); if (!pMoveMgr) return; CVehicleMgr* pVehicleMgr = pMoveMgr->GetVehicleMgr(); if (!pVehicleMgr) return; LTBOOL bVehicleTurning = pVehicleMgr->IsTurning(); int nVehicleTurnDir = pVehicleMgr->GetTurnDirection(); CantType eCantType = eCantNone; LTFLOAT fMaxCant = 0.0f, fCantRate = 0.0f; if (bVehicleTurning && pMoveMgr->CanDoFootstep()) { eCantType = nVehicleTurnDir > 0 ? eCantRight : eCantLeft; } fMaxCant = DEG2RAD(g_vtMaxVehicleHeadCant.GetFloat()); LTFLOAT fMinCant = fMaxCant * 0.25f; LTFLOAT fRoll = LimitToPosNegPi( g_pPlayerMgr->GetRoll() - pVehicleMgr->GetVehicleContourRoll() ); switch (eCantType) { case eCantRight : { if (fRoll > 0.0f) { fCantRate = g_vtVehicleHeadCantDownRate.GetFloat(); } else { fCantRate = g_vtVehicleHeadCantUpRate.GetFloat(); } } break; case eCantLeft : { if (fRoll < 0.0f) { fCantRate = g_vtVehicleHeadCantDownRate.GetFloat(); } else { fCantRate = g_vtVehicleHeadCantUpRate.GetFloat(); } } break; case eCantNone: { fCantRate = g_vtVehicleHeadCantDownRate.GetFloat(); } break; default : break; } if (fabs(fRoll) < fMinCant) { fCantRate *= 0.5f; } // This frame time is used since unlike ClientDE::GetFrameTime() the // max value is controlled by the game... LTFLOAT fFrameTime = g_pGameClientShell->GetFrameTime(); LTFLOAT fDelta = fCantRate * fFrameTime; switch (eCantType) { case eCantRight : { fRoll -= fDelta; if (fRoll < -fMaxCant) { fRoll = -fMaxCant; } } break; case eCantLeft : { fRoll += fDelta; if (fRoll > fMaxCant) { fRoll = fMaxCant; } } break; case eCantNone: default : { // We are not canting so move us toward zero... if (fRoll != 0.0f) { if (fRoll < 0.0f) { fRoll += fDelta; if (fRoll > 0.0f) { fRoll = 0.0f; } } else { fRoll -= fDelta; if (fRoll < 0.0f) { fRoll = 0.0f; } } } } break; } // Let the vehicle mgr adjust the value... pVehicleMgr->AdjustCameraRoll(fRoll); // Set the new value... g_pPlayerMgr->SetRoll(fRoll); }
[ [ [ 1, 546 ] ] ]
7222f295143779fcb4a95e9d02119424f4e8c438
3d7fc34309dae695a17e693741a07cbf7ee26d6a
/aluminizer/histogram_item.h
85b9726a566001a27eaa29c30e4e7007dea5faa0
[ "LicenseRef-scancode-public-domain" ]
permissive
nist-ionstorage/ionizer
f42706207c4fb962061796dbbc1afbff19026e09
70b52abfdee19e3fb7acdf6b4709deea29d25b15
refs/heads/master
2021-01-16T21:45:36.502297
2010-05-14T01:05:09
2010-05-14T01:05:09
20,006,050
5
0
null
null
null
null
UTF-8
C++
false
false
1,539
h
/* -*- mode: C++ ; c-file-style: "stroustrup" -*- ***************************** * Qwt Widget Library * Copyright (C) 1997 Josef Wilgen * Copyright (C) 2002 Uwe Rathmann * * This library is free software; you can redistribute it and/or * modify it under the terms of the Qwt License, Version 1.0 *****************************************************************************/ #ifndef HISTOGRAM_ITEM_H #define HISTOGRAM_ITEM_H #include <qglobal.h> #include <qcolor.h> #include <qwt_plot_item.h> class QwtIntervalData; class QString; class HistogramItem : public QwtPlotItem { public: explicit HistogramItem(const QString &title = QString::null); explicit HistogramItem(const QwtText &title); virtual ~HistogramItem(); void setData(const QwtIntervalData &data); const QwtIntervalData &data() const; void setColor(const QColor &); QColor color() const; virtual QwtDoubleRect boundingRect() const; virtual int rtti() const; virtual void draw(QPainter *, const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRect &) const; void setBaseline(double reference); double baseline() const; enum HistogramAttribute { Auto = 0, Xfy = 1 }; void setHistogramAttribute(HistogramAttribute, bool on = true); bool testHistogramAttribute(HistogramAttribute) const; protected: virtual void drawBar(QPainter *, Qt::Orientation o, const QRect &) const; private: void init(); class PrivateData; PrivateData *d_data; }; #endif
[ "trosen@814e38a0-0077-4020-8740-4f49b76d3b44" ]
[ [ [ 1, 65 ] ] ]
98323959467c70be3d91b09e1606a11be644898b
de2f72b217bc8a9b1f780090bedf425a2ad9587a
/Pangea/Physics/include/particle/ParticleData.h
d12060f0b28812725fbef369b203ea7514030914
[]
no_license
axelwass/oliveira
65b32a7f16cb7e00a95cdf3051a731a2004aaf5f
4c34730a720465311e367f8e25cc1cced46801c7
refs/heads/master
2021-01-18T14:18:42.622080
2011-04-18T18:39:08
2011-04-18T18:39:08
32,120,045
0
0
null
null
null
null
UTF-8
C++
false
false
2,461
h
/* * ParticleData.h * * Created on: Sep 23, 2010 * Author: mmerchan */ #include "../../../Generic/Generic.h" #include "DerivativeData.h" #define INFINITE_MASS -1 #ifndef PARTICLEDATA_H_ #define PARTICLEDATA_H_ class ParticleData { private: Vector3 position; Vector3 velocity; real inverseMass; public: // Returns true if the particle has finite mass bool hasFiniteMass(); // Returns the mass of the particle real getMass(); // Returns the mass of the particle real getInverseMass(); // Sets mass of particle void setInverseMass(real inverseMass); // Sets velocity of particle void setVelocity(const Vector3& velocity); // Sets position of particle void setPosition(const Vector3& position); // Returns the velocity of the particle Vector3 getVelocity(); // Returns the position of the particle Vector3 getPosition(); // Check if two particles are equal bool operator==(ParticleData& other); /** Returns a copy of this derivative scaled to the given value.*/ ParticleData operator*(const real value) const { ParticleData out; out.velocity = this->velocity * value; out.position = this->position * value; out.inverseMass = this->inverseMass; return out; } /** Returns the value of the given derivative added to this*/ ParticleData operator+(const DerivativeData& derivative) const{ ParticleData out; out.velocity = this->velocity + derivative.dv; out.position = this->position + derivative.dx; out.inverseMass = this->inverseMass; return out; } /** Returns the value of the given derivative added to this*/ ParticleData operator+(const ParticleData& other) const { ParticleData out; out.velocity = this->velocity + other.velocity; out.position = this->position + other.position; out.inverseMass = this->inverseMass; return out; } /** Returns the value of the given derivative substracted from this */ ParticleData operator-(const ParticleData& other) const { ParticleData out; out.velocity = this->velocity - other.velocity; out.position = this->position - other.position; out.inverseMass = this->inverseMass; return out; } // Uninitialized particle data ParticleData() { } // Defines data for particle ParticleData(const Vector3& position, real inverseMass); }; #endif /* PARTICLEDATA_H_ */
[ "merchante.mariano@d457d4b0-f835-b411-19da-99c4f284aa10" ]
[ [ [ 1, 98 ] ] ]
8b9b608eb27f66382636a4671f143205c42c8351
a14b1659f72560b52f84c4d930867c2dad1e20bb
/sg16-win2kXP2003/initterm.cpp
e236ed65def94b74b9d3034d3ad21f07694e964b
[]
no_license
SigrandLLC/drivers
d36a6d0e827112f3b8913b7f7b7b7c20f33756bc
e8c7f672db1a102e0402043f8a7de798a5bae725
refs/heads/master
2021-04-28T08:49:28.042779
2009-03-10T06:31:10
2009-03-10T06:31:10
122,025,316
0
2
null
null
null
null
UTF-8
C++
false
false
13,606
cpp
#include "common.h" #include <ndis.h> /* AdapterDesc class functionsConstructor */ AdapterDesc:: AdapterDesc ( void ) #ifdef _DEBUG : SL( this ), XmtDmaPool( this ), XmtDmaQueue( this ), RcvDmaPool( this ), RcvDmaQueue( this ), PacketsFromNdis( this ) #endif { DriverHandle=NULL; #ifdef _DEBUG IntDepth=0; InCompleteTxDepth=0; InCompleteRxDepth=0; TotalReceivedBytes=0; #endif LastIntEvents=0; PacketPoolAllocated=BufferPoolAllocated=false; InterruptRegistered=MapRegsAllocated=false; PacketPool=BufPool=NULL; HLDC=NULL; TxDmaBuffer=RxDmaBuffer=NULL; cmdp=NULL; NdisZeroMemory( &Stat, sizeof(Stat) ); XmitGood=RcvdGood=XmitBad=CrcErrors=MulticastCount=0; IntCount=0; MemoryWindowAddr=NULL; MemoryWindowPhysAddr=0; DmaMemAddr=NULL; DmaMemSize=0; XmtQueueLen=Driver_XmtQueueLenDef; RcvQueueLen=Driver_RcvQueueLenDef; TxRingRemovePos=RxRingRemovePos=0; InterruptNumber=0; ModemState=DOWN; ModemComplRtn=NULL; QI_InfoBuffer=NULL; NdisZeroMemory( MACAddress, sizeof(MACAddress) ); NdisZeroMemory( MulticastList, sizeof(MulticastList) ); FilterMode=0; NdisInitializeEvent( &cx_intr ); Reset(); Debug( 7, this, "Created adapter object %X", this ); } /* ----------------------------------------------------------------------------- * Destructor ------------------------------------------------------------------------------- */ AdapterDesc::~ AdapterDesc( void ) { Debug( 7, this, "Destroying adapter object %X", this ); Assert( XmtDmaPool.IsEmpty() && XmtDmaQueue.IsEmpty() ); Assert( RcvDmaPool.IsEmpty() && RcvDmaQueue.IsEmpty() ); Assert( PacketsFromNdis.IsEmpty() ); } /* ----------------------------------------------------------------------------- * Reset to initial state ------------------------------------------------------------------------------- */ void AdapterDesc::Reset( void ) { } /* ----------------------------------------------------------------------------- * Initialize the modem hardware ------------------------------------------------------------------------------- */ NDIS_STATUS AdapterDesc::CardStart( void ) { Debug( 0, this, "CardStart:ENTER" ); Check(); Debug( 7, this, "Initializing the modem" ); HLDC->CRA=0; HLDC->ResetStatusBits( ALL ); DisableInterrupts(); /* read the 8051 program code */ NDIS_STRING file_name=NDIS_STRING_CONST( "sg16.bin" ); NDIS_HANDLE handle; bool FileOpen=false; PVOID firmw_img=NULL; NDIS_STATUS Status; do { UINT firmw_len; Assert( KeGetCurrentIrql() == PASSIVE_LEVEL ); NdisOpenFile( &Status, &handle, &firmw_len, &file_name, HighestAddr ); if( Status != NDIS_STATUS_SUCCESS ) { Debug( 9, this, "CardStart:ERROR - NdisOpenFile (%X)", Status ); break; } FileOpen=true; NdisMapFile( &Status, &firmw_img, handle ); if( Status != NDIS_STATUS_SUCCESS ) { Debug( 9, this, "CardStart:ERROR - NdisMapFile (%X)", Status ); break; } if( !start_cx28975(firmw_img, firmw_len) ) { Status=NDIS_STATUS_FAILURE; break; } StartTransceiver(); Status=NDIS_STATUS_SUCCESS; } while( False ); if( FileOpen ) { if( firmw_img ) { NdisUnmapFile( handle ); } NdisCloseFile( handle ); } Debug( 0, this, "CardStart:EXIT" ); Check(); return Status; } /* ----------------------------------------------------------------------------- * Create packet pools/queues ------------------------------------------------------------------------------- */ NDIS_STATUS AdapterDesc::CreatePools( void ) { Debug( 0, this, "CreatePools: ENTER" ); Check(); NDIS_STATUS Status=NDIS_STATUS_FAILURE; do { NdisAllocatePacketPool( &Status, &PacketPool, RcvQueueLen, 16 ); /* * NdisAllocatePacketPoolEx (&Status, &PacketPool, * NUMBER_OF_MAP_REGS, 2, 16); */ if( Status != NDIS_STATUS_SUCCESS ) { Debug( 9, this, "MiniportInitialize:ERROR - NdisAllocatePacketPool (%X)", Status ); break; } PacketPoolAllocated=true; Debug( 7, this, "Allocated packet pool %X", PacketPool ); NdisAllocateBufferPool( &Status, &BufPool, RcvQueueLen ); if( Status != NDIS_STATUS_SUCCESS ) { Debug( 9, this, "MiniportInitialize:ERROR - NdisAllocateBufferPool (%X)", Status ); break; } BufferPoolAllocated=true; Debug( 7, this, "Allocated buffer pool %X", BufPool ); /* Initialize DMA pools */ PBYTE VA=PBYTE( DmaMemAddr ); DWORD PA=NdisGetPhysicalAddressLow( DmaMemPhysAddr ); for( UINT i=0; i < XmtQueueLen; i++ ) { Lock(); DmaPacketDesc *const DPD=XmtDmaPool.CreateElem( VA, PA, NULL ); Unlock(); if( !DPD ) { break; } VA+=DMA_BUFFER_SIZE; PA+=DMA_BUFFER_SIZE; } if( i < XmtQueueLen ) { Status=NDIS_STATUS_RESOURCES; break; } Debug( 7, this, "Created transmission DMA pool of %u elems", XmtQueueLen ); for( i=0; i < RcvQueueLen; i++ ) { PNDIS_PACKET Pkt; NdisAllocatePacket( &Status, &Pkt, PacketPool ); Assert( Status == NDIS_STATUS_SUCCESS ); Debug( 7, this, "Allocated packet desc %X", Pkt ); PNDIS_BUFFER Buf; NdisAllocateBuffer( &Status, &Buf, BufPool, VA, ETHERNET_MAX_SIZE ); Assert( Status == NDIS_STATUS_SUCCESS ); Debug( 5, this, "Allocated buffer desc %X (VA %X)", Buf, VA ); NdisChainBufferAtFront( Pkt, Buf ); Lock(); DmaPacketDesc *const DPD=RcvDmaPool.CreateElem( VA, PA, Pkt ); Unlock(); if( !DPD ) { NdisFreeBuffer( Buf ); NdisFreePacket( Pkt ); break; } NDIS_SET_PACKET_HEADER_SIZE( Pkt, ETHERNET_HEADER_SIZE ); PacketAddon::FromPkt( Pkt )->DPD=DPD; VA+=DMA_BUFFER_SIZE; PA+=DMA_BUFFER_SIZE; } if( i < RcvQueueLen ) { Status=NDIS_STATUS_RESOURCES; break; } Debug( 7, this, "Created reception DMA pool of %u elems", RcvQueueLen ); Assert( VA == PBYTE(DmaMemAddr) + DmaMemSize ); Assert( PA == NdisGetPhysicalAddressLow(DmaMemPhysAddr) + DmaMemSize ); Status=NDIS_STATUS_SUCCESS; } while( False ); if( Status != NDIS_STATUS_SUCCESS ) { DestroyPools(); } Debug( 0, this, "CreatePools: EXIT" ); return Status; } /* ----------------------------------------------------------------------------- * Destroy packet pools/queues ------------------------------------------------------------------------------- */ void AdapterDesc::DestroyPools( void ) { Check(); Assert( HLDC->IMR == 0 ); Assert( !IsLocked() ); Lock(); XmtDmaQueue.DestroyAll(); XmtDmaPool.DestroyAll(); Unlock(); Assert( RcvDmaQueue.IsEmpty() ); while( !RcvDmaPool.IsEmpty() ) { Lock(); DmaPacketDesc *const DPD=RcvDmaPool.RemoveFirst(); Unlock(); PNDIS_PACKET const Pkt=DPD->Pkt; Assert( Pkt ); delete DPD; PNDIS_BUFFER Buf; NdisQueryPacket( Pkt, NULL, NULL, &Buf, NULL ); Assert( Buf ); Debug( 7, this, "Freeing buffer desc %X", Buf ); NdisFreeBuffer( Buf ); Debug( 7, this, "Freeing packet %X", Pkt ); NdisFreePacket( Pkt ); } if( BufferPoolAllocated ) { Debug( 7, this, "Freeing buffer pool %X", BufPool ); NdisFreeBufferPool( BufPool ); BufferPoolAllocated=false; } if( PacketPoolAllocated ) { Debug( 7, this, "Freeing packet pool %X", PacketPool ); NdisFreePacketPool( PacketPool ); PacketPoolAllocated=false; } Check(); } /* ----------------------------------------------------------------------------- * Initialize the DMA/interrupt support ------------------------------------------------------------------------------- */ NDIS_STATUS AdapterDesc::InitDmaAndInt( void ) { Debug( 0, this, "InitDmaAndInt: ENTER" ); Check(); NDIS_STATUS Status=NDIS_STATUS_FAILURE; do { LARGE_INTEGER PhysAddr={ 0, 0 }; PhysAddr.u.LowPart=MemoryWindowPhysAddr; Status=NdisMMapIoSpace( &MemoryWindowAddr, DriverHandle, PhysAddr, SG16_MEMSIZE ); if( Status != NDIS_STATUS_SUCCESS ) { Debug( 9, this, "RegisterAdapter:ERROR - NdisMMapIoSpace (%X)", Status ); break; } Debug( 7, this, "I/O space mapped to %X", MemoryWindowAddr ); TxDmaBuffer=( DmaBuffer * ) ( MemoryWindowAddr ); RxDmaBuffer=( DmaBuffer * ) ( PBYTE(MemoryWindowAddr) + 0x400 ); HLDC=( HldcRegs * ) ( PBYTE(MemoryWindowAddr) + 0x800 ); cmdp=( cx28975_cmdarea * ) ( PBYTE(MemoryWindowAddr) + 0xC00 ); DmaMemSize=( XmtQueueLen + RcvQueueLen ) * DMA_BUFFER_SIZE; #ifdef _DEBUG NdisZeroMemory( TxDmaBuffer->BdArray, sizeof(TxDmaBuffer->BdArray) ); NdisZeroMemory( RxDmaBuffer->BdArray, sizeof(RxDmaBuffer->BdArray) ); #endif /* We must allocate map registers to use shared memory */ Status=NdisMAllocateMapRegisters( DriverHandle, 0, NDIS_DMA_32BITS, 1, DmaMemSize ); if( Status != NDIS_STATUS_SUCCESS ) { Debug( 9, this, "Cannot allocate map registers (%X)", Status ); break; } MapRegsAllocated=true; Debug( 7, this, "Allocated map registers" ); NdisMAllocateSharedMemory( DriverHandle, DmaMemSize, TRUE, &DmaMemAddr, &DmaMemPhysAddr ); if( !DmaMemAddr ) { Debug( 9, this, "Cannot allocate %u bytes of DMA memory", DmaMemSize ); Status=NDIS_STATUS_RESOURCES; break; } Debug( 7, this, "Allocated %u bytes of DMA mem (virt %X, phys %X)", DmaMemSize, DmaMemAddr, DmaMemPhysAddr ); Status=CreatePools(); if( Status != NDIS_STATUS_SUCCESS ) { break; } /* interrupts are disabled until CardStart completed */ Status=NdisMRegisterInterrupt( &Interrupt, DriverHandle, InterruptNumber, InterruptNumber, TRUE, TRUE, NdisInterruptLevelSensitive ); if( Status != NDIS_STATUS_SUCCESS ) { Debug( 9, this, "Cannot register interrupt (%X)", Status ); NdisWriteErrorLogEntry( DriverHandle, NDIS_ERROR_CODE_INTERRUPT_CONNECT, 0 ); break; } Debug( 7, this, "Registered interrupt %u", InterruptNumber ); InterruptRegistered=true; Status=CardStart(); if( Status != NDIS_STATUS_SUCCESS ) { NdisWriteErrorLogEntry( DriverHandle, Status, 0 ); break; } HLDC->CTDR=HLDC->LTDR=HLDC->CRDR=HLDC->LRDR=0; Assert( Status == NDIS_STATUS_SUCCESS ); } while( False ); if( Status != NDIS_STATUS_SUCCESS ) { TermDmaAndInt(); } Debug( 0, this, "InitDmaAndInt: EXIT" ); return Status; } /* ----------------------------------------------------------------------------- * Terminate the DMA/Interrupt support ------------------------------------------------------------------------------- */ void AdapterDesc::TermDmaAndInt( void ) { Debug( 0, this, "TermDmaAndInt: ENTER" ); if( InterruptRegistered ) { Debug( 7, this, "Deregistering interrupt %u", InterruptNumber ); NdisMDeregisterInterrupt( &Interrupt ); InterruptRegistered=false; } DestroyPools(); if( DmaMemAddr ) { Debug( 7, this, "Freeing rcv DMA mem (virt %X, phys %X)", DmaMemAddr, DmaMemPhysAddr ); NdisMFreeSharedMemory( DriverHandle, DmaMemSize, FALSE, DmaMemAddr, DmaMemPhysAddr ); DmaMemAddr=NULL; } if( MapRegsAllocated ) { NdisMFreeMapRegisters( DriverHandle ); MapRegsAllocated=false; } if( MemoryWindowAddr ) { Debug( 7, this, "Unmapping I/O space" ); NdisMUnmapIoSpace( DriverHandle, MemoryWindowAddr, SG16_MEMSIZE ); MemoryWindowAddr=NULL; TxDmaBuffer=RxDmaBuffer=NULL; HLDC=NULL; cmdp=NULL; } Debug( 0, this, "TermDmaAndInt: EXIT" ); } /* ----------------------------------------------------------------------------- * Initialization ------------------------------------------------------------------------------- */ NDIS_STATUS AdapterDesc::Init( NDIS_HANDLE MPH, NDIS_HANDLE WrapperConfigurationContext ) { DriverHandle=MPH; NdisMRegisterAdapterShutdownHandler( DriverHandle, this, MiniportShutdownOuter ); NdisMSetAttributesEx( DriverHandle, NDIS_HANDLE(this), 0, NDIS_ATTRIBUTE_DESERIALIZE | NDIS_ATTRIBUTE_BUS_MASTER, NdisInterfacePci ); NDIS_STATUS Status=NDIS_STATUS_FAILURE; do { NDIS_HANDLE ConfigHandle; NdisOpenConfiguration( &Status, &ConfigHandle, WrapperConfigurationContext ); if( Status != NDIS_STATUS_SUCCESS ) { Debug( 9, this, "Cannot open configuration (%X)", Status ); Status=NDIS_STATUS_FAILURE; break; } Status=ReadConfiguration( ConfigHandle ); NdisCloseConfiguration( ConfigHandle ); if( Status != NDIS_STATUS_SUCCESS ) { Debug( 9, this, "Cannot read configuration (%X)", Status ); break; } Status=InitDmaAndInt(); if( Status != NDIS_STATUS_SUCCESS ) { DbgPrint( "Init:cannot init DMA & INT\n" ); break; } Reset(); FillRcvQueue(); Status=NDIS_STATUS_SUCCESS; NdisMInitializeTimer( &LinkTimer, DriverHandle, LinkCheckFunc, (PVOID)this ); } while( False ); if( Status != NDIS_STATUS_SUCCESS ) { Term(); } return Status; } /* ----------------------------------------------------------------------------- * Termination ------------------------------------------------------------------------------- */ void AdapterDesc::Term( void ) { Assert( !IsLocked() ); if( HLDC ) { /* If HLDC initialized */ Lock(); DisableInterrupts(); HLDC->CRA=0; CancelRxPackets(); Unlock(); } BOOLEAN Cancelled; NdisMCancelTimer(&LinkTimer,&Cancelled); NdisMDeregisterAdapterShutdownHandler( DriverHandle ); TermDmaAndInt(); }
[ [ [ 1, 510 ] ] ]
956976ccba327d948829ce85fc558d7bc1ba40e0
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/nebula2/src/gui/nguisettingsmanagementwindow_main.cc
061d4de9efb8e78e322c89fd95ef19100f49d45c
[]
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
47,072
cc
//------------------------------------------------------------------------------ // nguisettingsmanagementwindow_main.cc // (C) 2006 RadonLabs GmbH //------------------------------------------------------------------------------ #include "gui/nguisettingsmanagementwindow.h" #include "gui/nguihorislidergroup.h" #include "gui/nguicolorslidergroup.h" #include "gui/nguisettingsfiledialog.h" #include "gui/nguiscenecontrolwindow.h" #include "gui/nguimessagebox.h" #include "gui/nguitextentry.h" #include "gui/nguitextview.h" #include "gui/nguiadjustdisplaywindow.h" #include "variable/nvariableserver.h" #include "util/nstream.h" #include "misc/nprefserver.h" #include "kernel/nfileserver2.h" nNebulaClass(nGuiSettingsManagementWindow, "nguiclientwindow"); //------------------------------------------------------------------------------ // constant strings const char * displayAdjustmentString = "Display Adjustment"; const char * sceneControlString = "Scene Control"; const char * sliderString = "Slider"; const char * colorSliderString = "ColorSlider"; // display adjustment keys for registry const char * daSaturateSlider = "DisplaySetting.Saturate.Slider"; const char * daBalanceColorSlider = "DisplaySetting.Balance.ColorSlider"; const char * daHDRIntesitySlider = "DisplaySetting.HDR_Intensity.Slider"; const char * daHDRThresholdSlider = "DisplaySetting.HDR_Threshold.Slider"; const char * daHDROffsetSlider = "DisplaySetting.HDR_Offset.Slider"; const char * daFogColorSlider = "DisplaySetting.Fog_Color.ColorSlider"; const char * daFogNearSlider = "DisplaySetting.Fog_Near.Slider"; const char * daFogFarSlider = "DisplaySetting.Fog_Far.Slider"; const char * daFocusDistSlider = "DisplaySetting.Focus_Dist.Slider"; const char * daFocusLengthSlider = "DisplaySetting.Focus_Length.Slider"; const char * daNoiseItensitySlider = "DisplaySetting.Noise_Intensity.Slider"; const char * daNoiseScaleSlider = "DisplaySetting.Noise_Scale.Slider"; const char * daNoiseFreqSlider = "DisplaySetting.Noise_Freq.Slider"; // scene control keys for registry const char * scAmbientColorSlider = "SceneControl.Ambient_Color.ColorSlider"; const char * scDiffueColorSlider = "SceneControl.Diffuse_Color.ColorSlider"; const char * scSpeculaColorSlider = "SceneControl.Specular_Color.ColorSlider"; const char * scLightDirectionSlider = "SceneControl.Light_Direction.Slider"; const char * scLightHeightSlider = "SceneControl.Light_Height.Slider"; // scene controls keys for xml const char * scXMLRoot = "Scene_Control"; const char * scXMLAmbientColor = "Ambient_Color"; const char * scXMLDiffuceColor = "Diffuse_Color"; const char * scXMLSpecularColor = "Specular_Color"; const char * scXMLLightDirection = "Light_Direction"; const char * scXMLLightHeight = "Light_Height"; // display adjustments keys for xml const char * daXMLRoot = "Display_Adjustments"; const char * daXMLSaturate = "Saturate"; const char * daXMLBalance = "Balance"; const char * daXMLHDRIntesity = "HDR_Intensity"; const char * daXMLHDRThreshold = "HDR_Threshold"; const char * daXMLHDROffset = "HDR_Offset"; const char * daXMLFogColor = "Fog_Color"; const char * daXMLFogNear = "Fog_Near"; const char * daXMLFogFar = "Fog_Far"; const char * daXMLFocusDist = "Focus_Dist"; const char * daXMLFocusLenght = "Focus_Length"; const char * daXMLNoiseIntesity = "Noise_Intensity"; const char * daXMLNoiseScale = "Noise_Scale"; const char * daXMLNoiseFreq = "Noise_Freq"; // char for directory const char * defaultDirectory = "user:options/"; //------------------------------------------------------------------------------ /** */ nGuiSettingsManagementWindow::nGuiSettingsManagementWindow() { // empty } //------------------------------------------------------------------------------ /** */ nGuiSettingsManagementWindow::~nGuiSettingsManagementWindow() { // empty } //------------------------------------------------------------------------------ /** */ void nGuiSettingsManagementWindow::OnShow() { // call parent class nGuiClientWindow::OnShow(); this->SetResizable(true); this->SetTitle("Settings Management"); vector2 buttonSize = nGuiServer::Instance()->ComputeScreenSpaceBrushSize("button_n"); // get client area form layout object nGuiFormLayout* layout = this->refFormLayout.get(); kernelServer->PushCwd(layout); // constants... const float border = 0.005f; // text label for display adjustment settings nGuiTextLabel* textLabel = (nGuiTextLabel*) kernelServer->New("nguitextlabel", "WindowSettingsSelcetionLabel"); textLabel->SetText("Select control set"); textLabel->SetFont("GuiSmall"); textLabel->SetAlignment(nGuiTextLabel::Center); vector2 textSize = textLabel->GetTextExtent(); vector2 textMinSize(0.0f, textSize.y * 1.25f); vector2 textMaxSize(1.0f, textSize.y * 1.25f); textLabel->SetColor(vector4(0.0f, 0.0f, 0.0f, 1.0f)); textLabel->SetMinSize(textMinSize); textLabel->SetMaxSize(textMaxSize); layout->AttachForm(textLabel, nGuiFormLayout::Left, border); layout->AttachForm(textLabel, nGuiFormLayout::Top, border); layout->AttachForm(textLabel, nGuiFormLayout::Right, border); textLabel->OnShow(); this->refWindowSelectionLabel = textLabel; // create text view field for widget selection nGuiTextView* textView = (nGuiTextView*) kernelServer->New("nguitextview", "WindowSettingsSelectionTextView"); n_assert(textView); textView->SetSelectionEnabled(true); textView->SetHighlightBrush("textentry_h"); textView->SetDefaultBrush("list_background"); textView->SetHighlightBrush("list_selection"); textView->SetMaxSize(vector2(1.0f, 0.1f)); layout->AttachWidget(textView, nGuiFormLayout::Top, this->refWindowSelectionLabel, border); layout->AttachForm(textView, nGuiFormLayout::Left, border); layout->AttachForm(textView, nGuiFormLayout::Right, border); textView->OnShow(); this->refWindowSelectionTextView = textView; // text label for display adjustment settings textLabel = (nGuiTextLabel*) kernelServer->New("nguitextlabel", "FileLabel"); textLabel->SetText("Specify file for save/load"); textLabel->SetFont("GuiSmall"); textLabel->SetAlignment(nGuiTextLabel::Center); textSize = textLabel->GetTextExtent(); textMinSize.y = textSize.y * 1.25f; textMaxSize.y = textSize.y * 1.25f; textLabel->SetColor(vector4(0.0f, 0.0f, 0.0f, 1.0f)); textLabel->SetMinSize(textMinSize); textLabel->SetMaxSize(textMaxSize); layout->AttachForm(textLabel, nGuiFormLayout::Left, border); layout->AttachWidget(textLabel, nGuiFormLayout::Top, this->refWindowSelectionTextView, border); layout->AttachForm(textLabel, nGuiFormLayout::Right, border); textLabel->OnShow(); this->refFileLabel = textLabel; // browse button, with new size buttonSize.x = 0.03f; nGuiTextButton* btn = (nGuiTextButton*) kernelServer->New("nguitextbutton", "BrowseButton"); btn->SetText("..."); btn->SetDefaultBrush("button_n"); btn->SetPressedBrush("button_p"); btn->SetHighlightBrush("button_h"); layout->AttachForm(btn, nGuiFormLayout::Right, border); layout->AttachWidget(btn, nGuiFormLayout::Top, this->refFileLabel, border); btn->SetMinSize(buttonSize); btn->SetMaxSize(buttonSize); btn->OnShow(); this->refBrowseButton = btn; // text label, for filename nGuiTextEntry * textEntry = (nGuiTextEntry*) kernelServer->New("nguitextentry", "FilenameEntry"); textEntry->SetText(""); textEntry->SetFont("GuiSmall"); textEntry->SetAlignment(nGuiTextEntry::Left); textEntry->SetDefaultBrush("textentry_n"); textEntry->SetPressedBrush("textentry_p"); textEntry->SetHighlightBrush("textentry_h"); textEntry->SetCursorBrush("textcursor"); buttonSize.x = 0.3f; textEntry->SetMinSize(buttonSize); buttonSize.x = 1.0f; textEntry->SetMaxSize(buttonSize); textEntry->SetFileMode(true); textEntry->SetInitialCursorPos(nGuiTextLabel::Right); layout->AttachWidget(textEntry, nGuiFormLayout::Top, this->refFileLabel, border); layout->AttachForm(textEntry, nGuiFormLayout::Left, border); layout->AttachWidget(textEntry, nGuiFormLayout::Right, this->refBrowseButton, border); textEntry->OnShow(); this->refFilenameEntry = textEntry; this->AddSupportedWindowsToList(); // load button buttonSize = nGuiServer::Instance()->ComputeScreenSpaceBrushSize("button_n"); btn = (nGuiTextButton*) kernelServer->New("nguitextbutton", "LoadButton"); btn->SetText("Load"); btn->SetDefaultBrush("button_n"); btn->SetPressedBrush("button_p"); btn->SetHighlightBrush("button_h"); btn->SetMinSize(buttonSize); btn->SetMaxSize(buttonSize); layout->AttachForm(btn, nGuiFormLayout::Left, border); layout->AttachWidget(btn, nGuiFormLayout::Top, this->refFilenameEntry, border); btn->OnShow(); this->refLoadButton = btn; // save button btn = (nGuiTextButton*) kernelServer->New("nguitextbutton", "SaveButton"); btn->SetText("Save as"); btn->SetDefaultBrush("button_n"); btn->SetPressedBrush("button_p"); btn->SetHighlightBrush("button_h"); btn->SetMinSize(buttonSize); btn->SetMaxSize(buttonSize); layout->AttachForm(btn, nGuiFormLayout::Right, border); layout->AttachWidget(btn, nGuiFormLayout::Top, this->refFilenameEntry, border); btn->OnShow(); this->refSaveButton = btn; // text label for default settings textLabel = (nGuiTextLabel*) kernelServer->New("nguitextlabel", "DefaultLabel"); textLabel->SetText("Manage default settings"); textLabel->SetFont("GuiSmall"); textLabel->SetAlignment(nGuiTextLabel::Center); textSize = textLabel->GetTextExtent(); textMinSize.y = textSize.y * 1.25f; textMaxSize.y = textSize.y * 1.25f; textLabel->SetColor(vector4(0.0f, 0.0f, 0.0f, 1.0f)); textLabel->SetMinSize(textMinSize); textLabel->SetMaxSize(textMaxSize); layout->AttachForm(textLabel, nGuiFormLayout::Left, border); layout->AttachWidget(textLabel, nGuiFormLayout::Top, this->refSaveButton, border); layout->AttachForm(textLabel, nGuiFormLayout::Right, border); textLabel->OnShow(); this->refDefaultLabel = textLabel; // reset button btn = (nGuiTextButton*) kernelServer->New("nguitextbutton", "ResetButton"); btn->SetText("Reset"); btn->SetDefaultBrush("button_n"); btn->SetPressedBrush("button_p"); btn->SetHighlightBrush("button_h"); btn->SetMinSize(buttonSize); btn->SetMaxSize(buttonSize); layout->AttachWidget(btn, nGuiFormLayout::Top, this->refDefaultLabel, border); layout->AttachForm(btn, nGuiFormLayout::Left, border); layout->AttachForm(btn, nGuiFormLayout::Bottom, border); btn->OnShow(); this->refResetButton = btn; // default button btn = (nGuiTextButton*) kernelServer->New("nguitextbutton", "SetDefaultButton"); btn->SetText("Set default"); btn->SetDefaultBrush("button_n"); btn->SetPressedBrush("button_p"); btn->SetHighlightBrush("button_h"); btn->SetMinSize(buttonSize); btn->SetMaxSize(buttonSize); layout->AttachWidget(btn, nGuiFormLayout::Top, this->refDefaultLabel, border); layout->AttachForm(btn, nGuiFormLayout::Right, border); btn->OnShow(); this->refSetDefaultButton = btn; // text label for default settings textLabel = (nGuiTextLabel*) kernelServer->New("nguitextlabel", "InfoLabel"); textLabel->SetText(""); textLabel->SetFont("GuiSmall"); textLabel->SetAlignment(nGuiTextLabel::Center); textSize = textLabel->GetTextExtent(); textMinSize.y = textSize.y * 1.25f; textMaxSize.y = textSize.y * 2.0f; textLabel->SetColor(vector4(0.0f, 0.0f, 0.0f, 1.0f)); textLabel->SetMinSize(textMinSize); textLabel->SetMaxSize(textMaxSize); layout->AttachForm(textLabel, nGuiFormLayout::Left, border); layout->AttachForm(textLabel, nGuiFormLayout::Right, border); layout->AttachForm(textLabel, nGuiFormLayout::Bottom, border); textLabel->OnShow(); this->refInfoLabel = textLabel; kernelServer->PopCwd(); // try to create default directory "home:work/save" if (!this->CheckDirAndCreate()) { this->SetInfoText("Default directory could not be created!", true); } // set new window rect float vSize = 11 * (border + this->refLoadButton->GetMaxSize().y) + // each button, text entry or label 1 * (border + this->refWindowSelectionTextView->GetMinSize().y); // each textview (with selection) rectangle rect(vector2(0.0f, 0.0f), vector2(0.38f, vSize)); this->SetRect(rect); // update all layouts this->UpdateLayout(this->rect); } //------------------------------------------------------------------------------ /** */ void nGuiSettingsManagementWindow::OnHide() { if (this->refWindowSelectionLabel.isvalid()) { this->refWindowSelectionLabel->Release(); } if (this->refWindowSelectionTextView.isvalid()) { this->refWindowSelectionTextView->Release(); } if (this->refResetButton.isvalid()) { this->refResetButton->Release(); } if (this->refSaveButton.isvalid()) { this->refSaveButton->Release(); } if (this->refLoadButton.isvalid()) { this->refLoadButton->Release(); } if (this->refBrowseButton.isvalid()) { this->refBrowseButton->Release(); } if (this->refSetDefaultButton.isvalid()) { this->refSetDefaultButton->Release(); } if (this->refFilenameEntry.isvalid()) { this->refFilenameEntry->Release(); } if (this->refDefaultLabel.isvalid()) { this->refDefaultLabel->Release(); } if (this->refFileLabel.isvalid()) { this->refFileLabel->Release(); } if (this->refMessageBox.isvalid()) { this->refMessageBox->Release(); } if (this->refInfoLabel.isvalid()) { this->refInfoLabel->Release(); } } //------------------------------------------------------------------------------ /** */ void nGuiSettingsManagementWindow::OnEvent(const nGuiEvent& event) { if ((event.GetType() == nGuiEvent::ButtonUp) && (event.GetWidget() == this->refResetButton)) { this->ResetValues(); } else if ((event.GetType() == nGuiEvent::ButtonUp) && (event.GetWidget() == this->refBrowseButton)) { this->CreateFileDialog(); } else if ((event.GetType() == nGuiEvent::ButtonUp) && (event.GetWidget() == this->refLoadButton)) { if (!strlen(refFilenameEntry->GetText()) == 0) { this->LoadValuesFromFile(refFilenameEntry->GetText()); } else { this->SetInfoText("Please specify a filename"); } } else if ((event.GetType() == nGuiEvent::ButtonUp) && (event.GetWidget() == this->refSaveButton)) { if (!strlen(refFilenameEntry->GetText()) == 0) { this->SaveValuesToFile(refFilenameEntry->GetText()); } else { this->SetInfoText("Please specify a filename"); } } else if ((event.GetType() == nGuiEvent::ButtonUp) && (event.GetWidget() == this->refSetDefaultButton)) { this->SaveValuesAsDefault(); } nGuiClientWindow::OnEvent(event); } //------------------------------------------------------------------------------ /** Reset display adjustment values. Opens the preferences server and calls methods to readvalues from server and assing values to window */ void nGuiSettingsManagementWindow::ResetValues() { // temp security var int iCount = 0; // first try to load values from registry nPrefServer* prefServer = nPrefServer::Instance(); if (!prefServer->IsOpen()) { if (prefServer->Open()) { if (strcmp(refWindowSelectionTextView->GetSelection(), sceneControlString) == 0) { if (false == (this->ResetSceneControls(prefServer))) { // error occured prefServer->Close(); return; } } else if (strcmp(refWindowSelectionTextView->GetSelection(), displayAdjustmentString) == 0) { if (false == (this->ResetDisplayAdjustments(prefServer))) { // error occured prefServer->Close(); return; } } else { prefServer->Close(); this->SetInfoText("No window/controls set has been selected!\n Please select one from the upper list."); return; } } else { this->SetInfoText("Registry could not be opened!\nAborting!", true); return; } } // all went good prefServer->Close(); this->SetInfoText("Registry successfully read!"); } //------------------------------------------------------------------------------ /** Resets the values for the display adjustments window Returns true if everything is ok */ bool nGuiSettingsManagementWindow::ResetDisplayAdjustments(nPrefServer* prefServer) { // temp var int iCount = 0; // check paramter n_assert(prefServer); // get pointer to display adjustments window and check nGuiAdjustDisplayWindow* adjustWindow = (nGuiAdjustDisplayWindow*)nGuiServer::Instance()->FindWindowByClass("nguiadjustdisplaywindow", 0); if (0 == adjustWindow) { this->SetInfoText("No 'Display Adjustments' window was found!\nMaybe no one is open?", true); return false; } // check again n_assert(adjustWindow); // read from registry and assign to window if (prefServer->KeyExists(daSaturateSlider)) { adjustWindow->refSaturateSlider->SetValue(prefServer->ReadFloat(daSaturateSlider)); iCount++; } if (prefServer->KeyExists(daBalanceColorSlider)) { adjustWindow->refBalanceSlider->SetColor(prefServer->ReadVector4(daBalanceColorSlider)); iCount++; } if (prefServer->KeyExists(daHDRIntesitySlider)) { adjustWindow->refHdrBloomIntensitySlider->SetValue(prefServer->ReadFloat(daHDRIntesitySlider)); iCount++; } if (prefServer->KeyExists(daHDRThresholdSlider)) { adjustWindow->refHdrBrightPassThresholdSlider->SetValue(prefServer->ReadFloat(daHDRThresholdSlider)); iCount++; } if (prefServer->KeyExists(daHDROffsetSlider)) { adjustWindow->refHdrBrightPassOffsetSlider->SetValue(prefServer->ReadFloat(daHDROffsetSlider)); iCount++; } if (prefServer->KeyExists(daFogColorSlider)) { adjustWindow->refFogColorSlider->SetColor(prefServer->ReadVector4(daFogColorSlider)); iCount++; } if (prefServer->KeyExists(daFogNearSlider)) { adjustWindow->refFogNearSlider->SetValue(prefServer->ReadFloat(daFogNearSlider)); iCount++; } if (prefServer->KeyExists(daFogFarSlider)) { adjustWindow->refFogFarSlider->SetValue(prefServer->ReadFloat(daFogFarSlider)); iCount++; } if (prefServer->KeyExists(daFocusDistSlider)) { adjustWindow->refFocusDistSlider->SetValue(prefServer->ReadFloat(daFocusDistSlider)); iCount++; } if (prefServer->KeyExists(daFocusLengthSlider)) { adjustWindow->refFocusLengthSlider->SetValue(prefServer->ReadFloat(daFocusLengthSlider)); iCount++; } if (prefServer->KeyExists(daNoiseItensitySlider)) { adjustWindow->refNoiseIntensitySlider->SetValue(prefServer->ReadFloat(daNoiseItensitySlider)); iCount++; } if (prefServer->KeyExists(daNoiseScaleSlider)) { adjustWindow->refNoiseScaleSlider->SetValue(prefServer->ReadFloat(daNoiseScaleSlider)); iCount++; } if (prefServer->KeyExists(daNoiseFreqSlider)) { adjustWindow->refNoiseFrequencySlider->SetValue(prefServer->ReadFloat(daNoiseFreqSlider)); iCount++; } adjustWindow->UpdateValuesFromSliders(); // check if all done if (13 != iCount) { this->SetInfoText("The number of read values differs the number of values in dialog!\nMaybe no default settings were never saved!", true); return false; } // everything ok return true; } //------------------------------------------------------------------------------ /** Resets the values for the scene controls window Returns true if everything is ok */ bool nGuiSettingsManagementWindow::ResetSceneControls(nPrefServer* prefServer) { // temp var int iCount = 0; // check paramter n_assert(prefServer); // get pointer to scene window and check nGuiSceneControlWindow* sceneWindow = (nGuiSceneControlWindow*)nGuiServer::Instance()->FindWindowByClass("nguiscenecontrolwindow", 0); if (0 == sceneWindow) { this->SetInfoText("No 'Scene Control' window was found!\nMaybe no one is open?", true); return false; } // check again n_assert(sceneWindow); // read keys from registry and assign to window if (prefServer->KeyExists(scAmbientColorSlider)) { sceneWindow->refAmbientSlider->SetColor(prefServer->ReadVector4(scAmbientColorSlider)); iCount++; } if (prefServer->KeyExists(scDiffueColorSlider)) { sceneWindow->refDiffuseSlider->SetColor(prefServer->ReadVector4(scDiffueColorSlider)); iCount++; } if (prefServer->KeyExists(scSpeculaColorSlider)) { sceneWindow->refSpecularSlider->SetColor(prefServer->ReadVector4(scSpeculaColorSlider)); iCount++; } if (prefServer->KeyExists(scLightDirectionSlider)) { sceneWindow->refLightDirection->SetValue(prefServer->ReadFloat(scLightDirectionSlider)); iCount++; } if (prefServer->KeyExists(scLightHeightSlider)) { sceneWindow->refLightHeight->SetValue(prefServer->ReadFloat(scLightHeightSlider)); iCount++; } // check if all done if (5 != iCount) { this->SetInfoText("The number of read values differs the number of values in dialog!\nMaybe no default settings were never saved!", true); return false; } // all went good return true; } //------------------------------------------------------------------------------ /** Opens a file dialog */ void nGuiSettingsManagementWindow::CreateFileDialog() { // try to create default directory "home:work/save" if (!this->CheckDirAndCreate()) { this->SetInfoText("Default directory could not be created!", true); return; } nGuiSettingsFileDialog* dialog = (nGuiSettingsFileDialog*) nGuiServer::Instance()->NewWindow("nguisettingsfiledialog", true); n_assert(dialog); dialog->SetSettingWindowRef(this); } //------------------------------------------------------------------------------ /** Loads specified xml file and assigns values to controls */ void nGuiSettingsManagementWindow::LoadValuesFromFile(nString filename) { // try to create default directory "home:work/save" if (!this->CheckDirAndCreate()) { this->SetInfoText("Default directory could not be created!", true); return; } // prepend work directory filename = defaultDirectory +filename; // check if file exists if (!(nFileServer2::Instance()->FileExists(filename))) { this->SetInfoText("The specified file does not exists!", true); return; } // check if file is a xml file if (!filename.CheckExtension("xml")) { this->SetInfoText("The specified file is no xml file!", true); return; } // create stream and write stuff nStream stream; stream.SetFilename(filename); stream.Open(nStream::Read); // open file if (!stream.IsOpen()) { this->SetInfoText("The xml file could not be opened, or is not well-formed!", true); return; } // check root element if (!stream.HasNode("/Settings")) { this->SetInfoText("The xml file doesn't contain the root element <Settings>!", true); stream.Close(); return; } stream.SetToNode("/Settings"); // check which part should be loaded if (strcmp(refWindowSelectionTextView->GetSelection(), sceneControlString) == 0) { if (false == (this->LoadSceneControlsFromStream(&stream))) { stream.Close(); return; } } else if (strcmp(refWindowSelectionTextView->GetSelection(), displayAdjustmentString) == 0) { if (false == (this->LoadDisplayAdjustmentsFromStream(&stream))) { stream.Close(); return; } } else { this->SetInfoText("No window/controls set has been selected!\n Please select one from the upper list."); stream.Close(); return; } this->SetInfoText("All settings successfully read!"); stream.Close(); } //------------------------------------------------------------------------------ /** Reads the scene control contet from given stream Assigns the read values to the scene control window */ bool nGuiSettingsManagementWindow::LoadSceneControlsFromStream(nStream* stream) { // temp variables int iFoundEntries = 0; // get the pointer to window and check nGuiSceneControlWindow* sceneWindow = (nGuiSceneControlWindow*)nGuiServer::Instance()->FindWindowByClass("nguiscenecontrolwindow", 0); if (0 == sceneWindow) { this->SetInfoText("No 'Scene Control' window was found!\nMaybe no one is open?", true); return false; } n_assert(sceneWindow); // check if the node exists if (!stream->HasNode(scXMLRoot)) { this->SetInfoText("No 'Scene Control' window was found!\nMaybe no one is open?", true); return false; } stream->SetToNode(scXMLRoot); // try to set first child if (stream->SetToFirstChild()) { for (int iCount = 0; iCount < 5; iCount++) { if (stream->GetCurrentNodeName() == scXMLAmbientColor && stream->GetAttrs()[0] == colorSliderString) { sceneWindow->refAmbientSlider->SetColor(stream->GetVector4(colorSliderString)); iFoundEntries++; } else if (stream->GetCurrentNodeName() == scXMLDiffuceColor && stream->GetAttrs()[0] == colorSliderString) { sceneWindow->refDiffuseSlider->SetColor(stream->GetVector4(colorSliderString)); iFoundEntries++; } else if (stream->GetCurrentNodeName() == scXMLSpecularColor && stream->GetAttrs()[0] == colorSliderString) { sceneWindow->refSpecularSlider->SetColor(stream->GetVector4(colorSliderString)); iFoundEntries++; } else if (stream->GetCurrentNodeName() == scXMLLightDirection && stream->GetAttrs()[0] == sliderString) { sceneWindow->refLightDirection->SetValue(stream->GetFloat(sliderString)); iFoundEntries++; } else if (stream->GetCurrentNodeName() == scXMLLightHeight && stream->GetAttrs()[0] == sliderString) { sceneWindow->refLightHeight->SetValue(stream->GetFloat(sliderString)); iFoundEntries++; } // trie to set next child if (5 > iFoundEntries) { if (!stream->SetToNextChild()) { this->SetInfoText("The childs of the sub element <Scene_Control>\ncontains not the required amount of elements!", true); return false; } } } // check if the number of read values equals the number of needed values if (5 != iFoundEntries) { this->SetInfoText("Not all required settings could be read!", true); return false; } } else { this->SetInfoText("The sub element <Scene_Control> contains no childs!", true); return false; } // everything ok return true; } //------------------------------------------------------------------------------ /** Reads the display adjustment contet from given stream Assigns the read values to the display adjustment window */ bool nGuiSettingsManagementWindow::LoadDisplayAdjustmentsFromStream(nStream* stream) { // temp variables int iFoundEntries = 0; // get the pointer to the window and check nGuiAdjustDisplayWindow* adjustWindow = (nGuiAdjustDisplayWindow*)nGuiServer::Instance()->FindWindowByClass("nguiadjustdisplaywindow", 0); if (0 == adjustWindow) { this->SetInfoText("No 'Display Adjustments' window was found!\nMaybe no one is open?", true); return false; } n_assert(adjustWindow); // check the node, if exists, assign as actuall if (!stream->HasNode(daXMLRoot)) { this->SetInfoText("The xml file doesn't contain the \nsub element <DisplayAdjustments>!", true); return false; } stream->SetToNode(daXMLRoot); // try to get childs if (stream->SetToFirstChild()) { // repeat for each for (int iCount = 0; iCount < 13; iCount++) { if (stream->GetCurrentNodeName() == daXMLSaturate && stream->GetAttrs()[0] == sliderString) { adjustWindow->refSaturateSlider->SetValue(stream->GetFloat(sliderString)); iFoundEntries++; } else if (stream->GetCurrentNodeName() == daXMLBalance && stream->GetAttrs()[0] == colorSliderString) { adjustWindow->refBalanceSlider->SetColor(stream->GetVector4(colorSliderString)); iFoundEntries++; } else if (stream->GetCurrentNodeName() == daXMLHDRIntesity && stream->GetAttrs()[0] == sliderString) { adjustWindow->refHdrBloomIntensitySlider->SetValue(stream->GetFloat(sliderString)); iFoundEntries++; } else if (stream->GetCurrentNodeName() == daXMLHDRThreshold && stream->GetAttrs()[0] == sliderString) { adjustWindow->refHdrBrightPassThresholdSlider->SetValue(stream->GetFloat(sliderString)); iFoundEntries++; } else if (stream->GetCurrentNodeName() == daXMLHDROffset && stream->GetAttrs()[0] == sliderString) { adjustWindow->refHdrBrightPassOffsetSlider->SetValue(stream->GetFloat(sliderString)); iFoundEntries++; } else if (stream->GetCurrentNodeName() == daXMLFogColor && stream->GetAttrs()[0] == colorSliderString) { adjustWindow->refFogColorSlider->SetColor(stream->GetVector4(colorSliderString)); iFoundEntries++; } else if (stream->GetCurrentNodeName() == daXMLFogNear && stream->GetAttrs()[0] == sliderString) { adjustWindow->refFogNearSlider->SetValue(stream->GetFloat(sliderString)); iFoundEntries++; } else if (stream->GetCurrentNodeName() == daXMLFogFar && stream->GetAttrs()[0] == sliderString) { adjustWindow->refFogFarSlider->SetValue(stream->GetFloat(sliderString)); iFoundEntries++; } else if (stream->GetCurrentNodeName() == daXMLFocusDist && stream->GetAttrs()[0] == sliderString) { adjustWindow->refFocusDistSlider->SetValue(stream->GetFloat(sliderString)); iFoundEntries++; } else if (stream->GetCurrentNodeName() == daXMLFocusLenght && stream->GetAttrs()[0] == sliderString) { adjustWindow->refFocusLengthSlider->SetValue(stream->GetFloat(sliderString)); iFoundEntries++; } else if (stream->GetCurrentNodeName() == daXMLNoiseIntesity && stream->GetAttrs()[0] == sliderString) { adjustWindow->refNoiseIntensitySlider->SetValue(stream->GetFloat(sliderString)); iFoundEntries++; } else if (stream->GetCurrentNodeName() == daXMLNoiseScale && stream->GetAttrs()[0] == sliderString) { adjustWindow->refNoiseScaleSlider->SetValue(stream->GetFloat(sliderString)); iFoundEntries++; } else if (stream->GetCurrentNodeName() == daXMLNoiseFreq && stream->GetAttrs()[0] == sliderString) { adjustWindow->refNoiseFrequencySlider->SetValue(stream->GetFloat(sliderString)); iFoundEntries++; } // trie to set next child if (13 > iFoundEntries) { if (!stream->SetToNextChild()) { this->SetInfoText("The childs of the sub element <Display_Adjustments>\ncontains not the required amount of elements!", true); return false; } } } // check if the number of read values is correct if (13 != iFoundEntries) { this->SetInfoText("Not all required settings could be read!", true); return false; } } else { this->SetInfoText("The sub element <Display_Adjustments> contains no childs!", true); return false; } // everything ok return true; } //------------------------------------------------------------------------------ /** Gets values from controls and save them into specified xml file ATTENTION: All controls will be saved into this file, but they can be read spereatly! */ void nGuiSettingsManagementWindow::SaveValuesToFile(nString filename) { // try to create default directory "user:options" if (!this->CheckDirAndCreate()) { this->SetInfoText("Default directory could not be created!", true); return; } // get pointer to window nGuiSceneControlWindow* sceneWindow = (nGuiSceneControlWindow*)nGuiServer::Instance()->FindWindowByClass("nguiscenecontrolwindow", 0); if (0 == sceneWindow) { this->SetInfoText("No 'Scene Control' window was found!\nMaybe no one is open?", true); return; } n_assert(sceneWindow); // get pointer to window nGuiAdjustDisplayWindow* adjustWindow = (nGuiAdjustDisplayWindow*)nGuiServer::Instance()->FindWindowByClass("nguiadjustdisplaywindow", 0); if (0 == adjustWindow) { this->SetInfoText("No 'Display Adjustments' window was found!\nMaybe no one is open?", true); return; } n_assert(adjustWindow); // check extension if (!filename.CheckExtension("xml")) { filename.StripExtension(); filename.Append(".xml"); refFilenameEntry->SetText(filename.Get()); } // prepend work path filename = defaultDirectory + filename; // create stream and write stuff nStream stream; stream.SetFilename(filename); stream.Open(nStream::Write); if (!stream.IsOpen()) { this->SetInfoText("The file could not be opended. Check your permissions!", true); return; } // write root node with attributes for schema stream.BeginNode("Settings"); // stream.SetString("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); // stream.SetString("xsi:noNamespaceSchemaLocation", "schema.xsd"); // write window content this->WriteXMLfromDisplayAdjustments(&stream, adjustWindow); this->WriteXMLfromSceneControls(&stream, sceneWindow); // close stream stream.Close(); // all went good this->SetInfoText("All settings written to\n'" + filename + "'"); } //------------------------------------------------------------------------------ /** Writes the <Display_Adjustments> note to given stream */ void nGuiSettingsManagementWindow::WriteXMLfromDisplayAdjustments(nStream* stream, nGuiAdjustDisplayWindow* adjustWindow) { stream->BeginNode(daXMLRoot); stream->BeginNode(daXMLSaturate); stream->SetFloat(sliderString, adjustWindow->refSaturateSlider->GetValue()); stream->EndNode(); stream->BeginNode(daXMLBalance); stream->SetVector4(colorSliderString, adjustWindow->refBalanceSlider->GetColor()); stream->EndNode(); stream->BeginNode(daXMLHDRIntesity); stream->SetFloat(sliderString, adjustWindow->refHdrBloomIntensitySlider->GetValue()); stream->EndNode(); stream->BeginNode(daXMLHDRThreshold); stream->SetFloat(sliderString, adjustWindow->refHdrBrightPassThresholdSlider->GetValue()); stream->EndNode(); stream->BeginNode(daXMLHDROffset); stream->SetFloat(sliderString, adjustWindow->refHdrBrightPassOffsetSlider->GetValue()); stream->EndNode(); stream->BeginNode(daXMLFogColor); stream->SetVector4(colorSliderString, adjustWindow->refFogColorSlider->GetColor()); stream->EndNode(); stream->BeginNode(daXMLFogNear); stream->SetFloat(sliderString, adjustWindow->refFogNearSlider->GetValue()); stream->EndNode(); stream->BeginNode(daXMLFogFar); stream->SetFloat(sliderString, adjustWindow->refFogFarSlider->GetValue()); stream->EndNode(); stream->BeginNode(daXMLFocusDist); stream->SetFloat(sliderString, adjustWindow->refFocusDistSlider->GetValue()); stream->EndNode(); stream->BeginNode(daXMLFocusLenght); stream->SetFloat(sliderString, adjustWindow->refFocusLengthSlider->GetValue()); stream->EndNode(); stream->BeginNode(daXMLNoiseIntesity); stream->SetFloat(sliderString, adjustWindow->refNoiseIntensitySlider->GetValue()); stream->EndNode(); stream->BeginNode(daXMLNoiseScale); stream->SetFloat(sliderString, adjustWindow->refNoiseScaleSlider->GetValue()); stream->EndNode(); stream->BeginNode(daXMLNoiseFreq); stream->SetFloat(sliderString, adjustWindow->refNoiseFrequencySlider->GetValue()); stream->EndNode(); stream->EndNode(); } //------------------------------------------------------------------------------ /** Writes the <Scene_Control> note to given stream */ void nGuiSettingsManagementWindow::WriteXMLfromSceneControls(nStream* stream, nGuiSceneControlWindow* sceneWindow) { stream->BeginNode(scXMLRoot); stream->BeginNode(scXMLAmbientColor); stream->SetVector4(colorSliderString, sceneWindow->refAmbientSlider->GetColor()); stream->EndNode(); stream->BeginNode(scXMLDiffuceColor); stream->SetVector4(colorSliderString, sceneWindow->refDiffuseSlider->GetColor()); stream->EndNode(); stream->BeginNode(scXMLSpecularColor); stream->SetVector4(colorSliderString, sceneWindow->refSpecularSlider->GetColor()); stream->EndNode(); stream->BeginNode(scXMLLightDirection); stream->SetFloat(sliderString, sceneWindow->refLightDirection->GetValue()); stream->EndNode(); stream->BeginNode(scXMLLightHeight); stream->SetFloat(sliderString, sceneWindow->refLightHeight->GetValue()); stream->EndNode(); stream->EndNode(); } //------------------------------------------------------------------------------ /** Saves the values as default values to the registry */ void nGuiSettingsManagementWindow::SaveValuesAsDefault() { // get pref server, and check if open, if not open nPrefServer* prefServer = nPrefServer::Instance(); if (!prefServer->IsOpen()) { if (prefServer->Open()) { if (strcmp(refWindowSelectionTextView->GetSelection(), sceneControlString) == 0) { nGuiSceneControlWindow* sceneWindow = (nGuiSceneControlWindow*)nGuiServer::Instance()->FindWindowByClass("nguiscenecontrolwindow", 0); if (0 == sceneWindow) { this->SetInfoText("No 'Scene Control' window was found!\nMaybe no one is open?", true); prefServer->Close(); return; } prefServer->WriteVector4(scAmbientColorSlider, sceneWindow->refAmbientSlider->GetColor()); prefServer->WriteVector4(scDiffueColorSlider, sceneWindow->refDiffuseSlider->GetColor()); prefServer->WriteVector4(scSpeculaColorSlider, sceneWindow->refSpecularSlider->GetColor()); prefServer->WriteFloat(scLightDirectionSlider, sceneWindow->refLightDirection->GetValue()); prefServer->WriteFloat(scLightHeightSlider, sceneWindow->refLightHeight->GetValue()); } else if (strcmp(refWindowSelectionTextView->GetSelection(), displayAdjustmentString) == 0) { nGuiAdjustDisplayWindow* adjustWindow = (nGuiAdjustDisplayWindow*)nGuiServer::Instance()->FindWindowByClass("nguiadjustdisplaywindow", 0); if (0 == adjustWindow) { this->SetInfoText("No 'Display Adjustments' window was found!\nMaybe no one is open?", true); prefServer->Close(); return; } adjustWindow->UpdateSlidersFromValues(); prefServer->WriteFloat(daSaturateSlider, adjustWindow->refSaturateSlider->GetValue()); prefServer->WriteVector4(daBalanceColorSlider, adjustWindow->refBalanceSlider->GetColor()); prefServer->WriteFloat(daHDRIntesitySlider, adjustWindow->refHdrBloomIntensitySlider->GetValue()); prefServer->WriteFloat(daHDRThresholdSlider, adjustWindow->refHdrBrightPassThresholdSlider->GetValue()); prefServer->WriteFloat(daHDROffsetSlider, adjustWindow->refHdrBrightPassOffsetSlider->GetValue()); prefServer->WriteVector4(daFogColorSlider,adjustWindow->refFogColorSlider->GetColor()); prefServer->WriteFloat(daFogNearSlider, adjustWindow->refFogNearSlider->GetValue()); prefServer->WriteFloat(daFogFarSlider, adjustWindow->refFogFarSlider->GetValue()); prefServer->WriteFloat(daFocusDistSlider, adjustWindow->refFocusDistSlider->GetValue()); prefServer->WriteFloat(daFocusLengthSlider, adjustWindow->refFocusLengthSlider->GetValue()); prefServer->WriteFloat(daNoiseItensitySlider, adjustWindow->refNoiseIntensitySlider->GetValue()); prefServer->WriteFloat(daNoiseScaleSlider, adjustWindow->refNoiseScaleSlider->GetValue()); prefServer->WriteFloat(daNoiseFreqSlider, adjustWindow->refNoiseFrequencySlider->GetValue()); } else { this->SetInfoText("No window/controls set has been selected!\n Please select one from the upper list."); return; } } else { this->SetInfoText("Registry could not be opened!", true); return; } } // all went good, close the pref server prefServer->Close(); this->SetInfoText("Successfully written to registry!"); } //------------------------------------------------------------------------------ /** Sets the filename wich was selected in filedialog to the text label */ void nGuiSettingsManagementWindow::SetSelectedFilename(const nString filename) { refFilenameEntry->SetText(filename.Get()); } //------------------------------------------------------------------------------ /** Sets the info label with given text */ void nGuiSettingsManagementWindow::SetInfoText(const nString filename, bool criticalError) { // set color to red if this is an critical error if (true == criticalError) { refInfoLabel->SetColor(vector4(0.8f, 0.0f, 0.0f, 1.0f)); } else { refInfoLabel->SetColor(vector4(0.0f, 0.0f, 0.0f, 1.0f)); } refInfoLabel->SetText(filename.Get()); } //------------------------------------------------------------------------------ /** Appends a string for each supported window to the list view */ void nGuiSettingsManagementWindow::AddSupportedWindowsToList() { // hard coded, for each supported window this->refWindowSelectionTextView->AppendLine(displayAdjustmentString); this->refWindowSelectionTextView->AppendLine(sceneControlString); } //------------------------------------------------------------------------------ /** Checks if the directory exists and creates if it doesnt exist */ bool nGuiSettingsManagementWindow::CheckDirAndCreate() { if (!(nFileServer2::Instance()->DirectoryExists(defaultDirectory))) { return nFileServer2::Instance()->MakePath(defaultDirectory); } return true; }
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 1223 ] ] ]
e42dc01eb1a6426a7d8f02a9a6a88be11532549e
38664d844d9fad34e88160f6ebf86c043db9f1c5
/branches/initialize/infostudio/InfoStudio/maindlg.h
4ddf76c6d4ac36dd037b981286f185426499732c
[]
no_license
cnsuhao/jezzitest
84074b938b3e06ae820842dac62dae116d5fdaba
9b5f6cf40750511350e5456349ead8346cabb56e
refs/heads/master
2021-05-28T23:08:59.663581
2010-11-25T13:44:57
2010-11-25T13:44:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,497
h
// maindlg.h : interface of the CMainDlg class // ///////////////////////////////////////////////////////////////////////////// #if !defined(AFX_MAINDLG_H__E4963EDC_726F_44D0_9B3E_C15C6559C430__INCLUDED_) #define AFX_MAINDLG_H__E4963EDC_726F_44D0_9B3E_C15C6559C430__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 #include <atlframe.h> #include "resource.h" #include "aboutdlg.h" #include "infoManageView.h" class CMainDlg : public CDialogImpl<CMainDlg>, public CUpdateUI<CMainDlg>, public CMessageFilter, public CIdleHandler { public: enum { IDD = IDD_MAINDLG }; virtual BOOL PreTranslateMessage(MSG* pMsg) { return CWindow::IsDialogMessage(pMsg); } virtual BOOL OnIdle() { return FALSE; } CInfoManageView _infoManageView; BEGIN_UPDATE_UI_MAP(CMainDlg) END_UPDATE_UI_MAP() BEGIN_MSG_MAP(CMainDlg) MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog) COMMAND_ID_HANDLER(ID_APP_ABOUT, OnAppAbout) COMMAND_ID_HANDLER(IDOK, OnOK) COMMAND_ID_HANDLER(IDCANCEL, OnCancel) MSG_WM_SIZE(OnSize) END_MSG_MAP() // Handler prototypes (uncomment arguments if needed): // LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) // LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) // LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/) LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { // center the dialog on the screen CenterWindow(); // set icons HICON hIcon = (HICON)::LoadImage(_Module.GetResourceInstance(), MAKEINTRESOURCE(IDR_MAINFRAME), IMAGE_ICON, ::GetSystemMetrics(SM_CXICON), ::GetSystemMetrics(SM_CYICON), LR_DEFAULTCOLOR); SetIcon(hIcon, TRUE); HICON hIconSmall = (HICON)::LoadImage(_Module.GetResourceInstance(), MAKEINTRESOURCE(IDR_MAINFRAME), IMAGE_ICON, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR); SetIcon(hIconSmall, FALSE); // register object for message filtering and idle updates CMessageLoop* pLoop = _Module.GetMessageLoop(); ATLASSERT(pLoop != NULL); pLoop->AddMessageFilter(this); pLoop->AddIdleHandler(this); UIAddChildWindowContainer(m_hWnd); _infoManageView.Create( m_hWnd ); _infoManageView.ShowWindow( SW_SHOW ); return TRUE; } LRESULT OnAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { CAboutDlg dlg; dlg.DoModal(); return 0; } LRESULT OnOK(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { // TODO: Add validation code CloseDialog(wID); return 0; } LRESULT OnCancel(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { CloseDialog(wID); return 0; } void CloseDialog(int nVal) { DestroyWindow(); ::PostQuitMessage(nVal); } void OnSize(UINT wParam, CSize size) { DefWindowProc(); int cx = size.cx; int cy = size.cy; if ( _infoManageView ) _infoManageView.SetWindowPos(NULL, 0, 0, cx , cy, SWP_NOACTIVATE | SWP_NOZORDER ); } }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_MAINDLG_H__E4963EDC_726F_44D0_9B3E_C15C6559C430__INCLUDED_)
[ "ken.shao@ba8f1dc9-3c1c-0410-9eed-0f8a660c14bd" ]
[ [ [ 1, 127 ] ] ]
a31cc749243027d72039a63695369265ac9b8cb3
8ade67ab53907d22e40286b377b86d1b1eeaf6f0
/optimize_ca/coverage/files.h.bak.h
fdea5a341dc13a0d2daada5460cd8efc4275111f
[]
no_license
robbywalker/ca-phf-research
1483d1113abd865347c4f26934d4a5f43cd2e9b2
7bce5bde73bd6d7314902687b3323dcaf93941a6
refs/heads/master
2021-01-16T18:40:29.238236
2011-04-24T18:29:55
2011-04-24T18:29:55
1,657,333
1
0
null
null
null
null
UTF-8
C++
false
false
6,891
h
#pragma once #include "../tabu/arrays/tuple.h" #include "../tabu/cphf/iterable_utuple.h" #include "../tabu/util/util.h" #include "../coverage/fhCache.h" #include "../coverage/byteCache.h" #include <stdio.h> #include <direct.h> #include <string.h> #include <stdlib.h> #include <io.h> namespace coverage { int bitCounts[] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 }; int bitIndex[] = { -1, 0, 1, -1, 2, -1, -1, -1, 3, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; class fileStore { int rows, columns, symbols, strength; int bytesPerUtuple; char * dir; bool empty; fhCache fhC; byteCache byteC; inline int uidx( const cphf::iterable_utuple & u ) { int uIdx = 0; for ( int i = 0; i < strength; i++ ) { uIdx *= symbols; uIdx += u[i]; } return uIdx; } public: fileStore( int rows, int columns, int symbols, int strength, bool create ) { this->rows = rows; this->columns = columns; this->symbols = symbols; this->strength = strength; bytesPerUtuple = rows / 8; if ( rows % 8 != 0 ) bytesPerUtuple++; dir = new char[255]; sprintf(dir, "%d-%d-%d-%d.tmp", rows, columns, symbols, strength ); if ( ! _mkdir( dir ) ) { empty = true; if ( !create ) { _rmdir( dir ); printf("Directory '%s' does not exist.\n", dir); printf("Please run the analyze_ca tool first.\n", dir); exit( 1 ); } } else { empty = false; } strcat( dir, "\\" ); fhC.setDir( dir ); fhC.setFileLength( bytesPerUtuple, util::ipow( symbols, strength ) ); byteC.setFHCache( &fhC ); } bool isEmpty() { return empty; } void setCovered( const arrays::tuple & t, const cphf::iterable_utuple & u, int row ) { int uIdx = this->uidx( u ); int rIdx = row / 8; int rq = row % 8; int fIdx = uIdx * bytesPerUtuple + rIdx; byteId id(t,fIdx); byteC.set( id, byteC.get( id ) | (1 << rq) ); } void unsetCovered( const arrays::tuple & t, const cphf::iterable_utuple & u, int row ) { int uIdx = this->uidx( u ); int rIdx = row / 8; int rq = row % 8; int fIdx = uIdx * bytesPerUtuple + rIdx; byteId id(t,fIdx); byteC.set( id, byteC.get( id ) & ~(1 << rq) ); } bool isCovered( const arrays::tuple & t, const cphf::iterable_utuple & u ) { int uIdx = this->uidx( u ); int fIdx = uIdx * bytesPerUtuple; bool found = false; byteId id(t,fIdx); for ( int i = 0; i < bytesPerUtuple && !found; i++ ) { id.second = fIdx + i; if ( byteC.get( id ) != 0 ) { found = true; } } return found; } bool isUnique( const arrays::tuple & t, const cphf::iterable_utuple & u ) { int uIdx = this->uidx( u ); int fIdx = uIdx * bytesPerUtuple; bool found = false; unsigned char buffer; byteId id(t,fIdx); for ( int i = 0; i < bytesPerUtuple; i++ ) { id.second = fIdx + i; buffer = byteC.get( id ); if ( buffer != 0 ) { if ( found ) { // multiple return false; } else { if ( bitCounts[ buffer ] == 1 ) { found = true; } else { // multiple return false; } } } } return found; } int getUnique( const arrays::tuple & t, const cphf::iterable_utuple & u ) { int uIdx = this->uidx( u ); int fIdx = uIdx * bytesPerUtuple; int ret = -1; unsigned char buffer; byteId id(t,fIdx); for ( int i = 0; i < bytesPerUtuple; i++ ) { id.second = fIdx + i; buffer = byteC.get( id ); if ( buffer != 0 ) { if ( ret != -1 ) { return -1; // a multiple } else { ret = bitIndex[ buffer ]; if ( ret == -1 ) // a multiple return -1; else ret += i*8; } } } return ret; } int getCount( const arrays::tuple & t, const cphf::iterable_utuple & u ) { int uIdx = this->uidx( u ); int fIdx = uIdx * bytesPerUtuple; int ret = 0; byteId id(t,fIdx); for ( int i = 0; i < bytesPerUtuple; i++ ) { id.second = fIdx + i; ret += bitCounts[ (unsigned char) byteC.get( id ) ]; } return ret; } int getDuo( const arrays::tuple & t, const cphf::iterable_utuple & u, int ignore ) { int uIdx = this->uidx( u ); int fIdx = uIdx * bytesPerUtuple; int ret = -1; int ignoreB = ignore / 8; int ignoreQ = ignore % 8; unsigned char buffer; byteId id(t,fIdx); for ( int i = 0; i < bytesPerUtuple; i++ ) { id.second = fIdx + i; buffer = byteC.get( id ); if ( i == ignoreB ) buffer &= ~(1 << ignoreQ); if ( buffer != 0 ) { if ( ret != -1 ) { return -1; // a multiple } else { ret = bitIndex[ buffer ]; if ( ret == -1 ) // a multiple return -1; else ret += i * 8; } } } return ret; } void persist() { byteC.flush(); } }; }
[ [ [ 1, 249 ] ] ]
8a36f21ac1af98b47504e419df9bd71b69f3de6e
b546f33f58d2fad0c6fd1bb431532ab6124c118a
/T42Secretary.cpp
62cef8786620c8a02288d8ea27c0c2821797da4c
[ "MIT" ]
permissive
hacker/T42
cdcc02f91d52262374f1e0b6f286e387bfb9b582
025f8c9b1a478eed9dcb9e0ac13b9e26e955860a
refs/heads/master
2021-01-20T11:59:58.800561
2005-08-06T13:59:18
2005-08-06T13:59:18
892,107
2
0
null
null
null
null
UTF-8
C++
false
false
2,838
cpp
// T42Secretary.cpp : implementation file // #include "stdafx.h" #include "T42.h" #include "T42Document.h" #include "T42Secretary.h" #include "T42View.h" #include "T42Frame.h" CT42Secretary::CT42Secretary() { m_logEntry.m_Time = CTime::GetCurrentTime(); CT42App* app = (CT42App*)AfxGetApp(); app->m_T42LinesBusy++; m_limitTime = app->m_T42STimeLimit; m_limitBytes = app->m_T42SBytesLimit; TRACE0("Secretary++\n"); } CT42Secretary::~CT42Secretary() { CT42App* app = (CT42App*)AfxGetApp(); app->m_T42LinesBusy--; TRACE0("Secretary--\n"); } BOOL CT42Secretary::OnAttach(T42Document* pDocument) { TRACE0("T42S - OnAttach\n"); return CT42Robot::OnAttach(pDocument); } BOOL CT42Secretary::OnConnect() { m_logEntry.m_Caller = m_pDocument->m_pView->m_pFrame->m_Target; m_logEntry.m_Callee = m_pDocument->m_pView->m_pFrame->m_LocalUser; m_logEntry.m_Message.Empty(); m_logEntry.m_Time = CTime::GetCurrentTime(); CT42App* app = (CT42App*)AfxGetApp(); CString greet = app->m_T42SGreeting; int ix; while((ix=greet.Find("%t"))>=0){ CString tmp; tmp.Format("%lu",app->m_T42STimeLimit.GetTotalSeconds()/60); greet = greet.Left(ix)+tmp+greet.Mid(ix+2); } while((ix=greet.Find("%c"))>=0){ CString tmp; tmp.Format("%u",app->m_T42SBytesLimit); greet = greet.Left(ix)+tmp+greet.Mid(ix+2); } m_pDocument->SendOver(greet); return TRUE; } BOOL CT42Secretary::OnReceive(char* pData,int nBytes) { if(m_limitBytes && m_pDocument->m_pView->m_remoteCtl.GetTextLength()>=m_limitBytes) OnDisconnect(); return TRUE; } BOOL CT42Secretary::OnDisconnect() { m_logEntry.m_Duration = CTime::GetCurrentTime()-m_logEntry.m_Time; EDITSTREAM es; memset(&es,0,sizeof(es)); es.dwCookie = (DWORD)&m_logEntry.m_Message; es.pfnCallback = ESINProc; m_pDocument->m_pView->m_remoteCtl.StreamOut(SF_RTF,es); m_logEntry.m_Status = CT42CallLogEntry::statusOk; CT42App* app = (CT42App*)AfxGetApp(); VERIFY(app->AddT42Call(m_logEntry)); m_pDocument->m_pView->m_pFrame->OnTalkClose(); return TRUE; } BOOL CT42Secretary::OnDetach() { TRACE0("T42S - OnDetach\n"); delete this; return TRUE; } BOOL CT42Secretary::OnIPResolved() { m_logEntry.m_Caller = m_pDocument->m_pView->m_pFrame->m_Target; return TRUE; } DWORD CALLBACK CT42Secretary::ESINProc(DWORD dwCookie,LPBYTE pbBuff,LONG cb,LONG FAR *pcb) { CString* str = (CString*)dwCookie; if(memchr(pbBuff,0,cb-1)){ (*pcb) = 0; return 1; } UINT p = str->GetLength(); CHAR* s = str->GetBuffer(p+cb+1); memmove(&s[p],pbBuff,cb); s[p+cb]=0; str->ReleaseBuffer(); (*pcb)=cb; return 0; } BOOL CT42Secretary::OnMinute() { if( m_limitTime.GetTotalSeconds() && (CTime::GetCurrentTime()-m_logEntry.m_Time)>=m_limitTime ) OnDisconnect(); return TRUE; }
[ [ [ 1, 121 ] ] ]
efdc8f88adb736abadfb8bc6b858452088233b9d
85c93419769170bb411bb28e3ad4790bc5d98181
/ui/guitrackerdiag.cpp
1acd6c040559da09bcdada91db80b48832e1dc42
[]
no_license
hirikesh/gorgoneye
68d6a5774474cf541a7870fe35d0893ad54e99dd
fb81a4a059839bdf2d070dbda0ecde1ec7599f3a
refs/heads/master
2021-01-10T10:00:43.506555
2010-11-04T23:09:31
2010-11-04T23:09:31
49,187,180
0
0
null
null
null
null
UTF-8
C++
false
false
5,155
cpp
#include <vector> #include <string> #include <QVBoxLayout> #include <QScrollArea> #include <QLabel> #include <QDebug> #include <QTreeWidget> #include <QHeaderView> #include <QGridLayout> #include <QButtonGroup> #include "trackers/basetracker.h" #include "detectors/basedetector.h" #include "ui/guiparamdiag.h" #include "ui/guitreewidgetitem.h" #include "ui/guiparam.h" #include "parameter.h" #include "model.h" #include "guitrackerdiag.h" GUITrackerDiag::GUITrackerDiag(const std::string& title, Model* m, QWidget *parent) : QFrame(parent), mainLayout(new QGridLayout(this)), paramLayout(new QVBoxLayout()), listTitle(new QLabel(title.c_str())), paramTitle(new QLabel("Tracking Parameters:")), trackerTree(new QTreeWidget()), scrollArea(new QScrollArea()), scrollContents(new QWidget()), buttonGroup(new QButtonGroup()), trackers(m->getPtrTrackers()) { initTreeList(); init(); } void GUITrackerDiag::initTreeList() { //bool firstItemAdded = true; int firstColumn = 0; BaseTracker* currTracker; for(unsigned int i = 0; i < trackers->size(); i++) { currTracker = trackers->at(i); GUITreeWidgetItem* currTrackerItem = new GUITreeWidgetItem(trackerTree, currTracker->getImageModes(), buttonGroup); // if (firstItemAdded) // { // firstItemAdded = false; // initItemAdded = currTrackerItem; // } // std::string trackerEntry = "Enable " + currTracker->name() + " Tracking"; std::string trackerEntry = currTracker->name(); currTrackerItem->setText(firstColumn, trackerEntry.c_str()); paramDialogs.push_back(currTrackerItem->getParamDialog()); if (currTracker->isEnabled()) { currTrackerItem->setCheckState(firstColumn, Qt::Checked); } else { currTrackerItem->setCheckState(firstColumn, Qt::Unchecked); } std::vector<BaseFilter*> filters = currTracker->getFilters(); for(unsigned int j = 0; j < filters.size(); j++) { GUITreeWidgetItem* currDetectorItem = new GUITreeWidgetItem(currTrackerItem, filters[j]->params(), buttonGroup); std::string trackerItemEntry = filters[j]->name() + " Filter"; currDetectorItem->setText(firstColumn, trackerItemEntry.c_str()); paramDialogs.push_back(currDetectorItem->getParamDialog()); } std::vector<BaseDetector*> detectors = currTracker->getDetectors(); for(unsigned int j = 0; j < detectors.size(); j++) { GUITreeWidgetItem* currDetectorItem = new GUITreeWidgetItem(currTrackerItem, detectors[j]->params(), buttonGroup); std::string trackerItemEntry = detectors[j]->name() + " Algorithm"; currDetectorItem->setText(firstColumn, trackerItemEntry.c_str()); paramDialogs.push_back(currDetectorItem->getParamDialog()); } } // When user chooses different tracker; destroy top-level item associated with tracker, it's parameter dialogs? and re-create it. //delete trackerTree->takeTopLevelItem(0); } void GUITrackerDiag::init() { trackerTree->header()->hide(); // trackerTree->expandAll(); for (unsigned int i = 0; i < paramDialogs.size(); i++) { paramDialogs[i]->hide(); paramLayout->addWidget(paramDialogs[i]); } paramLayout->setMargin(0); mainLayout->addWidget(listTitle, 0, 0); mainLayout->addWidget(trackerTree, 1, 0); mainLayout->addWidget(paramTitle, 2, 0); mainLayout->addWidget(scrollArea, 3, 0); scrollContents->setLayout(paramLayout); scrollArea->setWidget(scrollContents); scrollArea->setWidgetResizable(true); setMinimumWidth(240); QObject::connect(trackerTree, SIGNAL(itemChanged(QTreeWidgetItem*,int)), this, SLOT(trackerItemToggled(QTreeWidgetItem*, int))); QObject::connect(trackerTree, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)), this, SLOT(changeParamBox(QTreeWidgetItem*,QTreeWidgetItem*))); } void GUITrackerDiag::trackerItemToggled(QTreeWidgetItem * item, int index) { if(item->checkState(0) == Qt::Checked) { int currIndex = trackerTree->currentIndex().row(); BaseTracker* currTracker = trackers->at(currIndex); currTracker->enable(); } else { int currIndex = trackerTree->currentIndex().row(); BaseTracker* currTracker = trackers->at(currIndex); currTracker->disable(); } } void GUITrackerDiag::changeParamBox(QTreeWidgetItem *currItem, QTreeWidgetItem *prevItem) { if (currItem!= NULL) { if (prevItem != NULL) { GUITreeWidgetItem* previousItem = static_cast<GUITreeWidgetItem*>(prevItem); previousItem->getParamDialog()->hide(); } GUITreeWidgetItem* currentItem = static_cast<GUITreeWidgetItem*>(currItem); currentItem->getParamDialog()->show(); } }
[ "malcoholic@a09ac5dc-a04a-0975-72ff-3257ca587d63", "justcme@a09ac5dc-a04a-0975-72ff-3257ca587d63" ]
[ [ [ 1, 32 ], [ 34, 52 ], [ 55, 66 ], [ 69, 69 ], [ 74, 74 ], [ 78, 78 ], [ 83, 92 ], [ 94, 100 ], [ 103, 104 ], [ 107, 110 ], [ 113, 149 ] ], [ [ 33, 33 ], [ 53, 54 ], [ 67, 68 ], [ 70, 73 ], [ 75, 77 ], [ 79, 82 ], [ 93, 93 ], [ 101, 102 ], [ 105, 106 ], [ 111, 112 ] ] ]
9e61d83a9438f7a788ff05f33db866f869e741c7
14a00dfaf0619eb57f1f04bb784edd3126e10658
/Lab3/HalfEdgeMesh.cpp
44adc2ab266e56c8d5a11c852f87da8dea64d3c8
[]
no_license
SHINOTECH/modanimation
89f842262b1f552f1044d4aafb3d5a2ce4b587bd
43d0fde55cf75df9d9a28a7681eddeb77460f97c
refs/heads/master
2021-01-21T09:34:18.032922
2010-04-07T12:23:13
2010-04-07T12:23:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,702
cpp
/************************************************************************************************* * * Modeling and animation (TNM079) 2007 * Code base for lab assignments. Copyright: * Gunnar Johansson ([email protected]) * Ken Museth ([email protected]) * Michael Bang Nielsen ([email protected]) * Ola Nilsson ([email protected]) * Andreas Sderstrm ([email protected]) * *************************************************************************************************/ #include "HalfEdgeMesh.h" #include "ColorMap.h" #ifdef __APPLE__ #include "GLUT/glut.h" #else #include "GL/glut.h" #endif #include <limits> #include <queue> const unsigned int HalfEdgeMesh::BORDER = std::numeric_limits<unsigned int>::max(); const unsigned int HalfEdgeMesh::UNINITIALIZED = std::numeric_limits<unsigned int>::max()-1; HalfEdgeMesh::HalfEdgeMesh() : mVertSize(0) , mFaceSize(0) , mEdgeSize(0) { } HalfEdgeMesh::~HalfEdgeMesh() { } //----------------------------------------------------------------------------- bool HalfEdgeMesh::addTriangle(const Vector3<float> &v1, const Vector3<float> &v2, const Vector3<float> & v3){ // Add the vertices of the face/triangle unsigned int ind1, ind2, ind3; addVertex(v1, ind1); addVertex(v2, ind2); addVertex(v3, ind3); // Add all half-edge pairs unsigned int edgeind1, edgeind2, edgeind3; unsigned int edgeind1pair, edgeind2pair, edgeind3pair; addHalfEdgePair( ind1, ind2, edgeind1, edgeind1pair ); addHalfEdgePair( ind2, ind3, edgeind2, edgeind2pair ); addHalfEdgePair( ind3, ind1, edgeind3, edgeind3pair ); // Connect inner ring mEdges[edgeind1].next = edgeind2; mEdges[edgeind1 ].prev = edgeind3; mEdges[ edgeind2 ].next = edgeind3; mEdges[ edgeind2 ].prev = edgeind1; mEdges[edgeind3 ].next = edgeind1; mEdges[ edgeind3 ].prev = edgeind2; // Finally, create the face Face f; f.edge = edgeind1; mFaces.push_back( f ); // All half-edges share the same left face (previously added) int index = mFaceSize++; mEdges[edgeind1 ].face = index; mEdges[ edgeind2 ].face = index; mEdges[ edgeind3 ].face = index; return true; } //----------------------------------------------------------------------------- bool HalfEdgeMesh::addVertex(const Vector3<float> & v, unsigned int &indx) { // THashTable::iterator it = hash.find( x ); // std::map<Vector3<float>,unsigned int>::iterator it = mUniqueVerts.find(v); VertexHashTable::iterator it = mUniqueVerts.find( v ); if (it != mUniqueVerts.end()){ indx = (*it).second; // (*it).second == it.second, which to me was not as clear... return false; } mUniqueVerts[v] = indx = mVertSize; // op. [ ] constructs a new entry in map mVertSize++; Vertex vert; vert.vec = v; mVerts.push_back(vert); return true; } bool HalfEdgeMesh::addHalfEdgePair(unsigned int v1, unsigned int v2, unsigned int &indx1, unsigned int &indx2) { //// Search for the HalfEdge pair among existing edges //std::vector<HalfEdge>::reverse_iterator iter = mEdges.rbegin(); //std::vector<HalfEdge>::reverse_iterator iend = mEdges.rend(); //while (iter != iend) // { // if ((*iter).vert == v1 && mEdges[(*iter).pair].vert == v2) // { // indx1 = iter.base() - mEdges.begin() - 1; // indx2 = (*iter).pair; // return false; // } // iter++; // } std::pair<unsigned int, unsigned int> key = std::make_pair( std::min(v1,v2), std::max(v1,v2) ); EdgeHashTable::iterator it = mUniqueEdges.find( key ); //does not exist yet if ( mUniqueEdges.end() == it) { // If not found, add both half-edges indx1 = mEdgeSize++; indx2 = mEdgeSize++; // Create edges and set pair index HalfEdge edge1, edge2; edge1.pair = indx2; edge2.pair = indx1; // Connect the edges to the verts edge1.vert = v1; edge2.vert = v2; // Connect the verts to the edges mVerts[v1].edge = indx1; mVerts[v2].edge = indx2; // Store the edges mEdges.push_back(edge1); mEdges.push_back(edge2); mUniqueEdges[key] = mVerts[ std::min(v1,v2)].edge; return true; } //edge already created else { indx1 = (v1<v2)? it->second : mEdges[ it->second].pair; indx2 = (v1<v2)? mEdges[ it->second ].pair : it->second; return false; } } void HalfEdgeMesh::mergeBoundaryEdge(unsigned int indx) { } void HalfEdgeMesh::validate() { std::vector<HalfEdge>::iterator iterEdge = mEdges.begin(); std::vector<HalfEdge>::iterator iterEdgeEnd = mEdges.end(); while (iterEdge != iterEdgeEnd) { if ((*iterEdge).face == UNINITIALIZED || (*iterEdge).next == UNINITIALIZED || (*iterEdge).pair == UNINITIALIZED || (*iterEdge).prev == UNINITIALIZED || (*iterEdge).vert == UNINITIALIZED) std::cerr << "HalfEdge " << iterEdge - mEdges.begin() << " not properly initialized" << std::endl; iterEdge++; } std::cerr << "Done with edge check (checked " << mEdgeSize << " edges)" << std::endl; std::vector<Face>::iterator iterFace = mFaces.begin(); std::vector<Face>::iterator iterFaceEnd = mFaces.end(); while (iterFace != iterFaceEnd) { if ((*iterFace).edge == UNINITIALIZED) std::cerr << "Face " << iterFace - mFaces.begin() << " not properly initialized" << std::endl; iterFace++; } std::cerr << "Done with face check (checked " << mFaceSize << " faces)" << std::endl; std::vector<Vertex>::iterator iterVertex = mVerts.begin(); std::vector<Vertex>::iterator iterVertexEnd = mVerts.end(); while (iterVertex != iterVertexEnd) { if ((*iterVertex).edge == UNINITIALIZED) std::cerr << "Vertex " << iterVertex - mVerts.begin() << " not properly initialized" << std::endl; iterVertex++; } std::cerr << "Done with vertex check (checked " << mVertSize << " vertices)" << std::endl; std::cerr << "Looping through triangle neighborhood of each vertex... "; iterVertex = mVerts.begin(); iterVertexEnd = mVerts.end(); std::vector<unsigned int> foundTriangles; int emptyCount = 0; while (iterVertex != iterVertexEnd) { if (!findNeighbourTriangles(iterVertex - mVerts.begin(), foundTriangles)) emptyCount++; iterVertex++; } std::cerr << std::endl << "Done: " << emptyCount << " isolated vertices found" << std::endl; } //----------------------------------------------------------------------------- bool HalfEdgeMesh::findNeighbourTriangles(const unsigned int vertexIndex, std::vector<unsigned int>& foundTriangles) const { foundTriangles.clear(); unsigned int edge = mVerts.at( vertexIndex ).edge; //go to the previous so we can always proceed in the same way in the loop int pair = mEdges[edge].prev; edge = pair; int next(0); int face; //find the neighbours do { face = mEdges.at( pair ).face; for(int i = 0; i < foundTriangles.size(); i++) { // if the face already exists, RETURN if( foundTriangles[i] == face ) { return !(foundTriangles.size() == 0); } } foundTriangles.push_back( face ); next = mEdges[pair].next; pair = mEdges[next].pair; } while( pair != edge ); return !(foundTriangles.size() == 0); } float HalfEdgeMesh::area() { float totalArea(0); unsigned int numTriangles = mFaceSize; for (unsigned int i = 0; i < numTriangles; i++) { totalArea += calculateFaceNormal( i ).length() / 2.0f; } return totalArea; } float HalfEdgeMesh::volume() { float totalVolume(0); unsigned int numTriangles = mFaceSize; for (unsigned int i = 0; i < numTriangles; i++) { Vector3<float> normal = calculateFaceNormal( i ); float length = normal.length(); normal.normalize(); int edgeIndex1 = mFaces.at(i).edge; int edgeIndex2 = mEdges.at( edgeIndex1 ).next; int edgeIndex3 = mEdges.at( edgeIndex2 ).next; Vertex v1 = mVerts.at( mEdges.at( edgeIndex1 ).vert ); Vertex v2 = mVerts.at( mEdges.at( edgeIndex2 ).vert ); Vertex v3 = mVerts.at( mEdges.at( edgeIndex3 ).vert ); float area = length / 2.0f; totalVolume += (( v1.vec + v2.vec + v3.vec ) / 3.0f)*normal * area; } return totalVolume/3.0f; } int HalfEdgeMesh::genus() const { printf("Genus calculation not implemented for half-edge mesh!\n"); return 0; } int HalfEdgeMesh::shells() const { std::queue<Vertex> vertexQueue; return 0; } float HalfEdgeMesh::curvature(const unsigned int vertexIndex, const Vector3<float>& n) { printf("Curvature calculation not implemented for half-edge mesh!\n"); return 0; } void HalfEdgeMesh::calculateFaceNormals() { unsigned int numTriangles = mFaceSize; for (unsigned int i = 0; i < numTriangles; i++){ HalfEdge* edge = &mEdges[mFaces[i].edge]; Vector3<float>& p0 = mVerts[edge->vert].vec; edge = &mEdges[edge->next]; Vector3<float>& p1 = mVerts[edge->vert].vec; edge = &mEdges[edge->next]; Vector3<float>& p2 = mVerts[edge->vert].vec; // Calculate face normal Vector3<float> v1 = p1-p0; Vector3<float> v2 = p2-p0; Vector3<float> n = cross(v1,v2); n.normalize(); mFaces[i].normal = n; // assign normal to face } } void HalfEdgeMesh::calculateVertexNormals() { std::vector<unsigned int> foundTriangles; for (int i=0, endI=mVertSize; i<endI; i++) { findNeighbourTriangles(i, foundTriangles ); Vector3<float> normal; int endJ=foundTriangles.size(); for (int j=0; j<endJ; j++) { normal += calculateFaceNormal( foundTriangles[j] ).normalize(); } normal = normal/endJ; //mNormals.push_back( normal ); mVerts[i].normal = normal; } } Vector3<float> HalfEdgeMesh::calculateFaceNormal( unsigned int aTriangle ) { HalfEdge* edge = &mEdges[mFaces[aTriangle].edge]; Vector3<float>& p0 = mVerts[edge->vert].vec; edge = &mEdges[edge->next]; Vector3<float>& p1 = mVerts[edge->vert].vec; edge = &mEdges[edge->next]; Vector3<float>& p2 = mVerts[edge->vert].vec; // Calculate face normal Vector3<float> v1 = p1-p0; Vector3<float> v2 = p2-p0; Vector3<float> n = cross(v1,v2); return n.normalize(); } //----------------------------------------------------------------------------- void HalfEdgeMesh::draw() { ColorMap colorMap; glMatrixMode(GL_MODELVIEW); // Apply transform glPushMatrix(); // Push modelview matrix onto stack // Convert transform-matrix to format matching GL matrix format GLfloat glMatrix[16]; mTransform.toGLMatrix(glMatrix); // Load transform into modelview matrix glLoadMatrixf(glMatrix); // Draw geometry glBegin(GL_TRIANGLES); const int numTriangles = mFaceSize; for (int i = 0; i < numTriangles; i++){ HalfEdge* edge = &mEdges[mFaces[i].edge]; Vector3<float>& p0 = mVerts[edge->vert].vec; edge = &mEdges[edge->next]; Vector3<float>& p1 = mVerts[edge->vert].vec; edge = &mEdges[edge->next]; Vector3<float>& p2 = mVerts[edge->vert].vec; if (getShadingFlag() == FLAT_SHADING){ Vector3<float>& n = mFaces[i].normal; Vector3<float> color = colorMap.map(n, -1, 1); glColor3f(color[0],color[1], color[2]); glNormal3f(n[0], n[1], n[2]); glVertex3f(p0[0], p0[1], p0[2]); glVertex3f(p1[0], p1[1], p1[2]); glVertex3f(p2[0], p2[1], p2[2]); } else if (getShadingFlag() == SMOOTH_SHADING){ HalfEdge* edge = &mEdges[mFaces[i].edge]; unsigned int v1 = edge->vert; edge = &mEdges[edge->next]; unsigned int v2 = edge->vert; edge = &mEdges[edge->next]; unsigned int v3 = edge->vert; // Fetching normals - the normal index is the same as the vertex index Vector3<float>& n0 = mVerts[v1].normal; Vector3<float>& n1 = mVerts[v2].normal; Vector3<float>& n2 = mVerts[v3].normal; // Color mapping, maps the normal components to R,G,B. From [-1, 1] to [0,1] respectively Vector3<float> color0 = colorMap.map(n0, -1, 1); Vector3<float> color1 = colorMap.map(n1, -1, 1); Vector3<float> color2 = colorMap.map(n2, -1, 1); glColor3f(color0[0],color0[1], color0[2]); glNormal3f(n0[0], n0[1], n0[2]); glVertex3f(p0[0], p0[1], p0[2]); glColor3f(color1[0],color1[1], color1[2]); glNormal3f(n1[0], n1[1], n1[2]); glVertex3f(p1[0], p1[1], p1[2]); glColor3f(color2[0],color2[1], color2[2]); glNormal3f(n2[0], n2[1], n2[2]); glVertex3f(p2[0], p2[1], p2[2]); } else{ // No normals glVertex3f(p0[0], p0[1], p0[2]); glVertex3f(p1[0], p1[1], p1[2]); glVertex3f(p2[0], p2[1], p2[2]); } } glEnd(); // Restore modelview matrix glPopMatrix(); }
[ "jpjorge@da195381-492e-0410-b4d9-ef7979db4686", "onnepoika@da195381-492e-0410-b4d9-ef7979db4686" ]
[ [ [ 1, 1 ], [ 12, 19 ], [ 22, 25 ], [ 27, 27 ], [ 33, 34 ], [ 37, 38 ], [ 41, 42 ], [ 48, 48 ], [ 52, 52 ], [ 56, 56 ], [ 60, 60 ], [ 63, 63 ], [ 66, 67 ], [ 72, 72 ], [ 75, 75 ], [ 79, 79 ], [ 106, 108 ], [ 165, 165 ], [ 171, 171 ], [ 223, 223 ], [ 226, 226 ], [ 236, 236 ], [ 240, 243 ], [ 245, 252 ], [ 257, 257 ], [ 260, 261 ], [ 298, 298 ], [ 311, 312 ], [ 317, 318 ], [ 327, 327 ], [ 341, 342 ], [ 349, 349 ], [ 357, 357 ], [ 382, 383 ] ], [ [ 2, 11 ], [ 20, 21 ], [ 26, 26 ], [ 28, 32 ], [ 35, 36 ], [ 39, 40 ], [ 43, 47 ], [ 49, 51 ], [ 53, 55 ], [ 57, 59 ], [ 61, 62 ], [ 64, 65 ], [ 68, 71 ], [ 73, 74 ], [ 76, 78 ], [ 80, 105 ], [ 109, 164 ], [ 166, 170 ], [ 172, 222 ], [ 224, 225 ], [ 227, 235 ], [ 237, 239 ], [ 244, 244 ], [ 253, 256 ], [ 258, 259 ], [ 262, 297 ], [ 299, 310 ], [ 313, 316 ], [ 319, 326 ], [ 328, 340 ], [ 343, 348 ], [ 350, 356 ], [ 358, 381 ], [ 384, 471 ] ] ]
a862c232b5373b587c88012e457e70dff6569189
8a0a81978126520c0bfa0d2ad6bd1d35236f1aa2
/SegmentationRegional/RegionalSegmentationUI/regionalsegmentationui.cpp
6359f191b710101f4477edfe18a5e0e9bc6cef28
[]
no_license
zjucsxxd/BSplineLevelSetRegionalSegmentation
a64b4a096f65736659b6c74dce7cd973815b9a2c
a320ade9386861657476cca7fce97315de5e3e31
refs/heads/master
2021-01-20T23:03:26.244747
2011-12-10T13:10:56
2011-12-10T13:10:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,732
cpp
#include "regionalsegmentationui.h" #include <QtOpenCvWidget.h> #include <RegionalSegmentationWorker.h> #include <BSPlineLevelSet.h> #include <algorithm> using namespace cv; using namespace Qwt3D; Plot2D::Plot2D() : _levelSetFunction(this) { setTitle("The Level Set Function Surface"); setRotation(-30,0,15); setScale(1,1,1); setShift(0.15,0,0); setZoom(0.9); for (unsigned i=0; i!=coordinates()->axes.size(); ++i) { coordinates()->axes[i].setMajors(7); coordinates()->axes[i].setMinors(4); } coordinates()->axes[X1].setLabelString("X-axis"); coordinates()->axes[Y1].setLabelString("Y-axis"); coordinates()->axes[Z1].setLabelString( QChar (0X03A6)); // Phi - see http://www.unicode.org/charts/ setCoordinateStyle(FRAME); // NOCOORD FRAME BOX this->setPlotStyle(FILLED); // NOPLOT WIREFRAME HIDDENLINE FILLED FILLEDMESH POINTS USER setFloorStyle(FLOORISO); //FLOORISO FLOORDATA this->setSmoothMesh(true); } void Plot2D::update( const cv::Mat* m, const double n ) { if (m) { _levelSetFunction._pM = m; Size s = _levelSetFunction._pM->size(); _levelSetFunction.setMesh(s.height,s.width); _levelSetFunction.setDomain(0,s.height-1,0,s.width-1); _levelSetFunction.setMinZ(- _levelSetFunction.scaleDrawFactor * (n + n/2)); _levelSetFunction.setMaxZ( _levelSetFunction.scaleDrawFactor * (n)); } else { _levelSetFunction.setMesh(0,0); _levelSetFunction.setDomain(0,0,0,0); _levelSetFunction.setMinZ(0); } _levelSetFunction.create(); updateData(); updateGL(); _levelSetFunction._pM = NULL; } LevelSetFunctionSurface::LevelSetFunctionSurface( Qwt3D::SurfacePlot* pw ) : Function(pw), _pM(NULL), scaleDrawFactor(10.0) { } double LevelSetFunctionSurface::operator()( double x, double y ) { return scaleDrawFactor * _pM->at<double>(x,y); } RegionalSegmentationUI::RegionalSegmentationUI(QWidget *parent, Qt::WFlags flags) : QDialog(parent, flags), isMaskDrawing(false) { ui.setupUi(this); setWindowFlags( (windowFlags() | Qt::CustomizeWindowHint) & Qt::WindowMaximizeButtonHint); #define WINDOW_STYLE CV_WINDOW_AUTOSIZE // CV_WINDOW_FREERATIO CV_WINDOW_AUTOSIZE _2DLeftOpenCvQtWidget = new CvWidget("2D_Image_List", WINDOW_STYLE); ui.tab2DHorizontalLayout->addWidget(_2DLeftOpenCvQtWidget); _2DRightOpenCvQtWidget = new CvWidget("3D_Image_List", WINDOW_STYLE); ui.tab2DHorizontalLayout->addWidget(_2DRightOpenCvQtWidget); _2DPlot = new Plot2D(); ui.tab3DHorizontalLayout->addWidget(_2DPlot); //ui.tab3DHorizontalLayout->addWidget(_2DRightOpenCvQtWidget); connect( ui.openImageButton, SIGNAL(clicked()), this, SLOT(openImageButtonSlot())); connect( ui.drawMaskButton, SIGNAL(clicked()), this, SLOT(drawMaskButtonSlot())); connect( ui.runButton, SIGNAL(clicked()), this, SLOT(runButtonSlot())); ui.drawMaskButton->setDisabled(true); ui.runButton->setDisabled(true); _lastOpenedDir = QDir::currentPath(); worker = NULL; } RegionalSegmentationUI::~RegionalSegmentationUI() { delete _2DLeftOpenCvQtWidget; delete _2DRightOpenCvQtWidget; delete _2DPlot; } void RegionalSegmentationUI::setImage( CvWidget*& widget, Mat& image ) { const InputArray& _img = image; Mat img = _img.getMat(); CvMat c_img = img; widget->updateImage(&c_img); } void RegionalSegmentationUI::openImageButtonSlot() { //if (ui.tabWidget->currentIndex()) //{ // 3D Tab // QStringList fileList = QFileDialog::getOpenFileNames( this, tr("Pick Multiple Image Files"), // QDir::currentPath(), tr("Images (*.png *.bmp *.jpg)")); // if (fileList.isEmpty()) // return; // _3dImages.clear(); // foreach(QString file, fileList) // { // Mat image = imread(file.toStdString()); // _3dImages.append( QPair<cv::Mat, QString>(image,file)); // setImage(_2DRightOpenCvQtWidget, _3dImages[0].first); // } // ui.runButton->setDisabled(false); //} //else { // 2D Tab QString file = QFileDialog::getOpenFileName( this, tr("Pick an Image File"), _lastOpenedDir, tr("Images (*.png *.bmp *.jpg *.tif)")); if(file.isNull()) return; //No filename selected _lastOpenedDir = file; _2dImage.second = file; _2dImage.first = imread(file.toStdString()); setImage(_2DRightOpenCvQtWidget, _2dImage.first); setImage(_2DLeftOpenCvQtWidget, _2dImage.first); Size size = _2dImage.first.size(); size.width *= 2; size.width += ui.runButton->size().width() + 30; size.height += ui.textBrowser->size().height() + 95; this->resize( QSize(size.width,size.height)); ui.drawMaskButton->setDisabled(false); Size s = _2dImage.first.size(); maskInfo.first.setX(s.width/2); maskInfo.first.setY(s.height/2); maskInfo.second = min(maskInfo.first.x(), maskInfo.first.y())/2; drawMask2D(); drawMask3D(); ui.runButton->setDisabled(false); } } void RegionalSegmentationUI::drawMaskButtonSlot() { ui.runButton->setDisabled(true); ui.drawMaskButton->setDisabled(true); ui.openImageButton->setDisabled(true); ui.textBrowser->append("The mask is a circle. Select first the center of it!"); _2DLeftOpenCvQtWidget->setCursor(QCursor(Qt::CrossCursor)); _2DLeftOpenCvQtWidget->installEventFilter(this); setImage(_2DLeftOpenCvQtWidget, _2dImage.first); } void RegionalSegmentationUI::runButtonSlot() { ui.textBrowser->append("\r\n"); ui.runButton->setDisabled(true); ui.drawMaskButton->setDisabled(true); ui.openImageButton->setDisabled(true); ui.spinBoxPrecision->setDisabled(true); ui.spinBoxScale->setDisabled(true); ui.spinBoxMaxIteration->setDisabled(true); ui.spinBoxDrawDelay->setDisabled(true); //if (ui.tabWidget->currentIndex())◙ //{ // 3D Tab //} //else { // 2D Tab Mat mask = Mat::zeros(_2dImage.first.size(), CV_8U); circle(mask, cv::Point(maskInfo.first.x(), maskInfo.first.y()), maskInfo.second, 1, -1); if( worker ) delete worker; worker = new RegionalSegmentationWorker(this, _2dImage.first.clone(), mask, ui.spinBoxMaxIteration->value(), ui.spinBoxScale->value(), ui.spinBoxPrecision->value()); worker->_sleepTime = ui.spinBoxDrawDelay->value(); connect(worker, SIGNAL(finished()), this, SLOT(algorithmOver())); connect(worker, SIGNAL(drawTemp()), this, SLOT(drawTemp())); connect(worker, SIGNAL(message(const QString&)), ui.textBrowser, SLOT(append(const QString&))); worker->start(); //setImage(_2DRightOpenCvQtWidget, levelSetBSpline.drawContourAndMask(true)); } } bool RegionalSegmentationUI::eventFilter( QObject *watched, QEvent *e ) { if (watched == _2DLeftOpenCvQtWidget) { switch (e->type()) { case QEvent::MouseButtonPress: { drawMaskCenterPoint(static_cast<QMouseEvent*>(e)); break; } case QEvent::MouseButtonRelease: { drawMaskFinish(static_cast<QMouseEvent*>(e)); break; } case QEvent::MouseMove: { if( isMaskDrawing) drawCircleOnOutPut(static_cast<QMouseEvent*>(e)); break; } } } return QDialog::eventFilter(watched, e); } void RegionalSegmentationUI::drawMaskCenterPoint(QMouseEvent* info) { if(info->button() != Qt::LeftButton && info->button() != Qt::RightButton) return; ui.textBrowser->append("And now its radius!"); isMaskDrawing = true; saveMaskTemp = maskInfo; maskInfo.first = info->pos(); maskInfo.first.setY( maskInfo.first.y() - 28); // Adjust for the toolbar const unsigned int w = _2dImage.first.size().width; if ( w < 310) maskInfo.first.setX( maskInfo.first.x() - ((310-w) >> 1)); // Adjust for the toolbar } void RegionalSegmentationUI::drawCircleOnOutPut( QMouseEvent* info ) { QPoint p = info->pos(); p.setY( p.y() - 28); // Adjust for the toolbar const unsigned int w = _2dImage.first.size().width; if ( w < 310) p.setX( p.x() - ((310-w) >> 1)); // Adjust for the toolbar int x = maskInfo.first.x() - p.x(); int y = maskInfo.first.y() - p.y(); maskInfo.second = sqrt((double) (x*x + y*y) ); drawMask2D(); } void RegionalSegmentationUI::drawMaskFinish( QMouseEvent* info ) { drawCircleOnOutPut(info); if (!maskInfo.second) { maskInfo = saveMaskTemp; drawMask2D(); } drawMask3D(); isMaskDrawing = false; _2DLeftOpenCvQtWidget->removeEventFilter(this); _2DLeftOpenCvQtWidget->setCursor(QCursor(Qt::ArrowCursor)); ui.runButton->setDisabled(false); ui.drawMaskButton->setDisabled(false); ui.openImageButton->setDisabled(false);; } void RegionalSegmentationUI::drawMask2D() { Mat temp = _2dImage.first.clone(); circle(temp, cv::Point(maskInfo.first.x(), maskInfo.first.y()), maskInfo.second, cv::Scalar( 0, 255, 182 )); setImage(_2DLeftOpenCvQtWidget, temp); } void RegionalSegmentationUI::algorithmOver() { disconnect(worker, SIGNAL(finished()), this, SLOT(algorithmOver())); disconnect(worker, SIGNAL(drawTemp()), this, SLOT(drawTemp())); disconnect(worker, SIGNAL(message(const QString&)), ui.textBrowser, SLOT(append(const QString&))); delete worker; worker = NULL; ui.runButton->setDisabled(false); ui.drawMaskButton->setDisabled(false); ui.openImageButton->setDisabled(false); ui.spinBoxPrecision->setDisabled(false); ui.spinBoxScale->setDisabled(false); ui.spinBoxMaxIteration->setDisabled(false); ui.spinBoxDrawDelay->setDisabled(false); } void RegionalSegmentationUI::drawTemp() { if(!worker->_mutex.tryLock()) return; Mat temp = 255* worker->levelSetBSpline.tempMask().clone(); setImage(_2DRightOpenCvQtWidget, temp); _2DPlot->update(&worker->levelSetBSpline.LevelSetFunction().clone(), worker->levelSetBSpline.normInterValum()); Mat m = _2dImage.first.clone(); worker->levelSetBSpline.drawContour(true, m); setImage(_2DLeftOpenCvQtWidget, m); worker->_mutex.unlock(); } void RegionalSegmentationUI::drawMask3D() { Mat mask = Mat::zeros(_2dImage.first.size(), CV_8U); circle(mask, cv::Point(maskInfo.first.x(), maskInfo.first.y()), maskInfo.second, 1, -1); Mat temp = LevelSetSegmentation::BSPlineLevelSet::maskToSignedDistanceFunction(mask); const double Linf = 3/ *std::max_element(temp.begin<double>(), temp.end<double>(), [](double i, double j) -> bool { return abs(i) < abs(j); }); std::for_each(temp.begin<double>(), temp.end<double>(), [&Linf](double& i) { i *= Linf;}); /*Normalize the surface.*/ _2DPlot->update(&temp, 3); }
[ [ [ 1, 343 ] ] ]
92ba5ac40608afbd2a12511b5fc47cfe0b736307
38664d844d9fad34e88160f6ebf86c043db9f1c5
/branches/tags/mfc-import/controls/edit.h
fe8cf89f554e5bd3ebdbd5d057cf1b910d797c59
[]
no_license
cnsuhao/jezzitest
84074b938b3e06ae820842dac62dae116d5fdaba
9b5f6cf40750511350e5456349ead8346cabb56e
refs/heads/master
2021-05-28T23:08:59.663581
2010-11-25T13:44:57
2010-11-25T13:44:57
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
2,305
h
#pragma once #include "../base/skinctrl.h" namespace Skin { template<class BaseT = CEdit> struct SkinEdit : public SkinControlImpl<SkinEdit, BaseT> { enum { class_id = EDIT }; SkinEdit() { m_nPart = EP_EDITTEXT; } typedef SkinEdit<BaseT> this_type; typedef SkinControlImpl<SkinEdit, BaseT> base_type; BEGIN_MSG_MAP(this_type) MESSAGE_HANDLER(WM_NCPAINT, OnNcPaint) MSG_WM_CREATE(OnCreate) END_MSG_MAP() BOOL OnCreate(LPCREATESTRUCT) { m_nPart = EP_EDITTEXT; TCHAR className[256]; GetClassName(GetParent(), className, sizeof(className)); if(lstrcmpi(className, "COMBOBOX") != 0) { //Fix Combobox bug InstallScrollBar(); } SetMsgHandled(FALSE); return TRUE; } LRESULT OnNcPaint(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { LONG lExStyle; lExStyle = GetExStyle(); if (( GetStyle() & WS_BORDER) || (lExStyle & WS_EX_CLIENTEDGE) || (lExStyle & WS_EX_STATICEDGE)) { CRect rcw; GetWindowRect(&rcw); rcw.right -= rcw.left; rcw.bottom -= rcw.top; rcw.top = rcw.left = 0; HDC hdc = GetWindowDC( ); // »æÖÆÍâ¿ò CBrush brBorder; int nState = GetState(); COLORREF cr; _scheme->GetColor(class_id, m_nPart, nState, TMT_BORDERCOLOR, &cr); brBorder.CreateSolidBrush( cr ); FrameRect(hdc, CRect(0, 0, rcw.Width(), rcw.Height()), (HBRUSH)brBorder); brBorder.DeleteObject(); // »æÖÆÄÚ¿ò if ((lExStyle & WS_EX_CLIENTEDGE) || (lExStyle & WS_EX_STATICEDGE)) { InflateRect(&rcw, -1, -1); LONG lStyle = GetStyle(); CBrush brBorder; _scheme->GetColor(class_id, m_nPart, nState, TMT_TEXTBORDERCOLOR, &cr); brBorder.CreateSolidBrush( cr ); FrameRect(hdc, &rcw, (HBRUSH) brBorder); //if ((lExStyle & WS_EX_CLIENTEDGE) && (lExStyle & WS_EX_STATICEDGE)) { InflateRect(&rcw, -1, -1); FrameRect(hdc, &rcw, (HBRUSH)brBorder); } brBorder.DeleteObject(); } ReleaseDC( hdc ); } else { LRESULT lRet = DefWindowProc(); return lRet; } return 0; } int GetState() { return ETS_NORMAL; } private: int m_nPart; }; }; // namespace
[ "ken.shao@ba8f1dc9-3c1c-0410-9eed-0f8a660c14bd" ]
[ [ [ 1, 99 ] ] ]
fb75ded6025ff447c16d330805368a808501ff13
74e7667ad65cbdaa869c6e384fdd8dc7e94aca34
/MicroFrameworkPK_v4_1/BuildOutput/public/Release/Client/stubs/corlib_native_System_Delegate.cpp
6f217cae4b5f2a4cd7785201314607b27c97d07d
[ "BSD-3-Clause", "OpenSSL", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
gezidan/NETMF-LPC
5093ab223eb9d7f42396344ea316cbe50a2f784b
db1880a03108db6c7f611e6de6dbc45ce9b9adce
refs/heads/master
2021-01-18T10:59:42.467549
2011-06-28T08:11:24
2011-06-28T08:11:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,644
cpp
//----------------------------------------------------------------------------- // // ** WARNING! ** // This file was generated automatically by a tool. // Re-running the tool will overwrite this file. // You should copy this file to a custom location // before adding any customization in the copy to // prevent loss of your changes when the tool is // re-run. // //----------------------------------------------------------------------------- #include "corlib_native.h" #include "corlib_native_System_Delegate.h" using namespace System; INT8 Delegate::Equals( CLR_RT_HeapBlock* pMngObj, UNSUPPORTED_TYPE param0, HRESULT &hr ) { INT8 retVal = 0; return retVal; } UNSUPPORTED_TYPE Delegate::get_Method( CLR_RT_HeapBlock* pMngObj, HRESULT &hr ) { UNSUPPORTED_TYPE retVal = 0; return retVal; } UNSUPPORTED_TYPE Delegate::get_Target( CLR_RT_HeapBlock* pMngObj, HRESULT &hr ) { UNSUPPORTED_TYPE retVal = 0; return retVal; } UNSUPPORTED_TYPE Delegate::Combine( UNSUPPORTED_TYPE param0, UNSUPPORTED_TYPE param1, HRESULT &hr ) { UNSUPPORTED_TYPE retVal = 0; return retVal; } UNSUPPORTED_TYPE Delegate::Remove( UNSUPPORTED_TYPE param0, UNSUPPORTED_TYPE param1, HRESULT &hr ) { UNSUPPORTED_TYPE retVal = 0; return retVal; } INT8 Delegate::op_Equality( UNSUPPORTED_TYPE param0, UNSUPPORTED_TYPE param1, HRESULT &hr ) { INT8 retVal = 0; return retVal; } INT8 Delegate::op_Inequality( UNSUPPORTED_TYPE param0, UNSUPPORTED_TYPE param1, HRESULT &hr ) { INT8 retVal = 0; return retVal; }
[ [ [ 1, 60 ] ] ]
c88228e914de2d8ebc060742501b99cd60c58182
05f4bd87bd001ab38701ff8a71d91b198ef1cb72
/TPTaller/TP3/src/Textura.h
75a39ceb94628cffa7fdd8219345eb6a460ed8fd
[]
no_license
oscarcp777/tpfontela
ef6828a57a0bc52dd7313cde8e55c3fd9ff78a12
2489442b81dab052cf87b6dedd33cbb51c2a0a04
refs/heads/master
2016-09-01T18:40:21.893393
2011-12-03T04:26:33
2011-12-03T04:26:33
35,110,434
0
0
null
null
null
null
UTF-8
C++
false
false
278
h
#ifndef _TEXTURA_H_ #define _TEXTURA_H_ #include <iostream> class Textura { public: Textura(std::string id, std::string path); ~Textura(); std::string getId(); std::string getPath(); private: std::string id; std::string path; }; #endif
[ "rdubini@a1477896-89e5-11dd-84d8-5ff37064ad4b" ]
[ [ [ 1, 21 ] ] ]
f7fda2d4239afb4d94e4753bd3d40edd8e209f91
ad80c85f09a98b1bfc47191c0e99f3d4559b10d4
/code/src/node/nshaderprogramnode_main.cc
b26ba80b26a41c66757b3f6617f7605eb2b63644
[]
no_license
DSPNerd/m-nebula
76a4578f5504f6902e054ddd365b42672024de6d
52a32902773c10cf1c6bc3dabefd2fd1587d83b3
refs/heads/master
2021-12-07T18:23:07.272880
2009-07-07T09:47:09
2009-07-07T09:47:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,961
cc
#define N_IMPLEMENTS nShaderProgramNode //------------------------------------------------------------------------------ // (C) 2006 Ilya Kliot //------------------------------------------------------------------------------ #ifndef N_SL_PROGRAM #include "node/nshaderprogramnode.h" #endif #ifndef N_VECTOR_H #include "mathlib/vector.h" #endif #ifndef N_MATRIX_H #include "mathlib/matrix.h" #endif #ifndef N_PIXELSHADER_H #include "gfx/npixelshader.h" #endif nNebulaScriptClass(nShaderProgramNode, "nshadernode"); nShaderProgramNode::nShaderProgramNode() : nShaderNode(), initialized(false) { this->vertexFilename.clear(); this->fragmentFilename.clear(); } nShaderProgramNode::~nShaderProgramNode () { } void nShaderProgramNode::Update() { nPixelShader* ps = this->GetPixelShader(); if (!ps->GetActiveProgram()) return; if (!this->initialized && (this->fragmentFilename.size() || this->vertexFilename.size())) { this->initialized = ps->LoadShaders(this->vertexFilename.c_str(), this->fragmentFilename.c_str()); } if (this->initialized) { ps->Bind(); int* i = 0; float* f = 0; // color4* c4 = 0; vector4* v4 = 0; vector3* v3 = 0; vector2* v2 = 0; matrix44* m4 = 0; matrix33* m3 = 0; this->UpdateList(ps, i); this->UpdateList(ps, f); // this->UpdateList(ps, c4); this->UpdateList(ps, v4); this->UpdateList(ps, v3); this->UpdateList(ps, v2); this->UpdateList(ps, m4); this->UpdateList(ps, m3); if (!this->GetAttribVector4List()->empty()) { tNamedParamList<vector4>* il = this->GetAttribVector4List(); for (tNamedParamList<vector4>::iterator i = il->begin(); i != il->end(); i++) { if (i->second.desc == -1) i->second.desc = ps->GetIndexForAttrName(i->first.c_str()); if (i->second.desc >= 0) ps->SetAttribute(i->second.desc, i->second.param); } } ps->Unbind(); } } void nShaderProgramNode::Compute(nSceneGraph2* sceneGraph) { this->Update(); nShaderNode::Compute(sceneGraph); } /// set int named param void nShaderProgramNode::SetTexture( const char* name, int texUnit) { this->texUnits[name] = texUnit; } /// get texture unit named param int nShaderProgramNode::GetTexture( const char* name, long& err) { const tSLParam<int>* p = this->texUnits.find_by_name(name); err = 0; if (p) return p->param; else { err = UNDEFINED_PARAM; return 0; } } // attribute variables handling methods /// set vector4 attribute void nShaderProgramNode::SetAttribute( const char* name, const vector4& value ) { this->attribVector4[name] = value; } /// get vector4 attribute vector4 nShaderProgramNode::GetAttribute( const char* name, long& err ) { const tSLParam<vector4>* p = this->attribVector4.find_by_name(name); err = 0; if (p) return p->param; else { err = UNDEFINED_PARAM; return vector4(); } }
[ "plushe@411252de-2431-11de-b186-ef1da62b6547" ]
[ [ [ 1, 118 ] ] ]
55bbb34a5de95cf585674c7b5ddb2a39fe7addba
ab41c2c63e554350ca5b93e41d7321ca127d8d3a
/glm/gtx/vector_query.inl
507b7a8d371c2c6b0840153f805e38991ffb0f13
[]
no_license
burner/e3rt
2dc3bac2b7face3b1606ee1430e7ecfd4523bf2e
775470cc9b912a8c1199dd1069d7e7d4fc997a52
refs/heads/master
2021-01-11T08:08:00.665300
2010-04-26T11:42:42
2010-04-26T11:42:42
337,021
3
0
null
null
null
null
UTF-8
C++
false
false
3,825
inl
/////////////////////////////////////////////////////////////////////////////////////////////////// // OpenGL Mathematics Copyright (c) 2005 - 2009 G-Truc Creation (www.g-truc.net) /////////////////////////////////////////////////////////////////////////////////////////////////// // Created : 2007-03-05 // Updated : 2007-03-05 // Licence : This source is under MIT License // File : glm/gtx/vector_query.inl /////////////////////////////////////////////////////////////////////////////////////////////////// // Dependency: // - GLM core /////////////////////////////////////////////////////////////////////////////////////////////////// #include <cassert> namespace glm{ namespace gtx{ namespace vector_query { template <typename T> inline bool areCollinear( const detail::tvec2<T>& v0, const detail::tvec2<T>& v1, const T epsilon) { return length(cross(detail::tvec3<T>(v0, T(0)), detail::tvec3<T>(v1, T(0)))) < epsilon; } template <typename T> inline bool areCollinear( const detail::tvec3<T>& v0, const detail::tvec3<T>& v1, const T epsilon) { return length(cross(v0, v1)) < epsilon; } template <typename T> inline bool areCollinear( const detail::tvec4<T>& v0, const detail::tvec4<T>& v1, const T epsilon) { return length(cross(detail::tvec3<T>(v0), detail::tvec3<T>(v1))) < epsilon; } template <typename genType> inline bool areOpposite( const genType& v0, const genType& v1, const GLMvalType epsilon) { assert(isNormalized(v0) && isNormalized(v1)); return((genType::value_type(1) + dot(v0, v1)) <= epsilon); } template <typename genType> inline bool areOrthogonal( const genType& v0, const genType& v1, const GLMvalType epsilon) { return abs(dot(v0, v1)) <= max(GLMvalType(1), length(v0)) * max(GLMvalType(1), length(v1)) * epsilon; } template <typename genType> inline bool isNormalized( const genType& v, const GLMvalType epsilon) { return abs(length(v) - GLMvalType(1)) <= GLMvalType(2) * epsilon; } template <typename genType> inline bool isNull(const genType& v, const GLMvalType epsilon) { return length(v) <= epsilon; } template <typename T> inline bool isCompNull( const T s, const T epsilon) { return abs(s) < epsilon; } template <typename T> inline detail::tvec2<bool> isCompNull( const detail::tvec2<T>& v, const T epsilon) { return detail::tvec2<bool>( (abs(v.x) < epsilon), (abs(v.y) < epsilon)); } template <typename T> inline detail::tvec3<bool> isCompNull( const detail::tvec3<T>& v, const T epsilon) { return detail::tvec3<bool>( abs(v.x) < epsilon, abs(v.y) < epsilon, abs(v.z) < epsilon); } template <typename T> inline detail::tvec4<bool> isCompNull( const detail::tvec4<T>& v, const T epsilon) { return detail::tvec4<bool>( abs(v.x) < epsilon, abs(v.y) < epsilon, abs(v.z) < epsilon, abs(v.w) < epsilon); } template <typename genType> inline bool areOrthonormal( const genType& v0, const genType& v1, const GLMvalType epsilon) { return isNormalized(v0, epsilon) && isNormalized(v1, epsilon) && (abs(dot(v0, v1)) <= epsilon); } template <typename genType> inline bool areSimilar( const genType& v0, const genType& v1, const GLMvalType epsilon) { bool similar = true; for(typename genType::size_type i = 0; similar && i < genType::value_size(); i++) similar = (abs(v0[i] - v1[i]) <= epsilon); return similar; } }//namespace vector_query }//namespace gtx }//namespace glm
[ [ [ 1, 143 ] ] ]
6ae7b12d5136bf9da66e5d9330c890c1be8906b1
dd5c8920aa0ea96607f2498701c81bb1af2b3c96
/stlplus/source/persistent.tpp
7aba145596d25839ba27e7b0723a4c792f67b78f
[]
no_license
BackupTheBerlios/multicrew-svn
913279401e9cf886476a3c912ecd3d2b8d28344c
5087f07a100f82c37d2b85134ccc9125342c58d1
refs/heads/master
2021-01-23T13:36:03.990862
2005-06-10T16:52:32
2005-06-10T16:52:32
40,747,367
0
0
null
null
null
null
UTF-8
C++
false
false
19,552
tpp
/*------------------------------------------------------------------------------ Author: Andy Rushton Copyright: (c) Andy Rushton, 2004 License: BSD License, see ../docs/license.html ------------------------------------------------------------------------------*/ #include "stringio.hpp" #include "fileio.hpp" //////////////////////////////////////////////////////////////////////////////// // enumeration types template<typename T> void dump_enum(dump_context& context, const T& data) throw(persistent_dump_failed) { dump(context, (unsigned)data); } template<typename T> void restore_enum(restore_context& context, T& data) throw(persistent_restore_failed) { unsigned value = 0; restore(context, value); data = (T)value; } //////////////////////////////////////////////////////////////////////////////// // STL strings template<typename charT, typename traits, typename allocator> void dump_basic_string(dump_context& context, const std::basic_string<charT,traits,allocator>& data) throw(persistent_dump_failed) { dump(context, data.size()); for (size_t i = 0; i < data.size(); i++) dump(context,data[i]); } template<typename charT, typename traits, typename allocator> void restore_basic_string(restore_context& context, std::basic_string<charT,traits,allocator>& data) throw(persistent_restore_failed) { data.erase(); size_t size = 0; restore(context, size); for (size_t i = 0; i < size; i++) { charT ch; restore(context,ch); data += ch; } } //////////////////////////////////////////////////////////////////////////////// // Pointers // format: magic_key [ data ] template<typename T> void dump_pointer(dump_context& context, const T* const data) throw(persistent_dump_failed) { // register the address and get the magic key for it std::pair<bool,unsigned> mapping = context.pointer_map(data); dump(context,mapping.second); // if the address is null, then that is all that we need to do // however, if it is non-null and this is the first sight of the address, dump the contents if (data && !mapping.first) dump(context,*data); } template<typename T> void restore_pointer(restore_context& context, T*& data) throw(persistent_restore_failed) { if (data) { delete data; data = 0; } // get the magic key unsigned magic = 0; restore(context,magic); // now lookup the magic key to see if this pointer has already been restored // null pointers are always flagged as already restored std::pair<bool,void*> address = context.pointer_map(magic); if (address.first) { // seen before, so simply assign the old address data = (T*)address.second; } else { // this pointer has never been seen before and is non-null data = new T(); restore(context,*data); // add this pointer to the set of already seen objects context.pointer_add(magic,data); } } //////////////////////////////////////////////////////////////////////////////// // Cross-reference pointers // format: magic_key [ data ] template<typename T> void dump_xref(dump_context& context, const T* const data) throw(persistent_dump_failed) { // register the address and get the magic key for it std::pair<bool,unsigned> mapping = context.pointer_map(data); // if this is the first view of this pointer, simply throw an exception if (!mapping.first) throw persistent_dump_failed("tried to dump a cross-reference not seen before"); // otherwise, just dump the magic key dump(context,mapping.second); } template<typename T> void restore_xref(restore_context& context, T*& data) throw(persistent_restore_failed) { // Note: I do not try to delete the old data because this is a cross-reference // get the magic key unsigned magic = 0; restore(context,magic); // now lookup the magic key to see if this pointer has already been restored // null pointers are always flagged as already restored std::pair<bool,void*> address = context.pointer_map(magic); // if this is the first view of this pointer, simply throw an exception if (!address.first) throw persistent_restore_failed("tried to restore a cross-reference not seen before"); // seen before, so simply assign the old address data = (T*)address.second; } //////////////////////////////////////////////////////////////////////////////// // Polymorphous classes using the callback approach // format: address [ key data ] template<typename T> void dump_polymorph(dump_context& context, const T* data) throw(persistent_dump_failed) { try { // register the address and get the magic key for it std::pair<bool,unsigned> mapping = context.pointer_map(data); dump(context,mapping.second); // if the address is null, then that is all that we need to do // however, if it is non-null and this is the first sight of the address, dump the contents if (data && !mapping.first) { // callback method - get the callback data and perform the dump // this will throw persistent_illegal_type if not recognised, thus the try block dump_context::callback_data callback = context.lookup_type(typeid(*data)); // dump the magic key for the type dump(context, callback.first); // now call the callback that dumps the subclass callback.second(context,data); } } catch (const persistent_illegal_type& except) { // convert this to a simpler dump failed exception throw persistent_dump_failed(except.what()); } } template<typename T> void restore_polymorph(restore_context& context, T*& data) throw(persistent_restore_failed) { try { // first delete any previous object pointed to since the restore creates the object of the right subclass if (data) { delete data; data = 0; } // get the magic key unsigned magic = 0; restore(context,magic); // now lookup the magic key to see if this pointer has already been restored // null pointers are always flagged as already restored std::pair<bool,void*> address = context.pointer_map(magic); if (address.first) { // seen before, so simply map it to the existing address data = (T*)address.second; } else { // now restore the magic key that denotes the particular subclass unsigned short key = 0; restore(context, key); // callback approach // call the create callback to create an object of the right type // then call the restore callback to get the contents // this will throw persistent_illegal_type if not recognised - this is caught below restore_context::callback_data callbacks = context.lookup_type(key); void* void_data = callbacks.first(); data = (T*)void_data; try { callbacks.second(context,void_data); } catch(...) { // tidy up any memory allocated in this function if (data) { delete data; data = 0; } throw; } // add this pointer to the set of already seen objects context.pointer_add(magic,data); } } catch (const persistent_illegal_type& exception) { // convert this to a simpler dump failed exception throw persistent_restore_failed(exception.what()); } } //////////////////////////////////////////////////////////////////////////////// // Polymorphous classes using the interface approach // format: address [ key data ] template<typename T> void dump_interface(dump_context& context, const T* data) throw(persistent_dump_failed) { try { // register the address and get the magic key for it std::pair<bool,unsigned> mapping = context.pointer_map(data); dump(context,mapping.second); // if the address is null, then that is all that we need to do // however, if it is non-null and this is the first sight of the address, dump the contents if (data && !mapping.first) { // interface method // the lookup just finds the magic key and the type has a dump method // this will throw persistent_illegal_type if the type is not registered dump_context::interface_data key = context.lookup_interface(typeid(*data)); // dump the magic key for the type dump(context, key); // now call the dump method defined by the interface data->dump(context); } } catch (const persistent_illegal_type& exception) { // convert this to a simpler dump failed exception throw persistent_dump_failed(exception.what()); } } template<typename T> void restore_interface(restore_context& context, T*& data) throw(persistent_restore_failed) { try { // first delete any previous object pointed to since the restore creates the object of the right subclass if (data) { delete data; data = 0; } // get the magic key unsigned magic = 0; restore(context,magic); // now lookup the magic key to see if this pointer has already been restored // null pointers are always flagged as already restored std::pair<bool,void*> address = context.pointer_map(magic); if (address.first) { // seen this address before, so simply assign it data = (T*)address.second; } else { // now restore the magic key that denotes the particular subclass unsigned short key = 0; restore(context, key); // interface approach // first clone the sample object stored in the map - lookup_interface can throw persistent_illegal_type data = (T*)(context.lookup_interface(key)->clone()); // now restore the contents using the object's method try { data->restore(context); } catch(...) { if (data) { delete data; data = 0; } throw; } // add this pointer to the set of already seen objects context.pointer_add(magic,data); } } catch (const persistent_illegal_type& exception) { // convert this to a simpler dump failed exception throw persistent_restore_failed(exception.what()); } } //////////////////////////////////////////////////////////////////////////////// // format: data msB first, packed into bytes with lowest index at the byte's lsb // Note: the interface does not provide access to the internal storage and yet // to be efficient the std::bitset must be packed as bytes. Thus I have to do it the // hard way. template<size_t N> void dump_bitset(dump_context& context, const std::bitset<N>& data) throw(persistent_dump_failed) { size_t bits = data.size(); size_t bytes = (bits+7)/8; for (size_t B = bytes; B--; ) { unsigned char ch = 0; for (size_t b = 0; b < 8; b++) { size_t bit = B*8+b; if (bit < bits && data[bit]) ch |= (0x01 << b); } dump(context,ch); } } template<size_t N> void restore_bitset(restore_context& context, std::bitset<N>& data) throw(persistent_restore_failed) { size_t bits = data.size(); size_t bytes = (bits+7)/8; for (size_t B = bytes; B--; ) { unsigned char ch = 0; restore(context,ch); for (size_t b = 0; b < 8; b++) { size_t bit = B*8+b; if (bit >= bits) break; data.set(bit, ch & (0x01 << b) ? true : false); } } } //////////////////////////////////////////////////////////////////////////////// // complex template<typename T> void dump_complex(dump_context& context, const std::complex<T>& data) throw(persistent_dump_failed) { dump(context,data.real()); dump(context,data.imag()); } template<typename T> void restore_complex(restore_context& context, std::complex<T>& data) throw(persistent_restore_failed) { T re, im; restore(context,re); restore(context,im); data = std::complex<T>(re, im); } //////////////////////////////////////////////////////////////////////////////// // deque template<typename T> void dump_deque(dump_context& context, const std::deque<T>& data) throw(persistent_dump_failed) { dump(context,data.size()); for (typename std::deque<T>::const_iterator i = data.begin(); i != data.end(); i++) dump(context,*i); } template<typename T> void restore_deque(restore_context& context, std::deque<T>& data) throw(persistent_restore_failed) { data.clear(); size_t size = 0; restore(context,size); for (size_t i = 0; i < size; i++) { data.push_back(T()); restore(context,data.back()); } } //////////////////////////////////////////////////////////////////////////////// // list template<typename T> void dump_list(dump_context& context, const std::list<T>& data) throw(persistent_dump_failed) { dump(context,data.size()); for (typename std::list<T>::const_iterator i = data.begin(); i != data.end(); i++) dump(context,*i); } template<typename T> void restore_list(restore_context& context, std::list<T>& data) throw(persistent_restore_failed) { data.clear(); size_t size = 0; restore(context,size); for (size_t i = 0; i < size; i++) { data.push_back(T()); restore(context,data.back()); } } //////////////////////////////////////////////////////////////////////////////// // pair template<typename K, typename T> void dump_pair(dump_context& context, const std::pair<K,T>& data) throw(persistent_dump_failed) { dump(context,data.first); dump(context,data.second); } template<typename K, typename T> void restore_pair(restore_context& context, std::pair<K,T>& data) throw(persistent_restore_failed) { restore(context,data.first); restore(context,data.second); } //////////////////////////////////////////////////////////////////////////////// // Map template<typename K, typename T, typename P> void dump_map(dump_context& context, const std::map<K,T,P>& data) throw(persistent_dump_failed) { dump(context,data.size()); for (typename std::map<K,T,P>::const_iterator i = data.begin(); i != data.end(); i++) { dump(context,i->first); dump(context,i->second); } } template<typename K, typename T, typename P> void restore_map(restore_context& context, std::map<K,T,P>& data) throw(persistent_restore_failed) { data.clear(); size_t size = 0; restore(context,size); for (size_t j = 0; j < size; j++) { K key; restore(context,key); restore(context,data[key]); } } //////////////////////////////////////////////////////////////////////////////// // Multimap template<typename K, typename T, typename P> void dump_multimap(dump_context& context, const std::multimap<K,T,P>& data) throw(persistent_dump_failed) { dump(context,data.size()); for (typename std::multimap<K,T,P>::const_iterator i = data.begin(); i != data.end(); i++) { dump(context,i->first); dump(context,i->second); } } template<typename K, typename T, typename P> void restore_multimap(restore_context& context, std::multimap<K,T,P>& data) throw(persistent_restore_failed) { data.clear(); size_t size = 0; restore(context,size); for (size_t j = 0; j < size; j++) { K key; restore(context,key); typename std::multimap<K,T,P>::iterator v = data.insert(std::pair<K,T>(key,T())); restore(context,v->second); } } //////////////////////////////////////////////////////////////////////////////// // Set template<typename K, typename P> void dump_set(dump_context& context, const std::set<K,P>& data) throw(persistent_dump_failed) { dump(context,data.size()); for (typename std::set<K,P>::const_iterator i = data.begin(); i != data.end(); i++) dump(context,*i); } template<typename K, typename P> void restore_set(restore_context& context, std::set<K,P>& data) throw(persistent_restore_failed) { data.clear(); size_t size = 0; restore(context,size); typename std::set<K,P>::iterator i = data.begin(); for (size_t j = 0; j < size; j++) { K key; restore(context,key); // inserting using an iterator is O(n) rather than O(n*log(n)) data.insert(i, key); } } //////////////////////////////////////////////////////////////////////////////// // Multiset // Shame that a multiset is not just a derivative of set since it has the same interface template<typename K, typename P> void dump_multiset(dump_context& context, const std::multiset<K,P>& data) throw(persistent_dump_failed) { dump(context,data.size()); for (typename std::multiset<K,P>::const_iterator i = data.begin(); i != data.end(); i++) dump(context,*i); } template<typename K, typename P> void restore_multiset(restore_context& context, std::multiset<K,P>& data) throw(persistent_restore_failed) { data.clear(); size_t size = 0; restore(context,size); typename std::multiset<K,P>::iterator i = data.begin(); for (size_t j = 0; j < size; j++) { K key; restore(context,key); // inserting using an iterator is O(n) rather than O(n*log(n)) data.insert(i, key); } } //////////////////////////////////////////////////////////////////////////////// //vector template<typename T> void dump_vector(dump_context& context, const std::vector<T>& data) throw(persistent_dump_failed) { dump(context,data.size()); for (size_t i = 0; i < data.size(); i++) dump(context,data[i]); } template<typename T> void restore_vector(restore_context& context, std::vector<T>& data) throw(persistent_restore_failed) { size_t size = 0; restore(context,size); data.resize(size); for (size_t i = 0; i < size; i++) restore(context,data[i]); } //////////////////////////////////////////////////////////////////////////////// template<typename T> void dump_to_device(const T& source, otext& result, dump_context::installer installer) throw(persistent_dump_failed) { dump_context context(result); context.register_all(installer); dump(context, source); } template<typename T> void restore_from_device(itext& source, T& result, restore_context::installer installer) throw(persistent_restore_failed) { restore_context context(source); context.register_all(installer); restore(context, result); } template<typename T> void dump_to_string(const T& source, std::string& result, dump_context::installer installer) throw(persistent_dump_failed) { ostext output; dump_to_device(source, output, installer); result = output.get_string(); } template<typename T> void restore_from_string(const std::string& source, T& result, restore_context::installer installer) throw(persistent_restore_failed) { istext input(source); restore_from_device(input, result, installer); } template<typename T> void dump_to_file(const T& source, const std::string& filename, dump_context::installer installer) throw(persistent_dump_failed) { oftext output(filename); dump_to_device(source, output, installer); } template<typename T> void restore_from_file(const std::string& filename, T& result, restore_context::installer installer) throw(persistent_restore_failed) { iftext input(filename); restore_from_device(input, result, installer); } ////////////////////////////////////////////////////////////////////////////////
[ "schimmi@cb9ff89a-abed-0310-8fc6-a4cabe7d48c9" ]
[ [ [ 1, 621 ] ] ]
5ab5ef259542e9e0f13b4bed92429f1b281c9601
f8c850e4068e1c2684f082ed81541a0b175cb807
/Bradshaw_Tuition/Bradshaw_Tuition/Bradshaw_Tuition_calc.cpp
66fd8909dc8343f336c21a990f56198dfcfbf5c7
[]
no_license
dabrad26/programming-class-cpp
677738e9154de3bd103e41269a21dea21901b5d0
b1b23a187755400abeb9caebdf0ea0636cd2491b
refs/heads/main
2023-02-09T23:00:34.490541
2009-08-20T19:19:19
2009-08-20T19:19:19
327,986,006
0
0
null
null
null
null
UTF-8
C++
false
false
392
cpp
#include <iostream> using namespace std; int main() { double newTuition; double const IncreaseValue = 1.05; newTuition = 10000; cout << "Current tuition is: $" << newTuition << endl; for(int year = 1; year <= 10; year++) { newTuition = (newTuition * IncreaseValue); } cout << "Tuition ten years from now is $" << newTuition << endl; return 0; }
[ [ [ 1, 24 ] ] ]
a4d2df43f445b2e17827a0f18f562e9b10a01cc9
c1a2953285f2a6ac7d903059b7ea6480a7e2228e
/deitel/ch21/Fig21_37/fig22_37.cpp
8a0686befdaaf5d1b3946a1eff40689c86c3b6d0
[]
no_license
tecmilenio/computacion2
728ac47299c1a4066b6140cebc9668bf1121053a
a1387e0f7f11c767574fcba608d94e5d61b7f36c
refs/heads/master
2016-09-06T19:17:29.842053
2008-09-28T04:27:56
2008-09-28T04:27:56
50,540
4
3
null
null
null
null
UTF-8
C++
false
false
1,522
cpp
// Fig. 21.37: fig21_37.cpp // Using memmove. #include <iostream> using std::cout; using std::endl; #include <cstring> // memmove prototype using std::memmove; int main() { char x[] = "Home Sweet Home"; cout << "The string in array x before memmove is: " << x; cout << "\nThe string in array x after memmove is: " << static_cast< char * >( memmove( x, &x[ 5 ], 10 ) ) << endl; return 0; } // end main /************************************************************************** * (C) Copyright 1992-2008 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * **************************************************************************/
[ [ [ 1, 33 ] ] ]
6d11457b0025145bcbd7dd0e5808fdce90d12de5
dab945db8541c30011771caf8ddb63ec8c683618
/templates/DllProject/Projectname2.h
5625231beb6ef0254c2b1c00043ab22778d48090
[]
no_license
romanm11/bada-SDK-1.0.0-com.osp.ide
feb25cd9727e5f746cf618c752f933ca4a4ab61c
cd051d031310457a90eb558212b6c93b62b4dbf0
refs/heads/master
2020-04-06T04:20:24.837952
2010-10-27T18:46:27
2010-10-27T18:46:27
1,132,307
0
0
null
null
null
null
UTF-8
C++
false
false
508
h
#ifndef _$(baseName_upper)_H_ #define _$(baseName_upper)_H_ /** * This header file is included to define _EXPORT_. */ #include <FBase.h> #ifdef __cplusplus extern "C" { #endif // __cplusplus // This class is exported from Projectname.so class _EXPORT_ Ospc$(baseName) { public: Ospc$(baseName)(void); // TODO: Add your methods here }; // This method is exported from Projectname.so _EXPORT_ int Ospf$(baseName)(void); #ifdef __cplusplus } #endif // __cplusplus #endif
[ "rom@garay.(none)" ]
[ [ [ 1, 29 ] ] ]
c8ec2c20d4ec27e80b89a83ebe663a13e0198d30
24bc1634133f5899f7db33e5d9692ba70940b122
/src/ammo/game/application.cpp
ba62d6485625198149e1d2556d6c6c1354514abe
[]
no_license
deft-code/ammo
9a9cd9bd5fb75ac1b077ad748617613959dbb7c9
fe4139187dd1d371515a2d171996f81097652e99
refs/heads/master
2016-09-05T08:48:51.786465
2009-10-09T05:49:00
2009-10-09T05:49:00
32,252,326
0
0
null
null
null
null
UTF-8
C++
false
false
8,779
cpp
#include "ammo/game/application.hpp" #include "ammo/util/profiler.hpp" #include <CEGUI.h> using CEGUI::UDim; using CEGUI::UVector2; namespace ammo { /// Construct the application Application::Application() : _client(NULL), _server(NULL), _isDone(false) { } /// Load all the applications resources bool Application::Initialize() { // Initialize our renderwindow _window.Create(sf::VideoMode(800,600), "ammo"); // Hide the mouse cursor, let CEGUI handle it _window.ShowMouseCursor(false); // Initialize the GUI Manager if (!_guiMan.Initialize(&_window)) return false; // Create our window with Join/Host/Dedicated Server options CEGUI::WindowManager* winMgr = _guiMan.getWindowManager(); CEGUI::Window* layout = winMgr->loadWindowLayout("data/gui/ammo.layout"); layout->getChild("root/winserver")->setVisible(false); layout->getChild("root/winjoin")->setVisible(false); //CEGUI::Window* rootWin = winMgr->createWindow("DefaultWindow", "root"); // //CEGUI::Window* mainWin = winMgr->createWindow("WindowsLook/FrameWindow", "mainWin"); //mainWin->setMinSize(UVector2(UDim(0.0f, 200),UDim(0.0f, 150))); //mainWin->setSize(UVector2(UDim(0.0f, 400),UDim(0.0f, 300))); //mainWin->setPosition(UVector2(UDim(0.25f, 0), UDim(0.1f, 0))); //mainWin->setText("Welcome to Ammo"); //mainWin->setProperty("TitlebarEnabled", "False"); //mainWin->setProperty("CloseButtonEnabled", "False"); //mainWin->setProperty("SizingEnabled", "False"); //CEGUI::Window* btnJoin = winMgr->createWindow("WindowsLook/Button", "btnJoin"); //btnJoin->setMinSize(UVector2(UDim(0.0f, 100), UDim(0.0f, 20))); //btnJoin->setSize(UVector2(UDim(0.5f, 0), UDim(0.1f, 0))); //btnJoin->setPosition(UVector2(UDim(0.25f, 0), UDim(0.4f, 0))); //btnJoin->setText("Join Game"); //CEGUI::Window* btnHost = winMgr->createWindow("WindowsLook/Button", "btnHost"); //btnHost->setMinSize(UVector2(UDim(0.0f, 100), UDim(0.0f, 20))); //btnHost->setSize(UVector2(UDim(0.5f, 0), UDim(0.1f, 0))); //btnHost->setPosition(UVector2(UDim(0.25f, 0), UDim(0.5f, 0))); //btnHost->setText("Host Game"); // //mainWin->addChildWindow(btnJoin); //mainWin->addChildWindow(btnHost); //// Create our hidden windows for creating a server and joining a server //CEGUI::Window* servWin = winMgr->createWindow("WindowsLook/FrameWindow", "winMakeServer"); ////servWin->setModalState(true); //servWin->setMinSize(UVector2(UDim(0.0f, 200),UDim(0.0f, 150))); //servWin->setSize(UVector2(UDim(0.0f, 200),UDim(0.0f, 200))); //servWin->setPosition(UVector2(UDim(0.5f, 0), UDim(0.5f, 0))); //servWin->setText("Welcome to Ammo"); //servWin->setProperty("TitlebarEnabled", "False"); //servWin->setProperty("CloseButtonEnabled", "False"); //servWin->setProperty("SizingEnabled", "False"); //servWin->hide(); // //CEGUI::Window* lblPort = winMgr->createWindow("WindowsLook/StaticText","lblServPort"); //lblPort->setText("Port: (1025-65535)"); //servWin->addChildWindow(lblPort); //rootWin->addChildWindow(mainWin); //rootWin->addChildWindow(servWin); //mainWin->activate(); winMgr->getWindow("root/main/btnhost")->subscribeEvent(CEGUI::Window::EventMouseClick, CEGUI::Event::Subscriber(&Application::OnHostClick, this)); winMgr->getWindow("root/main/btnjoin")->subscribeEvent(CEGUI::Window::EventMouseClick, CEGUI::Event::Subscriber(&Application::OnJoinClick, this)); winMgr->getWindow("root/winserver/btncancel")->subscribeEvent(CEGUI::Window::EventMouseClick, CEGUI::Event::Subscriber(&Application::OnServCancelClick, this)); winMgr->getWindow("root/winjoin/btncancel")->subscribeEvent(CEGUI::Window::EventMouseClick, CEGUI::Event::Subscriber(&Application::OnJoinCancelClick, this)); winMgr->getWindow("root/winserver/btnhost")->subscribeEvent(CEGUI::Window::EventMouseClick, CEGUI::Event::Subscriber(&Application::OnServStartClick, this)); winMgr->getWindow("root/winjoin/btnjoin")->subscribeEvent(CEGUI::Window::EventMouseClick, CEGUI::Event::Subscriber(&Application::OnJoinStartClick, this)); _guiMan.setRootWindow(layout); return true; } /// Launch the application void Application::Run() { sf::Clock clock; sf::Event myEvent; float dt = 0; // TODO: // Allow us to create a server, and be able to quit gracefully while (!_isDone) { dt = clock.GetElapsedTime(); PROFILE_NEXT_FRAME(dt); clock.Reset(); _window.Clear(); while (_window.GetEvent(myEvent)) { //See if CEGUI should handle it if (_guiMan.HandleEvent(myEvent)) continue; switch (myEvent.Type) { case sf::Event::Closed: _window.Close(); _isDone = true; break; case sf::Event::KeyPressed: if (myEvent.Key.Code == sf::Key::Escape) //Stop(); break; default: break;//ignore } } if (_client && !_isDone) { PROFILE_TIMER(client) _client->Draw(dt); _client->Update(dt); } if (_server && !_isDone) { PROFILE_TIMER(server) _server->Update(dt); } _guiMan.Draw(); _window.Display(); } if (_client) { delete _client; } if (_server) { dt = clock.GetElapsedTime(); _server->Update(dt); delete _server; } } bool Application::OnHostClick(const CEGUI::EventArgs &e) { std::cout << "Host clicked." << std::endl; CEGUI::Window* servWin = _guiMan.getWindowManager()->getWindow("root/winserver"); servWin->show(); servWin->activate(); servWin->setModalState(true); return true; } bool Application::OnJoinClick(const CEGUI::EventArgs& e) { std::cout << "Join clicked." << std::endl; CEGUI::Window* servWin = _guiMan.getWindowManager()->getWindow("root/winjoin"); servWin->show(); servWin->activate(); servWin->setModalState(true); return true; } // Server window callbacks bool Application::OnServStartClick(const CEGUI::EventArgs& e) { // Get the server port int port = 0; int maxConns=1; // Get the port CEGUI::Window* txtWin = _guiMan.getWindowManager()->getWindow("root/winserver/inport"); port = atoi(txtWin->getText().c_str()); // Get the host txtWin = _guiMan.getWindowManager()->getWindow("root/winserver/inmaxplayers"); CEGUI::String mString = txtWin->getText(); std::string myString(mString.c_str()); maxConns = atoi(txtWin->getText().c_str()); _server = new ammo::Server(port, maxConns); std::cout << "Sleeping while server boots" << std::endl; #ifdef WIN32 Sleep(500); #else usleep(500*1000); #endif std::cout << "Server online." << std::endl; _client = new ammo::Client(&_window); _client->Connect("localhost", port,"",0); _guiMan.Disable(); CEGUI::Window* servWin = _guiMan.getWindowManager()->getWindow("Root"); servWin->deactivate(); servWin->setModalState(false); servWin->setVisible(false); return true; } bool Application::OnServCancelClick(const CEGUI::EventArgs& e) { CEGUI::Window* servWin = _guiMan.getWindowManager()->getWindow("root/winserver"); servWin->deactivate(); servWin->setModalState(false); servWin->setVisible(false); return true; } // Join window callbacks bool Application::OnJoinStartClick(const CEGUI::EventArgs& e) { int clientPort = 0; // Get the port CEGUI::Window* txtWin = _guiMan.getWindowManager()->getWindow("root/winjoin/inport"); clientPort = atoi(txtWin->getText().c_str()); // Get the host txtWin = _guiMan.getWindowManager()->getWindow("root/winjoin/inip"); _client = new ammo::Client(&_window); _client->Connect(txtWin->getText().c_str(), clientPort,"",0); _guiMan.Disable(); CEGUI::Window* servWin = _guiMan.getWindowManager()->getWindow("Root"); servWin->deactivate(); servWin->setModalState(false); servWin->setVisible(false); return true; } bool Application::OnJoinCancelClick(const CEGUI::EventArgs& e) { CEGUI::Window* servWin = _guiMan.getWindowManager()->getWindow("root/winjoin"); servWin->deactivate(); servWin->setModalState(false); servWin->setVisible(false); return true; } }
[ "PhillipSpiess@d8b90d80-bb63-11dd-bed2-db724ec49875", "j.nick.terry@d8b90d80-bb63-11dd-bed2-db724ec49875" ]
[ [ [ 1, 12 ], [ 17, 108 ], [ 110, 128 ], [ 130, 262 ] ], [ [ 13, 16 ], [ 109, 109 ], [ 129, 129 ], [ 263, 263 ] ] ]
189be9522662dc5fd9ce3f84d7a2a076a2663413
2aa5cc5456b48811b7e4dee09cd7d1b019e3f7cc
/engine/component/jsactorcomponent.cpp
5f28480f277ee598b8a543fe51012f7229bed819
[]
no_license
tstivers/eXistenZ
eb2da9d6d58926b99495319080e13f780862fca0
2f5df51fb71d44c3e2689929c9249d10223f8d56
refs/heads/master
2021-09-02T22:50:36.733142
2010-11-16T06:47:24
2018-01-04T00:51:21
116,196,014
0
0
null
null
null
null
UTF-8
C++
false
false
1,787
cpp
#include "precompiled.h" #include "component/jsactorcomponent.h" #include "component/jscomponent.h" #include "entity/jsentity.h" using namespace jscomponent; using namespace component; using namespace script; namespace jscomponent { static bool parseDesc(JSContext* cx, JSObject* obj, ActorComponent::desc_type& desc); // method declarations // static JSBool classMethod(JSContext *cx, uintN argc, jsval *vp); // property declarations // static JSBool propGetter(JSContext *cx, JSObject *obj, jsval id, jsval *vp); static JSClass class_ops = { "ActorComponent", JSCLASS_HAS_RESERVED_SLOTS(1), JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub }; static JSPropertySpec class_properties[] = { // {"name", id, flags, getter, setter}, WRAPPED_LINK(contactCallback, ActorComponent, ContactCallbackComponent), JS_PS_END }; static JSFunctionSpec class_methods[] = { // JS_FN("name", function, nargs, minargs, flags), JS_FN("setShapesGroup", WRAP_FASTNATIVE(ActorComponent::setShapesGroup), 1, 0), JS_FN("setContactReportFlags", WRAP_FASTNATIVE(ActorComponent::setContactReportFlags), 1, 0), JS_FS_END }; } ScriptedObject::ScriptClass ActorComponent::m_scriptClass = { &class_ops, class_properties, class_methods, NULL }; REGISTER_SCRIPT_INIT(ActorComponent, initClass, 20); static void initClass(ScriptEngine* engine) { RegisterScriptClass<ActorComponent, Component>(engine); //jsentity::RegisterCreateFunction(engine, "createActorComponent", createComponent<ActorComponent>); } bool jscomponent::parseDesc(JSContext* cx, JSObject* obj, ActorComponent::desc_type& desc) { return true; }
[ [ [ 1, 65 ] ] ]
549a026fc7f39c18b9396c6da03a3b6a97cdf4d1
78fb44a7f01825c19d61e9eaaa3e558ce80dcdf5
/guidriverMyGUIOgre/src/MyGUI_OgreTexture.cpp
e7ccec7c383c6ea1ef52e35d23babadff1f0310c
[]
no_license
LiberatorUSA/GUCE
a2d193e78d91657ccc4eab50fab06de31bc38021
a4d6aa5421f8799cedc7c9f7dc496df4327ac37f
refs/heads/master
2021-01-02T08:14:08.541536
2011-09-08T03:00:46
2011-09-08T03:00:46
41,840,441
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
6,838
cpp
/*! @file @author Albert Semenov @date 04/2009 @module */ #include <cstring> #include "MyGUI_OgreTexture.h" #include "MyGUI_DataManager.h" #include "MyGUI_OgreRenderManager.h" #include "MyGUI_OgreDiagnostic.h" #include "MyGUI_OgreRTTexture.h" #include <Ogre.h> #include "MyGUI_LastHeader.h" namespace MyGUI { OgreTexture::OgreTexture(const std::string& _name, const std::string& _group) : mName(_name), mGroup(_group), mNumElemBytes(0), mPixelFormat(Ogre::PF_UNKNOWN), mUsage(Ogre::TU_DEFAULT), mListener(nullptr), mRenderTarget(nullptr) { mTmpData.data = nullptr; } OgreTexture::~OgreTexture() { destroy(); } const std::string& OgreTexture::getName() const { return mName; } void OgreTexture::saveToFile(const std::string& _filename) { Ogre::uchar *readrefdata = (Ogre::uchar*)lock(TextureUsage::Read); Ogre::Image img; img = img.loadDynamicImage(readrefdata, mTexture->getWidth(), mTexture->getHeight(), mTexture->getFormat()); img.save(_filename); unlock(); } void OgreTexture::setInvalidateListener(ITextureInvalidateListener* _listener) { mListener = _listener; } void OgreTexture::destroy() { if (mTmpData.data != nullptr) { delete[] (uint8*)mTmpData.data; mTmpData.data = nullptr; } if (mRenderTarget != nullptr) { delete mRenderTarget; mRenderTarget = nullptr; } if (!mTexture.isNull()) { Ogre::TextureManager::getSingleton().remove(mTexture->getName()); mTexture.setNull(); } } int OgreTexture::getWidth() { return mTexture->getWidth(); } int OgreTexture::getHeight() { return mTexture->getHeight(); } void* OgreTexture::lock(TextureUsage _access) { if (_access == TextureUsage::Write) { return mTexture->getBuffer()->lock(Ogre::HardwareBuffer::HBL_DISCARD); } // здесь проверить режим создания, и возможно так залочить без пиксель бокса // для чтения копируем в пиксель бокс if (mTmpData.data != nullptr) { delete[] (uint8*)mTmpData.data; mTmpData.data = nullptr; } mTmpData = Ogre::PixelBox(mTexture->getWidth(), mTexture->getHeight(), mTexture->getDepth(), mTexture->getFormat()); mTmpData.data = new uint8[mTexture->getBuffer()->getSizeInBytes()]; mTexture->getBuffer()->blitToMemory(mTmpData); return mTmpData.data; } void OgreTexture::unlock() { if (mTexture->getBuffer()->isLocked()) { mTexture->getBuffer()->unlock(); } else if (mTmpData.data != nullptr) { delete[] (uint8*)mTmpData.data; mTmpData.data = nullptr; } } bool OgreTexture::isLocked() { return mTexture->getBuffer()->isLocked(); } Ogre::TextureUsage OgreTexture::convertUsage(TextureUsage _usage) { if (_usage == TextureUsage::Default) { return Ogre::TU_STATIC_WRITE_ONLY; } else if (_usage == TextureUsage::RenderTarget) { return Ogre::TU_RENDERTARGET; } else if (_usage.isValue(TextureUsage::Static)) { if (_usage.isValue(TextureUsage::Write)) { return Ogre::TU_STATIC_WRITE_ONLY; } else { return Ogre::TU_STATIC; } } else if (_usage.isValue(TextureUsage::Dynamic)) { if (_usage.isValue(TextureUsage::Write)) { return Ogre::TU_DYNAMIC_WRITE_ONLY; } else { return Ogre::TU_DYNAMIC; } } else if (_usage.isValue(TextureUsage::Stream)) { if (_usage.isValue(TextureUsage::Write)) { return Ogre::TU_DYNAMIC_WRITE_ONLY_DISCARDABLE; } else { return Ogre::TU_DYNAMIC; } } return Ogre::TU_DEFAULT; } Ogre::PixelFormat OgreTexture::convertFormat(PixelFormat _format) { if (_format == PixelFormat::L8) return Ogre::PF_BYTE_L; else if (_format == PixelFormat::L8A8) return Ogre::PF_BYTE_LA; else if (_format == PixelFormat::R8G8B8) return Ogre::PF_R8G8B8; else if (_format == PixelFormat::R8G8B8A8) return Ogre::PF_A8R8G8B8; return Ogre::PF_UNKNOWN; } void OgreTexture::setFormat(PixelFormat _format) { mOriginalFormat = _format; mPixelFormat = convertFormat(_format); mNumElemBytes = 0; if (_format == PixelFormat::L8) mNumElemBytes = 1; else if (_format == PixelFormat::L8A8) mNumElemBytes = 2; else if (_format == PixelFormat::R8G8B8) mNumElemBytes = 3; else if (_format == PixelFormat::R8G8B8A8) mNumElemBytes = 4; } void OgreTexture::setUsage(TextureUsage _usage) { mOriginalUsage = _usage; mUsage = convertUsage(_usage); } void OgreTexture::createManual(int _width, int _height, TextureUsage _usage, PixelFormat _format) { setFormat(_format); setUsage(_usage); mTexture = Ogre::TextureManager::getSingleton().createManual( mName, mGroup, Ogre::TEX_TYPE_2D, _width, _height, 0, mPixelFormat, mUsage, this); mTexture->load(); } void OgreTexture::loadFromFile(const std::string& _filename) { setUsage(TextureUsage::Default); Ogre::TextureManager* manager = Ogre::TextureManager::getSingletonPtr(); if ( !manager->resourceExists(_filename) ) { DataManager& resourcer = DataManager::getInstance(); if (!resourcer.isDataExist(_filename)) { MYGUI_PLATFORM_LOG(Error, "Texture '" + _filename + "' not found, set default texture"); } else { mTexture = manager->load(_filename, mGroup, Ogre::TEX_TYPE_2D, 0); } } else { mTexture = manager->getByName(_filename); } setFormatByOgreTexture(); } void OgreTexture::setFormatByOgreTexture() { mOriginalFormat = PixelFormat::Unknow; mPixelFormat = Ogre::PF_UNKNOWN; mNumElemBytes = 0; if (!mTexture.isNull()) { mPixelFormat = mTexture->getFormat(); if (mPixelFormat == Ogre::PF_BYTE_L) { mOriginalFormat = PixelFormat::L8; mNumElemBytes = 1; } else if (mPixelFormat == Ogre::PF_BYTE_LA) { mOriginalFormat = PixelFormat::L8A8; mNumElemBytes = 2; } else if (mPixelFormat == Ogre::PF_R8G8B8) { mOriginalFormat = PixelFormat::R8G8B8; mNumElemBytes = 3; } else if (mPixelFormat == Ogre::PF_A8R8G8B8) { mOriginalFormat = PixelFormat::R8G8B8A8; mNumElemBytes = 4; } else { mOriginalFormat = PixelFormat::Unknow; mNumElemBytes = Ogre::PixelUtil::getNumElemBytes(mPixelFormat); } } } void OgreTexture::loadResource(Ogre::Resource* resource) { if (mListener) mListener->textureInvalidate(this); } IRenderTarget* OgreTexture::getRenderTarget() { if (mRenderTarget == nullptr) mRenderTarget = new OgreRTTexture(mTexture); return mRenderTarget; } } // namespace MyGUI
[ [ [ 1, 305 ] ] ]
5f59480ca72aee881643baa8642a215d50fff46d
fd518ed0226c6a044d5e168ab50a0e4a37f8efa9
/iAuthor/Author/AppSettings.cpp
fba2f9b1f712519fa74e2b78d6a5868c52931e3b
[]
no_license
shilinxu/iprojects
e2e2394df9882afaacfb9852332f83cbef6a8c93
79bc8e45596577948c45cf2afcff331bc71ab026
refs/heads/master
2020-05-17T19:15:43.197685
2010-04-02T15:58:11
2010-04-02T15:58:11
41,959,151
0
0
null
null
null
null
UTF-8
C++
false
false
9,440
cpp
// AppSettings.cpp: implementation of the CAppSettings class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Author.h" #include "AppSettings.h" #include "ProductCode.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif #define PRODUCT_REG_KEY _T("Software\\MMCorp") ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// bool CAppSettings::m_bRegistration = false; bool CAppSettings::m_bLayeredWndEnable = false; CString CAppSettings::m_strUserName; CString CAppSettings::m_strPCode; CString CAppSettings::m_strRCode; CString CAppSettings::m_strAppFilePath; CString CAppSettings::m_strAppPath; CString CAppSettings::m_strSchemePath; CString CAppSettings::m_strWorkPath; CString CAppSettings::m_strTempPath; CString CAppSettings::m_strContentsPath; CString CAppSettings::m_strBoardPath; CString CAppSettings::m_strSlidePath; CString CAppSettings::m_strHelpPath; CString CAppSettings::m_strOptionToolbar; CString CAppSettings::m_strOptionRecord; CString CAppSettings::m_strOptionPen; CString CAppSettings::m_strOptionFolder; CString CAppSettings::m_strOptionSnapshot; CString CAppSettings::m_strOptionText; CString CAppSettings::m_strOptionCamera; CString CAppSettings::m_strOptionCodec; bool CAppSettings::m_bChangeSlideFolder; CAppSettings::CAppSettings() { } CAppSettings::~CAppSettings() { } void CAppSettings::Init() { char szTemp[MAX_PATH]; CString strPath; GetModuleFileName(AfxGetInstanceHandle(), szTemp, MAX_PATH); strPath = szTemp; m_strAppFilePath = m_strAppPath = strPath; int nLength = m_strAppPath.GetLength(); int nCount = m_strAppPath.ReverseFind('\\'); m_strAppPath.Delete(nCount, nLength-nCount); m_strWorkPath.Format("%s\\Work", m_strAppPath); m_strTempPath.Format("%s\\Temp", m_strAppPath); m_strContentsPath.Format("%s\\Contents", m_strAppPath); m_strBoardPath.Format("%s\\Board", m_strAppPath); m_strSlidePath.Format("%s\\Slide", m_strAppPath); m_strHelpPath.Format("%s\\Help\\%s", m_strAppPath, "Help.htm"); m_strSchemePath.Format("%s\\%s", m_strWorkPath, "Scheme.txt"); m_strOptionToolbar = "iAuthor\\Option\\Toolbar"; m_strOptionRecord = "iAuthor\\Option\\Record"; m_strOptionPen = "iAuthor\\Option\\Pen"; m_strOptionFolder = "iAuthor\\Option\\Folder"; m_strOptionSnapshot = "iAuthor\\Option\\Snapshot"; m_strOptionText = "iAuthor\\Option\\Text"; m_strOptionCamera = "iAuthor\\Option\\Camera"; m_strOptionCodec = "iAuthor\\Option\\Codec"; m_bChangeSlideFolder = true; OSVERSIONINFOEX osvi; BOOL bOsVersionInfoEx; ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); if( !(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osvi)) ) { osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO); if (! GetVersionEx ( (OSVERSIONINFO *) &osvi) ) { m_bLayeredWndEnable = false; return; } } if((osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0) || // Microsoft Windows 95 (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10) || // Microsoft Windows 98 (osvi.dwMajorVersion <= 4 && osvi.dwMinorVersion == 90)) // Microsoft Windows Me m_bLayeredWndEnable = false; else m_bLayeredWndEnable = true; m_strUserName = ""; m_strPCode = ""; m_strRCode = ""; HKEY hKey; char szUserName[MAX_PATH]; char szProductCode[MAX_PATH]; char szRegistryCode[MAX_PATH]; DWORD dwBufLen = MAX_PATH; if(ERROR_SUCCESS == RegOpenKeyEx( HKEY_CLASSES_ROOT, PRODUCT_REG_KEY, 0, KEY_QUERY_VALUE, &hKey)) { RegQueryValueEx( hKey, "UName", NULL, NULL, (LPBYTE)szUserName, &dwBufLen); m_strUserName.Format("%s", szUserName); dwBufLen = MAX_PATH; RegQueryValueEx( hKey, "PCode", NULL, NULL, (LPBYTE)szProductCode, &dwBufLen); m_strPCode.Format("%s", szProductCode); dwBufLen = MAX_PATH; RegQueryValueEx( hKey, "RCode", NULL, NULL, (LPBYTE)szRegistryCode, &dwBufLen); m_strRCode.Format("%s", szRegistryCode); RegCloseKey( hKey ); m_strPCode.MakeUpper(); if (m_strPCode.Find(_T("APREG"), 0) == -1) { m_bRegistration = false; return; } else { CProductCode pc; CString strSerialCode; strSerialCode.Format("%s-%s", m_strPCode, m_strRCode); bool ret = pc.CheckCode((LPCTSTR) strSerialCode, 10, strSerialCode.GetLength()); if (ret) m_bRegistration = true; else m_bRegistration = false; } } else m_bRegistration = false; } // disable DWM // HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers // full_path DISABLEDWM WINXPSP2 DISABLETHEMES HIGHDPIAWARE bool CAppSettings::CheckVistaDWM4Restart() { HKEY hKey; char szElement[MAX_PATH] = {0};; CString strElement; CString strValue = "WINXPSP2 DISABLEDWM"; //"WINXPSP2 DISABLEDWM"; CString strRegKey = "Software\\Microsoft\\Windows NT\\CurrentVersion\\AppCompatFlags\\Layers"; OSVERSIONINFOEX osvi; BOOL bOsVersionInfoEx; ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); if( !(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osvi)) ) { osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO); if (!GetVersionEx ( (OSVERSIONINFO *) &osvi) ) return false; } if(osvi.dwMajorVersion != 6) // Microsoft Windows Vista return false; bool bNeedRestart = false; DWORD dwBufLen = MAX_PATH; if (ERROR_SUCCESS != RegOpenKeyEx( HKEY_CURRENT_USER, strRegKey, 0, KEY_ALL_ACCESS, &hKey)) { if(ERROR_SUCCESS != RegCreateKeyEx( HKEY_CURRENT_USER, strRegKey, 0, "", 0, KEY_ALL_ACCESS, NULL, &hKey, &dwBufLen)) { AfxMessageBox("ERROR! : CheckVistaDWM4Restart"); return false; } } if (ERROR_SUCCESS == RegQueryValueEx( hKey, m_strAppFilePath, NULL, NULL, (LPBYTE)szElement, &dwBufLen)) strElement.Format("%s", szElement); if (strElement.IsEmpty()) { if (ERROR_SUCCESS == RegSetValueEx(hKey, m_strAppFilePath, 0L, REG_SZ, (CONST BYTE *)(LPCTSTR)strValue, strValue.GetLength() + 1)) bNeedRestart = true; } RegCloseKey( hKey ); return bNeedRestart; } bool CAppSettings::SetRegistration(LPCTSTR pszUserName, LPCTSTR pszPCode, LPCTSTR pszRCode) { CProductCode pc; CString strSerialCode; strSerialCode.Format("%s-%s", pszPCode, pszRCode); bool ret = pc.CheckCode((LPCTSTR) strSerialCode, 10, strSerialCode.GetLength()); if (!ret) return false; m_bRegistration = true; HKEY hKey; DWORD dw; if(ERROR_SUCCESS == RegCreateKeyEx(HKEY_CLASSES_ROOT, PRODUCT_REG_KEY, 0, "", 0, KEY_READ | KEY_WRITE, NULL, &hKey, &dw)) { RegSetValueEx(hKey, "UName", 0L, REG_BINARY, (CONST BYTE *) pszUserName, _tcslen(pszUserName) + 1); RegSetValueEx(hKey, "PCode", 0L, REG_BINARY, (CONST BYTE *) pszPCode, _tcslen(pszPCode) + 1); RegSetValueEx(hKey, "RCode", 0L, REG_BINARY, (CONST BYTE *) pszRCode, _tcslen(pszRCode) + 1); RegCloseKey( hKey ); m_strUserName = pszUserName; m_strPCode = pszPCode; m_strRCode = pszRCode; return true; } return false; } void CAppSettings::SetSlidePath(CString strPath) { m_strSlidePath = strPath; } void CAppSettings::SetContentsPath(CString strPath) { m_strContentsPath = strPath; } void CAppSettings::SetSlideFolderLock() { m_bChangeSlideFolder = false; } bool CAppSettings::IsEnableSliderFolderChange() { return m_bChangeSlideFolder; } ///////////////////////////////////////////////////////////////////////////// // bool CAppSettings::IsRegistration() { return m_bRegistration; } bool CAppSettings::IsLayeredWndEnable() { return m_bLayeredWndEnable; } CString& CAppSettings::GetUserName() { return m_strUserName; } CString& CAppSettings::GetPCode() { return m_strPCode; } CString& CAppSettings::GetRCode() { return m_strRCode; } CString& CAppSettings::GetSchemePath() { return m_strSchemePath; } CString& CAppSettings::GetAppPath() { return m_strAppPath; } CString& CAppSettings::GetWorkPath() { return m_strWorkPath; } CString& CAppSettings::GetTempPath() { return m_strTempPath; } CString& CAppSettings::GetContentsPath() { return m_strContentsPath; } CString& CAppSettings::GetSlidePath() { return m_strSlidePath; } CString& CAppSettings::GetBoardPath() { return m_strBoardPath; } CString& CAppSettings::GetHelpPath() { return m_strHelpPath; } CString& CAppSettings::GetOptionToolbarPath() { return m_strOptionToolbar; } CString& CAppSettings::GetOptionRecordPath() { return m_strOptionRecord; } CString& CAppSettings::GetOptionPenPath() { return m_strOptionPen; } CString& CAppSettings::GetOptionFolderPath() { return m_strOptionFolder; } CString& CAppSettings::GetOptionSnapshotPath() { return m_strOptionSnapshot; } CString& CAppSettings::GetOptionTextPath() { return m_strOptionText; } CString& CAppSettings::GetOptionCameraPath() { return m_strOptionCamera; } CString& CAppSettings::GetOptionCodecPath() { return m_strOptionCodec; }
[ [ [ 1, 379 ] ] ]
46ec8c34db3d19684e92b9701a5c97788d2c5157
7b379862f58f587d9327db829ae4c6493b745bb1
/JuceLibraryCode/modules/juce_gui_basics/drawables/juce_DrawableImage.cpp
2f7029310c407229d9c285fb5a8fc19aca672f86
[]
no_license
owenvallis/Nomestate
75e844e8ab68933d481640c12019f0d734c62065
7fe7c06c2893421a3c77b5180e5f27ab61dd0ffd
refs/heads/master
2021-01-19T07:35:14.301832
2011-12-28T07:42:50
2011-12-28T07:42:50
2,950,072
2
0
null
null
null
null
UTF-8
C++
false
false
9,924
cpp
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-11 by Raw Material Software Ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License (Version 2), as published by the Free Software Foundation. A copy of the license is included in the JUCE distribution, or can be found online at www.gnu.org/licenses. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ BEGIN_JUCE_NAMESPACE //============================================================================== DrawableImage::DrawableImage() : opacity (1.0f), overlayColour (0x00000000) { bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f)); bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f)); } DrawableImage::DrawableImage (const DrawableImage& other) : image (other.image), opacity (other.opacity), overlayColour (other.overlayColour), bounds (other.bounds) { } DrawableImage::~DrawableImage() { } //============================================================================== void DrawableImage::setImage (const Image& imageToUse) { image = imageToUse; setBounds (imageToUse.getBounds()); bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f)); bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f)); bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight())); recalculateCoordinates (nullptr); repaint(); } void DrawableImage::setOpacity (const float newOpacity) { opacity = newOpacity; } void DrawableImage::setOverlayColour (const Colour& newOverlayColour) { overlayColour = newOverlayColour; } void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds) { if (bounds != newBounds) { bounds = newBounds; if (bounds.isDynamic()) { Drawable::Positioner<DrawableImage>* const p = new Drawable::Positioner<DrawableImage> (*this); setPositioner (p); p->apply(); } else { setPositioner (nullptr); recalculateCoordinates (nullptr); } } } //============================================================================== bool DrawableImage::registerCoordinates (RelativeCoordinatePositionerBase& pos) { bool ok = pos.addPoint (bounds.topLeft); ok = pos.addPoint (bounds.topRight) && ok; return pos.addPoint (bounds.bottomLeft) && ok; } void DrawableImage::recalculateCoordinates (Expression::Scope* scope) { if (image.isValid()) { Point<float> resolved[3]; bounds.resolveThreePoints (resolved, scope); const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth()); const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight()); AffineTransform t (AffineTransform::fromTargetPoints (resolved[0].x, resolved[0].y, tr.x, tr.y, bl.x, bl.y)); if (t.isSingularity()) t = AffineTransform::identity; setTransform (t); } } //============================================================================== void DrawableImage::paint (Graphics& g) { if (image.isValid()) { if (opacity > 0.0f && ! overlayColour.isOpaque()) { g.setOpacity (opacity); g.drawImageAt (image, 0, 0, false); } if (! overlayColour.isTransparent()) { g.setColour (overlayColour.withMultipliedAlpha (opacity)); g.drawImageAt (image, 0, 0, true); } } } Rectangle<float> DrawableImage::getDrawableBounds() const { return image.getBounds().toFloat(); } bool DrawableImage::hitTest (int x, int y) { return Drawable::hitTest (x, y) && image.isValid() && image.getPixelAt (x, y).getAlpha() >= 127; } Drawable* DrawableImage::createCopy() const { return new DrawableImage (*this); } //============================================================================== const Identifier DrawableImage::valueTreeType ("Image"); const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity"); const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay"); const Identifier DrawableImage::ValueTreeWrapper::image ("image"); const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft"); const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight"); const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft"); //============================================================================== DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_) : ValueTreeWrapperBase (state_) { jassert (state.hasType (valueTreeType)); } var DrawableImage::ValueTreeWrapper::getImageIdentifier() const { return state [image]; } Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager) { return state.getPropertyAsValue (image, undoManager); } void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager) { state.setProperty (image, newIdentifier, undoManager); } float DrawableImage::ValueTreeWrapper::getOpacity() const { return (float) state.getProperty (opacity, 1.0); } Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager) { if (! state.hasProperty (opacity)) state.setProperty (opacity, 1.0, undoManager); return state.getPropertyAsValue (opacity, undoManager); } void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager) { state.setProperty (opacity, newOpacity, undoManager); } const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const { return Colour ((uint32) state [overlay].toString().getHexValue32()); } void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager) { if (newColour.isTransparent()) state.removeProperty (overlay, undoManager); else state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager); } Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager) { return state.getPropertyAsValue (overlay, undoManager); } RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const { return RelativeParallelogram (state.getProperty (topLeft, "0, 0"), state.getProperty (topRight, "100, 0"), state.getProperty (bottomLeft, "0, 100")); } void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager) { state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager); state.setProperty (topRight, newBounds.topRight.toString(), undoManager); state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager); } //============================================================================== void DrawableImage::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder) { const ValueTreeWrapper controller (tree); setComponentID (controller.getID()); const float newOpacity = controller.getOpacity(); const Colour newOverlayColour (controller.getOverlayColour()); Image newImage; const var imageIdentifier (controller.getImageIdentifier()); jassert (builder.getImageProvider() != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them! if (builder.getImageProvider() != nullptr) newImage = builder.getImageProvider()->getImageForIdentifier (imageIdentifier); const RelativeParallelogram newBounds (controller.getBoundingBox()); if (bounds != newBounds || newOpacity != opacity || overlayColour != newOverlayColour || image != newImage) { repaint(); opacity = newOpacity; overlayColour = newOverlayColour; if (image != newImage) setImage (newImage); setBoundingBox (newBounds); } } ValueTree DrawableImage::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const { ValueTree tree (valueTreeType); ValueTreeWrapper v (tree); v.setID (getComponentID()); v.setOpacity (opacity, nullptr); v.setOverlayColour (overlayColour, nullptr); v.setBoundingBox (bounds, nullptr); if (image.isValid()) { jassert (imageProvider != nullptr); // if you're using images, you need to provide something that can load and save them! if (imageProvider != nullptr) v.setImageIdentifier (imageProvider->getIdentifierForImage (image), nullptr); } return tree; } END_JUCE_NAMESPACE
[ "ow3nskip" ]
[ [ [ 1, 295 ] ] ]
29380712af00eaa79a61dc43fffb8bbc7549d896
0468c65f767387da526efe03b37e1d6e8ddd1815
/source/drivers/caanoo/gui.h
9a353aa48f2fbbf05eaf326a597a96dbcaf3c867
[]
no_license
arntsonl/fc2x
aadc4e1a6c4e1d5bfcc76a3815f1f033b2d7e2fd
57ffbf6bcdf0c0b1d1e583663e4466adba80081b
refs/heads/master
2021-01-13T02:22:19.536144
2011-01-11T22:48:58
2011-01-11T22:48:58
32,103,729
0
0
null
null
null
null
UTF-8
C++
false
false
1,010
h
#ifndef __GUI_H__ #define __GUI_H__ ///////////////////////////////////////////////// // GUI for Gp2X // Author: Luke Arntson // Created: 12/5/2010 by Luke Arntson // Modified: 12/5/2010 by Luke Arntson ////////////////////////////////////////////////// #include <vector> #include <linux/input.h> #include "joystick.h" class CanGUI { public: CanGUI(); ~CanGUI(); int update(); void render(unsigned char *screen); private: void clearFiles(); // clear our directory list.. char curPath[1024]; // Current working directory.. char nextPath[1024]; // Next directory to move to.. char fileName[1024]; // Full file name to load int state; // current GUI state std::vector<char *> files; bool updateRender; struct input_event gJoystick[16]; // up to 16 events.. void moveUp(); void moveDown(); bool northPressed; // don't double press.. bool southPressed; bool bPressed; int cursorID; int cursorOffset; // For multiple panes.. }; #endif // __GUI_H__
[ "Cthulhu32@e9098629-9c10-95be-0fa9-336bad66c20b" ]
[ [ [ 1, 40 ] ] ]
13f1f52c602952e4b7ac5fe174fd3022e0db4489
e2e49023f5a82922cb9b134e93ae926ed69675a1
/tools/aoslcpp/include/aosl/list_stage.hpp
918b59d7019b53d41eab490aedd5ecf09c8f8772
[]
no_license
invy/mjklaim-freewindows
c93c867e93f0e2fe1d33f207306c0b9538ac61d6
30de8e3dfcde4e81a57e9059dfaf54c98cc1135b
refs/heads/master
2021-01-10T10:21:51.579762
2011-12-12T18:56:43
2011-12-12T18:56:43
54,794,395
1
0
null
null
null
null
UTF-8
C++
false
false
6,296
hpp
// Copyright (C) 2005-2010 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema // to C++ data binding compiler, in the Proprietary License mode. // You should have received a proprietary license from Code Synthesis // Tools CC prior to generating this code. See the license text for // conditions. // /** * @file * @brief Generated from list_stage.xsd. */ #ifndef AOSLCPP_AOSL__LIST_STAGE_HPP #define AOSLCPP_AOSL__LIST_STAGE_HPP // Begin prologue. // #include <aoslcpp/common.hpp> // // End prologue. #include <xsd/cxx/config.hxx> #if (XSD_INT_VERSION != 3030000L) #error XSD runtime version mismatch #endif #include <xsd/cxx/pre.hxx> #include "aosl/list_stage_forward.hpp" #include <memory> // std::auto_ptr #include <limits> // std::numeric_limits #include <algorithm> // std::binary_search #include <xsd/cxx/xml/char-utf8.hxx> #include <xsd/cxx/tree/exceptions.hxx> #include <xsd/cxx/tree/elements.hxx> #include <xsd/cxx/tree/containers.hxx> #include <xsd/cxx/tree/list.hxx> #include <xsd/cxx/xml/dom/parsing-header.hxx> #include <xsd/cxx/tree/containers-wildcard.hxx> #ifndef XSD_DONT_INCLUDE_INLINE #define XSD_DONT_INCLUDE_INLINE #include "aosl/stage_forward.hpp" #undef XSD_DONT_INCLUDE_INLINE #else #include "aosl/stage_forward.hpp" #endif // XSD_DONT_INCLUDE_INLINE /** * @brief C++ namespace for the %artofsequence.org/aosl/1.0 * schema namespace. */ namespace aosl { /** * @brief Class corresponding to the %list_stage schema type. * * List of Stages. * * @nosubgrouping */ class List_stage: public ::xml_schema::Type { public: /** * @name stage * * @brief Accessor and modifier functions for the %stage * sequence element. */ //@{ /** * @brief Element type. */ typedef ::aosl::Stage StageType; /** * @brief Element sequence container type. */ typedef ::xsd::cxx::tree::sequence< StageType > StageSequence; /** * @brief Element iterator type. */ typedef StageSequence::iterator StageIterator; /** * @brief Element constant iterator type. */ typedef StageSequence::const_iterator StageConstIterator; /** * @brief Element traits type. */ typedef ::xsd::cxx::tree::traits< StageType, char > StageTraits; /** * @brief Return a read-only (constant) reference to the element * sequence. * * @return A constant reference to the sequence container. */ const StageSequence& stage () const; /** * @brief Return a read-write reference to the element sequence. * * @return A reference to the sequence container. */ StageSequence& stage (); /** * @brief Copy elements from a given sequence. * * @param s A sequence to copy elements from. * * For each element in @a s this function makes a copy and adds it * to the sequence. Note that this operation completely changes the * sequence and all old elements will be lost. */ void stage (const StageSequence& s); //@} /** * @name Constructors */ //@{ /** * @brief Create an instance from the ultimate base and * initializers for required elements and attributes. */ List_stage (); /** * @brief Create an instance from a DOM element. * * @param e A DOM element to extract the data from. * @param f Flags to create the new instance with. * @param c A pointer to the object that will contain the new * instance. */ List_stage (const ::xercesc::DOMElement& e, ::xml_schema::Flags f = 0, ::xml_schema::Container* c = 0); /** * @brief Copy constructor. * * @param x An instance to make a copy of. * @param f Flags to create the copy with. * @param c A pointer to the object that will contain the copy. * * For polymorphic object models use the @c _clone function instead. */ List_stage (const List_stage& x, ::xml_schema::Flags f = 0, ::xml_schema::Container* c = 0); /** * @brief Copy the instance polymorphically. * * @param f Flags to create the copy with. * @param c A pointer to the object that will contain the copy. * @return A pointer to the dynamically allocated copy. * * This function ensures that the dynamic type of the instance is * used for copying and should be used for polymorphic object * models instead of the copy constructor. */ virtual List_stage* _clone (::xml_schema::Flags f = 0, ::xml_schema::Container* c = 0) const; //@} /** * @brief Destructor. */ virtual ~List_stage (); // Implementation. // //@cond protected: void parse (::xsd::cxx::xml::dom::parser< char >&, ::xml_schema::Flags); protected: StageSequence stage_; //@endcond }; bool operator== (const List_stage&, const List_stage&); bool operator!= (const List_stage&, const List_stage&); } #ifndef XSD_DONT_INCLUDE_INLINE #include "aosl/stage.hpp" #include "aosl/stage.inl" #endif // XSD_DONT_INCLUDE_INLINE #include <iosfwd> namespace aosl { ::std::ostream& operator<< (::std::ostream&, const List_stage&); } #include <iosfwd> #include <xercesc/sax/InputSource.hpp> #include <xercesc/dom/DOMDocument.hpp> #include <xercesc/dom/DOMErrorHandler.hpp> namespace aosl { } #include <iosfwd> #include <xercesc/dom/DOMDocument.hpp> #include <xercesc/dom/DOMErrorHandler.hpp> #include <xercesc/framework/XMLFormatter.hpp> #include <xsd/cxx/xml/dom/auto-ptr.hxx> namespace aosl { void operator<< (::xercesc::DOMElement&, const List_stage&); } #ifndef XSD_DONT_INCLUDE_INLINE #include "aosl/list_stage.inl" #endif // XSD_DONT_INCLUDE_INLINE #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue. #endif // AOSLCPP_AOSL__LIST_STAGE_HPP
[ "klaim@localhost" ]
[ [ [ 1, 275 ] ] ]
40f94e502e4ba3bf1dbda99630493a259d582ef0
3ea33f3b6b61d71216d9e81993a7b6ab0898323b
/src/lobby/LobbyMessages.h
02ba97ae311939d87841a027c67b6d403cc66e62
[]
no_license
drivehappy/tlmp
fd1510f48ffea4020a277f28a1c4525dffb0397e
223c07c6a6b83e4242a5e8002885e23d0456f649
refs/heads/master
2021-01-10T20:45:15.629061
2011-07-07T00:43:00
2011-07-07T00:43:00
32,191,389
2
0
null
null
null
null
UTF-8
C++
false
false
1,524
h
#pragma once namespace TLMP { namespace Network { namespace Lobby { #define stringify(name) #name /** Version to signify any Messaging ID changes. */ const int LobbyMessageVersion = 1; /** Network Control Messages */ enum LobbyMessage { L_S_VERSION = 0, L_C_VERSION, L_C_PLAYERNAME, L_S_PLAYERNAME_BATCH, L_S_PLAYERNAME_JOIN, L_S_PLAYERNAME_LEAVE, L_S_CHAT_MESSAGE, L_C_CHAT_MESSAGE, L_C_VIEW_GAMES, // Client requests a list of current games L_S_VIEW_GAMES, // Server pushes a list of current games L_C_HOSTING_NEW_GAME, // Client informs us they're hosting a new game L_S_HOSTING_REPLY, // Ack L_C_REQUEST_JOINGAME, // Requests lobby server to connect to a hosted game L_S_REPLAY_JOINGAME, // Returns hosted game IP and Port }; /** Stringify of Control Messages */ static const char* LobbyMessageString[] = { "L_S_VERSION", "L_C_VERSION", "L_C_PLAYERNAME", "L_S_PLAYERNAME_BATCH", "L_S_PLAYERNAME_JOIN", "L_S_PLAYERNAME_LEAVE", "L_S_CHAT_MESSAGE", "L_C_CHAT_MESSAGE", "L_C_VIEW_GAMES", "L_S_VIEW_GAMES", "L_C_HOSTING_NEW_GAME", "L_S_HOSTING_REPLY", "L_C_REQUEST_JOINGAME", "L_S_REPLAY_JOINGAME", }; }; }; };
[ "drivehappy@7af81de8-dd64-11de-95c9-073ad895b44c" ]
[ [ [ 1, 60 ] ] ]
191b13568edd03d351ce252ef3e950e81d683265
b505ef7eb1a6c58ebcb73267eaa1bad60efb1cb2
/source/graphics/core/win32/opengl/deviceopengl_1.cpp
c699107b09adea34e68f4993eb672d439a85dafc
[]
no_license
roxygen/maid2
230319e05d6d6e2f345eda4c4d9d430fae574422
455b6b57c4e08f3678948827d074385dbc6c3f58
refs/heads/master
2021-01-23T17:19:44.876818
2010-07-02T02:43:45
2010-07-02T02:43:45
38,671,921
0
0
null
null
null
null
UTF-8
C++
false
false
10,672
cpp
#include"deviceopengl.h" #include"texture2dopengl.h" #include"rendertargetopengl.h" /* #include"depthstencild3d11.h" */ #include"drawcommandexecuteopengl.h" namespace Maid { namespace Graphics { DeviceOpenGL::DeviceOpenGL( Window& win ) :m_Window(win) ,m_hDC(NULL) ,m_hGLContext(NULL) { } void DeviceOpenGL::Initialize() { { m_OpenGLDLL.Initialize(); } m_hDC = ::GetDC( m_Window.GetHWND() ); PIXELFORMATDESCRIPTOR pfd; { ZERO( &pfd, sizeof(pfd) ); pfd.nSize = sizeof( pfd ); pfd.nVersion = 2; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 32; pfd.cDepthBits = 16; pfd.iLayerType = PFD_MAIN_PLANE; } const int pixelformat = ChoosePixelFormat( m_hDC, &pfd ); SetPixelFormat( m_hDC, pixelformat, &pfd ); m_hGLContext = m_OpenGLDLL.wglCreateContext( m_hDC ); m_OpenGLDLL.wglMakeCurrent( m_hDC, m_hGLContext ); // ↓はやったほうがいいのかな? pfdの値が変わる // DescribePixelFormat(m_hDC, pixelformat, sizeof(PIXELFORMATDESCRIPTOR), &pfd); { m_OpenGLExtension.Initialize( m_OpenGLDLL ); IOpenGLObject::SetRuntime( &m_OpenGLDLL, &m_OpenGLExtension ); } { const int x = 0; const int y = 0; const int w = m_Window.GetClientSize().w; const int h = m_Window.GetClientSize().h; const float minz = 0.0f; const float maxz = 0.0f; m_OpenGLDLL.glViewport( x, y, w, h ); m_OpenGLDLL.glDepthRange( minz, maxz ); } { ZERO( &m_SwapChainFormat, sizeof(m_SwapChainFormat) ); SWAPCHAINFORMAT& fmt = m_SwapChainFormat; fmt.Size.w = m_Window.GetClientSize().w; fmt.Size.h = m_Window.GetClientSize().h; switch( pfd.cColorBits ) { case 32: { fmt.Format = PIXELFORMAT_X08R08G08B08I; }break; default: { MAID_ASSERT( true, "未実装" ); }break; } fmt.MultiSample.Count = 0; fmt.MultiSample.Quality = 1; fmt.RefreshRate.Denominator = 1; fmt.RefreshRate.Numerator = 0; fmt.ScanlineOrder = SWAPCHAINFORMAT::SCANLINEORDER_PROGRESSIVE; fmt.Scaling = SWAPCHAINFORMAT::SCALING_STRETCHED; fmt.SyncInterval = 1; } UpdateDisplayAspect(); { DrawCommandExecuteOpenGL* p = new DrawCommandExecuteOpenGL(m_OpenGLDLL, m_OpenGLExtension); p->Initialize(); m_pDrawCommandExecute.reset(p); } } void DeviceOpenGL::Finalize() { m_pDrawCommandExecute.reset(); m_OpenGLDLL.wglMakeCurrent( NULL, NULL ); m_OpenGLDLL.wglDeleteContext( m_hGLContext ); ::ReleaseDC( m_Window.GetHWND(), m_hDC ); IOpenGLObject::SetRuntime(NULL, NULL); /* if( IsFullScreen() ) { m_pSwapChain->SetFullscreenState( FALSE, NULL ); } m_pSwapChain.reset(); m_pDevice.reset(); */ } void DeviceOpenGL::UpdateDisplayAspect() { const POINT2DI pos = m_Window.GetPosition(); POINT p = { pos.x, pos.y }; const HMONITOR hMon = ::MonitorFromPoint( p, MONITOR_DEFAULTTONEAREST ); MONITORINFO info; info.cbSize = sizeof(info); ::GetMonitorInfo(hMon, &info); const int w = info.rcMonitor.right - info.rcMonitor.left; const int h = info.rcMonitor.bottom - info.rcMonitor.top; m_DisplayAspect = SIZE2DI(w,h); } void DeviceOpenGL::SetFullScreenState( bool IsFull ) { /* const bool NowFull = IsFullScreen(); if( NowFull==IsFull ) { return ; } if( IsFull ) { // ウィンドウ -> フルスクリーンの時は、対象先の解像度を覚えておく UpdateDisplayAspect(); } { const BOOL full = IsFull? TRUE:FALSE; const HRESULT ret = m_pSwapChain->SetFullscreenState( full, NULL ); if( FAILED(ret) ) { MAID_WARNING("IDXGISwapChain::SetFullscreenState() " ); return ; } } */ } float DeviceOpenGL::GetTexelMapValue() const { return 0.0f; } void DeviceOpenGL::SerchSwapChainSurfaceFormat( std::vector<PIXELFORMAT>& mode ) const { /* static const DXGI_FORMAT TestFMT[] = { DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R16G16B16A16_UNORM, DXGI_FORMAT_R10G10B10A2_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM, }; for( int i=0; i<NUMELEMENTS(TestFMT); ++i ) { const DXGI_FORMAT fmt = TestFMT[i]; UINT flag = 0; const HRESULT ret = m_pDevice->CheckFormatSupport( fmt, &flag ); if( FAILED(ret) ) { continue; } const bool IsTextre2D = IsFlag( flag, D3D11_FORMAT_SUPPORT_TEXTURE2D ); const bool IsRenderTarget = IsFlag( flag, D3D11_FORMAT_SUPPORT_RENDER_TARGET ); if( IsTextre2D && IsRenderTarget ) { mode.push_back( DXGI_FORMATtoPIXELFORMAT(fmt) ); } } */ } void DeviceOpenGL::SetSwapChainFormat( const SWAPCHAINFORMAT& mode ) { /* DXGI_SWAP_CHAIN_DESC desc; const bool NowFull = IsFullScreen(); { const HRESULT ret = m_pSwapChain->GetDesc( &desc ); if( FAILED(ret) ) { MAID_WARNING("IDXGISwapChain::GetDesc() " << ret ); return ; } // 一回ウィンドウモードに戻してから開放しないとダメらしい if( NowFull ) { m_pSwapChain->SetFullscreenState( FALSE, NULL ); } m_pSwapChain.reset(); } m_Window.SetClientSize( mode.Size ); desc.BufferDesc.Width = mode.Size.w; desc.BufferDesc.Height = mode.Size.h; desc.BufferDesc.RefreshRate.Numerator = 60; desc.BufferDesc.RefreshRate.Denominator = 1; desc.BufferDesc.Format = PIXELFORMATtoDXGI_FORMAT(mode.Format); desc.BufferDesc.ScanlineOrdering = SWAPCHAINFORMATSCANLINEORDERtoDXGI_MODE_SCANLINE_ORDER(mode.ScanlineOrder); desc.BufferDesc.Scaling = SWAPCHAINFORMATSCALINGtoDXGI_MODE_SCALING(mode.Scaling); desc.BufferCount = 2; desc.SampleDesc.Count = mode.MultiSample.Count; desc.SampleDesc.Quality = mode.MultiSample.Quality; { IDXGISwapChain* p=NULL; const HRESULT ret = m_pFactory->CreateSwapChain( m_pDevice.get(), &desc, &p ); if( FAILED(ret) ) { MAID_WARNING("IDXGIFactory::CreateSwapChain " << ret ); } m_pSwapChain.reset(p); } if( NowFull ) { m_pSwapChain->SetFullscreenState( TRUE, NULL ); } m_SyncInterval = mode.SyncInterval; */ } SWAPCHAINFORMAT DeviceOpenGL::GetSwapChainFormat() const { SWAPCHAINFORMAT ret; /* DXGI_SWAP_CHAIN_DESC desc; { const HRESULT ret = m_pSwapChain->GetDesc( &desc ); if( FAILED(ret) ) { MAID_WARNING("IDXGISwapChain::GetDesc() " << ret ); return SWAPCHAINFORMAT(); } } ret.Size = SIZE2DI( desc.BufferDesc.Width, desc.BufferDesc.Height ); ret.Format = DXGI_FORMATtoPIXELFORMAT(desc.BufferDesc.Format); ret.MultiSample.Quality = desc.SampleDesc.Quality; ret.MultiSample.Count = desc.SampleDesc.Count; ret.RefreshRate.Numerator = desc.BufferDesc.RefreshRate.Numerator; ret.RefreshRate.Denominator = desc.BufferDesc.RefreshRate.Denominator; ret.Scaling = DXGI_MODE_SCALINGtoDISPLAYMODESCALING( desc.BufferDesc.Scaling ); ret.ScanlineOrder = DXGI_MODE_SCANLINE_ORDERtoSWAPCHAINFORMATSCANLINEORDER( desc.BufferDesc.ScanlineOrdering ); ret.SyncInterval = m_SyncInterval; */ return m_SwapChainFormat; } SIZE2DI DeviceOpenGL::GetDisplayAspect() const { return m_DisplayAspect; } void DeviceOpenGL::SerchEnableFormat( ENABLEFORMAT& caps ) const { MAID_ASSERT( !caps.Texture.empty(), "引数はemptyにしてください" ); MAID_ASSERT( !caps.DepthStencil.empty(), "引数はemptyにしてください" ); MAID_ASSERT( !caps.RenderTargetTexture.empty(), "引数はemptyにしてください" ); MAID_ASSERT( !caps.RenderTargetSurface.empty(), "引数はemptyにしてください" ); MAID_ASSERT( !caps.IndexBit.empty(), "引数はemptyにしてください" ); { caps.Texture.push_back(PIXELFORMAT_A08B08G08R08I); caps.MaxTextureSize = SIZE2DI(4096,4096); } { caps.DepthStencil.push_back(PIXELFORMAT_D16I); } { caps.RenderTargetTexture.push_back(PIXELFORMAT_A08B08G08R08I); } { caps.RenderTargetSurface.push_back(PIXELFORMAT_A08B08G08R08I); } { caps.IndexBit.push_back(16); } /* { caps.Texture.push_back(PIXELFORMAT_A08B08G08R08I); caps.Texture.push_back(PIXELFORMAT_A02B10G10R10I); caps.Texture.push_back(PIXELFORMAT_A16B16G16R16I); caps.Texture.push_back(PIXELFORMAT_A16B16G16R16F); caps.Texture.push_back(PIXELFORMAT_A32B32G32R32F); caps.MaxTextureSize = SIZE2DI(4096,4096); } { caps.DepthStencil.push_back(PIXELFORMAT_D16I); caps.DepthStencil.push_back(PIXELFORMAT_D24IS8); } { caps.RenderTargetTexture.push_back(PIXELFORMAT_A08B08G08R08I); caps.RenderTargetTexture.push_back(PIXELFORMAT_A02B10G10R10I); caps.RenderTargetTexture.push_back(PIXELFORMAT_A16B16G16R16I); caps.RenderTargetTexture.push_back(PIXELFORMAT_A16B16G16R16F); caps.RenderTargetTexture.push_back(PIXELFORMAT_A32B32G32R32F); } { caps.RenderTargetSurface.push_back(PIXELFORMAT_A08B08G08R08I); caps.RenderTargetSurface.push_back(PIXELFORMAT_A02B10G10R10I); caps.RenderTargetSurface.push_back(PIXELFORMAT_A16B16G16R16I); caps.RenderTargetSurface.push_back(PIXELFORMAT_A16B16G16R16F); caps.RenderTargetSurface.push_back(PIXELFORMAT_A32B32G32R32F); } { caps.IndexBit.push_back(16); } */ } void DeviceOpenGL::Present() { m_OpenGLDLL.glFlush(); SwapBuffers( m_hDC ); } SPDRAWCOMMANDEXECUTE DeviceOpenGL::GetDrawCommandExecute()const { return m_pDrawCommandExecute; } SPDRAWCOMMANDCAPTURE DeviceOpenGL::CreateDrawCommandCapture() { return SPDRAWCOMMANDCAPTURE(); } SPRENDERTARGET DeviceOpenGL::GetCurrentRenderTarget()const { SPTEXTURE2D pTex; { CREATERETEXTURE2DPARAM p; p.Size.w = m_Window.GetClientSize().w; p.Size.h = m_Window.GetClientSize().h; p.Format = PIXELFORMAT_X08R08G08B08I; p.Usage = RESOURCEUSAGE_GPUWRITE; p.BindFlags = RESOURCEBINDFLAG_RENDERTARGET; pTex.reset( new Texture2DOpenGL(p) ); } SPRENDERTARGET pTarget; { CREATERENDERTARGETPARAM p; p.Format = pTex->GetParam().Format; p.Dimension = CREATERENDERTARGETPARAM::DIMENSION_TEXTURE2D; pTarget.reset( new RenderTargetOpenGL(pTex,p) ); } return pTarget; } bool DeviceOpenGL::IsFullScreen() const { /* DXGI_SWAP_CHAIN_DESC desc; const HRESULT ret = m_pSwapChain->GetDesc( &desc ); if( FAILED(ret) ) { MAID_WARNING("IDXGISwapChain::GetDesc() " << ret ); return false; } return desc.Windowed == FALSE; */ return false; } }}
[ "renji2000@471aaf9e-aa7b-11dd-9b86-41075523de00" ]
[ [ [ 1, 404 ] ] ]
e57a8a02678dca160e258f5daa466ee79e2ddc04
b369aabb8792359175aedfa50e949848ece03180
/src/wblib/wblib/Q3BSPLoader.h
175aedcb8bf97b84bc38f3e1984b371a22835575
[]
no_license
LibreGamesArchive/magiccarpet
6d49246817ab913f693f172fcfc53bf4cc153842
39210d57096d5c412de0f33289fbd4d08c20899b
refs/heads/master
2021-05-08T02:00:46.182694
2009-01-06T20:25:36
2009-01-06T20:25:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,135
h
/* * http://www.thatsorange.com/portfolio/projects/ * http://w3studi.informatik.uni-stuttgart.de/~bischowg/OpenGL/OGLq3bsp.html * http://www.devmaster.net/articles/quake3collision/ * http://graphics.stanford.edu/~kekoa/q3/ * http://graphics.cs.brown.edu/games/quake/quake3.html * http://www.flipcode.com/archives/Simple_Quake3_BSP_Loader.shtml * * Features implemented: * - patch faces * - lightmaps * - texturing * - PVS data * - already visible list * - handles maps having no pvs information and no lightmaps * * Features outstanding: * - texture coords for patch faces * - light volumes * - shaders * - map objects * - frustum culling * - collision detection * * LightMap parsing * - you need the multitexturing extension. Insert a stack at startup. * - compute the amount of lightmap textures stored in the bsp by * sizeof lightmap lump divided by size of one TLightMap struct. * - Provide some kind of array or std::vector to hold the OpenGL * texture object IDs for each created lightmap texture. * - Parse the lightmap lump and create a 128x128 texture for each read * TLightMap struct. The lightmap textures are always 128x128 RGB * (3 Byte per pixel). The 128x128x3 bytes to generate a texture from are * stored in a TLightMap struct (it holds nothing else besides that). * Store the texture object ids in your vector or array in the same * sequence, you read them from the bsp. This sequence number is used * as reference point later. * - Before creating the texture from the bytes read from the lightmap lump, * you can adjust the brightness (gamma) of the image data to lighten * dark levels up * * LightMap rendering * - Apply lightmaps to rendered faces. Each face carries a lightmap ID. This * ID indexes into the vector or array you stored your lightmaps in. You * should bind the faces texture on texture unit 0 and the faces lightmap * texture onto texture unit 1 * * Usage: * - Create a variable and specify the bsp file's name and path to the * constructor * - Render the map using one of the DrawXXX() methods * When using Draw(app->camera.pos.x, app->camera.pos.y, app->camera.pos.z); * which needs the camera's position for visibility estimations, you can * insert the cameras OpenGL coordinates (unswizzled) without a division * by 64.0f. The loader takes care of that for you! * - CleanUp the map using the CleanUp() method * * Collision detection: * Q3BSP is based on a BSP tree. A bsp tree is made up of nodes. There is * exactly one root node. Each node is associated with a plane which * cuts right through it and a childnode in front of that plane and a child node * behind that plane. The child nodes are given by positive indices into the * node lump. If a node with negative indices for its children is encountered, * these indices do not point into the nodes lump, but can be transformed into * positive indices into the leaves lump. Leaves are not nodes! * * Every leave has brushes associated to it. A brush has sides associated with. * * * Statically: * 1. Load file into buffer * 2. Check magic number and version * 3. * * For each frame: */ #ifndef Q3BSP_H #define Q3BSP_H #include <GL/glew.h> #include <GL/glut.h> #include <string> #include <iostream> #include <fstream> #include <list> #include <map> #include <vector> #include "JPEGFile.h" #include "TGAFile.h" #define CONTENTS_SOLID 1 #define Q3EPSILON 0.03125f #define SCALE_FACTOR 64.0f //#define SCALE_FACTOR 1.0f #define DIRENTRYCOUNT 17 // Game-related object descriptions. #define ENTITIES 0 // Surface descriptions (assume these have been converted to OpenGL textures). #define TEXTURES 1 // Planes used by map geometry. #define PLANES_LUMP 2 // BSP tree nodes. #define NODES 3 // BSP tree leaves. #define LEAVES 4 // Lists of face indices, one list per leaf. #define LEAFFACES 5 // Lists of brush indices, one list per leaf. #define LEAFBRUSHES 6 // Descriptions of rigid world geometry in map (we only use model[0]). #define MODELS 7 // Convex polyhedra used to describe solid space. #define BRUSHES 8 // Brush surfaces. #define BRUSHSIDES 9 // Vertices used to describe faces. #define VERTEXES 10 // Lists of offsets, one list per mesh. #define MESHVERTS 11 // List of special map effects. #define EFFECTS 12 // Surface geometry. Clusters are made up of faces. Faces aren't single // triangles, but they are a set of triangles. Faces store an index into the // vertex lump (= 10) and therefore store the vertices they consist of. // These vertices have to be drawn as triangle fans. #define FACES 13 // Packed lightmap data (assume these have been converted to an OpenGL texture) #define LIGHTMAPS 14 // Local illumination data. #define LIGHTVOLS 15 // Cluster-cluster visibility data. #define VISDATA 16 // Faces from lump 13 each have a type // Simple triangle data #define FACE_TYPE_POLYGON 1 // b spline, needs tesselation before rendering #define FACE_TYPE_PATCH 2 // Simple triangle data #define FACE_TYPE_MESH 3 // a surface that always has to face the viewer #define FACE_TYPE_BILLBOARD 4 #ifdef _WIN32 #pragma(1) #endif /** * The header stores an array of these structures, which contains * offsets to the real lump data. This structure should better * be called TLumpDescriptor, as it is not the real lump */ struct TLump { int mOffset; // Offset to start of lump, relative to beginning of file. int mLength; // Length of lump. Always a multiple of 4. }; /** * Identifies file format and version number, stores lumps i.e. indices to * the file content */ struct THeader { char mMagicNumber[4]; // Magic number. Always "IBSP". int mVersion; // Version number 0x2e for the BSP files distributed with Quake 3. TLump mLumps[DIRENTRYCOUNT]; // Lump directory, seventeen entries. }; /** * Face of the Q3 map. * The faces lump stores information used to render the surfaces of the map. */ struct TFace { int mTexture; // Texture index. int mEffect; // Index into lump 12 (Effects), or -1. int mType; // Face type. 1=polygon, 2=patch, 3=mesh, 4=billboard int mVertex; // Index of first vertex. int m_n_vertexes; // Number of vertices. int mMeshvert; // Index of first meshvert. int m_n_meshverts; // Number of meshverts. int lm_index; // Lightmap index. int lm_start[2]; // Corner of this face's lightmap image in lightmap. int lm_size[2]; // Size of this face's lightmap image in lightmap. float lm_origin[3]; // World space origin of lightmap. float lm_vecs[2][3]; // World space lightmap s and t unit vectors. float mNormal[3]; // Surface normal. int mSize[2]; // Patch dimensions. }; /** * Vertex of the Q3 map. * The vertexes lump stores lists of vertices used to describe faces. */ //struct TVertex { // float mPosition[3]; // Vertex position. // float mTexcoord[2][2]; // Vertex texture coordinates. 0=surface, 1=lightmap. // float mNormal[3]; // Vertex normal. // unsigned char mColor[4]; // Vertex color. RGBA. //}; struct TVertex { float mPosition[3]; // Vertex position. float mTexcoord[2]; float mLightMap[2]; float mNormal[3]; // Vertex normal. unsigned char mColor[4]; // Vertex color. RGBA. }; /** * Entity of the Q3 map. * The entities lump stores game-related map information, * including information about the map name, weapons, health, armor, * triggers, spawn points, lights, and .md3 models to be placed in the map. */ struct TEntity { int mSize; // Size of the description. char* mBuffer; // Entity descriptions, stored as a string. }; /** * Texture of the Q3 map. * The textures lump stores information about surfaces and volumes, which are in turn associated with faces, brushes, and brushsides. */ struct TTexture { char mName[64]; // Texture name. int mFlags; // Surface flags. int mContents; // Content flags. }; /** * Plane of the Q3 map. * The planes lump stores a generic set of planes that are in turn referenced by nodes and brushsides. */ struct TPlane { float mNormal[3]; // Plane normal. float mDistance; // Distance from origin to plane along normal. }; /** * Node of the Q3 map bsp tree. * The nodes lump stores all of the nodes in the map's BSP tree. */ struct TNode { int mPlane; // Plane index. int mChildren[2]; // Children indices. Negative numbers are leaf indices: -(leaf+1). int mMins[3]; // Integer bounding box min coord. int mMaxs[3]; // Integer bounding box max coord. }; /** * Leaf of the Q3 map. * The leafs lump stores the leaves of the map's BSP tree. */ struct TLeaf { int mCluster; // Visdata cluster index. int mArea; // Areaportal area. int mMins[3]; // Integer bounding box min coord. int mMaxs[3]; // Integer bounding box max coord. int mLeafFace; // First leafface for leaf. int mNbLeafFaces; // Number of leaffaces for leaf. int mLeafBrush; // First leafbrush for leaf. int mNbLeafBrushes; // Number of leafbrushes for leaf. }; /** * LeafFace of the Q3 map. * The leaffaces lump stores lists of face indices, with one list per leaf. */ struct TLeafFace { int mFaceIndex; // Face index. }; /** * Leaf Brush of the Q3 map. * The leafbrushes lump stores lists of brush indices, with one list per leaf. */ struct TLeafBrush { int mBrushIndex; // Brush index. }; /** * Model of the Q3 map. * The models lump describes rigid groups of world geometry. */ struct TModel { float mMins[3]; // Bounding box min coord. float mMaxs[3]; // Bounding box max coord. int mFace; // First face for model. int mNbFaces; // Number of faces for model. int mBrush; // First brush for model. int mNBrushes; // Number of brushes for model. }; /** * Brush of the Q3 map. * The brushes lump stores a set of brushes, which are in turn used for collision detection. */ struct TBrush { int mBrushSide; // First brushside for brush. int mNbBrushSides; // Number of brushsides for brush. int mTextureIndex; // Texture index. }; /** * BrushSide of the Q3 map. * The brushsides lump stores descriptions of brush bounding surfaces. */ struct TBrushSide { int mPlaneIndex; // Plane index. int mTextureIndex; // Texture index. }; /** * MeshVert of the Q3 map. * The meshverts lump stores lists of vertex offsets, used to describe generalized triangle meshes. */ struct TMeshVert { int mMeshVert; // Vertex index offset, relative to first vertex of corresponding face. }; /** * Effect of the Q3 map. * The effects lump stores references to volumetric shaders (typically fog) which affect the rendering of a particular group of faces. */ struct TEffect { char mName[64]; // Effect shader. int mBrush; // Brush that generated this effect. int mUnknown; // Always 5, except in q3dm8, which has one effect with -1. }; /** * Lightmap of the Q3 map. * The lightmaps lump stores the light map textures used make surface lighting look more realistic. */ struct TLightMap { unsigned char mMapData[128][128][3];// Lightmap color data. RGB. }; /** * Light volume of the Q3 map. * The lightvols lump stores a uniform grid of lighting information used to illuminate non-map objects. */ struct TLightVol { unsigned char mAmbient[3]; // Ambient color component. RGB. unsigned char mDirectional[3]; // Directional color component. RGB. unsigned char mDir[2]; // Direction to light. 0=phi, 1=theta. }; /** * The Visibility data of the Q3 map. * The visdata lump stores bit vectors that provide cluster-to-cluster * visibility information. */ struct TVisData { int mNbClusters; // The number of clusters int mBytesPerCluster; // Bytes (8 bits) in the cluster's bitset unsigned char * mBuffer; // Array of bytes holding the cluster vis. }; #ifdef _WIN32 #pragma() #endif enum EntityParserMode {PREKEY, KEY, PREVALUE, VALUE}; struct KeyValuePair { char key[100]; char value[100]; }; class EntityDescriptor { public: std::list<KeyValuePair *> keyValueList; void CleanUp(); /** * Insert a key, get a value or null */ const char * Get(const char * _key); }; /** * Parses the entity string. * * { * "classname" "worldspawn" * } * * Each entity is contained inside a pair of squiggly brackets. Each entity * is a set of key value pairs. Key and value are surrounded by " characters. * Per entity there is exactly one classname_key */ class EntityParser { public: EntityParser(const char * _entitiyString); void Process(const char * _key, const char * _value); void EntityStart(); void EntityEnd(); void CleanUp(); EntityDescriptor * GetDescriptorContaining(const char * _key, const char * _value); std::list<EntityDescriptor *> entityDescriptorList; EntityDescriptor * currentDescriptor; }; /** * Used to tesselate patches inside the Grid of control points of a patch face * by two tier interpolation using quadratic bezier curves which describe * a biquadratic bezier surface */ class Bezier { private: int level; std::vector<TVertex> vertex; std::vector<unsigned int> indexes; std::vector<unsigned int> trianglesPerRow; std::vector<unsigned int *> rowIndexes; public: TVertex controls[9]; void tessellate(int level); void render(); void renderDebug(); }; class Q3BSP { public: Q3BSP(const std::string fileName); // Renders all the faces (= lump 13) without using // PVS logic void DrawWithoutPVS(); void DrawVertices(); // with PVS logic void Draw(float camPos[3]); void Draw(float camera_x, float camera_y, float camera_z); // finds the leaf, the camera is currently in int GetCurrentLeafIndex(float camPos[3]); void ResetAlreadyVisible(); bool IsPotentiallyVisible(int _camCluster, int _testCluster); int IsAlreadyVisible(int faceIndex); void MakeAlreadyVisible(int faceIndex); void RenderMeshFace(TFace f); void RenderPolygonFace(TFace f); void RenderPolygonFaceDebug(TFace f); void RenderPatchFaceDebug(int _faceIndex); void RenderLeaf(int _leafIndex); void RenderCluster(int _clusterIndex); void CleanUp(); int GetFaceCount() { return faceCount; } int GetClusterCount() { return clusterCount; } // Sets the member variable outputEnd to that point on the line segment // defined between _inputStart and _inputEnd, which is the first collision // point by the line segment and the solid part of the q3 level. By first // collision point is meant, that travelling from _inputStart to _inputEnd, // outputEnd is the first point where the traveller would collide into solid // walls. void Trace(float * _inputStart, float * _inputEnd); // Traverses BSP down according to the traceline until leaves are found. // Checks leaves for collision with the traceline void CheckNode(int _nodeIndex, float _startFraction, float _endFraction, float * _start, float * _end); //void CheckBrush(TBrush _brush, float * _inputStart, float * _inputEnd); void CheckBrush(TBrush _brush); /** * Draws the convex volume of a brush that is specified by a brushes * brushsides. Every brushside stores an index into the planes lump. These * planes indexed by the brushsides, are used to clip together the convex * volume */ //void DrawBrush(int _brushIndex); /** * Returns good flag, which is set to false if bsp file could not * be found on harddrive */ bool Good() { return good; } private: void ParseVector(const char * _vector, float * _dest); /** * opens the file, loads content into buffer, keeps the buffer * allocated, someone else (CleanUp()) has to delete it. * * Returns 0 in case of success, -1 otherwise */ int PerformFileHandling(const std::string fileName); // Parses the buffer, extracts the Q3BSP content void Parse(); void TesselatePatches(int _tesselationEdges); float DotProduct(float *v1, float *v2); void DumpLeavesContainingFace(int _faceIndex); void ChangeGamma(unsigned char * _pImage, int _size, float _factor); void CreateLightmapTexture(unsigned int & _textureObjectID, unsigned char * _pImageBits, int _width, int _height); public: float info_player_start[3]; int currentFace; int currentCluster; // These are the output variables of the collision detection algorithm // another output variabel, outputEnd, is a member of the class bool outputStartsOut; bool outputAllSolid; float outputFraction; float outputEnd[3]; float * inputStart; float * inputEnd; private: THeader * header; TFace * faces; TVertex * vertices; TEntity * entities; TTexture * textures; TPlane * planes; TNode * nodes; TLeaf * leaves; TLeafFace * leaffaces; TLeafBrush * leafbrushes; TModel * models; TBrush * brushes; TBrushSide * brushsides; TMeshVert * meshverts; TEffect * effects; TLightMap * lightmaps; TLightVol * lightvolumes; TVisData visdata; int faceCount; int vertexCount; int leafCount; int bytesInAlreadyVisibleList; int clusterCount; unsigned char *alreadyVisible; // used to store the complete file content char * buffer; std::map<int, std::vector<Bezier *> *> bezierMap; std::vector<int> texIDtexObjMap; bool noVisData; bool nolightmaps; float gamma; unsigned int * lightmapArray; bool good; }; #endif
[ [ [ 1, 595 ] ] ]
5e155c00a009ef139ca5d942377567ed2a4b9221
0a4a70ad5a0ffb570bba6b95d4d7a861fb97f62d
/id/DarkGDK/Image.h
9037e2b4d1b1106d3080c389b208a880dedab37e
[]
no_license
matthew-nichols/school-battleship
752ce9d588620e1e700c996dcaaa5b66d4bcf2d9
25de867956dd70972df57e6f0070a5c1bcc8efa4
refs/heads/master
2016-09-06T03:59:24.269637
2011-04-30T22:05:25
2011-04-30T22:05:25
32,114,609
0
0
null
null
null
null
UTF-8
C++
false
false
1,407
h
#ifndef IDKNOTI_DARKGDK_EVEN_BETTER_IMAGE #define IDKNOTI_DARKGDK_EVEN_BETTER_IMAGE #include <id/idDarkGDK.h> namespace DarkGDKExt { class Image { private: dbCImage i; static HandleAllocator<1, 65535> h; Image() {} void DecRef() { if (--(h.RefCount(i.ImageNumber())) == 0) { h.Deallocate(i.ImageNumber()); i.Delete(); } } void AddRef() { ++(h.RefCount(i.ImageNumber())); } public: Image(const char* filename) { i.ImageNumber() = h.Allocate(); AddRef(); i.Load(filename, 1); } Image(const Image& other) { i = other.i; ++(h.RefCount(i.ImageNumber())); } Image(Bitmap& bitmap) { i.ImageNumber() = h.Allocate(); AddRef(); int temp = dbCurrentBitmap(); bitmap.MakeCurrent(); i.Get(0, 0, bitmap.Width(), bitmap.Height(), 1); dbSetCurrentBitmap(temp); } Image& operator=(const Image& other) { if (this == &other) return *this; DecRef(); i = other.i; ++(h.RefCount(i.ImageNumber())); return *this; } void Paste(int x, int y) { i.Paste(x, y, 1); } void Paste(Idknoti::Vec2i v) { i.Paste(v, 1); } void PasteOpaque(int x, int y) { i.Paste(x, y); } void PasteOpaque(Idknoti::Vec2i v) { i.Paste(v); } int Width() { return i.GetWidth(); } int Height() { return i.GetHeight(); } ~Image() { DecRef(); } }; } #endif
[ "[email protected]@1af9ae56-1f64-8628-c089-4a8335a31a42" ]
[ [ [ 1, 95 ] ] ]
997210dd2c9c3a88d3eb1d83ebf98bc0e912d64d
100f177f0da7e0abf1c65d5dafaab5ff8061e17a
/dc_viewer/xllabeldisplay.h
74a1ad6546150888c88cdf7ae99e9284242f632d
[]
no_license
gulimujyujyu/xlzhuathku
61d39222a7854ffa6407031520a705b83adc3346
fe72d93fd29261cb34dc98bccafb0ae0ad50823a
refs/heads/master
2021-01-19T02:52:11.521328
2011-09-27T13:38:38
2011-09-27T13:38:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
504
h
#ifndef XLLABELDISPLAY_H #define XLLABELDISPLAY_H #include <QLabel> class XlLabelDisplay : public QLabel { Q_OBJECT public: XlLabelDisplay(QWidget *parent); ~XlLabelDisplay(); void setTempPath(QString a); signals: void labelDoubleClicked(); private slots: void saveImageLocally(); protected: void mouseDoubleClickEvent(QMouseEvent *ev); private: QAction *saveAction; private: QString tempPath; void createContextMenu(); }; #endif // XLLABELDISPLAY_H
[ [ [ 1, 33 ] ] ]
3241b4903c4de997ad08156bb7f98da534c3ab9a
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/nebula2/src/scene/ntransformanimator_cmds.cc
c0f2c9e2f7c42de255c050bc384f3de0472d6f2a
[]
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
10,786
cc
//------------------------------------------------------------------------------ // ntransformanimator_cmds.cc // (C) 2003 RadonLabs GmbH //------------------------------------------------------------------------------ #include "scene/ntransformanimator.h" #include "kernel/npersistserver.h" static void n_addposkey(void* slf, nCmd* cmd); static void n_addeulerkey(void* slf, nCmd* cmd); static void n_addscalekey(void* slf, nCmd* cmd); static void n_addquatkey(void* slf, nCmd* cmd); static void n_getnumposkeys(void* slf, nCmd* cmd); static void n_getnumeulerkeys(void* slf, nCmd* cmd); static void n_getnumscalekeys(void* slf, nCmd* cmd); static void n_getnumquatkeys(void* slf, nCmd* cmd); static void n_getposkeyat(void* slf, nCmd* cmd); static void n_geteulerkeyat(void* slf, nCmd* cmd); static void n_getscalekeyat(void* slf, nCmd* cmd); static void n_getquatkeyat(void* slf, nCmd* cmd); //------------------------------------------------------------------------------ /** @scriptclass ntransformanimator @cppclass nTransformAnimator @superclass nanimator @classinfo Animate attributes of a transform node. */ void n_initcmds(nClass* cl) { cl->BeginCmds(); cl->AddCmd("v_addposkey_ffff", 'ADPK', n_addposkey); cl->AddCmd("v_addeulerkey_ffff", 'ADEK', n_addeulerkey); cl->AddCmd("v_addscalekey_ffff", 'ADSK', n_addscalekey); cl->AddCmd("v_addquatkey_fffff", 'ADQK', n_addquatkey); cl->AddCmd("i_getnumposkeys_v", 'GNPK', n_getnumposkeys); cl->AddCmd("i_getnumeulerkeys_v", 'GNEK', n_getnumeulerkeys); cl->AddCmd("i_getnumscalekeys_v", 'GNSK', n_getnumscalekeys); cl->AddCmd("i_getnumquatkeys_v", 'GNQK', n_getnumquatkeys); cl->AddCmd("ffff_getposkeyat_i", 'GPKA', n_getposkeyat); cl->AddCmd("ffff_geteulerkeyat_i", 'GEKA', n_geteulerkeyat); cl->AddCmd("ffff_getscalekeyat_i", 'GSKA', n_getscalekeyat); cl->AddCmd("ffff_getquatkeyat_i", 'GQKA', n_getquatkeyat); cl->EndCmds(); } //------------------------------------------------------------------------------ /** @cmd addposkey @input f(Time), f(PosX), f(PosY), f(PosZ) @output v @info Add a position key to the position key array. */ static void n_addposkey(void* slf, nCmd* cmd) { nTransformAnimator* self = (nTransformAnimator*) slf; vector3 v0; float f0 = cmd->In()->GetF(); v0.x = cmd->In()->GetF(); v0.y = cmd->In()->GetF(); v0.z = cmd->In()->GetF(); self->AddPosKey(f0, v0); } //------------------------------------------------------------------------------ /** @cmd addeulerkey @input f(Time), f(EulerX), f(EulerY), f(EulerZ) @output v @info Add a euler angle key to the position key array. */ static void n_addeulerkey(void* slf, nCmd* cmd) { nTransformAnimator* self = (nTransformAnimator*) slf; vector3 v0; float f0 = cmd->In()->GetF(); v0.x = n_deg2rad(cmd->In()->GetF()); v0.y = n_deg2rad(cmd->In()->GetF()); v0.z = n_deg2rad(cmd->In()->GetF()); self->AddEulerKey(f0, v0); } //------------------------------------------------------------------------------ /** @cmd addscalekey @input f(Time), f(ScaleX), f(ScaleY), f(ScaleZ) @output v @info Add a scale key to the position key array. */ static void n_addscalekey(void* slf, nCmd* cmd) { nTransformAnimator* self = (nTransformAnimator*) slf; vector3 v0; float f0 = cmd->In()->GetF(); v0.x = cmd->In()->GetF(); v0.y = cmd->In()->GetF(); v0.z = cmd->In()->GetF(); self->AddScaleKey(f0, v0); } //------------------------------------------------------------------------------ /** @cmd addquatkey @input f(Time), f(QuatX), f(QuatY), f(QuatZ), f(QuatW) @output v @info Add a quaternion key to the rotation key array. Warning! DON'T mix quaternions and eulers! */ static void n_addquatkey(void* slf, nCmd* cmd) { nTransformAnimator* self = (nTransformAnimator*) slf; quaternion q0; float f0 = cmd->In()->GetF(); q0.x = cmd->In()->GetF(); q0.y = cmd->In()->GetF(); q0.z = cmd->In()->GetF(); q0.w = cmd->In()->GetF(); self->AddQuatKey(f0, q0); } //------------------------------------------------------------------------------ /** @cmd getnumposkeys @input v @output i(NumPosKeys) @info Return number of position keys. */ static void n_getnumposkeys(void* slf, nCmd* cmd) { nTransformAnimator* self = (nTransformAnimator*) slf; cmd->Out()->SetI(self->GetNumPosKeys()); } //------------------------------------------------------------------------------ /** @cmd getnumeulerkeys @input v @output i(NumEulerKeys) @info Return number of euler keys. */ static void n_getnumeulerkeys(void* slf, nCmd* cmd) { nTransformAnimator* self = (nTransformAnimator*) slf; cmd->Out()->SetI(self->GetNumEulerKeys()); } //------------------------------------------------------------------------------ /** @cmd getnumscalekeys @input v @output i(NumScaleKeys) @info Return number of scale keys. */ static void n_getnumscalekeys(void* slf, nCmd* cmd) { nTransformAnimator* self = (nTransformAnimator*) slf; cmd->Out()->SetI(self->GetNumScaleKeys()); } //------------------------------------------------------------------------------ /** @cmd getnumquatkeys @input v @output i(NumQuatKeys) @info Return number of quaternion keys. */ static void n_getnumquatkeys(void* slf, nCmd* cmd) { nTransformAnimator* self = (nTransformAnimator*) slf; cmd->Out()->SetI(self->GetNumQuatKeys()); } //------------------------------------------------------------------------------ /** @cmd getposkeyat @input i(Index) @output f(Time), f(PosX), f(PosY), f(PosZ) @info Get position key attributes at given index. */ static void n_getposkeyat(void* slf, nCmd* cmd) { nTransformAnimator* self = (nTransformAnimator*) slf; float f0; vector3 v0; self->GetPosKeyAt(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 geteulerkeyat @input i(Index) @output f(Time), f(EulerX), f(EulerY), f(EulerZ) @info Get euler key attributes at given index. */ static void n_geteulerkeyat(void* slf, nCmd* cmd) { nTransformAnimator* self = (nTransformAnimator*) slf; float f0; vector3 v0; self->GetEulerKeyAt(cmd->In()->GetI(), f0, v0); cmd->Out()->SetF(f0); cmd->Out()->SetF(n_rad2deg(v0.x)); cmd->Out()->SetF(n_rad2deg(v0.y)); cmd->Out()->SetF(n_rad2deg(v0.z)); } //------------------------------------------------------------------------------ /** @cmd getscalekeyat @input i(Index) @output f(Time), f(ScaleX), f(ScaleY), f(ScaleZ) @info Get scale key attributes at given index. */ static void n_getscalekeyat(void* slf, nCmd* cmd) { nTransformAnimator* self = (nTransformAnimator*) slf; float f0; vector3 v0; self->GetScaleKeyAt(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 getquatkeyat @input i(Index) @output f(Time), f(QuatX), f(QuatY), f(QuatZ), f(QuatW) @info Get quaternion key attributes at given index. */ static void n_getquatkeyat(void* slf, nCmd* cmd) { nTransformAnimator* self = (nTransformAnimator*) slf; float f0; quaternion q0; self->GetQuatKeyAt(cmd->In()->GetI(), f0, q0); cmd->Out()->SetF(f0); cmd->Out()->SetF(q0.x); cmd->Out()->SetF(q0.y); cmd->Out()->SetF(q0.z); cmd->Out()->SetF(q0.w); } //------------------------------------------------------------------------------ /** */ bool nTransformAnimator::SaveCmds(nPersistServer* ps) { if (nAnimator::SaveCmds(ps)) { nCmd* cmd; int curKey; int numKeys; //--- addposkey --- numKeys = this->GetNumPosKeys(); for (curKey = 0; curKey < numKeys; curKey++) { float time; vector3 val; cmd = ps->GetCmd(this, 'ADPK'); this->GetPosKeyAt(curKey, time, val); cmd->In()->SetF(time); cmd->In()->SetF(val.x); cmd->In()->SetF(val.y); cmd->In()->SetF(val.z); ps->PutCmd(cmd); } //--- addeulerkey --- numKeys = this->GetNumEulerKeys(); if (numKeys > 0) { for (curKey = 0; curKey < numKeys; curKey++) { float time; vector3 val; cmd = ps->GetCmd(this, 'ADEK'); this->GetEulerKeyAt(curKey, time, val); cmd->In()->SetF(time); cmd->In()->SetF(n_rad2deg(val.x)); cmd->In()->SetF(n_rad2deg(val.y)); cmd->In()->SetF(n_rad2deg(val.z)); ps->PutCmd(cmd); } } else { //--- addquatkey --- numKeys = this->GetNumQuatKeys(); for (curKey = 0; curKey < numKeys; curKey++) { float time; quaternion val; cmd = ps->GetCmd(this, 'ADQK'); this->GetQuatKeyAt(curKey, 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); } } //--- addscalekey --- numKeys = this->GetNumScaleKeys(); for (curKey = 0; curKey < numKeys; curKey++) { float time; vector3 val; cmd = ps->GetCmd(this, 'ADSK'); this->GetScaleKeyAt(curKey, time, val); cmd->In()->SetF(time); cmd->In()->SetF(val.x); cmd->In()->SetF(val.y); cmd->In()->SetF(val.z); ps->PutCmd(cmd); } return true; } return false; }
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 399 ] ] ]
5a13b2a39568d50e00ddff7755d7c96de3e834b4
40e58042e635ea2a61a6216dc3e143fd3e14709c
/paradebot10/FrameworkLogger.h
92b2f33a398fde52d282c2028e34f4316fd47fb7
[]
no_license
chopshop-166/frc-2011
005bb7f0d02050a19bdb2eb33af145d5d2916a4d
7ef98f84e544a17855197f491fc9f80247698dd3
refs/heads/master
2016-09-05T10:59:54.976527
2011-10-20T22:50:17
2011-10-20T22:50:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,283
h
/******************************************************************************* * Project : Framework * File Name : MemoryLog.h * Owner : Software Group (FIRST Chopshop Team 166) * Creation Date : January 18, 2010 * File Description : Header for general memory logger on chopshop robot *******************************************************************************/ /*----------------------------------------------------------------------------*/ /* Copyright (c) MHS Chopshop Team 166, 2010. All Rights Reserved. */ /*----------------------------------------------------------------------------*/ #pragma once #include <cstdio> #include <ctime> #include <string> using std::string; // // This class defines an interface to logging to memory and then into a .csv file // class FrameworkLogger { protected: FrameworkLogger() {}; // Constructor must be overloaded // Methods public: struct timespec starttime; // Time the task started at virtual ~FrameworkLogger(void) {}; virtual int DumpToFile(void) = 0; // Dump the data into a file // Members public: int Registered; // This handler has been registered with Robot166 FrameworkLogger *nextLog; // Link to the next block };
[ [ [ 1, 35 ] ] ]
997894ac1b63527eb3d5eab5a3a297634a5e8a5d
7d4faba77af44f30d314cf3a9f7590c33dd2cdff
/VedaSwig/src/Simulation/Geometry/Point.hpp
f29010df05959f567ef4bedd7c5d72c6c0193c6e
[]
no_license
BackupTheBerlios/veda-svn
ece326b3fa36460c3ee9255253baf802b335e7cd
fbc4c608fea9880b0bf418bd4154f205d89b4302
refs/heads/master
2020-12-24T17:35:16.139115
2006-10-02T09:57:45
2006-10-02T09:57:45
40,799,946
0
0
null
null
null
null
UTF-8
C++
false
false
2,561
hpp
#ifndef POINT_H_ #define POINT_H_ #include <string.h> #include "Packing/Archive.hpp" #include "Math.hpp" namespace Geometry { class Point { public: double x, y; public: Point(): x(0), y(0) { } Point(double a): x(a), y(a) { } Point(double n_x, double n_y): x(n_x), y(n_y) { } virtual ~Point() { } /* create some incedible points */ void makeRandom(const double& a = 1) { x = a * (2.0 * Rand() - 1.0); y = a * (2.0 * Rand() - 1.0); } void makeRandom(const Point& p){ x = p.x * (2 * Rand() - 1); y = p.y * (2 * Rand() - 1); } void makeNaN() { x = Nan(); y = Nan(); } void makeInf() { x = Inf(); y = Inf(); } /* check for sanity */ int valid(){ return isValid(x) && isValid(y); } /* operators */ Point & operator=(const Point & v) { x = v.x; y = v.y; return *this; } Point & operator+=(const Point & v) { x += v.x; y += v.y; return *this; } Point & operator-=(const Point & v) { x -= v.x; y -= v.y; return *this; } Point & operator*=(const double& a) { x*=a; y*=a; return *this; } Point & operator/=(const double& a) { x/=a; y/=a; return *this; } Point operator-() const { return Point(-x, -y); } Point operator+(const Point& p){ return Point(x + p.x, y + p.y); } Point operator*(const double& a) const { return Point(x * a, y * a); } Point operator/(const double& a){ return Point(x / a, y / a); } /* some insane operators */ double operator&(const Point p){ return x*p.x + y*p.y; } double operator^(const Point p){ return x*p.y - y*p.x; } double modulus() const {return Sqrt(Sqr(x) + Sqr(y)); } double manhat() const {return Abs(x) + Abs(y); } double modulusTo(const Point& p) const { return Sqrt(Sqr(x - p.x) + Sqr(y - p.y)); } double manhatTo(const Point& p) const { return Abs(x - p.x) + Abs(y - p.y); } virtual double distance(const Point& p) const { return modulusTo(p); } void turn () { double t = -x; x = y; y = t; } void turn_() { double t = x; x = -y; y = t; } Point turned(){ return Point(y, -x); } Point turned_(){return Point(-y, x); } void normalize(){ (*this) /= modulus(); } Point normalized(){ Point p = *this; return p / modulus(); } template<class TArchive> void linkArchive(TArchive & ar, const int v=0) { ar & nvp("x", x) & nvp("y", y); } }; Point operator-(const Point & p1, const Point& p); Point operator*(const double& a, const Point& p); double distance(const Point& p1, const Point& p2); } #endif /*POINT_H_*/
[ "aduha@24cd95de-1f16-0410-a8f5-8c352942cd3e" ]
[ [ [ 1, 107 ] ] ]
24d020ff08402b77737fcde2ebe60bf7dd7a9efc
c82ae5a5c899298a3155fd6d4b46be2638df41e9
/utchallenge.h
848e2b0be4e7c9496bfe3574fa1de45576b26246
[]
no_license
toslunar/UTyping
5a4e3ab46d218ab27fd2c2bcc635c5f792ccbc49
1b2eff072bda776ae4d7091f39d0c440f45d2727
refs/heads/master
2023-08-17T09:59:34.132597
2010-01-05T11:06:39
2010-01-05T11:06:39
412,716,324
3
1
null
null
null
null
SHIFT_JIS
C++
false
false
3,858
h
#ifndef __UTYPING_CHALLENGE #define __UTYPING_CHALLENGE #include "ututil.h" enum{ CHALLENGE_HIDDEN, /* 隠れるの */ CHALLENGE_SUDDEN, /* 突然現れるの */ CHALLENGE_STEALTH, /* 見えないの */ CHALLENGE_LYRICS_STEALTH, /* 歌詞が見えないの */ CHALLENGE_SIN, CHALLENGE_COS, CHALLENGE_TAN, CHALLENGE_NUM }; class CChallenge{ public: CChallenge(); void invalidate(); bool isEasy(); void reset(); void set(int pos); void reset(int pos); void flip(int pos); bool test(int pos)const; void speedUp(); void speedDown(); double speed()const; /* 流れる速さの標準との比を返す */ void keyUp(); void keyDown(); int key()const; double frequencyRate()const; /* 周波数が何倍されるか */ void getStr(char *buf)const; void read(FILE *fp); void write(FILE *fp)const; bool operator ==(CChallenge &challenge)const{ return m_isValid && challenge.m_isValid && (m_flags == challenge.m_flags && m_key == challenge.m_key); /* どちらかも有効で、speed以外の項目が等しいとき */ } private: bool m_isValid; bitset<CHALLENGE_NUM> m_flags; int m_speed; /* 円が流れる速さの標準との比の10倍(intでもつため) */ int m_key; }; CChallenge::CChallenge(){ reset(); } void CChallenge::invalidate(){ m_isValid = false; } bool CChallenge::isEasy(){ if(m_key < 0){ /* 再生速度を遅くした */ return true; } return false; } void CChallenge::reset(){ m_isValid = true; m_flags.reset(); m_speed = 10; m_key = 0; } void CChallenge::set(int pos){ m_flags.set(pos); } void CChallenge::reset(int pos){ m_flags.reset(pos); } void CChallenge::flip(int pos){ m_flags.flip(pos); } bool CChallenge::test(int pos)const{ return m_flags.test(pos); } void CChallenge::speedUp(){ if(m_speed < 20){ m_speed++; }else if(m_speed < 30){ m_speed += 2; }else if(m_speed < 40){ m_speed += 5; } } void CChallenge::speedDown(){ if(m_speed > 30){ m_speed -= 5; }else if(m_speed > 20){ m_speed -= 2; }else if(m_speed > 5){ m_speed--; } } double CChallenge::speed()const{ return m_speed / 10.0; } void CChallenge::keyUp(){ if(m_key < 12){ m_key++; } } void CChallenge::keyDown(){ if(m_key > -12){ m_key--; } } int CChallenge::key()const{ return m_key; } double CChallenge::frequencyRate()const{ return pow(2.0, m_key / 12.0); } void CChallenge::getStr(char *buf)const{ if(!m_isValid){ strcpy(buf, "----"); return; } strcpy(buf, ""); { char tmp[64]; sprintf(tmp, "x%.1f", speed()); strcat(buf, tmp); } if(test(CHALLENGE_SUDDEN)){ strcat(buf, "S"); } if(test(CHALLENGE_HIDDEN)){ strcat(buf, "H"); } if(test(CHALLENGE_STEALTH)){ strcat(buf, "C"); } if(test(CHALLENGE_LYRICS_STEALTH)){ strcat(buf, "L"); } if(m_key != 0){ char tmp[64]; sprintf(tmp, "%+d", m_key); strcat(buf, tmp); } if(test(CHALLENGE_SIN)){ strcat(buf, "s"); } if(test(CHALLENGE_COS)){ strcat(buf, "c"); } if(test(CHALLENGE_TAN)){ strcat(buf, "t"); } } void CChallenge::read(FILE *fp){ reset(); for(int i=0; i<CHALLENGE_NUM; i++){ if(getc(fp)){ set(i); } } for(int i=CHALLENGE_NUM; i<16; i++){ getc(fp); } readInt(m_speed, fp); readInt(m_key, fp); if(m_speed == 0){ /* 無効なときはすべて0なので、これを見ればOK */ m_isValid = false; }else{ m_isValid = true; } } void CChallenge::write(FILE *fp)const{ if(m_isValid){ for(int i=0; i<CHALLENGE_NUM; i++){ putc(test(i)?1:0, fp); } for(int i=CHALLENGE_NUM; i<16; i++){ putc(0, fp); } writeInt(m_speed, fp); writeInt(m_key, fp); }else{ for(int i=0; i<24; i++){ putc(0, fp); } } } #endif
[ [ [ 1, 215 ] ] ]
a2d1634856b8aafaeb728413ea92ccc4cc5f8372
b73f27ba54ad98fa4314a79f2afbaee638cf13f0
/projects/FilterSetting/ScreenSave.cpp
da3ea781a02af6c21f6ff0e33eb040360d0a5944
[]
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
WINDOWS-1252
C++
false
false
2,376
cpp
// ScreenSave.cpp : CScreenshotRecord µÄʵÏÖ #include "stdafx.h" #include ".\screensave.h" #include "globalvariable.h" #include <apputility\apputility.h> #include <typeconvert.h> // CScreenshotRecord STDMETHODIMP CScreenshotRecord::InterfaceSupportsErrorInfo(REFIID riid) { static const IID* arr[] = { &IID_IScreenSave }; for (INT_PTR i=0; i < sizeof(arr) / sizeof(arr[0]); i++) { if (InlineIsEqualGUID(*arr[i],riid)) return S_OK; } return S_FALSE; } STDMETHODIMP CScreenshotRecord::enableScreenSave(VARIANT_BOOL enabled) { g_configuration.getScreenshotSetting()->enable(convert(enabled)); return S_OK; } STDMETHODIMP CScreenshotRecord::setTimeSpan(LONG seconds) { g_configuration.getScreenshotSetting()->setTimeSpan(seconds); return S_OK; } STDMETHODIMP CScreenshotRecord::getTimeSpan(LONG* secs) { *secs = g_configuration.getScreenshotSetting()->getTimeSpan(); return S_OK; } STDMETHODIMP CScreenshotRecord::isEnabled(VARIANT_BOOL* enabled) { *enabled = convert(g_configuration.getScreenshotSetting()->isEnabled()); return S_OK; } STDMETHODIMP CScreenshotRecord::ClearCache(void) { ClearScreen(); return S_OK; } STDMETHODIMP CScreenshotRecord::getAutoClearSpan(LONG* days) { *days = g_configuration.getScreenshotAutoClean()->getTimespan(); return S_OK; } STDMETHODIMP CScreenshotRecord::setAutoClearTimespan(LONG days) { g_configuration.getScreenshotAutoClean()->setTimespan(days); return S_OK; } STDMETHODIMP CScreenshotRecord::get_AutocleanEnabled(VARIANT_BOOL* pVal) { *pVal = convert(g_configuration.getScreenshotAutoClean()->isEnabled()); return S_OK; } STDMETHODIMP CScreenshotRecord::put_AutocleanEnabled(VARIANT_BOOL newVal) { g_configuration.getScreenshotAutoClean()->enable(convert(newVal)); return S_OK; } STDMETHODIMP CScreenshotRecord::isSettingEnabled(VARIANT_BOOL* enabled) { *enabled = convert(g_configuration.getScreenshotSetting()->isSettingEnabled()); return S_OK; } STDMETHODIMP CScreenshotRecord::enableAutoClear(VARIANT_BOOL enabled) { g_configuration.getScreenshotAutoClean()->enable(convert(enabled)); return S_OK; } STDMETHODIMP CScreenshotRecord::isAutoClearEnabled(VARIANT_BOOL* enabled) { *enabled = convert(g_configuration.getScreenshotAutoClean()->isSettingEnabled()); return S_OK; }
[ "[email protected]", "ynkhpp@1a8edc88-4151-0410-b40c-1915dda2b29b" ]
[ [ [ 1, 1 ], [ 6, 7 ], [ 9, 9 ], [ 11, 11 ], [ 18, 18 ], [ 26, 27 ], [ 31, 32 ], [ 36, 43 ], [ 47, 48 ], [ 52, 60 ], [ 63, 95 ] ], [ [ 2, 5 ], [ 8, 8 ], [ 10, 10 ], [ 12, 17 ], [ 19, 25 ], [ 28, 30 ], [ 33, 35 ], [ 44, 46 ], [ 49, 51 ], [ 61, 62 ] ] ]
04885eb4ed6f76eabe508b01ed9d53973b7dfb8c
d425cf21f2066a0cce2d6e804bf3efbf6dd00c00
/Utils/Animated ProgressBar.cpp
2de88ebd81edbb9d4efee0c9f33256d83ab4105d
[]
no_license
infernuslord/ja2
d5ac783931044e9b9311fc61629eb671f376d064
91f88d470e48e60ebfdb584c23cc9814f620ccee
refs/heads/master
2021-01-02T23:07:58.941216
2011-10-18T09:22:53
2011-10-18T09:22:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,340
cpp
#ifdef PRECOMPILEDHEADERS #include "Utils All.h" #else #include "types.h" #include "Animated ProgressBar.h" #include "MemMan.h" #include "debug.h" #include "Font Control.h" #include "vsurface.h" #include "video.h" #include "Render Dirty.h" #include "music control.h" #include "Timer Control.h" #include "sysutil.h" #include "math.h" #endif double rStart, rEnd; double rActual; #define MAX_PROGRESSBARS 4 PROGRESSBAR *pBar[ MAX_PROGRESSBARS ]; UINT16 gusLeftmostShaded = 0; extern BOOLEAN bShowSmallImage; void CreateLoadingScreenProgressBar() { gusLeftmostShaded = 162; // Special case->show small image centered if (bShowSmallImage == TRUE) { if (iResolution > 0) { CreateProgressBar(0, iScreenWidthOffset + 162, iScreenHeightOffset + 427, iScreenWidthOffset + 480, iScreenHeightOffset + 443); } } else { if (iResolution == 0) { CreateProgressBar(0, 162, 427, 480, 443); } else if (iResolution == 1) { CreateProgressBar(0, 202, 533, 600, 554); } else if (iResolution == 2) { CreateProgressBar(0, 259, 683, 767, 708); } } SetProgressBarUseBorder(0, FALSE ); } void RemoveLoadingScreenProgressBar() { RemoveProgressBar( 0 ); SetFontShadow(DEFAULT_SHADOW); } // OJW - 20090422 void CreateProgressBarNoBorder( UINT8 ubProgressBarID, UINT16 usLeft, UINT16 usTop, UINT16 usRight, UINT16 usBottom ) { CreateProgressBar( ubProgressBarID, usLeft, usTop, usRight, usBottom ); SetProgressBarUseBorder( ubProgressBarID, FALSE ); } //This creates a single progress bar given the coordinates without a panel (containing a title and background). //A panel is automatically created if you specify a title using SetProgressBarTitle BOOLEAN CreateProgressBar( UINT8 ubProgressBarID, UINT16 usLeft, UINT16 usTop, UINT16 usRight, UINT16 usBottom ) { PROGRESSBAR *pNew; //Allocate new progress bar pNew = (PROGRESSBAR*)MemAlloc( sizeof( PROGRESSBAR ) ); Assert( pNew ); if( pBar[ ubProgressBarID ] ) RemoveProgressBar( ubProgressBarID ); memset( pNew, 0, sizeof( PROGRESSBAR ) ); pBar[ ubProgressBarID ] = pNew; pNew->ubProgressBarID = ubProgressBarID; //Assign coordinates pNew->usBarLeft = usLeft; pNew->usBarTop = usTop; pNew->usBarRight = usRight; pNew->usBarBottom = usBottom; //Init default data pNew->fPanel = FALSE; pNew->usMsgFont = (UINT16)FONT12POINT1; pNew->ubMsgFontForeColor = FONT_BLACK; pNew->ubMsgFontShadowColor = 0; SetRelativeStartAndEndPercentage( pNew->ubProgressBarID, 0, 100, NULL ); pNew->swzTitle = NULL; //Default the progress bar's color to be red pNew->ubColorFillRed = 150; pNew->ubColorFillGreen = 0; pNew->ubColorFillBlue = 0; pNew->fDisplayText = FALSE; //OJW - 20090222 pNew->uiFrameBuffer = FRAME_BUFFER; pNew->fDrawBorder = TRUE; return TRUE; } //You may also define a panel to go in behind the progress bar. You can now assign a title to go with //the panel. void DefineProgressBarPanel( UINT32 ubID, UINT8 r, UINT8 g, UINT8 b, UINT16 usLeft, UINT16 usTop, UINT16 usRight, UINT16 usBottom ) { PROGRESSBAR *pCurr; Assert( ubID < MAX_PROGRESSBARS ); pCurr = pBar[ ubID ]; if( !pCurr ) return; pCurr->fPanel = TRUE; pCurr->usPanelLeft = usLeft; pCurr->usPanelTop = usTop; pCurr->usPanelRight = usRight; pCurr->usPanelBottom = usBottom; pCurr->usColor = Get16BPPColor( FROMRGB( r, g, b ) ); //Calculate the slightly lighter and darker versions of the same rgb color pCurr->usLtColor = Get16BPPColor( FROMRGB( (UINT8)min( 255, (UINT16)(r*1.33)), (UINT8)min( 255, (UINT16)(g*1.33)), (UINT8)min( 255, (UINT16)(b*1.33)) )); pCurr->usDkColor = Get16BPPColor( FROMRGB( (UINT8)(r*0.75), (UINT8)(g*0.75), (UINT8)(b*0.75) ) ); } //Assigning a title for the panel will automatically position the text horizontally centered on the //panel and vertically centered from the top of the panel, to the top of the progress bar. void SetProgressBarTitle( UINT32 ubID, STR16 pString, UINT32 usFont, UINT8 ubForeColor, UINT8 ubShadowColor ) { PROGRESSBAR *pCurr; Assert( ubID < MAX_PROGRESSBARS ); pCurr = pBar[ ubID ]; if( !pCurr ) return; if( pCurr->swzTitle ) { MemFree( pCurr->swzTitle ); pCurr->swzTitle = NULL; } if( pString && wcslen( pString ) ) { pCurr->swzTitle = (STR16) MemAlloc( (UINT32) ( sizeof( CHAR16 ) * ( wcslen( pString ) + 1 ) ) ); swprintf( pCurr->swzTitle, pString ); } pCurr->usTitleFont = (UINT16)usFont; pCurr->ubTitleFontForeColor = ubForeColor; pCurr->ubTitleFontShadowColor = ubShadowColor; } //Unless you set up the attributes, any text you pass to SetRelativeStartAndEndPercentage will //default to FONT12POINT1 in a black color. void SetProgressBarMsgAttributes( UINT32 ubID, UINT32 usFont, UINT8 ubForeColor, UINT8 ubShadowColor ) { PROGRESSBAR *pCurr; Assert( ubID < MAX_PROGRESSBARS ); pCurr = pBar[ ubID ]; if( !pCurr ) return; pCurr->usMsgFont = (UINT16)usFont; pCurr->ubMsgFontForeColor = ubForeColor; pCurr->ubMsgFontShadowColor = ubShadowColor; } //OJW - 20090422 void SetProgressBarRenderBuffer( UINT32 ubID , UINT32 uiBufferID ) { PROGRESSBAR *pCurr; Assert( ubID < MAX_PROGRESSBARS ); pCurr = pBar[ ubID ]; if( !pCurr ) return; pCurr->uiFrameBuffer = uiBufferID; } void SetProgressBarUseBorder( UINT32 ubID , BOOLEAN bBorder ) { PROGRESSBAR *pCurr; Assert( ubID < MAX_PROGRESSBARS ); pCurr = pBar[ ubID ]; if( !pCurr ) return; pCurr->fDrawBorder = bBorder; } //When finished, the progress bar needs to be removed. void RemoveProgressBar( UINT8 ubID ) { Assert( ubID < MAX_PROGRESSBARS ); if( pBar[ubID] ) { if( pBar[ubID]->swzTitle ) MemFree( pBar[ubID]->swzTitle ); MemFree( pBar[ubID] ); pBar[ubID] = NULL; return; } } //An important setup function. The best explanation is through example. The example being the loading //of a file -- there are many stages of the map loading. In JA2, the first step is to load the tileset. //Because it is a large chunk of the total loading of the map, we may gauge that it takes up 30% of the //total load. Because it is also at the beginning, we would pass in the arguments ( 0, 30, "text" ). //As the process animates using UpdateProgressBar( 0 to 100 ), the total progress bar will only reach 30% //at the 100% mark within UpdateProgressBar. At that time, you would go onto the next step, resetting the //relative start and end percentage from 30 to whatever, until your done. void SetRelativeStartAndEndPercentage( UINT8 ubID, UINT16 uiRelStartPerc, UINT16 uiRelEndPerc, STR16 str) { PROGRESSBAR *pCurr; UINT16 usStartX, usStartY; Assert( ubID < MAX_PROGRESSBARS ); pCurr = pBar[ ubID ]; if( !pCurr ) return; pCurr->rStart = (double)uiRelStartPerc*0.01f; pCurr->rEnd = (double)uiRelEndPerc*0.01f; //Render the entire panel now, as it doesn't need update during the normal rendering if( pCurr->fPanel ) { //Draw panel ColorFillVideoSurfaceArea( FRAME_BUFFER, pCurr->usPanelLeft, pCurr->usPanelTop, pCurr->usPanelRight, pCurr->usPanelBottom, pCurr->usLtColor ); ColorFillVideoSurfaceArea( FRAME_BUFFER, pCurr->usPanelLeft+1, pCurr->usPanelTop+1, pCurr->usPanelRight, pCurr->usPanelBottom, pCurr->usDkColor ); ColorFillVideoSurfaceArea( FRAME_BUFFER, pCurr->usPanelLeft+1, pCurr->usPanelTop+1, pCurr->usPanelRight-1, pCurr->usPanelBottom-1, pCurr->usColor ); InvalidateRegion( pCurr->usPanelLeft, pCurr->usPanelTop, pCurr->usPanelRight, pCurr->usPanelBottom ); //Draw title if( pCurr->swzTitle ) { usStartX = pCurr->usPanelLeft + // left position (pCurr->usPanelRight - pCurr->usPanelLeft)/2 - // + half width StringPixLength( pCurr->swzTitle, pCurr->usTitleFont ) / 2; // - half string width usStartY = pCurr->usPanelTop + 3; SetFont( pCurr->usTitleFont ); SetFontForeground( pCurr->ubTitleFontForeColor ); SetFontShadow( pCurr->ubTitleFontShadowColor ); SetFontBackground( 0 ); mprintf( usStartX, usStartY, pCurr->swzTitle ); } } if( pCurr->fDisplayText ) { //Draw message if( str ) { if( pCurr->fUseSaveBuffer ) { UINT16 usFontHeight = GetFontHeight( pCurr->usMsgFont ); RestoreExternBackgroundRect( pCurr->usBarLeft, pCurr->usBarBottom, (INT16)(pCurr->usBarRight-pCurr->usBarLeft), (INT16)(usFontHeight + 3) ); } SetFont( pCurr->usMsgFont ); SetFontForeground( pCurr->ubMsgFontForeColor ); SetFontShadow( pCurr->ubMsgFontShadowColor ); SetFontBackground( 0 ); mprintf( pCurr->usBarLeft, pCurr->usBarBottom + 3, str ); } } } //This part renders the progress bar at the percentage level that you specify. If you have set relative //percentage values in the above function, then the uiPercentage will be reflected based off of the relative //percentages. void RenderProgressBar( UINT8 ubID, UINT32 uiPercentage ) { static UINT32 uiLastTime = 0; UINT32 uiCurTime = GetJA2Clock(); double rActual; PROGRESSBAR *pCurr=NULL; //UINT32 r, g; INT32 end; Assert( ubID < MAX_PROGRESSBARS ); pCurr = pBar[ubID]; if( pCurr == NULL ) return; if( pCurr ) { rActual = pCurr->rStart+(pCurr->rEnd-pCurr->rStart)*uiPercentage*0.01; if( fabs(rActual - pCurr->rLastActual) < 0.01 ) { return; } pCurr->rLastActual = ( DOUBLE )( ( INT32)( rActual * 100 ) * 0.01 ); end = (INT32)(pCurr->usBarLeft+2.0+rActual*(pCurr->usBarRight-pCurr->usBarLeft-4)); if( end < pCurr->usBarLeft+2 || end > pCurr->usBarRight-2 ) { return; } if( !pCurr->fDrawBorder ) { ColorFillVideoSurfaceArea( pCurr->uiFrameBuffer, //FRAME_BUFFER, pCurr->usBarLeft, pCurr->usBarTop, end, pCurr->usBarBottom, Get16BPPColor(FROMRGB( pCurr->ubColorFillRed, pCurr->ubColorFillGreen, pCurr->ubColorFillBlue )) ); //if( pCurr->usBarRight > gusLeftmostShaded ) //{ // ShadowVideoSurfaceRect( FRAME_BUFFER, gusLeftmostShaded+1, pCurr->usBarTop, end, pCurr->usBarBottom ); // gusLeftmostShaded = (UINT16)end; //} } else { //Border edge of the progress bar itself in gray ColorFillVideoSurfaceArea( pCurr->uiFrameBuffer, pCurr->usBarLeft, pCurr->usBarTop, pCurr->usBarRight, pCurr->usBarBottom, Get16BPPColor(FROMRGB(160, 160, 160)) ); //Interior of progress bar in black ColorFillVideoSurfaceArea( pCurr->uiFrameBuffer, pCurr->usBarLeft+2, pCurr->usBarTop+2, pCurr->usBarRight-2, pCurr->usBarBottom-2, Get16BPPColor(FROMRGB( 0, 0, 0)) ); ColorFillVideoSurfaceArea(pCurr->uiFrameBuffer, pCurr->usBarLeft+2, pCurr->usBarTop+2, end, pCurr->usBarBottom-2, Get16BPPColor(FROMRGB(72 , 155, 24))); } InvalidateRegion( pCurr->usBarLeft, pCurr->usBarTop, pCurr->usBarRight, pCurr->usBarBottom ); ExecuteBaseDirtyRectQueue(); EndFrameBufferRender(); RefreshScreen( NULL ); } // update music here if( uiCurTime > ( uiLastTime + 200 ) ) { MusicPoll( TRUE ); uiLastTime = GetJA2Clock(); } } void SetProgressBarColor( UINT8 ubID, UINT8 ubColorFillRed, UINT8 ubColorFillGreen, UINT8 ubColorFillBlue ) { PROGRESSBAR *pCurr=NULL; Assert( ubID < MAX_PROGRESSBARS ); pCurr = pBar[ubID]; if( pCurr == NULL ) return; pCurr->ubColorFillRed = ubColorFillRed; pCurr->ubColorFillGreen = ubColorFillGreen; pCurr->ubColorFillBlue = ubColorFillBlue; } void SetProgressBarTextDisplayFlag( UINT8 ubID, BOOLEAN fDisplayText, BOOLEAN fUseSaveBuffer, BOOLEAN fSaveScreenToFrameBuffer ) { PROGRESSBAR *pCurr=NULL; Assert( ubID < MAX_PROGRESSBARS ); pCurr = pBar[ubID]; if( pCurr == NULL ) return; pCurr->fDisplayText = fDisplayText; pCurr->fUseSaveBuffer = fUseSaveBuffer; //if we are to use the save buffer, blit the portion of the screen to the save buffer if( fSaveScreenToFrameBuffer ) { UINT16 usFontHeight = GetFontHeight( pCurr->usMsgFont )+3; //blit everything to the save buffer ( cause the save buffer can bleed through ) BlitBufferToBuffer(guiRENDERBUFFER, guiSAVEBUFFER, pCurr->usBarLeft, pCurr->usBarBottom, (UINT16)(pCurr->usBarRight-pCurr->usBarLeft), usFontHeight ); } }
[ "jazz_ja@b41f55df-6250-4c49-8e33-4aa727ad62a1" ]
[ [ [ 1, 395 ] ] ]
2268ca2001ca5befba62dd963ddd7f0f9b6e42dd
6bdb3508ed5a220c0d11193df174d8c215eb1fce
/Codes/Halak/Internal/GlyphSurface.h
73ca7fda1a6579e8ada360684a5ad44aa94d3668
[]
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
829
h
#pragma once #ifndef __HALAK_GLYPHSURFACE_H__ #define __HALAK_GLYPHSURFACE_H__ # include <Halak/FWD.h> # include <Halak/Rectangle.h> namespace Halak { class GlyphSurface { public: Rectangle Allocate(const void* buffer, int width, int height, int pitch); void Deallocate(const Rectangle& rectangle); const RectangleStorage& GetStorage() const; Texture2D* GetTexture() const; private: GlyphSurface(GraphicsDevice* graphicsDevice, int width, int height); ~GlyphSurface(); private: RectangleStorage* storage; DynamicTexture2DPtr texture; friend class GlyphTable; }; } #endif
[ [ [ 1, 31 ] ] ]
51975aecfbcd6fdfc19bd4c9ed9cbc66afc65797
d6a28d9d845a20463704afe8ebe644a241dc1a46
/tests/drawRectOutline.cpp
3a1150a8c8e4605a03e1047abc6e6cb6d3f2a6c8
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-other-permissive", "Zlib" ]
permissive
marky0720/irrlicht-android
6932058563bf4150cd7090d1dc09466132df5448
86512d871eeb55dfaae2d2bf327299348cc5202c
refs/heads/master
2021-04-30T08:19:25.297407
2010-10-08T08:27:33
2010-10-08T08:27:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,368
cpp
#include "testUtils.h" using namespace irr; bool testWithDriver(video::E_DRIVER_TYPE driverType) { IrrlichtDevice *device = createDevice(driverType, core::dimension2du(160, 120)); if (!device) return true; video::IVideoDriver* driver = device->getVideoDriver(); driver->beginScene(true, true, video::SColor(255,100,101,140)); core::recti r; r.UpperLeftCorner = core::position2di(1,1); r.LowerRightCorner = core::position2di(100,100); driver->draw2DRectangleOutline( r ); r += core::position2di( 10 , 10 ); driver->draw2DRectangleOutline( r , video::SColor(128, 255, 128, 128) ); driver->getMaterial2D().Thickness=12.f; driver->enableMaterial2D(); r += core::position2di( 10 , 10 ); driver->draw2DRectangleOutline( r , video::SColor(128, 255, 128, 128) ); driver->endScene(); bool result = takeScreenshotAndCompareAgainstReference(driver, "-drawRectOutline.png", 99.79f ); device->closeDevice(); device->run(); device->drop(); return result ; } bool drawRectOutline(void) { // TODO: Only OpenGL supports thick lines bool result = testWithDriver(video::EDT_BURNINGSVIDEO); result &= testWithDriver(video::EDT_DIRECT3D8); result &= testWithDriver(video::EDT_DIRECT3D9); result &= testWithDriver(video::EDT_OPENGL); result &= testWithDriver(video::EDT_SOFTWARE); return result; }
[ "hybrid@dfc29bdd-3216-0410-991c-e03cc46cb475" ]
[ [ [ 1, 49 ] ] ]
73fe62cc20efde79cdc8cd30c62636621c7358d2
d752d83f8bd72d9b280a8c70e28e56e502ef096f
/FugueDLL/Virtual Machine/Core Entities/Block.h
e00abaf2db5979244892d27053dca317e2231b68
[]
no_license
apoch/epoch-language.old
f87b4512ec6bb5591bc1610e21210e0ed6a82104
b09701714d556442202fccb92405e6886064f4af
refs/heads/master
2021-01-10T20:17:56.774468
2010-03-07T09:19:02
2010-03-07T09:19:02
34,307,116
0
0
null
null
null
null
UTF-8
C++
false
false
3,702
h
// // The Epoch Language Project // FUGUE Virtual Machine // // Class encapsulating a block of statements. // #pragma once // Dependencies #include "Virtual Machine/Core Entities/RValue.h" #include "Virtual Machine/Core Entities/Operation.h" // Forward declarations class HeapStorage; namespace VM { // Forward declarations class ScopeDescription; class ActivatedScope; // // Block of sequentially executed operations // class Block { // Destruction public: Block(bool deletescopes = true) : DeleteScopes(deletescopes), BoundScope(NULL) { } virtual ~Block(); // Execution interface public: virtual void ExecuteBlock(ExecutionContext& context, HeapStorage* heapstorage, bool enterscopes = true, unsigned skipinstructions = 0); // Operation-list interface public: void AddOperation(OperationPtr op); void InsertHeadOperation(OperationPtr op); void ReplaceOperationFromEnd(size_t numopsfromend, OperationPtr op, const VM::ScopeDescription& scope); void RemoveTailOperations(size_t numops); void RemoveOperationFromEnd(size_t numops, const ScopeDescription& scope); void ShiftUpTailOperation(size_t offset); void ShiftUpTailOperationGroup(size_t offset, const VM::ScopeDescription& scope); void ReverseTailOperations(size_t numops, const ScopeDescription& scope); OperationPtr PopTailOperation() { OperationPtr ret(Operations.back()); Operations.pop_back(); return ret; } Operation* GetTailOperation() { return *Operations.rbegin(); } Operation* GetOperationFromEnd(size_t numopsfromend, const ScopeDescription& scope); size_t GetNumOperations() const { return Operations.size(); } void EraseOperation(Operation* op); const std::vector<Operation*>& GetAllOperations() const { return Operations; } std::vector<Operation*>& GetAllOperations() { return Operations; } // Lexical scoping interface public: void BindToScope(ScopeDescription* scope) { BoundScope = scope; } const ScopeDescription* GetBoundScope() const { return BoundScope; } ScopeDescription* GetBoundScope() { return BoundScope; } void DoNotDeleteScope() { DeleteScopes = false; } // Traversal interface public: template <class TraverserT> void Traverse(TraverserT& traverser) { if(traverser.EnterBlock(*this)) { if(BoundScope) BoundScope->Traverse(traverser); for(std::vector<Operation*>::const_iterator iter = Operations.begin(); iter != Operations.end(); ++iter) { // We need to reset this every iteration so that the results of traversing // contained operations do not accidentally leave us in a different scope. if(BoundScope) traverser.SetCurrentScope(BoundScope); SelfAwareBase* op = dynamic_cast<SelfAwareBase*>(*iter); if(op) op->Traverse(traverser); else throw NotImplementedException("An operation class is not derived from SelfAware"); } traverser.ExitBlock(*this); } } template <class TraverserT> void TraverseExternal(TraverserT& traverser) const { traverser.EnterBlock(*this); if(BoundScope) BoundScope->TraverseExternal(traverser); for(std::vector<Operation*>::const_iterator iter = Operations.begin(); iter != Operations.end(); ++iter) (*iter)->TraverseExternal(traverser); traverser.ExitBlock(*this); } // Additional helpers public: size_t CountTailOps(size_t numops, const ScopeDescription& scope) const; // Internal storage private: std::vector<Operation*> Operations; ScopeDescription* BoundScope; bool DeleteScopes; }; }
[ "[email protected]", "don.apoch@localhost", "Mike Lewis@localhost" ]
[ [ [ 1, 40 ], [ 42, 45 ], [ 47, 50 ], [ 52, 81 ], [ 85, 95 ], [ 97, 97 ], [ 114, 117 ], [ 119, 139 ] ], [ [ 41, 41 ], [ 46, 46 ], [ 51, 51 ], [ 82, 84 ], [ 96, 96 ], [ 99, 113 ], [ 118, 118 ] ], [ [ 98, 98 ] ] ]
301c0e5bcc95cf77ec9bc548c29db5602a630bd4
c8f467a4cee0b4067b93936574c884c9de0b36cf
/source/Irrlicht/CGUIButton.cpp
fc0130d91e43d7b98d22fa4b7d90ccd49db29181
[ "LicenseRef-scancode-unknown-license-reference", "Zlib", "LicenseRef-scancode-other-permissive" ]
permissive
flaithbheartaigh/mirrlicht
1ff418d29017e55e5f4a27a70dcfd5a88cb244b5
ccc16e8f5465fb72e81ae986e56ef2e4c3e7654b
refs/heads/master
2021-01-10T11:29:49.569701
2009-01-12T21:08:31
2009-01-12T21:08:31
49,994,212
0
0
null
null
null
null
UTF-8
C++
false
false
10,878
cpp
// Copyright (C) 2002-2007 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #include "CGUIButton.h" #include "IGUISkin.h" #include "IGUIEnvironment.h" #include "IVideoDriver.h" #include "IGUIFont.h" #include "os.h" namespace irr { namespace gui { //! constructor CGUIButton::CGUIButton(IGUIEnvironment* environment, IGUIElement* parent, s32 id, core::rect<s32> rectangle, bool noclip) : IGUIButton(environment, parent, id, rectangle), Pressed(false), IsPushButton(false), UseAlphaChannel(false), Border(true), MouseOverTime(0), FocusTime(0), ClickTime(0), SpriteBank(0), OverrideFont(0), Image(0), PressedImage(0) { #ifdef _DEBUG setDebugName("CGUIButton"); #endif setNotClipped(noclip); // reset sprites for (u32 i=0; i<EGBS_COUNT; ++i) ButtonSprites[i].Index = -1; } //! destructor CGUIButton::~CGUIButton() { if (OverrideFont) OverrideFont->drop(); if (Image) Image->drop(); if (PressedImage) PressedImage->drop(); if (SpriteBank) SpriteBank->drop(); } //! Sets if the button should use the skin to draw its border void CGUIButton::setDrawBorder(bool border) { Border = border; } void CGUIButton::setSpriteBank(IGUISpriteBank* sprites) { if (sprites) sprites->grab(); if (SpriteBank) SpriteBank->drop(); SpriteBank = sprites; } void CGUIButton::setSprite(EGUI_BUTTON_STATE state, s32 index, video::SColor color, bool loop) { if (SpriteBank) { ButtonSprites[(u32)state].Index = index; ButtonSprites[(u32)state].Color = color; ButtonSprites[(u32)state].Loop = loop; } else { ButtonSprites[(u32)state].Index = -1; } } //! called if an event happened. bool CGUIButton::OnEvent(SEvent event) { if (!IsEnabled) return Parent ? Parent->OnEvent(event) : false; switch(event.EventType) { case EET_KEY_INPUT_EVENT: if (event.KeyInput.PressedDown && (event.KeyInput.Key == KEY_RETURN || event.KeyInput.Key == KEY_SPACE)) { if (!IsPushButton) setPressed(true); else setPressed(!Pressed); return true; } else if (!event.KeyInput.PressedDown && Pressed && (event.KeyInput.Key == KEY_RETURN || event.KeyInput.Key == KEY_SPACE)) { Environment->removeFocus(this); if (!IsPushButton) setPressed(false); if (Parent) { SEvent newEvent; newEvent.EventType = EET_GUI_EVENT; newEvent.GUIEvent.Caller = this; newEvent.GUIEvent.EventType = EGET_BUTTON_CLICKED; Parent->OnEvent(newEvent); } return true; } break; case EET_GUI_EVENT: if (event.GUIEvent.EventType == EGET_ELEMENT_FOCUS_LOST) { if (event.GUIEvent.Caller == (IGUIElement*) this && !IsPushButton) setPressed(false); } break; case EET_MOUSE_INPUT_EVENT: if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) { if (Environment->hasFocus(this) && !AbsoluteClippingRect.isPointInside(core::position2d<s32>(event.MouseInput.X, event.MouseInput.Y))) { Environment->removeFocus(this); return false; } if (!IsPushButton) setPressed(true); Environment->setFocus(this); return true; } else if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) { bool wasPressed = Pressed; Environment->removeFocus(this); if ( !AbsoluteClippingRect.isPointInside( core::position2d<s32>(event.MouseInput.X, event.MouseInput.Y ) ) ) { if (!IsPushButton) setPressed(false); return true; } if (!IsPushButton) setPressed(false); else { setPressed(!Pressed); } if ((!IsPushButton && wasPressed && Parent) || (IsPushButton && wasPressed != Pressed)) { SEvent newEvent; newEvent.EventType = EET_GUI_EVENT; newEvent.GUIEvent.Caller = this; newEvent.GUIEvent.EventType = EGET_BUTTON_CLICKED; Parent->OnEvent(newEvent); } return true; } break; } return Parent ? Parent->OnEvent(event) : false; } //! draws the element and its children void CGUIButton::draw() { if (!IsVisible) return; IGUISkin* skin = Environment->getSkin(); irr::video::IVideoDriver* driver = Environment->getVideoDriver(); IGUIFont* font = OverrideFont; if (!OverrideFont) font = skin->getFont(); core::rect<s32> rect = AbsoluteRect; // todo: move sprite up and text down if the pressed state has a sprite // draw sprites for focused and mouse-over core::position2di spritePos = AbsoluteRect.getCenter(); if (!Pressed) { if (Border) skin->draw3DButtonPaneStandard(this, rect, &AbsoluteClippingRect); if (Image) { core::position2d<s32> pos = AbsoluteRect.getCenter(); pos.X -= ImageRect.getWidth() / 2; pos.Y -= ImageRect.getHeight() / 2; driver->draw2DImage(Image, pos, ImageRect, &AbsoluteClippingRect, video::SColor(255,255,255,255), UseAlphaChannel); } if (SpriteBank && ButtonSprites[EGBS_BUTTON_UP].Index != -1) { // draw pressed sprite SpriteBank->draw2DSprite(ButtonSprites[EGBS_BUTTON_UP].Index, spritePos, &AbsoluteClippingRect, ButtonSprites[EGBS_BUTTON_UP].Color, ClickTime, os::Timer::getTime(), ButtonSprites[EGBS_BUTTON_UP].Loop, true); } } else { if (Border) skin->draw3DButtonPanePressed(this, rect, &AbsoluteClippingRect); if (PressedImage) { core::position2d<s32> pos = AbsoluteRect.getCenter(); pos.X -= PressedImageRect.getWidth() / 2; pos.Y -= PressedImageRect.getHeight() / 2; // patch by Alan Tyndall/Jonas Petersen if (Image == PressedImage) { pos.X += 1; pos.Y += 1; } driver->draw2DImage(PressedImage, pos, PressedImageRect, &AbsoluteClippingRect, video::SColor(255,255,255,255), UseAlphaChannel); } if (SpriteBank && ButtonSprites[EGBS_BUTTON_DOWN].Index != -1) { // draw sprite SpriteBank->draw2DSprite(ButtonSprites[EGBS_BUTTON_DOWN].Index, spritePos, &AbsoluteClippingRect, ButtonSprites[EGBS_BUTTON_DOWN].Color, ClickTime, os::Timer::getTime(), ButtonSprites[EGBS_BUTTON_DOWN].Loop, true); } } if (Text.size()) { rect = AbsoluteRect; if (Pressed) rect.UpperLeftCorner.Y += 2; if (font) font->draw(Text.c_str(), rect, skin->getColor(IsEnabled ? EGDC_BUTTON_TEXT : EGDC_GRAY_TEXT), true, true, &AbsoluteClippingRect); } IGUIElement::draw(); } //! sets another skin independent font. if this is set to zero, the button uses the font of the skin. void CGUIButton::setOverrideFont(IGUIFont* font) { if (OverrideFont) OverrideFont->drop(); OverrideFont = font; if (OverrideFont) OverrideFont->grab(); } //! Sets an image which should be displayed on the button when it is in normal state. void CGUIButton::setImage(video::ITexture* image) { if (Image) Image->drop(); Image = image; if (image) ImageRect = core::rect<s32>(core::position2d<s32>(0,0), image->getSize()); if (Image) Image->grab(); if (!PressedImage) setPressedImage(Image); } //! Sets an image which should be displayed on the button when it is in normal state. void CGUIButton::setImage(video::ITexture* image, const core::rect<s32>& pos) { if (Image) Image->drop(); Image = image; ImageRect = pos; if (Image) Image->grab(); if (!PressedImage) setPressedImage(Image, pos); } //! Sets an image which should be displayed on the button when it is in pressed state. void CGUIButton::setPressedImage(video::ITexture* image) { if (PressedImage) PressedImage->drop(); PressedImage = image; if (image) PressedImageRect = core::rect<s32>(core::position2d<s32>(0,0), image->getSize()); if (PressedImage) PressedImage->grab(); } //! Sets an image which should be displayed on the button when it is in pressed state. void CGUIButton::setPressedImage(video::ITexture* image, const core::rect<s32>& pos) { if (PressedImage) PressedImage->drop(); PressedImage = image; PressedImageRect = pos; if (PressedImage) PressedImage->grab(); } //! Sets if the button should behave like a push button. Which means it //! can be in two states: Normal or Pressed. With a click on the button, //! the user can change the state of the button. void CGUIButton::setIsPushButton(bool isPushButton) { IsPushButton = isPushButton; } //! Returns if the button is currently pressed bool CGUIButton::isPressed() { _IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX; return Pressed; } //! Sets the pressed state of the button if this is a pushbutton void CGUIButton::setPressed(bool pressed) { if (Pressed != pressed) { ClickTime = os::Timer::getTime(); Pressed = pressed; } } //! Sets if the alpha channel should be used for drawing images on the button (default is false) void CGUIButton::setUseAlphaChannel(bool useAlphaChannel) { UseAlphaChannel = useAlphaChannel; } //! Returns if the alpha channel should be used for drawing images on the button bool CGUIButton::getUseAlphaChannel() { return UseAlphaChannel; } //! Writes attributes of the element. void CGUIButton::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options=0) { IGUIButton::serializeAttributes(out,options); out->addBool ("PushButton", IsPushButton ); if (IsPushButton) out->addBool ("Pressed", Pressed); out->addTexture ("Image", Image); out->addRect ("ImageRect", ImageRect); out->addTexture ("PressedImage", PressedImage); out->addRect ("PressedImageRect",PressedImageRect); out->addBool ("Border", Border); out->addBool ("UseAlphaChannel", UseAlphaChannel); // out->addString ("OverrideFont", OverrideFont); } //! Reads attributes of the element void CGUIButton::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options=0) { IGUIButton::deserializeAttributes(in,options); IsPushButton = in->getAttributeAsBool("PushButton"); Pressed = IsPushButton ? in->getAttributeAsBool("Pressed") : false; core::rect<s32> rec = in->getAttributeAsRect("ImageRect"); if (rec.isValid()) setImage( in->getAttributeAsTexture("Image"), rec); else setImage( in->getAttributeAsTexture("Image") ); rec = in->getAttributeAsRect("PressedImageRect"); if (rec.isValid()) setPressedImage( in->getAttributeAsTexture("PressedImage"), rec); else setPressedImage( in->getAttributeAsTexture("PressedImage") ); setDrawBorder(in->getAttributeAsBool("Border")); UseAlphaChannel = in->getAttributeAsBool("UseAlphaChannel"); // setOverrideFont(in->getAttributeAsString("OverrideFont")); updateAbsolutePosition(); } } // end namespace gui } // end namespace irr
[ "limingchina@c8d24273-d621-0410-9a95-1b5ff033c8bf" ]
[ [ [ 1, 438 ] ] ]
dc3f3ee9ca47d7187b2ce6dc7b5b676ab2e4f6d2
db93a4d93dbeecef7a35d2b5c6833c1482b3fc63
/MastersThesis/Test/main.cpp
b81bbd253ae2fb5bc05f9e1c5b319b9f3bc980be
[]
no_license
schiappino/my-masters-thesis
d71bed348cfcd5587b7cb5b29b825eee4570ca01
b58c7e977c55ad90994d346cdbc23365c3439c9d
refs/heads/master
2021-01-10T04:06:25.661663
2011-12-01T22:21:47
2011-12-01T22:21:47
50,738,346
0
0
null
null
null
null
UTF-8
C++
false
false
319
cpp
#include <iostream> #include <opencv2/objdetect/objdetect.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> using namespace std; using namespace cv; int main() { Mat img = imread("../Data/images/lena.jpg", 1 ); imshow( "OpenCV window", img ); waitKey(); return 0; };
[ [ [ 1, 15 ] ] ]
a5b4353a8a1a8dfb277dbd86d2367cd0cc258afe
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ObjectDLL/ObjectShared/AIGoalObstruct.h
132b63ff53ae7dfdbbe1acbe24d8244888cebff8
[]
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
2,448
h
//---------------------------------------------------------------------------- // // MODULE: AIGoalObstruct.h // // PURPOSE: CAIGoalObstruct declaration // // CREATED: 11.12.2001 // // (c) 2001 Monolith Productions, Inc. All Rights Reserved // // // COMMENTS: - // // //---------------------------------------------------------------------------- #ifndef __AIGOALOBSTRUCT_H__ #define __AIGOALOBSTRUCT_H__ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 // Includes #include "AIGoalAbstractStimulated.h" #include "AINode.h" // Forward declarations // Globals // Statics //---------------------------------------------------------------------------- // // CLASS: CAIGoalObstruct // // PURPOSE: // //---------------------------------------------------------------------------- class CAIGoalObstruct : public CAIGoalAbstractStimulated { public: // Public members DECLARE_AI_FACTORY_CLASS_SPECIFIC(Goal, CAIGoalObstruct, kGoal_Obstruct); CAIGoalObstruct() {} // Save / Load virtual void Save(ILTMessage_Write *pMsg); virtual void Load(ILTMessage_Read *pMsg); // Activation. virtual void ActivateGoal(); // Updating. void UpdateGoal(); // Attractor Handling. virtual AINode* HandleGoalAttractors(); // Sense Handling. virtual LTBOOL HandleGoalSenseTrigger(AISenseRecord* pSenseRecord); protected: // Protected members // State Handling. void HandleStateObstruct(); int GetAttractorCount(); AINode* FindAndSetupNode(EnumAINodeType kNodeType); void SetLastStimulusSource(HOBJECT hStim); HOBJECT GetLastStimulusSource(void); void SetObstructNode(HOBJECT hNode); HOBJECT GetObstructNode(void); AINodeObstruct* GetObstructObject(void); void SetFailedNode(HOBJECT hNode); HOBJECT GetFailedNode(void); private: // Private members // Copy Constructor and Asignment Operator private to prevent // automatic generation and inappropriate, unintentional use // Intentionally left unimplemented. CAIGoalObstruct(const CAIGoalObstruct& rhs); CAIGoalObstruct& operator=(const CAIGoalObstruct& rhs ); // Save: LTObjRef m_hNodeObstruct; LTObjRef m_hNodeObstructFailed; // Don't Save: }; #endif // __AIGOALOBSTRUCT_H__
[ [ [ 1, 107 ] ] ]
624975f3496a386fe5c8fa762c2e90e61a630a3f
fec97339b4f90ddcc8d49d39c048140f05b2db6e
/barreldialog.h
62939cdaf31ba025157f21afaf50c91a13681257
[]
no_license
SirEOF/geomdef
55ea012b898029baaf60fae8fc236ca8ab855cfb
0e9508539703b697882df82c84fb92d34a3e3dff
refs/heads/master
2021-05-29T06:43:54.986200
2010-02-01T11:24:21
2010-02-01T11:24:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,083
h
////////////////////////////////////////////////////////////////////////////////// /// \file barreldialog.h /// \author Grzegorz Kurek /// \author [email protected] /// \version 1.0.1 /// \date 20-01-2010 /// \brief Deklaracja klasy bedacej oknem pomocniczym korekcji obiektywu. /////////////////////////////////////////////////////////////////////////////////// #ifndef BARRELDIALOG_H #define BARRELDIALOG_H #include <QDialog> #include <QImage> #include <QGraphicsScene> #include <QGraphicsItem> #include "ControllerXML.h" #include "interpolation.h" namespace Ui { class barreldialog; } //////////////////////////////////////////////////////////////////////////////// /// \class barreldialog /// \brief Klasa oodpowiedzialna za korekcje obiektywu /////////////////////////////////////////////////////////////////////////////// class barreldialog : public QDialog { Q_OBJECT public: ////////////////////////////////////////////////////////////////////////// /// barreldialog /// \brief Konstruktor przyjmujacy obrazek oraz rodzica /// \param img obrazek na ktorym zostana wykonane przeksztalcenia /// \param parent rodzic ///////////////////////////////////////////////////////////////////////// barreldialog(QImage *img,QWidget *parent = 0); ////////////////////////////////////////////////////////////////////////// /// barreldialog /// \brief Destruktor ///////////////////////////////////////////////////////////////////////// ~barreldialog(); protected: void changeEvent(QEvent *e); private: Ui::barreldialog *ui; ControllerXML *cxml; QGraphicsScene *scene; QImage image; Interpolation *interp; QRgb rgb; void clearScene(); private slots: void on_pushButton_2_clicked(); void on_pushButton_3_clicked(); void on_pushButton_clicked(); void setParamsSlot(); signals: void CloseSignalCancel(); void CloseSignalOk(qreal a,qreal b,qreal c,qreal d); }; #endif // BARRELDIALOG_H
[ "lukasz.madon@e2a736ec-deac-11de-b357-fb893c5a43fa" ]
[ [ [ 1, 73 ] ] ]
82d413acde90cb906dc87adb1b3c9a0712703968
823e34ee3931091af33fbac28b5c5683a39278e4
/WebServer/WebServerDlg.cpp
40246c8b2de2e3ea9b9354b45a2ca22198fccd58
[]
no_license
tangooricha/tangoorichas-design-for-graduation
aefdd0fdf0e8786308c22311f2598ad62b3f5be8
cf227651b9baa0deb5748a678553b145a3ce6803
refs/heads/master
2020-06-06T17:48:37.691814
2010-04-14T07:22:23
2010-04-14T07:22:23
34,887,842
0
0
null
null
null
null
UTF-8
C++
false
false
5,183
cpp
// WebServerDlg.cpp : implementation file // #include "stdafx.h" #include "WebServer.h" #include "WebServerDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CWebServerDlg dialog CWebServerDlg::CWebServerDlg(CWnd* pParent /*=NULL*/) : CDialog(CWebServerDlg::IDD, pParent) { //{{AFX_DATA_INIT(CWebServerDlg) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CWebServerDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CWebServerDlg) // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CWebServerDlg, CDialog) //{{AFX_MSG_MAP(CWebServerDlg) ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_BTN_START, OnBtnStart) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CWebServerDlg message handlers BOOL CWebServerDlg::OnInitDialog() { CDialog::OnInitDialog(); // 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 // TODO: Add extra initialization here return TRUE; // return TRUE unless you set the focus to a control } // 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 CWebServerDlg::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 CWebServerDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon; } void CWebServerDlg::OnBtnStart() { // TODO: Add your control notification handler code here CSocket sockSrv,sockConnect; int indexI,recvByteCounterCurrent,requestDataLength,httpMethodLength,requestPagePathLength,httpVersionLength; TCHAR recvBufferTmp[2048],recvBuffer[2048],*pRecvByteTmp,*pRecvByte,*pRecvByteCurrent,webPageFileContent[65536]; CString requestData,requestDataTmp,httpMethod,requestPagePath,httpVersion,webPage200,webPage404,sendData; CFileFind webPageFileFind; CFile webPageFile; DWORD webPageFileLength; pRecvByte=recvBuffer; pRecvByteCurrent=recvBuffer; sockSrv.Create(8080); sockSrv.Listen(); sockSrv.Accept(sockConnect); for(indexI=0;indexI!=1;) { recvByteCounterCurrent=0; pRecvByteTmp=recvBufferTmp; recvByteCounterCurrent=sockConnect.Receive(recvBufferTmp,2048); pRecvByteCurrent+=recvByteCounterCurrent; for(;pRecvByte!=pRecvByteCurrent;pRecvByteTmp++,pRecvByte++) { *pRecvByte=*pRecvByteTmp; if(*pRecvByte=='\r') { indexI=1; break; } } } pRecvByte++; *pRecvByte='\0'; requestData=recvBuffer; requestDataLength=requestData.GetLength(); requestDataTmp=requestData; httpMethodLength=requestData.Find(' '); requestDataTmp.Delete(httpMethodLength,requestDataLength-httpMethodLength); httpMethod=requestDataTmp; requestData.Delete(0,httpMethodLength+1); requestDataLength=requestData.GetLength(); requestDataTmp=requestData; requestPagePathLength=requestData.Find(' '); requestDataTmp.Delete(requestPagePathLength,requestDataLength-requestPagePathLength); requestPagePath=requestDataTmp; requestData.Delete(0,requestPagePathLength+1); requestDataLength=requestData.GetLength(); requestDataTmp=requestData; httpVersionLength=8; requestDataTmp.Delete(httpVersionLength,requestDataLength-httpVersionLength); httpVersion=requestDataTmp; webPage200=httpVersion+" 200 OK\t\nContent-Type: text/html; charset=UTF-8\t\nServer: Earthquake Web Server\t\n\t\n"; webPage404=httpVersion+" 404 Not Found"; requestPagePath.Replace('/','\\'); if(requestPagePath=='\\') { requestPagePath="\\index.html"; } if(webPageFileFind.FindFile(requestPagePath)) { webPageFile.Open(requestPagePath,CFile::modeRead|CFile::typeBinary); for(indexI=0;indexI<65536;indexI++) { webPageFileContent[indexI]='\0'; } webPageFileLength=webPageFile.GetLength(); webPageFile.Read(webPageFileContent,(UINT)webPageFileLength-1); sendData=webPage200+webPageFileContent; } else { sendData=webPage404; } sockConnect.Send(sendData,sendData.GetLength()); }
[ "[email protected]@91cf4698-544a-0410-9e3e-f171e2291419" ]
[ [ [ 1, 182 ] ] ]
465eaa0f276a0e3f28291c05e171f73ef7a27bb0
6581dacb25182f7f5d7afb39975dc622914defc7
/easyMule/easyMule/src/WorkLayer/otherfunctions.cpp
f7f1ab76eb002b42d5835d2cd3ae6c0ffd10a6d6
[]
no_license
dice2019/alexlabonline
caeccad28bf803afb9f30b9e3cc663bb2909cc4f
4c433839965ed0cff99dad82f0ba1757366be671
refs/heads/master
2021-01-16T19:37:24.002905
2011-09-21T15:20:16
2011-09-21T15:20:16
null
0
0
null
null
null
null
GB18030
C++
false
false
122,850
cpp
/* * $Id: otherfunctions.cpp 16576 2009-11-13 06:25:24Z huby $ * * this file is part of eMule * Copyright (C)2002-2006 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net ) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "stdafx.h" #include <sys/stat.h> #include <share.h> #include <io.h> #include <atlrx.h> #include <atlconv.h> //#include "emule.h" #include "OtherFunctions.h" #include "DownloadQueue.h" #include "Preferences.h" #include "PartFile.h" #include "SharedFileList.h" #include "KnownFileList.h" #include "UpDownClient.h" #include "Opcodes.h" #include "WebServices.h" #include <shlobj.h> #include "emuledlg.h" #include "MenuCmds.h" #include "ZipFile.h" #include "RarFile.h" #include <atlbase.h> #include "StringConversion.h" #include "shahashset.h" #include "collection.h" #include "SafeFile.h" #include "FileFormat.h" #include "Kademlia/Kademlia/kademlia.h" #include "kademlia/kademlia/UDPFirewallTester.h" #include "Imagehlp.h" //added by thilon on 2006.04.20 #include "resource.h" #include "GlobalVariable.h" #include "Util.h" #include "ED2KLink.h" #include "BetterSP2.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif CWebServices theWebServices; // Base chars for encode an decode functions static byte base16Chars[17] = "0123456789ABCDEF"; static byte base32Chars[33] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; #define BASE16_LOOKUP_MAX 23 static byte base16Lookup[BASE16_LOOKUP_MAX][2] = { { '0', 0x0 }, { '1', 0x1 }, { '2', 0x2 }, { '3', 0x3 }, { '4', 0x4 }, { '5', 0x5 }, { '6', 0x6 }, { '7', 0x7 }, { '8', 0x8 }, { '9', 0x9 }, { ':', 0x9 }, { ';', 0x9 }, { '<', 0x9 }, { '=', 0x9 }, { '>', 0x9 }, { '?', 0x9 }, { '@', 0x9 }, { 'A', 0xA }, { 'B', 0xB }, { 'C', 0xC }, { 'D', 0xD }, { 'E', 0xE }, { 'F', 0xF } }; CString CastItoXBytes(uint16 count, bool isK, bool isPerSec, uint32 decimal){ return CastItoXBytes((double)count, isK, isPerSec, decimal); } CString CastItoXBytes(uint32 count, bool isK, bool isPerSec, uint32 decimal){ return CastItoXBytes((double)count, isK, isPerSec, decimal); } CString CastItoXBytes(uint64 count, bool isK, bool isPerSec, uint32 decimal){ return CastItoXBytes((double)count, isK, isPerSec, decimal); } #if defined(_DEBUG) && defined(USE_DEBUG_EMFILESIZE) CString CastItoXBytes(EMFileSize count, bool isK, bool isPerSec, uint32 decimal){ return CastItoXBytes((double)count, isK, isPerSec, decimal); } #endif CString CastItoXBytes(float count, bool isK, bool isPerSec, uint32 decimal){ return CastItoXBytes((double)count, isK, isPerSec, decimal); } CString CastItoXBytes(double count, bool isK, bool isPerSec, uint32 decimal){ if( count <= 0.0 ) { if(isPerSec) return _T("0 ") + GetResString(IDS_BYTESPERSEC); else return _T("0 ") + GetResString(IDS_BYTES); } else if( isK ) { if( count > 1.7E+300 ) count = 1.7E+300; else count *= 1024.0; } CString buffer; if( isPerSec ) { if (count < 1024.0) buffer.Format(_T("%.0f %s"), count, GetResString(IDS_BYTESPERSEC)); else if (count < 1024000.0) buffer.Format(_T("%.*f %s"), decimal, count/1024.0, GetResString(IDS_KBYTESPERSEC)); else if (count < 1048576000.0) buffer.Format(_T("%.*f %s"), decimal, count/1048576.0, GetResString(IDS_MBYTESPERSEC)); else if (count < 1073741824000.0) buffer.Format(_T("%.*f %s"), decimal, count/1073741824.0, GetResString(IDS_GBYTESPERSEC)); else buffer.Format(_T("%.*f %s"), decimal, count/1099511627776.0, GetResString(IDS_TBYTESPERSEC)); } else { if (count < 1024.0) buffer.Format(_T("%.0f %s"), count, GetResString(IDS_BYTES)); else if (count < 1024000.0) buffer.Format(_T("%.*f %s"), decimal, count/1024.0, GetResString(IDS_KBYTES)); else if (count < 1048576000.0) buffer.Format(_T("%.*f %s"), decimal, count/1048576.0, GetResString(IDS_MBYTES)); else if (count < 1073741824000.0) buffer.Format(_T("%.*f %s"), decimal, count/1073741824.0, GetResString(IDS_GBYTES)); else buffer.Format(_T("%.*f %s"), decimal, count/1099511627776.0, GetResString(IDS_TBYTES)); } return buffer; } CString CastItoIShort(uint16 count, bool isK, uint32 decimal){ return CastItoIShort((double)count, isK, decimal); } CString CastItoIShort(uint32 count, bool isK, uint32 decimal){ return CastItoIShort((double)count, isK, decimal); } CString CastItoIShort(uint64 count, bool isK, uint32 decimal){ return CastItoIShort((double)count, isK, decimal); } CString CastItoIShort(float count, bool isK, uint32 decimal){ return CastItoIShort((double)count, isK, decimal); } CString CastItoIShort(double count, bool isK, uint32 decimal){ if( count <= 0.0 ) { return _T("0"); } else if( isK ) { if( count > 1.7E+300 ) count = 1.7E+300; else count *= 1000.0; } CString output; if (count < 1000.0) output.Format(_T("%.0f"), count); else if (count < 1000000.0) output.Format(_T("%.*f %s"), decimal, count/1000.0, GetResString(IDS_KILO)); else if (count < 1000000000.0) output.Format(_T("%.*f %s"), decimal, count/1000000.0, GetResString(IDS_MEGA)); else if (count < 1000000000000.0) output.Format(_T("%.*f %s"), decimal, count/1000000000.0, GetResString(IDS_GIGA)); else if (count < 1000000000000000.0) output.Format(_T("%.*f %s"), decimal, count/1000000000000.0, GetResString(IDS_TERRA)); return output; } CString CastSecondsToHM(time_t tSeconds) { if (tSeconds == -1) // invalid or unknown time value return _T("?"); CString buffer; UINT count = tSeconds; if (count < 60) buffer.Format(_T("%u %s"), count, GetResString(IDS_SECS)); else if (count < 3600) buffer.Format(_T("%u:%02u %s"), count/60, count - (count/60)*60, GetResString(IDS_MINS)); else if (count < 86400) buffer.Format(_T("%u:%02u %s"), count/3600, (count - (count/3600)*3600)/60, GetResString(IDS_HOURS)); else { UINT cntDays = count/86400; UINT cntHrs = (count - cntDays*86400)/3600; buffer.Format(_T("%u %s %u %s"), cntDays, GetResString(IDS_DAYS), cntHrs, GetResString(IDS_HOURS)); } return buffer; } CString CastSecondsToLngHM(time_t tSeconds) { if (tSeconds == -1) // invalid or unknown time value return _T("?"); CString buffer; UINT count = tSeconds; if (count < 60) buffer.Format(_T("%u %s"), count, GetResString(IDS_LONGSECS)); else if (count < 3600) buffer.Format(_T("%u:%02u %s"), count/60, count - (count/60)*60, GetResString(IDS_LONGMINS)); else if (count < 86400) buffer.Format(_T("%u:%02u %s"), count/3600, (count - (count/3600)*3600)/60, GetResString(IDS_LONGHRS)); else { UINT cntDays = count/86400; UINT cntHrs = (count - cntDays*86400)/3600; if (cntHrs) buffer.Format(_T("%u %s %u:%02u %s"), cntDays, GetResString(IDS_DAYS2), cntHrs, (count - (cntDays*86400) - (cntHrs*3600))/60, GetResString(IDS_LONGHRS)); else buffer.Format(_T("%u %s %u %s"), cntDays, GetResString(IDS_DAYS2), (count - (cntDays*86400) - (cntHrs*3600))/60, GetResString(IDS_LONGMINS)); } return buffer; } void ShellOpenFile(CString name) { ShellExecute(NULL, _T("open"), name, NULL, NULL, SW_SHOW); } void ShellOpenFile(CString name, LPCTSTR pszVerb) { ShellExecute(NULL, pszVerb, name, NULL, NULL, SW_SHOW); } namespace { bool IsHexDigit(int c) { switch (c) { case '0': return true; case '1': return true; case '2': return true; case '3': return true; case '4': return true; case '5': return true; case '6': return true; case '7': return true; case '8': return true; case '9': return true; case 'A': return true; case 'B': return true; case 'C': return true; case 'D': return true; case 'E': return true; case 'F': return true; case 'a': return true; case 'b': return true; case 'c': return true; case 'd': return true; case 'e': return true; case 'f': return true; default: return false; } } } CString URLDecode(const CString& inStr) { // decode escape sequences CString res; for (int x = 0; x < inStr.GetLength(); x++) { if (inStr.GetAt(x) == _T('%') && x + 2 < inStr.GetLength() && IsHexDigit(inStr.GetAt(x+1)) && IsHexDigit(inStr.GetAt(x+2))) { TCHAR hexstr[3]; _tcsncpy(hexstr, inStr.Mid(x+1, 2), 2); hexstr[2] = _T('\0'); x += 2; // Convert the hex to ASCII res.AppendChar((TCHAR)_tcstoul(hexstr, NULL, 16)); } else { res.AppendChar(inStr.GetAt(x)); } } return res; } CString URLEncode(const CString& sInT) { CStringA sIn(sInT); LPCSTR pInBuf = sIn; CString sOut; LPTSTR pOutBuf = sOut.GetBuffer(sIn.GetLength() * 3); if(pOutBuf) { // do encoding while (*pInBuf) { if (_ismbcalnum((BYTE)*pInBuf) || _mbschr((unsigned char *)"-_.", (BYTE)*pInBuf)) *pOutBuf++ = (BYTE)*pInBuf; else { *pOutBuf++ = _T('%'); *pOutBuf++ = toHex((BYTE)*pInBuf >> 4); *pOutBuf++ = toHex((BYTE)*pInBuf % 16); } pInBuf++; } *pOutBuf = _T('\0'); sOut.ReleaseBuffer(); } return sOut; } CString EncodeURLQueryParam(const CString& sInT) { CStringA sIn(sInT); LPCSTR pInBuf = sIn; // query = *uric // uric = reserved | unreserved | escaped // reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | "," // unreserved = alphanum | mark // mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")" // // See also: http://www.w3.org/MarkUp/html-spec/html-spec_8.html CString sOut; LPTSTR pOutBuf = sOut.GetBuffer(sIn.GetLength() * 3); if (pOutBuf) { // do encoding while (*pInBuf) { if (_ismbcalnum((BYTE)*pInBuf)) *pOutBuf++ = (BYTE)*pInBuf; else if (_ismbcspace((BYTE)*pInBuf)) *pOutBuf++ = _T('+'); else { *pOutBuf++ = _T('%'); *pOutBuf++ = toHex((BYTE)*pInBuf >> 4); *pOutBuf++ = toHex((BYTE)*pInBuf % 16); } pInBuf++; } *pOutBuf = _T('\0'); sOut.ReleaseBuffer(); } return sOut; } CString MakeStringEscaped(CString in) { in.Replace(_T("&"), _T("&&")); return in; } CString RemoveAmbersand(const CString& rstr) { CString str(rstr); str.Remove(_T('&')); return str; } bool HaveEd2kRegAccess() { CRegKey regkey; DWORD dwRegResult = regkey.Create(HKEY_CLASSES_ROOT, _T("ed2k\\shell\\open\\command")); regkey.Close(); return (dwRegResult == ERROR_SUCCESS); } bool Ask4RegFix(bool checkOnly, bool dontAsk, bool bAutoTakeCollections) { // Barry - Make backup first if (!checkOnly) BackupReg(); // check registry if ed2k links is assigned to easymule CRegKey regkey; if (regkey.Create(HKEY_CLASSES_ROOT, _T("ed2k\\shell\\open\\command")) == ERROR_SUCCESS) { TCHAR rbuffer[500]; ULONG maxsize = ARRSIZE(rbuffer); regkey.QueryStringValue(NULL, rbuffer, &maxsize); TCHAR modbuffer[490]; //MODIFIED by fengwen on 2007/02/27 <begin> : 如果存在Ed2kLoader.exe,则用Ed2kLoader.exe来处理ed2k //::GetModuleFileName(NULL, modbuffer, ARRSIZE(modbuffer)); _tcsncpy(modbuffer, GetAppDir(), 489); _tcscat(modbuffer, _T("\\Ed2kLoader.exe")); if (!PathFileExists(modbuffer)) ::GetModuleFileName(NULL, modbuffer, ARRSIZE(modbuffer)); //MODIFIED by fengwen on 2007/02/27 <end> : 如果存在Ed2kLoader.exe,则用Ed2kLoader.exe来处理ed2k CString strCanonFileName = modbuffer; strCanonFileName.Replace(_T("%"), _T("%%")); TCHAR regbuffer[520]; _sntprintf(regbuffer, ARRSIZE(regbuffer), _T("\"%s\" \"%%1\""), strCanonFileName); if (_tcsicmp(rbuffer, regbuffer) != 0) { if (checkOnly) return true; if (dontAsk || (AfxMessageBox(GetResString(IDS_ASSIGNED2K), MB_ICONQUESTION|MB_YESNO) == IDYES)) { regkey.SetStringValue(NULL, regbuffer); regkey.Create(HKEY_CLASSES_ROOT, _T("ed2k\\DefaultIcon")); regkey.SetStringValue(NULL, modbuffer); regkey.Create(HKEY_CLASSES_ROOT, _T("ed2k")); regkey.SetStringValue(NULL, _T("URL: ed2k Protocol")); regkey.SetStringValue(_T("URL Protocol"), _T("")); regkey.Open(HKEY_CLASSES_ROOT, _T("ed2k\\shell\\open")); regkey.RecurseDeleteKey(_T("ddexec")); regkey.RecurseDeleteKey(_T("ddeexec")); } } else { regkey.Open(HKEY_CLASSES_ROOT, _T("ed2k\\shell\\open")); regkey.RecurseDeleteKey(_T("ddexec")); regkey.RecurseDeleteKey(_T("ddeexec")); } if (bAutoTakeCollections) DoCollectionRegFix(false); regkey.Close(); } if (checkOnly) return DoCollectionRegFix(true); else return false; } void BackupReg(void) { // Look for pre-existing old ed2k links CRegKey regkey; if (regkey.Create(HKEY_CLASSES_ROOT, _T("ed2k\\shell\\open\\command")) == ERROR_SUCCESS) { TCHAR rbuffer[500]; ULONG maxsize = ARRSIZE(rbuffer); // Is it ok to write new values if ((regkey.QueryStringValue(_T("OldDefault"), rbuffer, &maxsize) != ERROR_SUCCESS) || (maxsize == 0)) { maxsize = ARRSIZE(rbuffer); if ( regkey.QueryStringValue(NULL, rbuffer, &maxsize) == ERROR_SUCCESS ) regkey.SetStringValue(_T("OldDefault"), rbuffer); regkey.Create(HKEY_CLASSES_ROOT, _T("ed2k\\DefaultIcon")); maxsize = ARRSIZE(rbuffer); if (regkey.QueryStringValue(NULL, rbuffer, &maxsize) == ERROR_SUCCESS) regkey.SetStringValue(_T("OldIcon"), rbuffer); } regkey.Close(); } } // Barry - Restore previous values void RevertReg(void) { // restore previous ed2k links before being assigned to emule CRegKey regkey; if (regkey.Create(HKEY_CLASSES_ROOT, _T("ed2k\\shell\\open\\command")) == ERROR_SUCCESS) { TCHAR rbuffer[500]; ULONG maxsize = ARRSIZE(rbuffer); if (regkey.QueryStringValue(_T("OldDefault"), rbuffer, &maxsize) == ERROR_SUCCESS) { regkey.SetStringValue(NULL, rbuffer); regkey.DeleteValue(_T("OldDefault")); regkey.Create(HKEY_CLASSES_ROOT, _T("ed2k\\DefaultIcon")); maxsize = ARRSIZE(rbuffer); if (regkey.QueryStringValue(_T("OldIcon"), rbuffer, &maxsize) == ERROR_SUCCESS) { regkey.SetStringValue(NULL, rbuffer); regkey.DeleteValue(_T("OldIcon")); } } regkey.Close(); } } int GetMaxWindowsTCPConnections() { OSVERSIONINFOEX osvi; ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); if(!GetVersionEx((OSVERSIONINFO*)&osvi)) { //if OSVERSIONINFOEX doesn't work, try OSVERSIONINFO osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO); if(!GetVersionEx((OSVERSIONINFO*)&osvi)) return -1; //shouldn't ever happen } if(osvi.dwPlatformId == VER_PLATFORM_WIN32_NT) // Windows NT product family return -1; //no limits if(osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) { // Windows 95 product family if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0) { //old school 95 HKEY hKey; DWORD dwValue; DWORD dwLength = sizeof(dwValue); LONG lResult; RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("System\\CurrentControlSet\\Services\\VxD\\MSTCP"), 0, KEY_QUERY_VALUE, &hKey); lResult = RegQueryValueEx(hKey, TEXT("MaxConnections"), NULL, NULL, (LPBYTE)&dwValue, &dwLength); RegCloseKey(hKey); if(lResult != ERROR_SUCCESS || lResult < 1) return 100; //the default for 95 is 100 return dwValue; } else { //98 or ME HKEY hKey; TCHAR szValue[32]; DWORD dwLength = sizeof(szValue); LONG lResult; RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("System\\CurrentControlSet\\Services\\VxD\\MSTCP"), 0, KEY_QUERY_VALUE, &hKey); lResult = RegQueryValueEx(hKey, TEXT("MaxConnections"), NULL, NULL, (LPBYTE)szValue, &dwLength); RegCloseKey(hKey); LONG lMaxConnections; if(lResult != ERROR_SUCCESS || (lMaxConnections = _tstoi(szValue)) < 1) return 100; //the default for 98/ME is 100 return lMaxConnections; } } return -1; //give the user the benefit of the doubt, most use NT+ anyway } WORD DetectWinVersion() { OSVERSIONINFOEX osvi; ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); if(!GetVersionEx((OSVERSIONINFO*)&osvi)) { osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); if(!GetVersionEx((OSVERSIONINFO*)&osvi)) return FALSE; } switch(osvi.dwPlatformId) { case VER_PLATFORM_WIN32_NT: if(osvi.dwMajorVersion <= 4) return _WINVER_NT4_; if(osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0) return _WINVER_2K_; if(osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1) return _WINVER_XP_; if(osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2) return _WINVER_2003_; if(osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0) return _WINVER_VISTA_; if(osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 1) return _WINVER_WIN7_; return _WINVER_XP_; // never return Win95 if we get the info about a NT system case VER_PLATFORM_WIN32_WINDOWS: if(osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0) return _WINVER_95_; if(osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10) return _WINVER_98_; if(osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90) return _WINVER_ME_; break; default: break; } return _WINVER_95_; // there should'nt be anything lower than this } int IsRunningXPSP2(){ OSVERSIONINFOEX osvi; ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); if(!GetVersionEx((OSVERSIONINFO*)&osvi)) { osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); if(!GetVersionEx((OSVERSIONINFO*)&osvi)) return 0; } if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT && osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1){ if (osvi.wServicePackMajor >= 2) return 1; } return 0; } uint64 GetFreeDiskSpaceX(LPCTSTR pDirectory) { extern bool g_bUnicoWS; static BOOL _bInitialized = FALSE; static BOOL (WINAPI *_pfnGetDiskFreeSpaceEx)(LPCTSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER) = NULL; static BOOL (WINAPI *_pfnGetDiskFreeSpaceExA)(LPCSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER) = NULL; if (!_bInitialized) { _bInitialized = TRUE; if (g_bUnicoWS) { (FARPROC&)_pfnGetDiskFreeSpaceExA = GetProcAddress(GetModuleHandle(_T("kernel32.dll")), "GetDiskFreeSpaceExA"); } else { // Why does it not work to load "GetDiskFreeSpaceExW" explicitly from UnicoWS.dll ? //extern HMODULE g_hUnicoWS; //(FARPROC&)_pGetDiskFreeSpaceEx = GetProcAddress(g_hUnicoWS != NULL ? g_hUnicoWS : GetModuleHandle(_T("kernel32.dll")), _TWINAPI("GetDiskFreeSpaceEx")); (FARPROC&)_pfnGetDiskFreeSpaceEx = GetProcAddress(GetModuleHandle(_T("kernel32.dll")), _TWINAPI("GetDiskFreeSpaceEx")); } } if (_pfnGetDiskFreeSpaceEx) { ULARGE_INTEGER nFreeDiskSpace; ULARGE_INTEGER dummy; // nFreeDiskSpace.QuadPart=0; if ( (*_pfnGetDiskFreeSpaceEx)(pDirectory, &nFreeDiskSpace, &dummy, &dummy)==TRUE) return nFreeDiskSpace.QuadPart; else return 0; } else if (_pfnGetDiskFreeSpaceExA) { USES_CONVERSION; ULARGE_INTEGER nFreeDiskSpace; // nFreeDiskSpace.QuadPart=0; ULARGE_INTEGER dummy; if ( (*_pfnGetDiskFreeSpaceExA)(T2CA(pDirectory), &nFreeDiskSpace, &dummy, &dummy)==TRUE) return nFreeDiskSpace.QuadPart; else return 0; } else { TCHAR cDrive[16]; const TCHAR *p = _tcschr(pDirectory, _T('\\')); if (p) { memcpy(cDrive, pDirectory, (p - pDirectory)*sizeof(TCHAR)); cDrive[p - pDirectory] = _T('\0'); } else _tcscpy(cDrive, pDirectory); DWORD dwSectPerClust, dwBytesPerSect, dwFreeClusters, dwDummy; if (GetDiskFreeSpace(cDrive, &dwSectPerClust, &dwBytesPerSect, &dwFreeClusters, &dwDummy)) return (dwFreeClusters * dwSectPerClust * dwBytesPerSect); else return 0; } } CString GetRateString(UINT rate) { switch (rate){ case 0: return GetResString(IDS_CMT_NOTRATED); case 1: return GetResString(IDS_CMT_FAKE); case 2: return GetResString(IDS_CMT_POOR); case 3: return GetResString(IDS_CMT_FAIR); case 4: return GetResString(IDS_CMT_GOOD); case 5: return GetResString(IDS_CMT_EXCELLENT); } return GetResString(IDS_CMT_NOTRATED); } // Returns a BASE32 encoded byte array // // [In] // buffer: Pointer to byte array // bufLen: Lenght of buffer array // // [Return] // CString object with BASE32 encoded byte array CString EncodeBase32(const unsigned char* buffer, unsigned int bufLen) { CString Base32Buff; unsigned int i, index; unsigned char word; for(i = 0, index = 0; i < bufLen;) { // Is the current word going to span a byte boundary? if (index > 3) { word = (BYTE)(buffer[i] & (0xFF >> index)); index = (index + 5) % 8; word <<= index; if (i < bufLen - 1) word |= buffer[i + 1] >> (8 - index); i++; } else { word = (BYTE)((buffer[i] >> (8 - (index + 5))) & 0x1F); index = (index + 5) % 8; if (index == 0) i++; } Base32Buff += (char) base32Chars[word]; } return Base32Buff; } // Returns a BASE16 encoded byte array // // [In] // buffer: Pointer to byte array // bufLen: Lenght of buffer array // // [Return] // CString object with BASE16 encoded byte array CString EncodeBase16(const unsigned char* buffer, unsigned int bufLen) { CString Base16Buff; for(unsigned int i = 0; i < bufLen; i++) { Base16Buff += base16Chars[buffer[i] >> 4]; Base16Buff += base16Chars[buffer[i] & 0xf]; } return Base16Buff; } // Decodes a BASE16 string into a byte array // // [In] // base16Buffer: String containing BASE16 // base16BufLen: Lenght BASE16 coded string's length // // [Out] // buffer: byte array containing decoded string bool DecodeBase16(const TCHAR *base16Buffer, unsigned int base16BufLen, byte *buffer, unsigned int bufflen) { unsigned int uDecodeLengthBase16 = DecodeLengthBase16(base16BufLen); if (uDecodeLengthBase16 > bufflen) return false; memset(buffer, 0, uDecodeLengthBase16); for(unsigned int i = 0; i < base16BufLen; i++) { int lookup = toupper(base16Buffer[i]) - '0'; // Check to make sure that the given word falls inside a valid range byte word = 0; if ( lookup < 0 || lookup >= BASE16_LOOKUP_MAX) word = 0xFF; else word = base16Lookup[lookup][1]; if(i % 2 == 0) { buffer[i/2] = word << 4; } else { buffer[(i-1)/2] |= word; } } return true; } // Calculates length to decode from BASE16 // // [In] // base16Length: Actual length of BASE16 string // // [Return] // New length of byte array decoded unsigned int DecodeLengthBase16(unsigned int base16Length) { return base16Length / 2U; } uint32 DecodeBase32(LPCTSTR pszInput, uchar* paucOutput, uint32 nBufferLen) { if (pszInput == NULL) return false; uint32 nDecodeLen = (_tcslen(pszInput)*5)/8; if ((_tcslen(pszInput)*5) % 8 > 0) nDecodeLen++; uint32 nInputLen = _tcslen( pszInput ); if (paucOutput == NULL || nBufferLen == 0) return nDecodeLen; if (nDecodeLen > nBufferLen || paucOutput == NULL) return 0; DWORD nBits = 0; int nCount = 0; for ( int nChars = nInputLen ; nChars-- ; pszInput++ ) { if ( *pszInput >= 'A' && *pszInput <= 'Z' ) nBits |= ( *pszInput - 'A' ); else if ( *pszInput >= 'a' && *pszInput <= 'z' ) nBits |= ( *pszInput - 'a' ); else if ( *pszInput >= '2' && *pszInput <= '7' ) nBits |= ( *pszInput - '2' + 26 ); else return 0; nCount += 5; if ( nCount >= 8 ) { *paucOutput++ = (BYTE)( nBits >> ( nCount - 8 ) ); nCount -= 8; } nBits <<= 5; } return nDecodeLen; } uint32 DecodeBase32(LPCTSTR pszInput, CAICHHash& Hash){ return DecodeBase32(pszInput, Hash.GetRawHash(), Hash.GetHashSize()); } CWebServices::CWebServices() { m_tDefServicesFileLastModified = 0; } CString CWebServices::GetDefaultServicesFile() const { return thePrefs.GetMuleDirectory(EMULE_CONFIGDIR) + _T("webservices.dat"); } void CWebServices::RemoveAllServices() { m_aServices.RemoveAll(); m_tDefServicesFileLastModified = 0; } int CWebServices::ReadAllServices() { RemoveAllServices(); CString strFilePath = GetDefaultServicesFile(); FILE* readFile = _tfsopen(strFilePath, _T("r"), _SH_DENYWR); if (readFile != NULL) { CString name, url, sbuffer; while (!feof(readFile)) { TCHAR buffer[1024]; if (_fgetts(buffer, ARRSIZE(buffer), readFile) == NULL) break; sbuffer = buffer; // ignore comments & too short lines if (sbuffer.GetAt(0) == _T('#') || sbuffer.GetAt(0) == _T('/') || sbuffer.GetLength() < 5) continue; int iPos = sbuffer.Find(_T(',')); if (iPos > 0) { CString strUrlTemplate = sbuffer.Right(sbuffer.GetLength() - iPos - 1).Trim(); if (!strUrlTemplate.IsEmpty()) { bool bFileMacros = false; static const LPCTSTR _apszMacros[] = { _T("#hashid"), _T("#filesize"), _T("#filename"), _T("#name"), _T("#cleanfilename"), _T("#cleanname") }; for (int i = 0; i < ARRSIZE(_apszMacros); i++) { if (strUrlTemplate.Find(_apszMacros[i]) != -1) { bFileMacros = true; break; } } SEd2kLinkService svc; svc.uMenuID = MP_WEBURL + m_aServices.GetCount(); svc.strMenuLabel = sbuffer.Left(iPos).Trim(); svc.strUrl = strUrlTemplate; svc.bFileMacros = bFileMacros; m_aServices.Add(svc); } } } fclose(readFile); struct _stat st; if (_tstat(strFilePath, &st) == 0) m_tDefServicesFileLastModified = st.st_mtime; } return m_aServices.GetCount(); } int CWebServices::GetAllMenuEntries(CTitleMenu* pMenu, DWORD dwFlags) { if (m_aServices.GetCount() == 0) { ReadAllServices(); } else { struct _stat st; if (_tstat(GetDefaultServicesFile(), &st) == 0 && st.st_mtime > m_tDefServicesFileLastModified) ReadAllServices(); } int iMenuEntries = 0; for (int i = 0; i < m_aServices.GetCount(); i++) { const SEd2kLinkService& rSvc = m_aServices.GetAt(i); if ((dwFlags & WEBSVC_GEN_URLS) && rSvc.bFileMacros) continue; if ((dwFlags & WEBSVC_FILE_URLS) && !rSvc.bFileMacros) continue; if (pMenu->AppendMenu(MF_STRING, MP_WEBURL + i, rSvc.strMenuLabel, _T("WEB"))) iMenuEntries++; } return iMenuEntries; } bool CWebServices::RunURL(const CAbstractFile* file, UINT uMenuID) { for (int i = 0; i < m_aServices.GetCount(); i++) { const SEd2kLinkService& rSvc = m_aServices.GetAt(i); if (rSvc.uMenuID == uMenuID) { CString strUrlTemplate = rSvc.strUrl; if (file != NULL) { // Convert hash to hexadecimal text and add it to the URL strUrlTemplate.Replace(_T("#hashid"), md4str(file->GetFileHash())); // Add file size to the URL CString temp; temp.Format(_T("%I64u"), file->GetFileSize()); strUrlTemplate.Replace(_T("#filesize"), temp); // add complete filename to the url strUrlTemplate.Replace(_T("#filename"), EncodeURLQueryParam(file->GetFileName())); // add basename to the url CString strBaseName = file->GetFileName(); PathRemoveExtension(strBaseName.GetBuffer(strBaseName.GetLength())); strBaseName.ReleaseBuffer(); strUrlTemplate.Replace(_T("#name"), EncodeURLQueryParam(strBaseName)); // add cleaned up complete filename to the url strUrlTemplate.Replace(_T("#cleanfilename"), EncodeURLQueryParam(CleanupFilename(file->GetFileName()))); // add cleaned up basename to the url strUrlTemplate.Replace(_T("#cleanname"), EncodeURLQueryParam(CleanupFilename(strBaseName, false))); } // Open URL TRACE(_T("Starting URL: %s\n"), strUrlTemplate); return (int)ShellExecute(NULL, NULL, strUrlTemplate, NULL, thePrefs.GetMuleDirectory(EMULE_EXECUTEABLEDIR), SW_SHOWDEFAULT) > 32; } } return false; } void CWebServices::Edit() { ShellExecute(NULL, _T("open"), thePrefs.GetTxtEditor(), _T("\"") + thePrefs.GetMuleDirectory(EMULE_CONFIGDIR) + _T("webservices.dat\""), NULL, SW_SHOW); } typedef struct { LPCTSTR pszInitialDir; LPCTSTR pszDlgTitle; } BROWSEINIT, *LPBROWSEINIT; extern "C" int CALLBACK BrowseCallbackProc(HWND hWnd, UINT uMsg, LPARAM lParam, LPARAM lpData) { if (uMsg == BFFM_INITIALIZED) { // Set initial directory if ( ((LPBROWSEINIT)lpData)->pszInitialDir != NULL ) { SendMessage(hWnd, BFFM_SETSELECTION, TRUE, (LPARAM)((LPBROWSEINIT)lpData)->pszInitialDir); HWND hEdit = NULL; hEdit = FindWindowEx(hWnd,NULL,_T("EDIT"),NULL); if (hEdit) SetWindowText(hEdit,((LPBROWSEINIT)lpData)->pszInitialDir); } // Set dialog's window title if ( ((LPBROWSEINIT)lpData)->pszDlgTitle != NULL ) SendMessage(hWnd, WM_SETTEXT, 0, (LPARAM)((LPBROWSEINIT)lpData)->pszDlgTitle); } //{begin} VC-dgkang 2008年8月6日 else if (uMsg == BFFM_VALIDATEFAILED && lParam) { CString tcs; tcs.Format(GetResString(IDS_IMPORTPATH_INVALID),(LPCTSTR)lParam); AfxGetMainWnd()->MessageBox(tcs,NULL,MB_OK | MB_ICONINFORMATION); return 1; } else if (uMsg == BFFM_SELCHANGED) { HWND hEdit = NULL; TCHAR szPath[1024]; hEdit = FindWindowEx(hWnd,NULL,_T("EDIT"),NULL); if (hEdit && SHGetPathFromIDList((LPITEMIDLIST)lParam, szPath)) { SetWindowText(hEdit,szPath); } } //{end} return 0; } bool SelectDir(HWND hWnd, LPTSTR pszPath, LPCTSTR pszTitle, LPCTSTR pszDlgTitle, BOOL bHasNewFolderBn) { bool bResult = false; CoInitialize(0); LPMALLOC pShlMalloc; if (SHGetMalloc(&pShlMalloc) == NOERROR) { BROWSEINFO BrsInfo = {0}; BrsInfo.hwndOwner = hWnd; BrsInfo.lpszTitle = (pszTitle != NULL) ? pszTitle : pszDlgTitle; BrsInfo.ulFlags = BIF_VALIDATE | BIF_EDITBOX | BIF_USENEWUI | BIF_NEWDIALOGSTYLE; /*| BIF_NEWDIALOGSTYLE | BIF_SHAREABLE | BIF_USENEWUI ; BIF_RETURNONLYFSDIRS | | BIF_DONTGOBELOWDOMAIN */; if (!bHasNewFolderBn) BrsInfo.ulFlags |= BIF_NONEWFOLDERBUTTON; BROWSEINIT BrsInit = {0}; if (pszPath != NULL || pszTitle != NULL || pszDlgTitle != NULL){ // Need the 'BrowseCallbackProc' to set those strings BrsInfo.lpfn = BrowseCallbackProc; BrsInfo.lParam = (LPARAM)&BrsInit; BrsInit.pszDlgTitle = (pszDlgTitle != NULL) ? pszDlgTitle : NULL/*pszTitle*/; BrsInit.pszInitialDir = pszPath; } LPITEMIDLIST pidlBrowse; if ((pidlBrowse = SHBrowseForFolder(&BrsInfo)) != NULL){ if (SHGetPathFromIDList(pidlBrowse, pszPath)) bResult = true; pShlMalloc->Free(pidlBrowse); } pShlMalloc->Release(); } CoUninitialize(); return bResult; } void MakeFoldername(LPTSTR pszPath) { CString strPath(pszPath); if (!strPath.IsEmpty()) // don't canonicalize an empty path, we would get a "\" { PathCanonicalize(pszPath, strPath); PathRemoveBackslash(pszPath); } } void MakeFoldername(CString &rstrPath) { if (!rstrPath.IsEmpty()) // don't canonicalize an empty path, we would get a "\" { CString strNewPath; LPTSTR pszNewPath = strNewPath.GetBuffer(MAX_PATH); PathCanonicalize(pszNewPath, rstrPath); PathRemoveBackslash(pszNewPath); strNewPath.ReleaseBuffer(); rstrPath = strNewPath; } } CString StringLimit(CString in, UINT length) { if ((UINT)in.GetLength() <= length || length < 10) return in; return (in.Left(length-8) + _T("...") + in.Right(8)); } BOOL DialogBrowseFile(CString& rstrPath, LPCTSTR pszFilters, LPCTSTR pszDefaultFileName, DWORD dwFlags,bool openfilestyle) { CFileDialog myFileDialog(openfilestyle,NULL,pszDefaultFileName, dwFlags | OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, pszFilters, NULL, 0/*automatically use explorer style open dialog on systems which support it*/); if (myFileDialog.DoModal() != IDOK) return FALSE; rstrPath = myFileDialog.GetPathName(); return TRUE; } void md4str(const uchar* hash, TCHAR* pszHash) { static const TCHAR _acHexDigits[] = _T("0123456789ABCDEF"); for (int i = 0; i < 16; i++){ *pszHash++ = _acHexDigits[hash[i] >> 4]; *pszHash++ = _acHexDigits[hash[i] & 0xf]; } *pszHash = _T('\0'); } CString md4str(const uchar* hash) { TCHAR szHash[MAX_HASHSTR_SIZE]; md4str(hash, szHash); return CString(szHash); } void md4strA(const uchar* hash, CHAR* pszHash) { static const CHAR _acHexDigits[] = "0123456789ABCDEF"; for (int i = 0; i < 16; i++){ *pszHash++ = _acHexDigits[hash[i] >> 4]; *pszHash++ = _acHexDigits[hash[i] & 0xf]; } *pszHash = '\0'; } CStringA md4strA(const uchar* hash) { CHAR szHash[MAX_HASHSTR_SIZE]; md4strA(hash, szHash); return CStringA(szHash); } bool strmd4(const char* pszHash, uchar* hash) { memset(hash, 0, 16); for (int i = 0; i < 16; i++) { char byte[3]; byte[0] = pszHash[i*2+0]; byte[1] = pszHash[i*2+1]; byte[2] = '\0'; UINT b; if (sscanf(byte, "%x", &b) != 1) return false; hash[i] = (char)b; } return true; } bool strmd4(const CString& rstr, uchar* hash) { memset(hash, 0, 16); if (rstr.GetLength() != 16*2) return false; for (int i = 0; i < 16; i++) { char byte[3]; byte[0] = (char)rstr[i*2+0]; byte[1] = (char)rstr[i*2+1]; byte[2] = '\0'; UINT b; if (sscanf(byte, "%x", &b) != 1) return false; hash[i] = (char)b; } return true; } void StripTrailingCollon(CString& rstr) { if (!rstr.IsEmpty()) { if (rstr[rstr.GetLength() - 1] == _T(':')) rstr = rstr.Left(rstr.GetLength() - 1); } } CString ValidFilename(CString filename) { filename = URLDecode(filename); if(filename.GetLength() > 100) filename = filename.Left(100); // remove invalid filename characters filename.Replace(_T("\\"), _T("")); filename.Replace(_T("\""), _T("")); filename.Replace(_T("/"), _T("")); filename.Replace(_T(":"), _T("")); filename.Replace(_T("*"), _T("")); filename.Replace(_T("?"), _T("")); filename.Replace(_T("<"), _T("")); filename.Replace(_T(">"), _T("")); filename.Replace(_T("|"), _T("")); filename.Trim(); return filename; } CString CleanupFilename(CString filename, bool bExtension) { filename = URLDecode(filename); filename.MakeLower(); //remove substrings, defined in the preferences (.ini) CString strlink = thePrefs.GetFilenameCleanups(); strlink.MakeLower(); int curPos = 0; CString resToken = strlink.Tokenize(_T("|"), curPos); while (!resToken.IsEmpty()) { filename.Replace(resToken, _T("")); resToken = strlink.Tokenize(_T("|"), curPos); } // Replace "." with space - except the last one (extension-dot) int extpos = bExtension ? filename.ReverseFind(_T('.')) : filename.GetLength(); if (extpos > 0) { for (int i = 0; i < extpos; i++) { if (filename.GetAt(i) != _T('.')) continue; if (i > 0 && i < filename.GetLength()-1 && _istdigit(filename.GetAt(i-1)) && _istdigit(filename.GetAt(i+1))) continue; filename.SetAt(i, _T(' ')); } } // replace space-holders with spaces filename.Replace(_T('_'), _T(' ')); filename.Replace(_T('+'), _T(' ')); filename.Replace(_T('='), _T(' ')); // remove invalid filename characters filename.Replace(_T("\\"), _T("")); filename.Replace(_T("\""), _T("")); filename.Replace(_T("/"), _T("")); filename.Replace(_T(":"), _T("")); filename.Replace(_T("*"), _T("")); filename.Replace(_T("?"), _T("")); filename.Replace(_T("<"), _T("")); filename.Replace(_T(">"), _T("")); filename.Replace(_T("|"), _T("")); // remove [AD] CString tempStr; int pos1 = -1; for (;;) { pos1 = filename.Find(_T('['), pos1+1); if (pos1 == -1) break; int pos2 = filename.Find(_T(']'), pos1); if (pos1 > -1 && pos2 > pos1) { if (pos2 - pos1 > 1) { tempStr = filename.Mid(pos1+1, pos2-pos1-1); int numcount = 0; for (int i = 0; i < tempStr.GetLength(); i++) { if (_istdigit(tempStr.GetAt(i))) numcount++; } if (numcount > tempStr.GetLength()/2) continue; } filename = filename.Left(pos1) + filename.Right(filename.GetLength()-pos2-1); pos1--; } else break; } // Make leading Caps if (filename.GetLength() > 1) { tempStr = filename.GetAt(0); tempStr.MakeUpper(); filename.SetAt(0, tempStr.GetAt(0)); int topos = filename.ReverseFind(_T('.')) - 1; if (topos < 0) topos = filename.GetLength() - 1; for (int ix = 0; ix < topos; ix++) { if (!_istalpha(filename.GetAt(ix))) { if ( (ix < filename.GetLength()-2 && _istdigit(filename.GetAt(ix+2))) || filename.GetAt(ix)==_T('\'') ) continue; tempStr = filename.GetAt(ix+1); tempStr.MakeUpper(); filename.SetAt(ix+1, tempStr.GetAt(0)); } } } // additional formatting filename.Replace(_T("()"), _T("")); filename.Replace(_T(" "), _T(" ")); filename.Replace(_T(" ."), _T(".")); filename.Replace(_T("( "), _T("(")); filename.Replace(_T(" )"), _T(")")); filename.Replace(_T("()"), _T("")); filename.Replace(_T("{ "), _T("{")); filename.Replace(_T(" }"), _T("}")); filename.Replace(_T("{}"), _T("")); filename.Trim(); return filename; } struct SED2KFileType { LPCTSTR pszExt; EED2KFileType iFileType; } _aED2KFileTypes[] = { { _T(".669"), ED2KFT_AUDIO }, { _T(".aac"), ED2KFT_AUDIO }, { _T(".aif"), ED2KFT_AUDIO }, { _T(".aiff"), ED2KFT_AUDIO }, { _T(".amf"), ED2KFT_AUDIO }, { _T(".ams"), ED2KFT_AUDIO }, { _T(".ape"), ED2KFT_AUDIO }, { _T(".au"), ED2KFT_AUDIO }, { _T(".dbm"), ED2KFT_AUDIO }, { _T(".dmf"), ED2KFT_AUDIO }, { _T(".dsm"), ED2KFT_AUDIO }, { _T(".far"), ED2KFT_AUDIO }, { _T(".flac"), ED2KFT_AUDIO }, { _T(".it"), ED2KFT_AUDIO }, { _T(".m4a"), ED2KFT_AUDIO }, { _T(".mdl"), ED2KFT_AUDIO }, { _T(".med"), ED2KFT_AUDIO }, { _T(".mid"), ED2KFT_AUDIO }, { _T(".midi"), ED2KFT_AUDIO }, { _T(".mka"), ED2KFT_AUDIO }, { _T(".mod"), ED2KFT_AUDIO }, { _T(".mol"), ED2KFT_AUDIO }, { _T(".mp1"), ED2KFT_AUDIO }, { _T(".mp2"), ED2KFT_AUDIO }, { _T(".mp3"), ED2KFT_AUDIO }, { _T(".mpa"), ED2KFT_AUDIO }, { _T(".mpc"), ED2KFT_AUDIO }, { _T(".mpp"), ED2KFT_AUDIO }, { _T(".mtm"), ED2KFT_AUDIO }, { _T(".nst"), ED2KFT_AUDIO }, { _T(".ogg"), ED2KFT_AUDIO }, { _T(".okt"), ED2KFT_AUDIO }, { _T(".psm"), ED2KFT_AUDIO }, { _T(".ptm"), ED2KFT_AUDIO }, { _T(".ra"), ED2KFT_AUDIO }, { _T(".rmi"), ED2KFT_AUDIO }, { _T(".s3m"), ED2KFT_AUDIO }, { _T(".stm"), ED2KFT_AUDIO }, { _T(".ult"), ED2KFT_AUDIO }, { _T(".umx"), ED2KFT_AUDIO }, { _T(".wav"), ED2KFT_AUDIO }, { _T(".wma"), ED2KFT_AUDIO }, { _T(".wow"), ED2KFT_AUDIO }, { _T(".xm"), ED2KFT_AUDIO }, { _T(".3g2"), ED2KFT_VIDEO }, { _T(".3gp"), ED2KFT_VIDEO }, { _T(".3gp2"), ED2KFT_VIDEO }, { _T(".3gpp"), ED2KFT_VIDEO }, { _T(".asf"), ED2KFT_VIDEO }, { _T(".avi"), ED2KFT_VIDEO }, { _T(".divx"), ED2KFT_VIDEO }, { _T(".m1v"), ED2KFT_VIDEO }, { _T(".m2v"), ED2KFT_VIDEO }, { _T(".mkv"), ED2KFT_VIDEO }, { _T(".mov"), ED2KFT_VIDEO }, { _T(".mp1v"), ED2KFT_VIDEO }, { _T(".mp2v"), ED2KFT_VIDEO }, { _T(".mp4"), ED2KFT_VIDEO }, { _T(".mpe"), ED2KFT_VIDEO }, { _T(".mpeg"), ED2KFT_VIDEO }, { _T(".mpg"), ED2KFT_VIDEO }, { _T(".mps"), ED2KFT_VIDEO }, { _T(".mpv"), ED2KFT_VIDEO }, { _T(".mpv1"), ED2KFT_VIDEO }, { _T(".mpv2"), ED2KFT_VIDEO }, { _T(".ogm"), ED2KFT_VIDEO }, { _T(".qt"), ED2KFT_VIDEO }, { _T(".ram"), ED2KFT_VIDEO }, { _T(".rm"), ED2KFT_VIDEO }, { _T(".rv"), ED2KFT_VIDEO }, { _T(".rv9"), ED2KFT_VIDEO }, { _T(".swf"), ED2KFT_VIDEO }, { _T(".ts"), ED2KFT_VIDEO }, { _T(".vivo"), ED2KFT_VIDEO }, { _T(".vob"), ED2KFT_VIDEO }, { _T(".wmv"), ED2KFT_VIDEO }, { _T(".xvid"), ED2KFT_VIDEO }, { _T(".rmvb"), ED2KFT_VIDEO }, // Added by thilon on 2006.10.10 { _T(".wm"), ED2KFT_VIDEO }, { _T(".bmp"), ED2KFT_IMAGE }, { _T(".dcx"), ED2KFT_IMAGE }, { _T(".emf"), ED2KFT_IMAGE }, { _T(".gif"), ED2KFT_IMAGE }, { _T(".ico"), ED2KFT_IMAGE }, { _T(".jpeg"), ED2KFT_IMAGE }, { _T(".jpg"), ED2KFT_IMAGE }, { _T(".pct"), ED2KFT_IMAGE }, { _T(".pcx"), ED2KFT_IMAGE }, { _T(".pic"), ED2KFT_IMAGE }, { _T(".pict"), ED2KFT_IMAGE }, { _T(".png"), ED2KFT_IMAGE }, { _T(".psd"), ED2KFT_IMAGE }, { _T(".psp"), ED2KFT_IMAGE }, { _T(".tga"), ED2KFT_IMAGE }, { _T(".tif"), ED2KFT_IMAGE }, { _T(".tiff"), ED2KFT_IMAGE }, { _T(".wmf"), ED2KFT_IMAGE }, { _T(".xif"), ED2KFT_IMAGE }, { _T(".7z"), ED2KFT_ARCHIVE }, { _T(".ace"), ED2KFT_ARCHIVE }, { _T(".alz"), ED2KFT_ARCHIVE }, { _T(".arj"), ED2KFT_ARCHIVE }, { _T(".bz2"), ED2KFT_ARCHIVE }, { _T(".cab"), ED2KFT_ARCHIVE }, { _T(".cbz"), ED2KFT_ARCHIVE }, { _T(".cbr"), ED2KFT_ARCHIVE }, { _T(".gz"), ED2KFT_ARCHIVE }, { _T(".hqx"), ED2KFT_ARCHIVE }, { _T(".lha"), ED2KFT_ARCHIVE }, { _T(".lzh"), ED2KFT_ARCHIVE }, { _T(".msi"), ED2KFT_ARCHIVE }, { _T(".rar"), ED2KFT_ARCHIVE }, { _T(".sea"), ED2KFT_ARCHIVE }, { _T(".sit"), ED2KFT_ARCHIVE }, { _T(".tar"), ED2KFT_ARCHIVE }, { _T(".tgz"), ED2KFT_ARCHIVE }, { _T(".uc2"), ED2KFT_ARCHIVE }, { _T(".z"), ED2KFT_ARCHIVE }, { _T(".zip"), ED2KFT_ARCHIVE }, { _T(".bat"), ED2KFT_PROGRAM }, { _T(".cmd"), ED2KFT_PROGRAM }, { _T(".com"), ED2KFT_PROGRAM }, { _T(".exe"), ED2KFT_PROGRAM }, { _T(".bin"), ED2KFT_CDIMAGE }, { _T(".bwa"), ED2KFT_CDIMAGE }, { _T(".bwi"), ED2KFT_CDIMAGE }, { _T(".bws"), ED2KFT_CDIMAGE }, { _T(".bwt"), ED2KFT_CDIMAGE }, { _T(".ccd"), ED2KFT_CDIMAGE }, { _T(".cue"), ED2KFT_CDIMAGE }, { _T(".dmg"), ED2KFT_CDIMAGE }, { _T(".dmz"), ED2KFT_CDIMAGE }, { _T(".img"), ED2KFT_CDIMAGE }, { _T(".iso"), ED2KFT_CDIMAGE }, { _T(".mdf"), ED2KFT_CDIMAGE }, { _T(".mds"), ED2KFT_CDIMAGE }, { _T(".nrg"), ED2KFT_CDIMAGE }, { _T(".sub"), ED2KFT_CDIMAGE }, { _T(".toast"), ED2KFT_CDIMAGE }, { _T(".chm"), ED2KFT_DOCUMENT }, { _T(".css"), ED2KFT_DOCUMENT }, { _T(".diz"), ED2KFT_DOCUMENT }, { _T(".doc"), ED2KFT_DOCUMENT }, { _T(".dot"), ED2KFT_DOCUMENT }, { _T(".hlp"), ED2KFT_DOCUMENT }, { _T(".htm"), ED2KFT_DOCUMENT }, { _T(".html"), ED2KFT_DOCUMENT }, { _T(".nfo"), ED2KFT_DOCUMENT }, { _T(".pdf"), ED2KFT_DOCUMENT }, { _T(".pps"), ED2KFT_DOCUMENT }, { _T(".ppt"), ED2KFT_DOCUMENT }, { _T(".ps"), ED2KFT_DOCUMENT }, { _T(".rtf"), ED2KFT_DOCUMENT }, { _T(".txt"), ED2KFT_DOCUMENT }, { _T(".wri"), ED2KFT_DOCUMENT }, { _T(".xls"), ED2KFT_DOCUMENT }, { _T(".xml"), ED2KFT_DOCUMENT }, { _T(".emulecollection"), ED2KFT_EMULECOLLECTION } }; int __cdecl CompareE2DKFileType(const void* p1, const void* p2) { return _tcscmp( ((const SED2KFileType*)p1)->pszExt, ((const SED2KFileType*)p2)->pszExt ); } EED2KFileType GetED2KFileTypeID(LPCTSTR pszFileName) { LPCTSTR pszExt = _tcsrchr(pszFileName, _T('.')); if (pszExt == NULL) return ED2KFT_ANY; CString strExt(pszExt); strExt.MakeLower(); SED2KFileType ft; ft.pszExt = strExt; ft.iFileType = ED2KFT_ANY; const SED2KFileType* pFound = (SED2KFileType*)bsearch(&ft, _aED2KFileTypes, ARRSIZE(_aED2KFileTypes), sizeof _aED2KFileTypes[0], CompareE2DKFileType); if (pFound != NULL) return pFound->iFileType; return ED2KFT_ANY; } // Retuns the ed2k file type string ID which is to be used for publishing+searching LPCSTR GetED2KFileTypeSearchTerm(EED2KFileType iFileID) { if (iFileID == ED2KFT_AUDIO) return ED2KFTSTR_AUDIO; if (iFileID == ED2KFT_VIDEO) return ED2KFTSTR_VIDEO; if (iFileID == ED2KFT_IMAGE) return ED2KFTSTR_IMAGE; if (iFileID == ED2KFT_PROGRAM) return ED2KFTSTR_PROGRAM; if (iFileID == ED2KFT_DOCUMENT) return ED2KFTSTR_DOCUMENT; // NOTE: Archives and CD-Images are published+searched with file type "Pro" // NOTE: If this gets changed, the function 'GetED2KFileTypeSearchID' also needs to get updated! if (iFileID == ED2KFT_ARCHIVE) return ED2KFTSTR_PROGRAM; if (iFileID == ED2KFT_CDIMAGE) return ED2KFTSTR_PROGRAM; if (iFileID == ED2KFT_EMULECOLLECTION) return ED2KFTSTR_EMULECOLLECTION; return NULL; } // Retuns the ed2k file type integer ID which is to be used for publishing+searching EED2KFileType GetED2KFileTypeSearchID(EED2KFileType iFileID) { if (iFileID == ED2KFT_AUDIO) return ED2KFT_AUDIO; if (iFileID == ED2KFT_VIDEO) return ED2KFT_VIDEO; if (iFileID == ED2KFT_IMAGE) return ED2KFT_IMAGE; if (iFileID == ED2KFT_PROGRAM) return ED2KFT_PROGRAM; if (iFileID == ED2KFT_DOCUMENT) return ED2KFT_DOCUMENT; // NOTE: Archives and CD-Images are published+searched with file type "Pro" // NOTE: If this gets changed, the function 'GetED2KFileTypeSearchTerm' also needs to get updated! if (iFileID == ED2KFT_ARCHIVE) return ED2KFT_PROGRAM; if (iFileID == ED2KFT_CDIMAGE) return ED2KFT_PROGRAM; return ED2KFT_ANY; } // Returns a file type which is used eMule internally only, examining the extension of the given filename CString GetFileTypeByName(LPCTSTR pszFileName) { EED2KFileType iFileType = GetED2KFileTypeID(pszFileName); switch (iFileType) { case ED2KFT_AUDIO: return _T(ED2KFTSTR_AUDIO); case ED2KFT_VIDEO: return _T(ED2KFTSTR_VIDEO); case ED2KFT_IMAGE: return _T(ED2KFTSTR_IMAGE); case ED2KFT_DOCUMENT: return _T(ED2KFTSTR_DOCUMENT); case ED2KFT_PROGRAM: return _T(ED2KFTSTR_PROGRAM); case ED2KFT_ARCHIVE: return _T(ED2KFTSTR_ARCHIVE); case ED2KFT_CDIMAGE: return _T(ED2KFTSTR_CDIMAGE); case ED2KFT_EMULECOLLECTION:return _T(ED2KFTSTR_EMULECOLLECTION); default: return _T(""); } } // Returns a file type which is used eMule internally only (GUI) CString GetFileTypeDisplayStrFromED2KFileType(LPCTSTR pszED2KFileType) { ASSERT( pszED2KFileType != NULL ); if (pszED2KFileType != NULL) { if (_tcscmp(pszED2KFileType, _T(ED2KFTSTR_AUDIO)) == 0) return GetResString(IDS_SEARCH_AUDIO); else if (_tcscmp(pszED2KFileType, _T(ED2KFTSTR_VIDEO)) == 0) return GetResString(IDS_SEARCH_VIDEO); else if (_tcscmp(pszED2KFileType, _T(ED2KFTSTR_IMAGE)) == 0) return GetResString(IDS_SEARCH_PICS); else if (_tcscmp(pszED2KFileType, _T(ED2KFTSTR_DOCUMENT)) == 0) return GetResString(IDS_SEARCH_DOC); else if (_tcscmp(pszED2KFileType, _T(ED2KFTSTR_PROGRAM)) == 0) return GetResString(IDS_SEARCH_PRG); else if (_tcscmp(pszED2KFileType, _T(ED2KFTSTR_ARCHIVE)) == 0) return GetResString(IDS_SEARCH_ARC); else if (_tcscmp(pszED2KFileType, _T(ED2KFTSTR_CDIMAGE)) == 0) return GetResString(IDS_SEARCH_CDIMG); else if (_tcscmp(pszED2KFileType, _T(ED2KFTSTR_EMULECOLLECTION)) == 0) return GetResString(IDS_SEARCH_EMULECOLLECTION); } return _T(""); } class CED2KFileTypes{ public: CED2KFileTypes(){ qsort(_aED2KFileTypes, ARRSIZE(_aED2KFileTypes), sizeof _aED2KFileTypes[0], CompareE2DKFileType); #ifdef _DEBUG // check for duplicate entries LPCTSTR pszLast = _aED2KFileTypes[0].pszExt; for (int i = 1; i < ARRSIZE(_aED2KFileTypes); i++){ ASSERT( _tcscmp(pszLast, _aED2KFileTypes[i].pszExt) != 0 ); pszLast = _aED2KFileTypes[i].pszExt; } #endif } }; CED2KFileTypes theED2KFileTypes; // get the list sorted *before* any code is accessing it TCHAR *stristr(const TCHAR *str1, const TCHAR *str2) { const TCHAR *cp = str1; const TCHAR *s1; const TCHAR *s2; if (!*str2) return (TCHAR *)str1; while (*cp) { s1 = cp; s2 = str2; while (*s1 && *s2 && _totlower(*s1) == _totlower(*s2)) s1++, s2++; if (!*s2) return (TCHAR *)cp; cp++; } return NULL; } CString GetNextString(const CString& rstr, LPCTSTR pszTokens, int& riStart) { CString strResult; if (pszTokens != NULL && riStart != -1) { int iToken = rstr.Find(pszTokens, riStart); if (iToken != -1) { int iLen = iToken - riStart; if (iLen >= 0) { strResult = rstr.Mid(riStart, iLen); riStart += iLen + 1; } } else { strResult = rstr.Mid(riStart); riStart = -1; } } return strResult; } CString GetNextString(const CString& rstr, TCHAR chToken, int& riStart) { CString strResult; if (chToken != _T('\0') && riStart != -1) { int iToken = rstr.Find(chToken, riStart); if (iToken != -1) { int iLen = iToken - riStart; if (iLen >= 0) { strResult = rstr.Mid(riStart, iLen); riStart += iLen + 1; } } else { strResult = rstr.Mid(riStart); riStart = -1; } } return strResult; } int GetSystemErrorString(DWORD dwError, CString &rstrError) { // FormatMessage language flags: // // - MFC uses: MAKELANGID(LANG_NEUTRAL, SUBLANG_SYS_DEFAULT) // SUBLANG_SYS_DEFAULT = 0x02 (system default) // // - SDK uses: MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT) // SUBLANG_DEFAULT = 0x01 (user default) // // // Found in "winnt.h" // ------------------ // Language IDs. // // The following two combinations of primary language ID and // sublanguage ID have special semantics: // // Primary Language ID Sublanguage ID Result // ------------------- --------------- ------------------------ // LANG_NEUTRAL SUBLANG_NEUTRAL Language neutral // LANG_NEUTRAL SUBLANG_DEFAULT User default language // LANG_NEUTRAL SUBLANG_SYS_DEFAULT System default language // // *** SDK notes also: // If you pass in zero, 'FormatMessage' looks for a message for LANGIDs in // the following order: // // 1) Language neutral // 2) Thread LANGID, based on the thread's locale value // 3) User default LANGID, based on the user's default locale value // 4) System default LANGID, based on the system default locale value // 5) US English LPTSTR pszSysMsg = NULL; DWORD dwLength = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwError, MAKELANGID(LANG_NEUTRAL, SUBLANG_SYS_DEFAULT), (LPTSTR)&pszSysMsg, 0, NULL); if (pszSysMsg != NULL && dwLength != 0) { if (dwLength >= 2 && pszSysMsg[dwLength - 2] == _T('\r')) pszSysMsg[dwLength - 2] = _T('\0'); rstrError = pszSysMsg; rstrError.Replace(_T("\r\n"), _T(" ")); // some messages contain CRLF within the message!? } else { rstrError.Empty(); } if (pszSysMsg) LocalFree(pszSysMsg); return rstrError.GetLength(); } int GetModuleErrorString(DWORD dwError, CString &rstrError, LPCTSTR pszModule) { LPTSTR pszSysMsg = NULL; DWORD dwLength = FormatMessage(FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS, GetModuleHandle(pszModule), dwError, MAKELANGID(LANG_NEUTRAL, SUBLANG_SYS_DEFAULT), (LPTSTR)&pszSysMsg, 0, NULL); if (pszSysMsg != NULL && dwLength != 0) { if (dwLength >= 2 && pszSysMsg[dwLength - 2] == _T('\r')) pszSysMsg[dwLength - 2] = _T('\0'); rstrError = pszSysMsg; rstrError.Replace(_T("\r\n"), _T(" ")); // some messages contain CRLF within the message!? } else { rstrError.Empty(); } if (pszSysMsg) LocalFree(pszSysMsg); return rstrError.GetLength(); } int GetErrorMessage(DWORD dwError, CString &rstrErrorMsg, DWORD dwFlags) { int iMsgLen = GetSystemErrorString(dwError, rstrErrorMsg); if (iMsgLen == 0) { if ((long)dwError >= 0) rstrErrorMsg.Format(_T("Error %u"), dwError); else rstrErrorMsg.Format(_T("Error 0x%08x"), dwError); } else if (dwFlags & 1) { CString strFullErrorMsg; if ((long)dwError >= 0) strFullErrorMsg.Format(_T("Error %u: %s"), dwError, rstrErrorMsg); else strFullErrorMsg.Format(_T("Error 0x%08x: %s"), dwError, rstrErrorMsg); rstrErrorMsg = strFullErrorMsg; } return rstrErrorMsg.GetLength(); } CString GetErrorMessage(DWORD dwError, DWORD dwFlags) { CString strError; GetErrorMessage(dwError, strError, dwFlags); return strError; } LPCTSTR GetShellExecuteErrMsg(DWORD dwShellExecError) { /* The error codes returned from 'ShellExecute' consist of the 'old' WinExec * error codes and some additional error codes. * * Error Code WinExec * ---------------------------------------------------------------------------- * 0 0 "Out of memory" Yes * ERROR_FILE_NOT_FOUND 2 (== SE_ERR_FNF) Yes * SE_ERR_FNF 2 (== ERROR_FILE_NOT_FOUND) Yes * ERROR_PATH_NOT_FOUND 3 (== SE_ERR_PNF) Yes * SE_ERR_PNF 3 (== ERROR_PATH_NOT_FOUND) Yes * SE_ERR_ACCESSDENIED 5 Yes * SE_ERR_OOM 8 Yes * ERROR_BAD_FORMAT 11 Yes * SE_ERR_SHARE 26 No * SE_ERR_ASSOCINCOMPLETE 27 No * SE_ERR_DDETIMEOUT 28 No * SE_ERR_DDEFAIL 29 No * SE_ERR_DDEBUSY 30 No * SE_ERR_NOASSOC 31 No * SE_ERR_DLLNOTFOUND 32 No * * Using "FormatMessage(FORMAT_MESSAGE_FROM_HMODULE, <shell32.dll>" does *not* work! */ static const struct _tagERRMSG { UINT uId; LPCTSTR pszMsg; } s_aszWinExecErrMsg[] = { { 0, _T("The operating system is out of memory or resources.")}, { 1, _T("Call to MS-DOS Int 21 Function 4B00h was invalid.")}, {/* 2*/SE_ERR_FNF, _T("The specified file was not found.")}, {/* 3*/SE_ERR_PNF, _T("The specified path was not found.")}, { 4, _T("Too many files were open.")}, {/* 5*/SE_ERR_ACCESSDENIED, _T("The operating system denied access to the specified file.")}, { 6, _T("Library requires separate data segments for each task.")}, { 7, _T("There were MS-DOS Memory block problems.")}, {/* 8*/SE_ERR_OOM, _T("There was insufficient memory to start the application.")}, { 9, _T("There were MS-DOS Memory block problems.")}, {10, _T("Windows version was incorrect.")}, {11, _T("Executable file was invalid. Either it was not a Windows application or there was an error in the .EXE image.")}, {12, _T("Application was designed for a different operating system.")}, {13, _T("Application was designed for MS-DOS 4.0.")}, {14, _T("Type of executable file was unknown.")}, {15, _T("Attempt was made to load a real-mode application (developed for an earlier version of Windows).")}, {16, _T("Attempt was made to load a second instance of an executable file containing multiple data segments that were not marked read-only.")}, {17, _T("Attempt was made in large-frame EMS mode to load a second instance of an application that links to certain nonshareable DLLs that are already in use.")}, {18, _T("Attempt was made in real mode to load an application marked for use in protected mode only.")}, {19, _T("Attempt was made to load a compressed executable file. The file must be decompressed before it can be loaded.")}, {20, _T("Dynamic-link library (DLL) file was invalid. One of the DLLs required to run this application was corrupt.")}, {21, _T("Application requires Microsoft Windows 32-bit extensions.")}, /*22-31 RESERVED FOR FUTURE USE. NOT RETURNED BY VERSION 3.0.*/ {24, _T("Command line too long.")}, // 30.03.99 []: Seen under WinNT 4.0/Win98 for a very long command line! /*non-WinExec error codes*/ {/*26*/SE_ERR_SHARE, _T("A sharing violation occurred.")}, {/*27*/SE_ERR_ASSOCINCOMPLETE, _T("The file name association is incomplete or invalid.")}, {/*28*/SE_ERR_DDETIMEOUT, _T("The DDE transaction could not be completed because the request timed out.")}, {/*29*/SE_ERR_DDEFAIL, _T("The DDE transaction failed.")}, {/*30*/SE_ERR_DDEBUSY, _T("The DDE transaction could not be completed because other DDE transactions were being processed.")}, {/*31*/SE_ERR_NOASSOC, _T("There is no application associated with the given file name extension.")}, {/*32*/SE_ERR_DLLNOTFOUND, _T("The specified dynamic-link library was not found.")} }; if (dwShellExecError > 32) return _T(""); // No error // Search error message for (UINT i = 0; i < ARRSIZE(s_aszWinExecErrMsg); i++) { if (s_aszWinExecErrMsg[i].uId == dwShellExecError) return s_aszWinExecErrMsg[i].pszMsg; } return _T("Unknown error."); } int GetDesktopColorDepth() { HDC hdcScreen = ::GetDC(HWND_DESKTOP); int iColorBits = GetDeviceCaps(hdcScreen, BITSPIXEL) * GetDeviceCaps(hdcScreen, PLANES); ::ReleaseDC(HWND_DESKTOP, hdcScreen); return iColorBits; } int GetAppImageListColorFlag() { int iColorBits = GetDesktopColorDepth(); int iIlcFlag; if (iColorBits >= 32) iIlcFlag = ILC_COLOR32; else if (iColorBits >= 24) iIlcFlag = ILC_COLOR24; else if (iColorBits >= 16) iIlcFlag = ILC_COLOR16; else if (iColorBits >= 8) iIlcFlag = ILC_COLOR8; else if (iColorBits >= 4) iIlcFlag = ILC_COLOR4; else iIlcFlag = ILC_COLOR; return iIlcFlag; } CString DbgGetHexDump(const uint8* data, UINT size) { CString buffer; buffer.Format(_T("Size=%u"), size); buffer += _T(", Data=["); UINT i = 0; for(; i < size && i < 50; i++){ if (i > 0) buffer += _T(" "); TCHAR temp[3]; _stprintf(temp, _T("%02x"), data[i]); buffer += temp; } buffer += (i == size) ? _T("]") : _T("..]"); return buffer; } void DbgSetThreadName(LPCSTR szThreadName, ...) { #ifdef DEBUG #ifndef MS_VC_EXCEPTION #define MS_VC_EXCEPTION 0x406d1388 typedef struct tagTHREADNAME_INFO { DWORD dwType; // must be 0x1000 LPCSTR szName; // pointer to name (in same addr space) DWORD dwThreadID; // thread ID (-1 caller thread) DWORD dwFlags; // reserved for future use, must be zero } THREADNAME_INFO; #endif __try { va_list args; va_start(args, szThreadName); int lenBuf = 0; char *buffer = NULL; int lenResult; do // the VS debugger truncates the string to 31 characters anyway! { lenBuf += 128; delete[] buffer; buffer = new char[lenBuf]; lenResult = _vsnprintf(buffer, lenBuf, szThreadName, args); } while (lenResult == -1); va_end(args); THREADNAME_INFO info; info.dwType = 0x1000; info.szName = buffer; info.dwThreadID = (DWORD)-1; info.dwFlags = 0; __try { RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(DWORD), (DWORD *)&info); } __except (EXCEPTION_CONTINUE_EXECUTION) { } delete [] buffer; } __except (EXCEPTION_CONTINUE_EXECUTION) {} #else UNREFERENCED_PARAMETER(szThreadName); #endif } CString RemoveFileExtension(const CString& rstrFilePath) { int iDot = rstrFilePath.ReverseFind(_T('.')); if (iDot == -1) return rstrFilePath; return rstrFilePath.Mid(0, iDot); } int CompareDirectories(const CString& rstrDir1, const CString& rstrDir2) { // use case insensitive compare as a starter if (rstrDir1.CompareNoCase(rstrDir2)==0) return 0; // if one of the paths ends with a '\' the paths may still be equal from the file system's POV CString strDir1(rstrDir1); CString strDir2(rstrDir2); PathRemoveBackslash(strDir1.GetBuffer()); // remove any available backslash strDir1.ReleaseBuffer(); PathRemoveBackslash(strDir2.GetBuffer()); // remove any available backslash strDir2.ReleaseBuffer(); return strDir1.CompareNoCase(strDir2); // compare again } bool IsGoodIP(uint32 nIP, bool forceCheck) { // always filter following IP's // ------------------------------------------- // 0.0.0.0 invalid // 127.0.0.0 - 127.255.255.255 Loopback // 224.0.0.0 - 239.255.255.255 Multicast // 240.0.0.0 - 255.255.255.255 Reserved for Future Use // 255.255.255.255 invalid if (nIP==0 || (uint8)nIP==127 || (uint8)nIP>=224){ #ifdef _DEBUG if (nIP==0x0100007F && thePrefs.GetAllowLocalHostIP()) return true; #endif return false; } if (!thePrefs.FilterLANIPs() && !forceCheck/*ZZ:UploadSpeedSense*/) return true; // filter LAN IP's // ------------------------------------------- // 0.* "This" Network // 10.0.0.0 - 10.255.255.255 Class A // 172.16.0.0 - 172.31.255.255 Class B // 192.168.0.0 - 192.168.255.255 Class C uint8 nFirst = (uint8)nIP; uint8 nSecond = (uint8)(nIP >> 8); if (nFirst==192 && nSecond==168) // check this 1st, because those LANs IPs are mostly spreaded return false; if (nFirst==172 && nSecond>=16 && nSecond<=31) return false; if (nFirst==0 || nFirst==10) return false; return true; } // VC-kernel[2007-01-18]: bool IsLanIP(uint32 nIP, bool /*forceCheck*/) { //if (!thePrefs.FilterLANIPs() && !forceCheck/*ZZ:UploadSpeedSense*/) // return true; // LAN IP's // ------------------------------------------- // 10.0.0.0 - 10.255.255.255 Class A // 172.16.0.0 - 172.31.255.255 Class B // 192.168.0.0 - 192.168.255.255 Class C uint8 nFirst = (uint8)nIP; uint8 nSecond = (uint8)(nIP >> 8); if (nFirst==192 && nSecond==168) // check this 1st, because those LANs IPs are mostly spreaded return true; if (nFirst==172 && nSecond>=16 && nSecond<=31) return true; if (nFirst==10) return true; return false; } bool IsGoodIPPort(uint32 nIP, uint16 nPort) { return IsGoodIP(nIP) && nPort!=0; } CString GetFormatedUInt(ULONG ulVal) { TCHAR szVal[12]; _ultot(ulVal, szVal, 10); static NUMBERFMT nf; if (nf.Grouping == 0) { nf.NumDigits = 0; nf.LeadingZero = 0; nf.Grouping = 3; // we are hardcoding the following two format chars by intention because the C-RTL also has the decimal sep hardcoded to '.' nf.lpDecimalSep = _T("."); nf.lpThousandSep = _T(","); nf.NegativeOrder = 0; } CString strVal; const int iBuffSize = ARRSIZE(szVal)*2; int iResult = GetNumberFormat(LOCALE_SYSTEM_DEFAULT, 0, szVal, &nf, strVal.GetBuffer(iBuffSize), iBuffSize); strVal.ReleaseBuffer(); if (iResult == 0) strVal = szVal; return strVal; } CString GetFormatedUInt64(ULONGLONG ullVal) { TCHAR szVal[24]; _ui64tot(ullVal, szVal, 10); static NUMBERFMT nf; if (nf.Grouping == 0) { nf.NumDigits = 0; nf.LeadingZero = 0; nf.Grouping = 3; // we are hardcoding the following two format chars by intention because the C-RTL also has the decimal sep hardcoded to '.' nf.lpDecimalSep = _T("."); nf.lpThousandSep = _T(","); nf.NegativeOrder = 0; } CString strVal; const int iBuffSize = ARRSIZE(szVal)*2; int iResult = GetNumberFormat(LOCALE_SYSTEM_DEFAULT, 0, szVal, &nf, strVal.GetBuffer(iBuffSize), iBuffSize); strVal.ReleaseBuffer(); if (iResult == 0) strVal = szVal; return strVal; } void Debug(LPCTSTR pszFmtMsg, ...) { va_list pArgs; va_start(pArgs, pszFmtMsg); CString strBuff; #ifdef _DEBUG time_t tNow = time(NULL); int iTimeLen = _tcsftime(strBuff.GetBuffer(40), 40, _T("%H:%M:%S "), localtime(&tNow)); strBuff.ReleaseBuffer(iTimeLen); #endif strBuff.AppendFormatV(pszFmtMsg, pArgs); // get around a bug in the debug device which is not capable of dumping long strings int i = 0; while (i < strBuff.GetLength()){ OutputDebugString(strBuff.Mid(i, 1024)); i += 1024; } va_end(pArgs); } void DebugHexDump(const uint8* data, UINT lenData) { int lenLine = 16; UINT pos = 0; byte c = 0; while (pos < lenData) { CStringA line; CStringA single; line.Format("%08X ", pos); lenLine = min((lenData - pos), 16); for (int i=0; i<lenLine; i++) { single.Format(" %02X", data[pos+i]); line += single; if (i == 7) line += ' '; } line += CString(' ', 60 - line.GetLength()); for (int i=0; i<lenLine; i++) { c = data[pos + i]; single.Format("%c", (((c > 31) && (c < 127)) ? (_TUCHAR)c : '.')); line += single; } Debug(_T("%hs\n"), line); pos += lenLine; } } void DebugHexDump(CFile& file) { int iSize = (int)(file.GetLength() - file.GetPosition()); if (iSize > 0) { uint8* data = NULL; try{ data = new uint8[iSize]; file.Read(data, iSize); DebugHexDump(data, iSize); } catch(CFileException* e){ TRACE("*** DebugHexDump(CFile&); CFileException\n"); e->Delete(); } catch(CMemoryException* e){ TRACE("*** DebugHexDump(CFile&); CMemoryException\n"); e->Delete(); } delete[] data; } } LPCTSTR DbgGetFileNameFromID(const uchar* hash) { CKnownFile* reqfile = CGlobalVariable::sharedfiles->GetFileByID(hash); if (reqfile != NULL) return reqfile->GetFileName(); CPartFile* partfile = CGlobalVariable::downloadqueue->GetFileByID(hash); if (partfile != NULL) return partfile->GetFileName(); CKnownFile* knownfile = CGlobalVariable::knownfiles->FindKnownFileByID(hash); if (knownfile != NULL) return knownfile->GetFileName(); return NULL; } CString DbgGetFileInfo(const uchar* hash) { if (hash == NULL) return CString(); CString strInfo(_T("File=")); LPCTSTR pszName = DbgGetFileNameFromID(hash); if (pszName != NULL) strInfo += pszName; else strInfo += md4str(hash); return strInfo; } CString DbgGetFileStatus(UINT nPartCount, CSafeMemFile* data) { CString strFileStatus; if (nPartCount == 0) strFileStatus = _T("Complete"); else { CString strPartStatus; UINT nAvailableParts = 0; UINT nPart = 0; while (nPart < nPartCount) { uint8 ucPartMask; try { ucPartMask = data->ReadUInt8(); } catch (CFileException* ex) { ex->Delete(); strPartStatus = _T("*PacketException*"); break; } for (int i = 0; i < 8; i++) { bool bPartAvailable = (((ucPartMask >> i) & 1) != 0); if (bPartAvailable) nAvailableParts++; strPartStatus += bPartAvailable ? _T('#') : _T('.'); nPart++; if (nPart == nPartCount) break; } } strFileStatus.Format(_T("Parts=%u Avail=%u %s"), nPartCount, nAvailableParts, strPartStatus); } return strFileStatus; } CString DbgGetBlockInfo(const Requested_Block_Struct* block) { return DbgGetBlockInfo(block->StartOffset, block->EndOffset); } CString DbgGetBlockInfo(uint64 StartOffset, uint64 EndOffset) { CString strInfo; strInfo.Format(_T("%I64u-%I64u (%I64u bytes)"), StartOffset, EndOffset, EndOffset - StartOffset + 1); strInfo.AppendFormat(_T(", Part %I64u"), StartOffset/PARTSIZE); if (StartOffset/PARTSIZE != EndOffset/PARTSIZE) strInfo.AppendFormat(_T("-%I64u(**)"), EndOffset/PARTSIZE); strInfo.AppendFormat(_T(", Block %I64u"), StartOffset/EMBLOCKSIZE); if (StartOffset/EMBLOCKSIZE != EndOffset/EMBLOCKSIZE) { strInfo.AppendFormat(_T("-%I64u"), EndOffset/EMBLOCKSIZE); if (EndOffset/EMBLOCKSIZE - StartOffset/EMBLOCKSIZE > 1) strInfo += _T("(**)"); } return strInfo; } CString DbgGetBlockFileInfo(const Requested_Block_Struct* block, const CPartFile* partfile) { CString strInfo(DbgGetBlockInfo(block)); strInfo += _T("; "); strInfo += DbgGetFileInfo(partfile ? partfile->GetFileHash() : NULL); return strInfo; } int GetHashType(const uchar* hash) { if (hash[5] == 13 && hash[14] == 110) return SO_OLDEMULE; else if (hash[5] == 14 && hash[14] == 111) return SO_EMULE; else if (hash[5] == 'M' && hash[14] == 'L') return SO_MLDONKEY; else return SO_UNKNOWN; } LPCTSTR DbgGetHashTypeString(const uchar* hash) { int iHashType = GetHashType(hash); if (iHashType == SO_EMULE) return _T("eMule"); if (iHashType == SO_MLDONKEY) return _T("MLdonkey"); if (iHashType == SO_OLDEMULE) return _T("Old eMule"); ASSERT( iHashType == SO_UNKNOWN ); return _T("Unknown"); } CString DbgGetClientID(uint32 nClientID) { CString strClientID; if (IsLowID(nClientID)) strClientID.Format(_T("LowID=%u"), nClientID); else strClientID = ipstr(nClientID); return strClientID; } #define _STRVAL(o) {_T(#o), o} CString DbgGetDonkeyClientTCPOpcode(UINT opcode) { static const struct { LPCTSTR pszOpcode; UINT uOpcode; } _aOpcodes[] = { _STRVAL(OP_HELLO), _STRVAL(OP_SENDINGPART), _STRVAL(OP_REQUESTPARTS), _STRVAL(OP_FILEREQANSNOFIL), _STRVAL(OP_END_OF_DOWNLOAD), _STRVAL(OP_ASKSHAREDFILES), _STRVAL(OP_ASKSHAREDFILESANSWER), _STRVAL(OP_HELLOANSWER), _STRVAL(OP_CHANGE_CLIENT_ID), _STRVAL(OP_MESSAGE), _STRVAL(OP_SETREQFILEID), _STRVAL(OP_FILESTATUS), _STRVAL(OP_HASHSETREQUEST), _STRVAL(OP_HASHSETANSWER), _STRVAL(OP_STARTUPLOADREQ), _STRVAL(OP_ACCEPTUPLOADREQ), _STRVAL(OP_CANCELTRANSFER), _STRVAL(OP_OUTOFPARTREQS), _STRVAL(OP_REQUESTFILENAME), _STRVAL(OP_REQFILENAMEANSWER), _STRVAL(OP_CHANGE_SLOT), _STRVAL(OP_QUEUERANK), _STRVAL(OP_ASKSHAREDDIRS), _STRVAL(OP_ASKSHAREDFILESDIR), _STRVAL(OP_ASKSHAREDDIRSANS), _STRVAL(OP_ASKSHAREDFILESDIRANS), _STRVAL(OP_ASKSHAREDDENIEDANS) }; for (int i = 0; i < ARRSIZE(_aOpcodes); i++) { if (_aOpcodes[i].uOpcode == opcode) return _aOpcodes[i].pszOpcode; } CString strOpcode; strOpcode.Format(_T("0x%02x"), opcode); return strOpcode; } CString DbgGetMuleClientTCPOpcode(UINT opcode) { static const struct { LPCTSTR pszOpcode; UINT uOpcode; } _aOpcodes[] = { _STRVAL(OP_EMULEINFO), _STRVAL(OP_EMULEINFOANSWER), _STRVAL(OP_COMPRESSEDPART), _STRVAL(OP_QUEUERANKING), _STRVAL(OP_FILEDESC), _STRVAL(OP_REQUESTSOURCES), _STRVAL(OP_ANSWERSOURCES), _STRVAL(OP_REQUESTSOURCES2), _STRVAL(OP_ANSWERSOURCES2), _STRVAL(OP_PUBLICKEY), _STRVAL(OP_SIGNATURE), _STRVAL(OP_SECIDENTSTATE), _STRVAL(OP_REQUESTPREVIEW), _STRVAL(OP_PREVIEWANSWER), _STRVAL(OP_MULTIPACKET), _STRVAL(OP_MULTIPACKETANSWER), _STRVAL(OP_PEERCACHE_QUERY), _STRVAL(OP_PEERCACHE_ANSWER), _STRVAL(OP_PEERCACHE_ACK), _STRVAL(OP_PUBLICIP_ANSWER), _STRVAL(OP_PUBLICIP_REQ), _STRVAL(OP_PORTTEST), _STRVAL(OP_CALLBACK), _STRVAL(OP_BUDDYPING), _STRVAL(OP_BUDDYPONG), _STRVAL(OP_REASKCALLBACKTCP), _STRVAL(OP_AICHANSWER), _STRVAL(OP_AICHREQUEST), _STRVAL(OP_AICHFILEHASHANS), _STRVAL(OP_AICHFILEHASHREQ), _STRVAL(OP_COMPRESSEDPART_I64), _STRVAL(OP_SENDINGPART_I64), _STRVAL(OP_REQUESTPARTS_I64), _STRVAL(OP_MULTIPACKET_EXT), //_STRVAL(OP_CHATCAPTCHAREQ), //_STRVAL(OP_CHATCAPTCHARES), _STRVAL(OP_FWCHECKUDPREQ), _STRVAL(OP_KAD_FWTCPCHECK_ACK) }; for (int i = 0; i < _countof(_aOpcodes); i++) { if (_aOpcodes[i].uOpcode == opcode) return _aOpcodes[i].pszOpcode; } CString strOpcode; strOpcode.Format(_T("0x%02x"), opcode); return strOpcode; } #undef _STRVAL CString DbgGetClientTCPPacket(UINT protocol, UINT opcode, UINT size) { CString str; if (protocol == OP_EDONKEYPROT) str.Format(_T("protocol=eDonkey opcode=%s size=%u"), DbgGetDonkeyClientTCPOpcode(opcode), size); else if (protocol == OP_PACKEDPROT) str.Format(_T("protocol=Packed opcode=%s size=%u"), DbgGetMuleClientTCPOpcode(opcode), size); else if (protocol == OP_EMULEPROT) str.Format(_T("protocol=eMule opcode=%s size=%u"), DbgGetMuleClientTCPOpcode(opcode), size); else str.Format(_T("protocol=0x%02x opcode=0x%02x size=%u"), protocol, opcode, size); return str; } CString DbgGetClientTCPOpcode(UINT protocol, UINT opcode) { CString str; if (protocol == OP_EDONKEYPROT) str.Format(_T("%s"), DbgGetDonkeyClientTCPOpcode(opcode)); else if (protocol == OP_PACKEDPROT) str.Format(_T("%s"), DbgGetMuleClientTCPOpcode(opcode)); else if (protocol == OP_EMULEPROT) str.Format(_T("%s"), DbgGetMuleClientTCPOpcode(opcode)); else str.Format(_T("protocol=0x%02x opcode=0x%02x"), protocol, opcode); return str; } void DebugRecv(LPCSTR pszMsg, const CUpDownClient* client, const uchar* packet, uint32 nIP) { // 111.222.333.444 = 15 chars if (client){ if (client != NULL && packet != NULL) Debug(_T("%-24hs from %s; %s\n"), pszMsg, client->DbgGetClientInfo(true), DbgGetFileInfo(packet)); else if (client != NULL && packet == NULL) Debug(_T("%-24hs from %s\n"), pszMsg, client->DbgGetClientInfo(true)); else if (client == NULL && packet != NULL) Debug(_T("%-24hs; %s\n"), pszMsg, DbgGetFileInfo(packet)); else Debug(_T("%-24hs\n"), pszMsg); } else{ if (nIP != 0 && packet != NULL) Debug(_T("%-24hs from %-15s; %s\n"), pszMsg, ipstr(nIP), DbgGetFileInfo(packet)); else if (nIP != 0 && packet == NULL) Debug(_T("%-24hs from %-15s\n"), pszMsg, ipstr(nIP)); else if (nIP == 0 && packet != NULL) Debug(_T("%-24hs; %s\n"), pszMsg, DbgGetFileInfo(packet)); else Debug(_T("%-24hs\n"), pszMsg); } } void DebugSend(LPCSTR pszMsg, const CUpDownClient* client, const uchar* packet) { if (client != NULL && packet != NULL) Debug(_T(">>> %-20hs to %s; %s\n"), pszMsg, client->DbgGetClientInfo(true), DbgGetFileInfo(packet)); else if (client != NULL && packet == NULL) Debug(_T(">>> %-20hs to %s\n"), pszMsg, client->DbgGetClientInfo(true)); else if (client == NULL && packet != NULL) Debug(_T(">>> %-20hs; %s\n"), pszMsg, DbgGetFileInfo(packet)); else Debug(_T(">>> %-20hs\n"), pszMsg); } void DebugSend(LPCSTR pszOpcode, uint32 ip, uint16 port) { TCHAR szIPPort[22]; _stprintf(szIPPort, _T("%s:%u"), ipstr(ntohl(ip)), port); Debug(_T(">>> %-20hs to %-21s\n"), pszOpcode, szIPPort); } void DebugSendF(LPCSTR pszOpcode, uint32 ip, uint16 port, LPCTSTR pszMsg, ...) { va_list args; va_start(args, pszMsg); TCHAR szIPPort[22]; _stprintf(szIPPort, _T("%s:%u"), ipstr(ntohl(ip)), port); CString str; str.Format(_T(">>> %-20hs to %-21s; "), pszOpcode, szIPPort); str.AppendFormatV(pszMsg, args); va_end(args); Debug(_T("%s\n"), str); } void DebugRecv(LPCSTR pszOpcode, uint32 ip, uint16 port) { TCHAR szIPPort[22]; _stprintf(szIPPort, _T("%s:%u"), ipstr(ntohl(ip)), port); Debug(_T("%-24hs from %-21s\n"), pszOpcode, szIPPort); } void DebugHttpHeaders(const CStringAArray& astrHeaders) { for (int i = 0; i < astrHeaders.GetCount(); i++) { const CStringA& rstrHdr = astrHeaders.GetAt(i); Debug(_T("<%hs\n"), rstrHdr); } } ULONGLONG GetDiskFileSize(LPCTSTR pszFilePath) { static BOOL _bInitialized = FALSE; static DWORD (WINAPI *_pfnGetCompressedFileSize)(LPCTSTR, LPDWORD) = NULL; if (!_bInitialized){ _bInitialized = TRUE; (FARPROC&)_pfnGetCompressedFileSize = GetProcAddress(GetModuleHandle(_T("kernel32.dll")), _TWINAPI("GetCompressedFileSize")); } // If the file is not compressed nor sparse, 'GetCompressedFileSize' returns the 'normal' file size. if (_pfnGetCompressedFileSize) { ULONGLONG ullCompFileSize; LPDWORD pdwCompFileSize = (LPDWORD)&ullCompFileSize; pdwCompFileSize[0] = (*_pfnGetCompressedFileSize)(pszFilePath, &pdwCompFileSize[1]); if (pdwCompFileSize[0] != INVALID_FILE_SIZE || GetLastError() == NO_ERROR) return ullCompFileSize; } // If 'GetCompressedFileSize' failed or is not available, use the default function WIN32_FIND_DATA fd; HANDLE hFind = FindFirstFile(pszFilePath, &fd); if (hFind == INVALID_HANDLE_VALUE) return 0; FindClose(hFind); return (ULONGLONG)fd.nFileSizeHigh << 32 | (ULONGLONG)fd.nFileSizeLow; } // Listview helper function void GetPopupMenuPos(CListCtrl& lv, CPoint& point) { // If the context menu was not opened using the right mouse button, // but the keyboard (Shift+F10), get a useful position for the context menu. if (point.x == -1 && point.y == -1) { int iIdxItem = lv.GetNextItem(-1, LVNI_SELECTED | LVNI_FOCUSED); if (iIdxItem != -1) { CRect rc; if (lv.GetItemRect(iIdxItem, &rc, LVIR_BOUNDS)) { point.x = rc.left + lv.GetColumnWidth(0) / 2; point.y = rc.top + rc.Height() / 2; lv.ClientToScreen(&point); } } else { point.x = 16; point.y = 32; lv.ClientToScreen(&point); } } } void GetPopupMenuPos(CTreeCtrl& tv, CPoint& point) { // If the context menu was not opened using the right mouse button, // but the keyboard (Shift+F10), get a useful position for the context menu. if (point.x == -1 && point.y == -1) { HTREEITEM hSel = tv.GetNextItem(TVI_ROOT, TVGN_CARET); if (hSel) { CRect rcItem; if (tv.GetItemRect(hSel, &rcItem, TRUE)) { point.x = rcItem.left; point.y = rcItem.top; tv.ClientToScreen(&point); } } else { point.x = 16; point.y = 32; tv.ClientToScreen(&point); } } } time_t safe_mktime(struct tm* ptm) { if (ptm == NULL) return -1; return mktime(ptm); } CString StripInvalidFilenameChars(const CString& strText, bool bKeepSpaces) { LPCTSTR pszSource = strText; CString strDest; while (*pszSource != _T('\0')) { if (!(((_TUCHAR)*pszSource >= 0 && (_TUCHAR)*pszSource <= 31) || // lots of invalid chars for filenames in windows :=) *pszSource == _T('\"') || *pszSource == _T('*') || *pszSource == _T('<') || *pszSource == _T('>') || *pszSource == _T('?') || *pszSource == _T('|') || *pszSource == _T('\\') || *pszSource == _T('/') || *pszSource == _T(':')) ) { if (!bKeepSpaces && *pszSource == _T(' ')) strDest += _T("%20"); else strDest += *pszSource; } pszSource++; } const LPCTSTR apszReservedFilenames[] = { _T("NUL"), _T("CON"), _T("PRN"), _T("AUX"), _T("CLOCK$"), _T("COM1"),_T("COM2"),_T("COM3"),_T("COM4"),_T("COM5"),_T("COM6"),_T("COM7"),_T("COM8"),_T("COM9"), _T("LPT1"),_T("LPT2"),_T("LPT3"),_T("LPT4"),_T("LPT5"),_T("LPT6"),_T("LPT7"),_T("LPT8"),_T("LPT9") }; for (int i = 0; i < _countof(apszReservedFilenames); i++) { int nPrefixLen = _tcslen(apszReservedFilenames[i]); if (_tcsnicmp(strDest, apszReservedFilenames[i], nPrefixLen) == 0) { if (strDest.GetLength() == nPrefixLen) { // Filename is a reserved file name: // Append an underscore character strDest += _T("_"); break; } else if (strDest[nPrefixLen] == _T('.')) { // Filename starts with a reserved file name followed by a '.' character: // Replace that ',' character with an '_' character. LPTSTR pszDest = strDest.GetBuffer(strDest.GetLength()); pszDest[nPrefixLen] = _T('_'); strDest.ReleaseBuffer(strDest.GetLength()); break; } } } return strDest; } CString CreateED2kLink(const CAbstractFile* pFile, bool bEscapeLink) { if( pFile->GetFileSize()==(uint64)0 || pFile->HasNullHash() ) return _T(""); CString strLink; CString strFileName = pFile->GetFileName(); if( pFile->GetFileNameConflicted() ) { int nBracketPos1 = strFileName.ReverseFind(_T('(')); int nBracketPos2 = strFileName.ReverseFind(_T(')')); if( nBracketPos2>nBracketPos1 && nBracketPos1>=1 ) strFileName.Delete(nBracketPos1,nBracketPos2-nBracketPos1+1); } strLink.Format(_T("ed2k://|file|%s|%I64u|%s|"), EncodeUrlUtf8(StripInvalidFilenameChars(strFileName, false)), pFile->GetFileSize(), EncodeBase16(pFile->GetFileHash(),16)); if (bEscapeLink) strLink += _T("/"); return strLink; } CString CreateHTMLED2kLink(const CAbstractFile* f) { CString strCode = _T("<a href=\"") + CreateED2kLink(f) + _T("\">") + StripInvalidFilenameChars(f->GetFileName(), true) + _T("</a>"); return strCode; } bool operator==(const CCKey& k1,const CCKey& k2) { return !md4cmp(k1.m_key, k2.m_key); } bool operator==(const CSKey& k1,const CSKey& k2) { return !md4cmp(k1.m_key, k2.m_key); } CString ipstr(uint32 nIP) { // following gives the same string as 'inet_ntoa(*(in_addr*)&nIP)' but is not restricted to ASCII strings const BYTE* pucIP = (BYTE*)&nIP; CString strIP; strIP.ReleaseBuffer(_stprintf(strIP.GetBuffer(3+1+3+1+3+1+3), _T("%u.%u.%u.%u"), pucIP[0], pucIP[1], pucIP[2], pucIP[3])); return strIP; } CString ipstr(uint32 nIP, uint16 nPort) { // following gives the same string as 'inet_ntoa(*(in_addr*)&nIP)' but is not restricted to ASCII strings const BYTE* pucIP = (BYTE*)&nIP; CString strIP; strIP.ReleaseBuffer(_stprintf(strIP.GetBuffer(3+1+3+1+3+1+3+1+5), _T("%u.%u.%u.%u:%u"), pucIP[0], pucIP[1], pucIP[2], pucIP[3], nPort)); return strIP; } CString ipstr(LPCTSTR pszAddress, uint16 nPort) { CString strIPPort; strIPPort.Format(_T("%s:%u"), pszAddress, nPort); return strIPPort; } CStringA ipstrA(uint32 nIP) { const BYTE* pucIP = (BYTE*)&nIP; CStringA strIP; strIP.ReleaseBuffer(sprintf(strIP.GetBuffer(3+1+3+1+3+1+3), "%u.%u.%u.%u", pucIP[0], pucIP[1], pucIP[2], pucIP[3])); return strIP; } void ipstrA(CHAR* pszAddress, int iMaxAddress, uint32 nIP) { const BYTE* pucIP = (BYTE*)&nIP; _snprintf(pszAddress, iMaxAddress, "%u.%u.%u.%u", pucIP[0], pucIP[1], pucIP[2], pucIP[3]); } bool IsDaylightSavingTimeActive(LONG& rlDaylightBias) { TIME_ZONE_INFORMATION tzi; if (GetTimeZoneInformation(&tzi) != TIME_ZONE_ID_DAYLIGHT) return false; rlDaylightBias = tzi.DaylightBias; return true; } bool IsNTFSVolume(LPCTSTR pszVolume) { DWORD dwMaximumComponentLength = 0; DWORD dwFileSystemFlags = 0; TCHAR szFileSystemNameBuffer[128]; if (!GetVolumeInformation(pszVolume, NULL, 0, NULL, &dwMaximumComponentLength, &dwFileSystemFlags, szFileSystemNameBuffer, 128)) return false; return (_tcscmp(szFileSystemNameBuffer, _T("NTFS")) == 0); } bool IsFATVolume(LPCTSTR pszVolume) { DWORD dwMaximumComponentLength = 0; DWORD dwFileSystemFlags = 0; TCHAR szFileSystemNameBuffer[128]; if (!GetVolumeInformation(pszVolume, NULL, 0, NULL, &dwMaximumComponentLength, &dwFileSystemFlags, szFileSystemNameBuffer, 128)) return false; return (_tcsnicmp(szFileSystemNameBuffer, _T("FAT"), 3) == 0); } bool IsFileOnNTFSVolume(LPCTSTR pszFilePath) { CString strRootPath(pszFilePath); BOOL bResult = PathStripToRoot(strRootPath.GetBuffer()); strRootPath.ReleaseBuffer(); if (!bResult) return false; PathAddBackslash(strRootPath.GetBuffer()); strRootPath.ReleaseBuffer(); return IsNTFSVolume(strRootPath); } bool IsFileOnFATVolume(LPCTSTR pszFilePath) { CString strRootPath(pszFilePath); BOOL bResult = PathStripToRoot(strRootPath.GetBuffer()); strRootPath.ReleaseBuffer(); if (!bResult) return false; PathAddBackslash(strRootPath.GetBuffer()); strRootPath.ReleaseBuffer(); return IsFATVolume(strRootPath); } bool IsAutoDaylightTimeSetActive() { CRegKey key; if (key.Open(HKEY_LOCAL_MACHINE, _T("SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation"), KEY_READ) == ERROR_SUCCESS) { DWORD dwDisableAutoDaylightTimeSet = 0; if (key.QueryDWORDValue(_T("DisableAutoDaylightTimeSet"), dwDisableAutoDaylightTimeSet) == ERROR_SUCCESS) { if (dwDisableAutoDaylightTimeSet) return false; } } return true; // default to 'Automatically adjust clock for daylight saving changes' } bool AdjustNTFSDaylightFileTime(uint32& ruFileDate, LPCTSTR pszFilePath) { if (!thePrefs.GetAdjustNTFSDaylightFileTime()) return false; if (ruFileDate == 0 || ruFileDate == -1) return false; // See also KB 129574 LONG lDaylightBias = 0; if (IsDaylightSavingTimeActive(lDaylightBias)) { if (IsAutoDaylightTimeSetActive()) { if (IsFileOnNTFSVolume(pszFilePath)) { ruFileDate += lDaylightBias*60; return true; } } else { // If 'Automatically adjust clock for daylight saving changes' is disabled and // if the file's date is within DST period, we get again a wrong file date. // // If 'Automatically adjust clock for daylight saving changes' is disabled, // Windows always reports 'Active DST'(!!) with a bias of '0' although there is no // DST specified. This means also, that there is no chance to determine if a date is // within any DST. // Following code might be correct, but because we don't have a DST and because we don't have a bias, // the code won't do anything useful. /*struct tm* ptm = localtime((time_t*)&ruFileDate); bool bFileDateInDST = (ptm && ptm->tm_isdst == 1); if (bFileDateInDST) { ruFileDate += lDaylightBias*60; return true; }*/ } } return false; } bool ExpandEnvironmentStrings(CString& rstrStrings) { DWORD dwSize = ExpandEnvironmentStrings(rstrStrings, NULL, 0); if (dwSize == 0) return false; CString strExpanded; DWORD dwCount = ExpandEnvironmentStrings(rstrStrings, strExpanded.GetBuffer(dwSize-1), dwSize); if (dwCount == 0 || dwCount != dwSize){ ASSERT(0); return false; } strExpanded.ReleaseBuffer(dwCount-1); rstrStrings = strExpanded; return true; } uint16 GetRandomUInt16() { #if RAND_MAX == 0x7fff // get 2 random numbers UINT uRand0 = rand(); UINT uRand1 = rand(); // NOTE: if that assert fires, you have most likely called that function *without* calling 'srand' first. // NOTE: each spawned thread HAS to call 'srand' for itself to get real random numbers. ASSERT( !(uRand0 == 41 && uRand1 == 18467) ); return (uint16)(uRand0 | ((uRand1 >= RAND_MAX/2) ? 0x8000 : 0x0000)); #else #error "Implement it!" #endif } uint32 GetRandomUInt32() { #if RAND_MAX == 0x7fff //return ((uint32)GetRandomUInt16() << 16) | (uint32)GetRandomUInt16(); // this would give the receiver the following information: // random number N // random number N+1 is below or greater/equal than 0x8000 // random number N+2 // random number N+3 is below or greater/equal than 0x8000 uint32 uRand0 = GetRandomUInt16(); srand(GetTickCount()); uint32 uRand1 = GetRandomUInt16(); return (uRand0 << 16) | uRand1; #else #error "Implement it!" #endif } HWND ReplaceRichEditCtrl(CWnd* pwndRE, CWnd* pwndParent, CFont* pFont) { HWND hwndNewRE = NULL; ASSERT( pwndRE ); if (pwndRE) { CHAR szClassName[MAX_PATH]; if (GetClassNameA(*pwndRE, szClassName, ARRSIZE(szClassName)) && __ascii_stricmp(szClassName, "RichEdit20W")==0) return NULL; CRect rcWnd; pwndRE->GetWindowRect(&rcWnd); DWORD dwStyle = pwndRE->GetStyle(); dwStyle |= WS_VSCROLL | WS_HSCROLL; DWORD dwExStyle = pwndRE->GetExStyle(); CString strText; pwndRE->GetWindowText(strText); UINT uCtrlID = GetWindowLong(*pwndRE, GWL_ID); pwndRE->DestroyWindow(); pwndRE = NULL; pwndParent->ScreenToClient(&rcWnd); HWND hwndNewRE = CreateWindowEx(dwExStyle, RICHEDIT_CLASS, strText, dwStyle, rcWnd.left, rcWnd.top, rcWnd.Width(), rcWnd.Height(), pwndParent->m_hWnd, (HMENU)uCtrlID, NULL, NULL); if (hwndNewRE && pFont && pFont->m_hObject) ::SendMessage(hwndNewRE, WM_SETFONT, (WPARAM)pFont->m_hObject, 0); } return hwndNewRE; } void InstallSkin(LPCTSTR /*pszSkinPackage*/) { // Comment UI /*if (thePrefs.GetSkinProfileDir().IsEmpty() || _taccess(thePrefs.GetSkinProfileDir(), 0) != 0) { AfxMessageBox(GetResString(IDS_INSTALL_SKIN_NODIR), MB_ICONERROR); return; } static const TCHAR _szSkinSuffix[] = _T(".") EMULSKIN_BASEEXT _T(".ini"); TCHAR szExt[_MAX_EXT]; _tsplitpath(pszSkinPackage, NULL, NULL, NULL, szExt); _tcslwr(szExt); if (_tcscmp(szExt, _T(".zip")) == 0) { CZIPFile zip; if (zip.Open(pszSkinPackage)) { // Search the "*.eMuleSkin.ini" file.. CZIPFile::File* zfIniFile = NULL; for (int i = 0; i < zip.GetCount(); i++) { CZIPFile::File* zf = zip.GetFile(i); if (zf && zf->m_sName.Right(ARRSIZE(_szSkinSuffix)-1).CompareNoCase(_szSkinSuffix) == 0) { zfIniFile = zf; break; } } if (zfIniFile) { for (int i = 0; i < zip.GetCount(); i++) { CZIPFile::File* zf = zip.GetFile(i); if (zf) { if (zf->m_sName.IsEmpty()) continue; if (zf->m_sName[0] == _T('\\') || zf->m_sName[0] == _T('/')) continue; if (zf->m_sName.Find(_T(':')) != -1) continue; if (zf->m_sName.Find(_T("..\\")) != -1 || zf->m_sName.Find(_T("../")) != -1) continue; if (zf->m_sName[zf->m_sName.GetLength()-1] == _T('/')) { CString strDstDirPath; PathCanonicalize(strDstDirPath.GetBuffer(MAX_PATH), thePrefs.GetMuleDirectory(EMULE_SKINDIR) + _T('\\') + zf->m_sName.Left(zf->m_sName.GetLength()-1)); strDstDirPath.ReleaseBuffer(); if (!CreateDirectory(strDstDirPath, NULL)){ DWORD dwError = GetLastError(); CString strError; strError.Format(GetResString(IDS_INSTALL_SKIN_DIR_ERROR), strDstDirPath, GetErrorMessage(dwError)); AfxMessageBox(strError, MB_ICONERROR); break; } } else { CString strDstFilePath; PathCanonicalize(strDstFilePath.GetBuffer(MAX_PATH), thePrefs.GetMuleDirectory(EMULE_SKINDIR) + _T('\\') + zf->m_sName); strDstFilePath.ReleaseBuffer(); SetLastError(0); if (!zf->Extract(strDstFilePath)){ DWORD dwError = GetLastError(); CString strError; strError.Format(GetResString(IDS_INSTALL_SKIN_FILE_ERROR), zf->m_sName, strDstFilePath, GetErrorMessage(dwError)); AfxMessageBox(strError, MB_ICONERROR); break; } } } } } else { AfxMessageBox(GetResString(IDS_INSTALL_SKIN_PKG_ERROR), MB_ICONERROR); } zip.Close(); } else { AfxMessageBox(GetResString(IDS_INSTALL_SKIN_PKG_ERROR), MB_ICONERROR); } } else if (_tcscmp(szExt, _T(".rar")) == 0) { CRARFile rar; if (rar.Open(pszSkinPackage)) { bool bError = false; bool bFoundSkinINIFile = false; CString strFileName; while (rar.GetNextFile(strFileName)) { if (strFileName.IsEmpty()) { rar.Skip(); continue; } if (strFileName[0] == _T('\\') || strFileName[0] == _T('/')) { rar.Skip(); continue; } if (strFileName.Find(_T(':')) != -1) { rar.Skip(); continue; } if (strFileName.Find(_T("..\\")) != -1 || strFileName.Find(_T("../")) != -1) { rar.Skip(); continue; } if (!bFoundSkinINIFile && strFileName.Right(ARRSIZE(_szSkinSuffix)-1).CompareNoCase(_szSkinSuffix) == 0) bFoundSkinINIFile = true; // No need to care about possible available sub-directories. UnRAR.DLL cares about that automatically. CString strDstFilePath; PathCanonicalize(strDstFilePath.GetBuffer(MAX_PATH), thePrefs.GetMuleDirectory(EMULE_SKINDIR) + _T('\\') + strFileName); strDstFilePath.ReleaseBuffer(); SetLastError(0); if (!rar.Extract(strDstFilePath)) { DWORD dwError = GetLastError(); CString strError; strError.Format(GetResString(IDS_INSTALL_SKIN_FILE_ERROR), strFileName, strDstFilePath, GetErrorMessage(dwError)); AfxMessageBox(strError, MB_ICONERROR); bError = true; break; } } if (!bError && !bFoundSkinINIFile) AfxMessageBox(GetResString(IDS_INSTALL_SKIN_PKG_ERROR), MB_ICONERROR); rar.Close(); } else { CString strError; strError.Format(_T("%s\r\n\r\nDownload latest version of UNRAR.DLL from http://www.rarlab.com and copy UNRAR.DLL into eMule installation folder."), GetResString(IDS_INSTALL_SKIN_PKG_ERROR)); AfxMessageBox(strError, MB_ICONERROR); } }*/ } void TriggerPortTest(uint16 /*tcp*/, uint16 /*udp*/) { CString m_sTestURL; // do not alter the connection test, this is a manual test only. If you want to change the behaviour, use your server! // Comment UI //m_sTestURL.Format(PORTTESTURL, tcp, udp , thePrefs.GetLanguageID()); // the portcheck will need to do an obfuscated callback too if obfuscation is requested, so we have to provide our userhash so it can create the key if (thePrefs.IsClientCryptLayerRequested()) m_sTestURL += _T("&obfuscated_test=") + md4str(thePrefs.GetUserHash()); ShellOpenFile(m_sTestURL); } int CompareLocaleStringNoCase(LPCTSTR psz1, LPCTSTR psz2) { __try { if( psz1==NULL || psz2==NULL ) return 0; // SDK says: The 'CompareString' function is optimized to run at the highest speed when 'dwCmpFlags' is set to 0 // or NORM_IGNORECASE, and 'cchCount1' and 'cchCount2' have the value -1. int iResult = CompareString(GetThreadLocale(), NORM_IGNORECASE, psz1, -1, psz2, -1); if (iResult == 0) return 0; return iResult - 2; } //catch( ... ) __except(1) { return 0; } } int CompareLocaleString(LPCTSTR psz1, LPCTSTR psz2) { // SDK says: The 'CompareString' function is optimized to run at the highest speed when 'dwCmpFlags' is set to 0 // or NORM_IGNORECASE, and 'cchCount1' and 'cchCount2' have the value -1. int iResult = CompareString(GetThreadLocale(), 0, psz1, -1, psz2, -1); if (iResult == 0) return 0; return iResult - 2; } int __cdecl CompareCStringPtrLocaleStringNoCase(const void* p1, const void* p2) { const CString* pstr1 = (const CString*)p1; const CString* pstr2 = (const CString*)p2; return CompareLocaleStringNoCase(*pstr1, *pstr2); } int __cdecl CompareCStringPtrLocaleString(const void* p1, const void* p2) { const CString* pstr1 = (const CString*)p1; const CString* pstr2 = (const CString*)p2; return CompareLocaleString(*pstr1, *pstr2); } void Sort(CStringArray& astr, int (__cdecl *pfnCompare)(const void*, const void*)) { qsort(astr.GetData(), astr.GetCount(), sizeof(CString*), pfnCompare); } int __cdecl CompareCStringPtrPtrLocaleStringNoCase(const void* p1, const void* p2) { const CString* pstr1 = *(const CString**)p1; const CString* pstr2 = *(const CString**)p2; return CompareLocaleStringNoCase(*pstr1, *pstr2); } int __cdecl CompareCStringPtrPtrLocaleString(const void* p1, const void* p2) { const CString* pstr1 = *(const CString**)p1; const CString* pstr2 = *(const CString**)p2; return CompareLocaleString(*pstr1, *pstr2); } void Sort(CSimpleArray<const CString*>& apstr, int (__cdecl *pfnCompare)(const void*, const void*)) { qsort(apstr.GetData(), apstr.GetSize(), sizeof(CString*), pfnCompare); } CString GetAutoStartRegString() { TCHAR sExeFilePath[490]; DWORD length; length = ::GetModuleFileName(NULL, sExeFilePath, 490); if(!length) return _T(""); CString sFullExeCommand; sFullExeCommand.Format(_T("%s -AutoStart"), sExeFilePath); return sFullExeCommand; } bool IsAutoStartRegistered() { CString strKeyName; TCHAR szValue[MAX_PATH]; ULONG ulValueCch = MAX_PATH; LONG lResult; strKeyName = _T("eMuleAutoStart"); CRegKey mKey; lResult = mKey.Open(HKEY_CURRENT_USER, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Run"), KEY_READ); if (ERROR_SUCCESS != lResult) return false; lResult = mKey.QueryStringValue(strKeyName, szValue, &ulValueCch); mKey.Close(); if (ERROR_SUCCESS != lResult || 0 == ulValueCch) return false; CString sFullExeCommand = GetAutoStartRegString(); if (0 == sFullExeCommand.CompareNoCase(szValue)) return true; else return false; } void AddAutoStart() { //#ifndef _DEBUG if (IsAutoStartRegistered()) return; RemAutoStart(); CString strKeyName; strKeyName = _T("eMuleAutoStart"); CString sFullExeCommand = GetAutoStartRegString(); CRegKey mKey; mKey.Create(HKEY_CURRENT_USER, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Run"), REG_NONE,REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL,NULL); mKey.SetStringValue(strKeyName, sFullExeCommand); mKey.Close(); //#endif } void RemAutoStart() { if (!IsAutoStartRegistered()) return; CString strKeyName; strKeyName = _T("eMuleAutoStart"); CRegKey mKey; mKey.Create(HKEY_CURRENT_USER, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Run"), REG_NONE,REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL,NULL); mKey.DeleteValue(strKeyName); mKey.Close(); } int FontPointSizeToLogUnits(int nPointSize) { HDC hDC = ::GetDC(NULL); if (hDC) { // convert nPointSize to logical units based on pDC POINT pt; pt.y = ::GetDeviceCaps(hDC, LOGPIXELSY) * nPointSize; pt.y /= 720; // 72 points/inch, 10 decipoints/point pt.x = 0; ::DPtoLP(hDC, &pt, 1); POINT ptOrg = { 0, 0 }; ::DPtoLP(hDC, &ptOrg, 1); nPointSize = -abs(pt.y - ptOrg.y); ::ReleaseDC(NULL, hDC); } return nPointSize; } bool IsUnicodeFile(LPCTSTR pszFilePath) { bool bResult = false; FILE* fp = _tfsopen(pszFilePath, _T("rb"), _SH_DENYWR); if (fp != NULL) { WORD wBOM = 0; bResult = (fread(&wBOM, sizeof(wBOM), 1, fp) == 1 && wBOM == 0xFEFF); fclose(fp); } return bResult; } bool RegularExpressionMatch(CString regexpr, CString teststring) { CAtlRegExp<> reFN; REParseError status = reFN.Parse( regexpr ); if (REPARSE_ERROR_OK != status) { // Unexpected error. return false; } CAtlREMatchContext<> mcUrl; if (!reFN.Match( teststring, &mcUrl)) { // Unexpected error. return false; } else { return true; } } ULONGLONG GetModuleVersion(LPCTSTR pszFilePath) { ULONGLONG ullVersion = 0; DWORD dwUnused; DWORD dwVerInfSize = GetFileVersionInfoSize(const_cast<LPTSTR>(pszFilePath), &dwUnused); if (dwVerInfSize != 0) { LPBYTE pucVerInf = (LPBYTE)calloc(dwVerInfSize, 1); if (pucVerInf) { if (GetFileVersionInfo(const_cast<LPTSTR>(pszFilePath), 0, dwVerInfSize, pucVerInf)) { VS_FIXEDFILEINFO* pFileInf = NULL; UINT uLen = 0; if (VerQueryValue(pucVerInf, _T("\\"), (LPVOID*)&pFileInf, &uLen) && pFileInf && uLen) { ullVersion = MAKEDLLVERULL(HIWORD(pFileInf->dwFileVersionMS), LOWORD(pFileInf->dwFileVersionMS), HIWORD(pFileInf->dwFileVersionLS), LOWORD(pFileInf->dwFileVersionLS)); } } free(pucVerInf); } } return ullVersion; } ULONGLONG GetModuleVersion(HMODULE hModule) { TCHAR szFilePath[MAX_PATH] = {0}; if (GetModuleFileName(hModule, szFilePath, _countof(szFilePath)) == 0 || szFilePath[0] == _T('\0')) return 0; return GetModuleVersion(szFilePath); } int GetPathDriveNumber(CString path) { if (path.GetLength()<3 || path.GetAt(1)!=_T(':') || path.GetAt(2)!=_T('\\')) return -1; return path.MakeLower().GetAt(0) - 97; } UINT64 GetFreeTempSpace(int){ return GetFreeDiskSpaceX(thePrefs.GetMuleDirectory(EMULE_INCOMINGDIR)); } bool DoCollectionRegFix(bool checkOnly) { //Changed by thilon on 2007.11.05, for 默认关联ED2K链接 /*int iHandled = 0;*/ CRegKey regkey; if (regkey.Create(HKEY_CLASSES_ROOT, COLLECTION_FILEEXTENSION) == ERROR_SUCCESS) { TCHAR szBuff[MAX_PATH]; ULONG nSize = _countof(szBuff); regkey.QueryStringValue(NULL, szBuff, &nSize); if (_tcsicmp(szBuff, _T("easyMule")) != 0) { regkey.SetStringValue(NULL, _T("easyMule")); //iHandled++; } regkey.Close(); } /*if (checkOnly && iHandled == 0) { return true; }*/ if (regkey.Create(HKEY_CLASSES_ROOT, _T("easyMule\\shell\\open\\command")) == ERROR_SUCCESS) { TCHAR rbuffer[500]; ULONG maxsize = ARRSIZE(rbuffer); regkey.QueryStringValue(NULL, rbuffer, &maxsize); TCHAR modbuffer[490]; ::GetModuleFileName(NULL, modbuffer, ARRSIZE(modbuffer)); CString strCanonFileName = modbuffer; strCanonFileName.Replace(_T("%"), _T("%%")); TCHAR regbuffer[520]; _sntprintf(regbuffer, ARRSIZE(regbuffer), _T("\"%s\" \"%%1\""), strCanonFileName); if (_tcsicmp(rbuffer, regbuffer) != 0) { if (checkOnly) return true; regkey.SetStringValue(NULL, regbuffer); regkey.Create(HKEY_CLASSES_ROOT, _T("easyMule\\DefaultIcon")); regkey.SetStringValue(NULL, CString(modbuffer) + CString(_T(",1"))); regkey.Create(HKEY_CLASSES_ROOT, _T("easyMule")); regkey.SetStringValue(NULL, _T("easyMule Collection File")); regkey.Open(HKEY_CLASSES_ROOT, _T("easyMule\\shell\\open")); regkey.RecurseDeleteKey(_T("ddexec")); regkey.RecurseDeleteKey(_T("ddeexec")); regkey.Create(HKEY_CLASSES_ROOT, COLLECTION_FILEEXTENSION); regkey.SetStringValue(NULL, _T("easyMule")); } else { regkey.Open(HKEY_CLASSES_ROOT, _T("easyMule\\shell\\open")); regkey.RecurseDeleteKey(_T("ddexec")); regkey.RecurseDeleteKey(_T("ddeexec")); regkey.Create(HKEY_CLASSES_ROOT, COLLECTION_FILEEXTENSION); regkey.SetStringValue(NULL, _T("easyMule")); } regkey.Close(); } return false; } bool gotostring(CFile &file, uchar *find, LONGLONG plen) { bool found = false; LONGLONG i=0; LONGLONG j=0; //LONGLONG plen = strlen(find); LONGLONG len = file.GetLength() - file.GetPosition(); uchar temp; while (!found && i < len) { file.Read(&temp,1); if (temp == find[j]) j++; else if(temp == find[0]) j=1; else j=0; if (j==plen) return true; i++; } return false; } //Chocobo Start //获取随机端口,added by Chocobo on 2006.08.02 uint16 SafeRandomPort(void) { uint16 safelist[]={4160,4170, 4660,4670, 5140,5150, 5610,5620, 6250,6260, 6640,6650, 7110,7120, 7550,7560}; int iFragNum = sizeof(safelist)/sizeof(uint16)/2; int iTotal = 0; int port = 0; for( int i = 0; i < iFragNum; i++ ) { iTotal += safelist[2*i+1]- safelist[2*i]; } int rval = (int)(((double)rand() / RAND_MAX) * iTotal); for( int i = 0; rval >= 0; i++ ) { port = safelist[i*2] + min( rval, safelist[i*2+1] - safelist[i*2]); rval -= safelist[i*2+1] - safelist[i*2]; } return (uint16) port; } static void swap_byte (uint8* a, uint8* b) { uint8 bySwap; bySwap = *a; *a = *b; *b = bySwap; } RC4_Key_Struct* RC4CreateKey(const uchar* pachKeyData, uint32 nLen, RC4_Key_Struct* key, bool bSkipDiscard){ uint8 index1; uint8 index2; uint8* pabyState; if (key == NULL) key = new RC4_Key_Struct; pabyState= &key->abyState[0]; for (int i = 0; i < 256; i++) pabyState[i] = (uint8)i; key->byX = 0; key->byY = 0; index1 = 0; index2 = 0; for (int i = 0; i < 256; i++){ index2 = (pachKeyData[index1] + pabyState[i] + index2) % 256; swap_byte(&pabyState[i], &pabyState[index2]); index1 = (uint8)((index1 + 1) % nLen); } if (!bSkipDiscard) RC4Crypt(NULL, NULL, 1024, key); return key; } void RC4Crypt(const uchar* pachIn, uchar* pachOut, uint32 nLen, RC4_Key_Struct* key){ ASSERT( key != NULL && nLen > 0 ); if (key == NULL) return; uint8 byX = key->byX;; uint8 byY = key->byY; uint8* pabyState = &key->abyState[0];; uint8 byXorIndex; for (uint32 i = 0; i < nLen; i++) { byX = (byX + 1) % 256; byY = (pabyState[byX] + byY) % 256; swap_byte(&pabyState[byX], &pabyState[byY]); byXorIndex = (pabyState[byX] + pabyState[byY]) % 256; if (pachIn != NULL) pachOut[i] = pachIn[i] ^ pabyState[byXorIndex]; } key->byX = byX; key->byY = byY; } EFileType GetFileTypeEx(CKnownFile* kfile, bool checkextention, bool checkfileheader, bool nocached) { if (!nocached && kfile->GetVerifiedFileType()!=FILETYPE_UNKNOWN) return kfile->GetVerifiedFileType(); // check file header first EFileType res=FILETYPE_UNKNOWN; CPartFile* pfile=(CPartFile*)kfile; bool test4iso=(kfile->IsPartFile()==false || ( (uint64)pfile->GetFileSize()>0x8000+HEADERCHECKSIZE && pfile->IsComplete(0x8000,0x8000+HEADERCHECKSIZE,true) ) ); if (checkfileheader && (!kfile->IsPartFile() || pfile->IsComplete(0,HEADERCHECKSIZE,true) || test4iso ) ){ unsigned char* headerbuf=headerbuf=(unsigned char*)calloc(HEADERCHECKSIZE,1); if (headerbuf==NULL) return FILETYPE_UNKNOWN; // :-o try { CFile inFile; if (inFile.Open(pfile->GetFilePath(), CFile::modeRead | CFile::shareDenyNone)){ if (kfile->IsPartFile()==false || pfile->IsComplete(0,HEADERCHECKSIZE,true)) { int read=inFile.Read(headerbuf,HEADERCHECKSIZE); if (read==HEADERCHECKSIZE){ if (memcmp(headerbuf,FILEHEADER_ZIP , sizeof(FILEHEADER_ZIP ))==0) res=ARCHIVE_ZIP; else if (memcmp(headerbuf,FILEHEADER_RAR, sizeof(FILEHEADER_RAR))==0) res=ARCHIVE_RAR; else if (memcmp(headerbuf+7,FILEHEADER_ACE_ID, sizeof(FILEHEADER_ACE_ID))==0) res=ARCHIVE_ACE; else if (memcmp(headerbuf,FILEHEADER_WM_ID, sizeof(FILEHEADER_WM_ID))==0) res=WM; else if (memcmp(headerbuf,FILEHEADER_AVI_ID, sizeof(FILEHEADER_AVI_ID))==0 && strncmp((const char*)headerbuf+8,"AVI",3)==0 ) res=VIDEO_AVI; else if (memcmp(headerbuf,FILEHEADER_MP3_ID, sizeof(FILEHEADER_MP3_ID))==0 || memcmp(headerbuf,FILEHEADER_MP3_ID2, sizeof(FILEHEADER_MP3_ID2))==0 ) res=AUDIO_MPEG; else if (memcmp(headerbuf,FILEHEADER_MPG_ID, sizeof(FILEHEADER_MPG_ID))==0) res=VIDEO_MPG; else if (memcmp(headerbuf,FILEHEADER_PDF_ID, sizeof(FILEHEADER_PDF_ID))==0) res=DOCUMENT_PDF; else if (memcmp(headerbuf,FILEHEADER_PNG_ID, sizeof(FILEHEADER_PNG_ID))==0) res=PIC_PNG; else if (memcmp(headerbuf,FILEHEADER_JPG_ID, sizeof(FILEHEADER_JPG_ID))==0 && ( headerbuf[3]==0xe1 || headerbuf[3]==0xe0 ) ) res=PIC_JPG; else if (memcmp(headerbuf,FILEHEADER_GIF_ID, sizeof(FILEHEADER_GIF_ID))==0 && headerbuf[5]==0x61 && (headerbuf[4]==0x37 || headerbuf[4]==0x39 ) ) res=PIC_JPG; else if (memcmp(headerbuf,FILEHEADER_EXECUTABLE_ID, sizeof(FILEHEADER_EXECUTABLE_ID))==0 ) res=FILETYPE_EXECUTABLE; else if (((headerbuf[0] & 0xFF) == 0xFF) && ((headerbuf[1] & 0xE0) == 0xE0)) { res=AUDIO_MPEG; } } } if (res==FILETYPE_UNKNOWN && test4iso) { inFile.Seek(0x8000 , CFile::begin); int read=inFile.Read(headerbuf,HEADERCHECKSIZE); if (read==HEADERCHECKSIZE) { if (memcmp(headerbuf,FILEHEADER_ISO_ID, sizeof(FILEHEADER_ISO_ID))==0) res=IMAGE_ISO; } } inFile.Close(); } } catch(...) { ASSERT(0); } free(headerbuf); if (res!=FILETYPE_UNKNOWN) { kfile->SetVerifiedFileType(res); return res; } } if (!checkextention) return res; CString extLC; int posD=kfile->GetFileName().ReverseFind(_T('.')); if (posD>=0) extLC=kfile->GetFileName().Mid(posD+1).MakeUpper(); SFileExts* ext = _fileexts; if (ext){ while (ext->ftype!=FILETYPE_UNKNOWN) { CString testext=ext->extlist; if (testext.Find( _T('|') + extLC + _T('|') )!=-1) return ext->ftype; ext++; } } // rar multivolume old naming if (extLC.GetLength()==3 && extLC.GetAt(0)=='r' && isdigit(extLC.GetAt(1) && isdigit(extLC.GetAt(2) ))) return ARCHIVE_RAR; return FILETYPE_UNKNOWN; } CString GetFiletypeName(EFileType ftype) { SFileExts* ext = _fileexts; if (ext){ while (ext->ftype!=FILETYPE_UNKNOWN) { if (ftype==ext->ftype) return ext->label; ext++; } } return _T("?"); } int IsExtentionTypeof(EFileType ftype, CString fext) { fext=_T('|') + fext + _T('|') ; SFileExts* ext = _fileexts; if (ext){ while (ext->ftype!=FILETYPE_UNKNOWN) { CString testext=ext->extlist; if (ftype==ext->ftype && testext.Find( fext )!=-1) // type matches acceptable extention return true; if (ftype!=ext->ftype && testext.Find( fext )!=-1) // not just unknown ext, but from a different type! return -1; ext++; } } return false; } uint32 LevenshteinDistance(const CString& str1, const CString& str2) { uint32 n1 = str1.GetLength(); uint32 n2 = str2.GetLength(); uint32* p = new uint32[n2+1]; uint32* q = new uint32[n2+1]; uint32* r; p[0] = 0; for(uint32 j = 1; j <= n2; ++j) p[j] = p[j-1] + 1; for(uint32 i = 1; i <= n1; ++i) { q[0] = p[0] + 1; for(uint32 j = 1; j <= n2; ++j ) { uint32 d_del = p[j] + 1; uint32 d_ins = q[j-1] + 1; uint32 d_sub = p[j-1] + (str1.GetAt(i-1) == str2.GetAt(j-1) ? 0 : 1); q[j] = min(min(d_del, d_ins), d_sub); } r = p; p = q; q = r; } uint32 tmp = p[n2]; delete[] p; delete[] q; return tmp; } // Wrapper for _tmakepath which ensures that the outputbuffer does not exceed MAX_PATH // using a smaller buffer without checking the sizes prior calling this function is not safe // If the resulting path would be bigger than MAX_PATH-1, it will be empty and return false (similar to PathCombine) bool _tmakepathlimit(TCHAR *path, const TCHAR *drive, const TCHAR *dir, const TCHAR *fname, const TCHAR *ext){ if (path == NULL){ ASSERT( false ); return false; } uint32 nSize = 64; // the function should actually only add 4 (+1 nullbyte) bytes max extra if (drive != NULL) nSize += _tcsclen(drive); if (dir != NULL) nSize += _tcsclen(dir); if (fname != NULL) nSize += _tcsclen(fname); if (ext != NULL) nSize += _tcsclen(ext); TCHAR* tchBuffer = new TCHAR[nSize]; _tmakepath(tchBuffer, drive, dir, fname, ext); if (_tcslen(tchBuffer) >= MAX_PATH){ path[0] = _T('\0'); ASSERT( false ); delete[] tchBuffer; return false; } else{ _tcscpy(path, tchBuffer); delete[] tchBuffer; return true; } } uint8 GetMyConnectOptions(bool bEncryption, bool bCallback){ // Connect options Tag // 4 Reserved (!) // 1 Direct Callback // 1 CryptLayer Required // 1 CryptLayer Requested // 1 CryptLayer Supported const uint8 uSupportsCryptLayer = (thePrefs.IsClientCryptLayerSupported() && bEncryption) ? 1 : 0; const uint8 uRequestsCryptLayer = (thePrefs.IsClientCryptLayerRequested() && bEncryption) ? 1 : 0; const uint8 uRequiresCryptLayer = (thePrefs.IsClientCryptLayerRequired() && bEncryption) ? 1 : 0; // direct callback is only possible if connected to kad, tcp firewalled and verified UDP open (for example on a full cone NAT) const uint8 uDirectUDPCallback = (bCallback && CGlobalVariable::IsFirewalled() && Kademlia::CKademlia::IsRunning() && !Kademlia::CUDPFirewallTester::IsFirewalledUDP(true) && Kademlia::CUDPFirewallTester::IsVerified()) ? 1 : 0; const uint8 byCryptOptions = (uDirectUDPCallback << 3) | (uRequiresCryptLayer << 2) | (uRequestsCryptLayer << 1) | (uSupportsCryptLayer << 0); return byCryptOptions; } CString PriorityToString(uint8 uPriority, bool bIsAuto) { CString strPriority; switch (uPriority) { case PR_VERYLOW : strPriority = GetResString(IDS_PRIOVERYLOW); break; case PR_LOW : if( bIsAuto ) strPriority = GetResString(IDS_PRIOAUTOLOW); else strPriority = GetResString(IDS_PRIOLOW); break; case PR_NORMAL : if( bIsAuto ) strPriority = GetResString(IDS_PRIOAUTONORMAL); else strPriority = GetResString(IDS_PRIONORMAL); break; case PR_HIGH : if( bIsAuto ) strPriority = GetResString(IDS_PRIOAUTOHIGH); else strPriority = GetResString(IDS_PRIOHIGH); break; case PR_VERYHIGH : strPriority = GetResString(IDS_PRIORELEASE); break; //Xman PowerRelease case PR_POWER: strPriority = GetResString(IDS_POWERRELEASE); break; //Xman end default: strPriority.Empty(); } return strPriority; } CED2KFileLink* CreateFileLinkFromUrl(LPCTSTR lpszUrl) { CED2KLink *pLink = NULL; try { pLink = CED2KLink::CreateLinkFromUrl(lpszUrl); } catch(...) { return NULL; } if (CED2KLink::kFile != pLink->GetKind()) { SAFE_DELETE(pLink); return NULL; } else { return (CED2KFileLink*) pLink; } } // Added by Soar Chin 09/25/2007 to filter extensions LPCTSTR tcscmp_m(LPCTSTR pszWhere, LPCTSTR pszWhat) { if (*pszWhere == 0) return *pszWhat == 0 ? pszWhere : NULL; if (*pszWhat == 0) return NULL; if (*pszWhat == '*') { if (pszWhat [1] == 0) return pszWhere; LPCTSTR psz = tcscmp_m (pszWhere, pszWhat+1); if (psz) return psz; return tcscmp_m (pszWhere+1, pszWhat); } if (*pszWhat != '?') { if (*pszWhere != *pszWhat) return NULL; } return tcscmp_m (pszWhere+1, pszWhat+1) ? pszWhere : NULL; } BOOL IsSuitableExt(LPCTSTR pszExt) { static const TCHAR * pszExts[] = {_T("EXE"),_T("ZIP"),_T("ARJ"),_T("RAR"),_T("LZH"),_T("Z"),_T("GZ"),_T("TGZ"),_T("BZ2"), _T("TBZ2"),_T("GZIP"),_T("TAR"),_T("BIN"),_T("MP3"),_T("M4A"),_T("WAV"),_T("RA"),_T("RAM"),_T("AAC"),_T("AIF"),_T("AVI"), _T("MPG"),_T("MPEG"),_T("QT"), _T("PLJ"),_T("ASF"),_T("MOV"),_T("RM"),_T("MP4"),_T("WMA"),_T("WMV"),_T("MPE"),_T("MPA"), _T("R0*"),_T("R1*"),_T("A0*"),_T("A1*"),_T("TIF"),_T("TIFF"),_T("PDF"),_T("MSI"),_T("ACE"),_T("ISO"),_T("OGG"),_T("7Z"), _T("SEA"),_T("SIT"),_T("SITX"),_T("PPT"),_T("PPS"),_T("CHM"),_T("RMVB"),NULL}; TCHAR * strExt = new TCHAR[_tcslen(pszExt) + 1]; _tcscpy(strExt, pszExt); _tcsupr(strExt); for(const TCHAR ** pszCur = pszExts; *pszCur != NULL; pszCur ++) { if(tcscmp_m(strExt, *pszCur) != NULL) { delete[] strExt; return TRUE; } } delete[] strExt; return FALSE; } BOOL TestUrl(LPCTSTR pszURL, BOOL bTestExt) { if(_tcsnicmp(pszURL, _T("ed2k://"), 7) == 0) return TRUE; if(_tcsnicmp(pszURL, _T("http://"), 7) == 0 || _tcsnicmp (pszURL, _T("ftp://"), 6) == 0) { LPTSTR pszLp = (LPTSTR)_tcsrchr(pszURL, '<'); if(pszLp != NULL) *pszLp = 0; LPCTSTR pszDot = _tcsrchr(pszURL, '.'); if(pszDot == NULL || (bTestExt && !IsSuitableExt(pszDot + 1))) return FALSE; if(pszLp != NULL) *pszLp = '<'; return TRUE; } return FALSE; } CString Decode3URL(LPCTSTR url) { USES_CONVERSION; CStringA tmp; CString Result = url; if (StrStrI(url,_T("thunder://")) == url) { tmp = CStringA(T2CA(url)).Mid(10); tmp = DecodeBase64(tmp); if (tmp.GetLength() > 4 && tmp.Left(2) == _T("AA") && tmp.Right(2) == _T("ZZ")) { tmp = tmp.Mid(2,tmp.GetLength() - 4); Result = OptUtf8ToStr(tmp); } } else if (StrStrI(url,_T("Flashget://")) == url) { tmp = CStringA(T2CA(url)).Mid(11); tmp = DecodeBase64(tmp); if (tmp.GetLength() > 20 && tmp.Left(10) == _T("[FLASHGET]") && tmp.Right(10) == _T("[FLASHGET]")) { tmp = tmp.Mid(10,tmp.GetLength() - 20); Result = OptUtf8ToStr(tmp); } } else if (StrStrI(url,_T("qqdl://")) == url) { tmp = CStringA(T2CA(url)).Mid(7); tmp = DecodeBase64(tmp); if (tmp.GetLength() > 0) { Result = OptUtf8ToStr(tmp); } } return Result; } CString FilterUrls(LPCTSTR pszURL) { CString url; CString result = _T(""); INT len = _tcslen(pszURL), i = 0, j = 0; for(i = 0, j = _tcscspn(pszURL + i, _T("\r\n")); i < len; i += j + 1, j = _tcscspn(pszURL + i, _T("\r\n"))) { if(j > 10) { url.SetString(pszURL + i, j); url = Decode3URL(url); if(TestUrl(url)) result = result + url + _T("\r\n"); } } return result; } BOOL CanChangeHalfOpenConn() { CBetterSP2 betterSP2; return betterSP2.DetectSystemInformation(); } void ChangeHalfOpenConn(int iConnectionCount) { CBetterSP2 betterSP2; if (!betterSP2.DetectSystemInformation()) return; int iConn; if (iConnectionCount < RANGE_MAXHALFOPEN_MIN || iConnectionCount > RANGE_MAXHALFOPEN_MAX) iConn = DFLT_MAXHALFOPEN; else if (iConnectionCount == 0) iConn = DFLT_MAXHALFOPEN; else iConn = iConnectionCount; if (iConn == (int)thePrefs.GetMaxHalfConnections()) return; betterSP2.ChangeTCPIPValue(iConn); thePrefs.SetMaxHalfConnections(iConn); } void ForceBringWindowToTop(HWND hWnd) { ::SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); ::SetWindowPos(hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); SetForegroundWindow(hWnd); SetActiveWindow(hWnd); SetFocus(hWnd); } void BringWindowToSight(HWND hWnd) { if (IsIconic(hWnd)) ShowWindow(hWnd, SW_RESTORE); else if (!IsWindowVisible(hWnd)) ShowWindow(hWnd, SW_SHOW); } void ConvertStrToStrList(CList<CString> *pList, const CString &str) { BOOL bDone; int iStarPos; int iEndPos; CString strLine; int iSepLen; //分隔符的长度 bDone = FALSE; iStarPos = iEndPos = 0; do { iEndPos = str.Find(_T("\n"), iStarPos); if (-1 == iEndPos) { iSepLen = 0; strLine = str.Mid(iStarPos); bDone = TRUE; } else { if (_T('\r') == str.GetAt(iEndPos - 1)) { iSepLen = 2; iEndPos--; } else iSepLen = 1; strLine = str.Mid(iStarPos, iEndPos - iStarPos); iStarPos = iEndPos + iSepLen; } if (!strLine.IsEmpty()) pList->AddTail(strLine.Trim()); } while(!bDone); } CStringA ParseRef(CStringA& url) { int iPos = url.Find('<', 0); CStringA ref = ""; if(iPos > 0) { int iEnd = url.Find('>', iPos); if(iEnd > 0) { ref = url.Mid(iPos + 1, iEnd - iPos - 1).Trim(); int iRef = ref.Find("referer="); if(iRef >= 0) ref = ref.Mid(iRef + 8); else ref = ""; } url = url.Left(iPos); } int pos = url.Find( "#" ); if( pos > 0 ) { url = url.Left( pos ); } return ref; } CStringW ParseRef(CStringW& url) { int iPos = url.Find('<', 0); CStringW ref = _T(""); if(iPos > 0) { int iEnd = url.Find('>', iPos); if(iEnd > 0) { ref = url.Mid(iPos + 1, iEnd - iPos - 1).Trim(); int iRef = ref.Find(_T("referer=")); if(iRef >= 0) ref = ref.Mid(iRef + 8); else ref = ""; } url = url.Left(iPos); int pos = url.Find( L"#" ); if( pos > 0 ) { url = url.Left( pos ); } } return ref; } CString GetFileNameFromUrlStr(const CString& strUrl) { CString sUrlShort,strFileName; if( strUrl.Find(_T("://"))>0 ) sUrlShort = strUrl.Right( strUrl.GetLength() - strUrl.Find(_T("://")) -3 ); else sUrlShort = strUrl; sUrlShort = OptUtf8ToStr(URLDecode(sUrlShort)); if( sUrlShort.Find(_T('#'))>0 ) sUrlShort = sUrlShort.Left( sUrlShort.Find(_T('#')) ); //cut the referer&other info need process by client.. if( sUrlShort.Find(_T('<'))>0 ) sUrlShort = sUrlShort.Left( sUrlShort.Find(_T('<')) ); //cut the referer info.. sUrlShort.Replace(_T('\\'),_T('/')); sUrlShort.Trim(); int iIndex = sUrlShort.ReverseFind(_T('/')); if( iIndex==-1 ) { strFileName = _T("Index.htm"); } else { strFileName = sUrlShort; if(sUrlShort.Find(_T('?'))>0) { strFileName = strFileName.Left(strFileName.Find(_T('?'))); } if(sUrlShort.Find(_T('#'))>0 ) { strFileName = strFileName.Left( strFileName.Find(_T('#'))); } iIndex = strFileName.ReverseFind( _T('/') ); if( iIndex==-1 ) strFileName = _T("Index.htm"); else strFileName = strFileName.Right( strFileName.GetLength() - 1 - iIndex ); if (strFileName.IsEmpty()) strFileName = _T("Index.htm"); } return strFileName; } static inline bool is_base64(unsigned char c) { return (isalnum(c) || (c == '+') || (c == '/')); } static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; static std::string base64_decode(unsigned char const* encoded_string, unsigned int in_len) { int i = 0; int j = 0; int in_ = 0; unsigned char char_array_4[4], char_array_3[3]; std::string ret; while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) { char_array_4[i++] = encoded_string[in_]; in_++; if (i ==4) { for (i = 0; i <4; i++) char_array_4[i] = base64_chars.find(char_array_4[i]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (i = 0; (i < 3); i++) ret += char_array_3[i]; i = 0; } } if (i) { for (j = i; j <4; j++) char_array_4[j] = 0; for (j = 0; j <4; j++) char_array_4[j] = base64_chars.find(char_array_4[j]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (j = 0; (j < i - 1); j++) ret += char_array_3[j]; } return ret; } CStringA DecodeBase64(LPCSTR lpsz) { if (!lpsz) return CStringA(_T("")); std::string str = base64_decode((const unsigned char *)lpsz,strlen(lpsz)); return CStringA (str.c_str()); } BOOL HasNetWorkDrives() { DWORD BitMask; BitMask = ::GetLogicalDrives(); char szDrive[10] = {'\0'}; UINT DriveType; for(int i = 0; i < 26 ; i++) { if (!BitMask >> i) break; if (BitMask >> i & 1) { szDrive[0] = i+'A'; szDrive[1] = ':' ; szDrive[2] = '\0' ; DriveType = GetDriveTypeA(szDrive); if(DriveType == DRIVE_REMOTE) return TRUE; } } return FALSE; }
[ "damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838" ]
[ [ [ 1, 4325 ] ] ]
18b6234c217480f65bc799d8cc91390c9c3606be
f6c641b102ebbffb48e93dd554a0b7eb7e639be7
/Source/Base/Base Graphics Library/WrapMode.cpp
201103eb8fe9d00e4f4eed5896659cb56eb6eda1
[]
no_license
ZAsprose/rtrt-on-gpu
e3ca4921a3429cbc72e0cee8afd946200b83573d
4949e373c273f963467658ca25d39244da7fb4e6
refs/heads/master
2021-01-10T14:42:45.293509
2010-08-25T18:37:19
2010-08-25T18:37:19
53,016,647
0
0
null
null
null
null
UTF-8
C++
false
false
2,386
cpp
/* ----------------------------------------------------------------------------- | B A S E G R A P H I C S L I B R A R Y | ----------------------------------------------------------------------------- Copyright (c) 2009 - 2010 Denis Bogolepov ( denisbogol @ gmail.com ) This library is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "WrapMode.hpp" namespace graphics { /************************************************************************/ /* PUBLIC FIELDS */ /************************************************************************/ const WrapMode WrapMode :: Clamp ( GL_CLAMP, GL_CLAMP, GL_CLAMP ); const WrapMode WrapMode :: Repeat ( GL_REPEAT, GL_REPEAT, GL_REPEAT ); /************************************************************************/ /* CONSTRUCTOR AND DESTRUCTOR */ /************************************************************************/ WrapMode :: WrapMode ( GLint s, GLint t, GLint r ) { WrapS = s; WrapT = t; WrapR = r; } /************************************************************************/ /* PUBLIC METHODS */ /************************************************************************/ void WrapMode :: Setup ( GLenum target ) { glTexParameteri ( target, GL_TEXTURE_WRAP_S, WrapS ); glTexParameteri ( target, GL_TEXTURE_WRAP_T, WrapT ); glTexParameteri ( target, GL_TEXTURE_WRAP_R, WrapR ); } }
[ [ [ 1, 58 ] ] ]
66b4a4eba99e515d9ca10cc753060f405f492596
28b097d96e87de603d75faf24e56394ac16d239f
/logger/myIDDrawSurface7.cpp
4bec67e0ec0da333ab8b263fd7b4db901809c2a7
[]
no_license
RazorbladeByte/ddhack
ecfe5845c24110daf5a89d6937612f5243bc9883
b564e26ad89e112426a0c08e12040eef130bf826
refs/heads/master
2016-09-11T02:41:34.702359
2011-08-17T13:58:14
2011-08-17T13:58:14
2,220,900
9
3
null
null
null
null
UTF-8
C++
false
false
11,267
cpp
#include "StdAfx.h" #include <varargs.h> myIDDrawSurface7::myIDDrawSurface7(LPDIRECTDRAWSURFACE7 pOriginal) { logf(this, "myIDDrawSurface7 Constructor"); m_pIDDrawSurface = pOriginal; } myIDDrawSurface7::~myIDDrawSurface7(void) { logf(this, "myIDDrawSurface7 Destructor"); } HRESULT __stdcall myIDDrawSurface7::QueryInterface (REFIID, LPVOID FAR * b) { logf(this, "myIDDrawSurface7::QueryInterface"); *b = NULL; return E_NOTIMPL; } ULONG __stdcall myIDDrawSurface7::AddRef(void) { logf(this, "myIDDrawSurface7::AddRef"); return(m_pIDDrawSurface->AddRef()); } ULONG __stdcall myIDDrawSurface7::Release(void) { logf(this, "myIDDrawSurface7::Release"); // call original routine ULONG count = m_pIDDrawSurface->Release(); logf(this, "Object Release."); // in case no further Ref is there, the Original Object has deleted itself // so do we here if (count == 0) { m_pIDDrawSurface = NULL; delete(this); } return(count); } HRESULT __stdcall myIDDrawSurface7::AddAttachedSurface(LPDIRECTDRAWSURFACE7 a) { logf(this, "myIDDrawSurface7::AddAttachedSurface"); return m_pIDDrawSurface->AddAttachedSurface(((myIDDrawSurface7*)a)->m_pIDDrawSurface); } HRESULT __stdcall myIDDrawSurface7::AddOverlayDirtyRect(LPRECT a) { logf(this, "myIDDrawSurface7::AddOverlayDirtyRect"); return m_pIDDrawSurface->AddOverlayDirtyRect(a); } HRESULT __stdcall myIDDrawSurface7::Blt(LPRECT a,LPDIRECTDRAWSURFACE7 b, LPRECT c,DWORD d, LPDDBLTFX e) { if (a && c) logf(this, "myIDDrawSurface7::Blt([%d,%d,%d,%d],%08x,[%d,%d,%d,%d],%d,%08x)", a->top,a->left,a->bottom,a->right, b, c->top,c->left,c->bottom,c->right, d, e->dwDDFX); else if (a) logf(this, "myIDDrawSurface7::Blt([%d,%d,%d,%d],%08x,[null],%d,%08x)", a->top,a->left,a->bottom,a->right, b, d, e->dwDDFX); else if (c) logf(this, "myIDDrawSurface7::Blt([null],%08x,[%d,%d,%d,%d],%d,%08x)", b, c->top,c->left,c->bottom,c->right, d, e->dwDDFX); else logf(this, "myIDDrawSurface7::Blt([null],%08x,[null],%d,%08x)", b, d, e->dwDDFX); if (b) b = ((myIDDrawSurface7*)b)->m_pIDDrawSurface; return m_pIDDrawSurface->Blt(a,b,c,d,e); } HRESULT __stdcall myIDDrawSurface7::BltBatch(LPDDBLTBATCH a, DWORD b, DWORD c) { logf(this, "myIDDrawSurface7::BltBatch"); return m_pIDDrawSurface->BltBatch(a,b,c); } HRESULT __stdcall myIDDrawSurface7::BltFast(DWORD a,DWORD b,LPDIRECTDRAWSURFACE7 c, LPRECT d,DWORD e) { logf(this, "myIDDrawSurface7::BltFast"); return m_pIDDrawSurface->BltFast(a,b,((myIDDrawSurface7*)c)->m_pIDDrawSurface,d,e); } HRESULT __stdcall myIDDrawSurface7::DeleteAttachedSurface(DWORD a,LPDIRECTDRAWSURFACE7 b) { logf(this, "myIDDrawSurface7::DeleteAttachedSurface"); return m_pIDDrawSurface->DeleteAttachedSurface(a,((myIDDrawSurface7*)b)->m_pIDDrawSurface); } HRESULT __stdcall myIDDrawSurface7::EnumAttachedSurfaces(LPVOID a,LPDDENUMSURFACESCALLBACK7 b) { logf(this, "myIDDrawSurface7::EnumAttachedSurfaces"); return m_pIDDrawSurface->EnumAttachedSurfaces(a,b); } HRESULT __stdcall myIDDrawSurface7::EnumOverlayZOrders(DWORD a,LPVOID b,LPDDENUMSURFACESCALLBACK7 c) { logf(this, "myIDDrawSurface7::EnumOverlayZOrders"); return m_pIDDrawSurface->EnumOverlayZOrders(a,b,c); } HRESULT __stdcall myIDDrawSurface7::Flip(LPDIRECTDRAWSURFACE7 a, DWORD b) { logf(this, "myIDDrawSurface7::Flip(%08x,%d)", a, b); if (a) a = ((myIDDrawSurface7*)a)->m_pIDDrawSurface; return m_pIDDrawSurface->Flip(a,b); } HRESULT __stdcall myIDDrawSurface7::GetAttachedSurface(LPDDSCAPS2 a, LPDIRECTDRAWSURFACE7 FAR * b) { HRESULT r = m_pIDDrawSurface->GetAttachedSurface(a,b); *b = new myIDDrawSurface7(*b); logf(this, "myIDDrawSurface7::GetAttachedSurface([%d], %08x) return %d", a->dwCaps, b, r); return r; } HRESULT __stdcall myIDDrawSurface7::GetBltStatus(DWORD a) { logf(this, "myIDDrawSurface7::GetBltStatus"); return m_pIDDrawSurface->GetBltStatus(a); } HRESULT __stdcall myIDDrawSurface7::GetCaps(LPDDSCAPS2 a) { logf(this, "myIDDrawSurface7::GetCaps"); return m_pIDDrawSurface->GetCaps(a); } HRESULT __stdcall myIDDrawSurface7::GetClipper(LPDIRECTDRAWCLIPPER FAR* a) { logf(this, "myIDDrawSurface7::GetClipper"); return m_pIDDrawSurface->GetClipper(a); } HRESULT __stdcall myIDDrawSurface7::GetColorKey(DWORD a, LPDDCOLORKEY b) { logf(this, "myIDDrawSurface7::GetColorKey"); return m_pIDDrawSurface->GetColorKey(a,b); } HRESULT __stdcall myIDDrawSurface7::GetDC(HDC FAR *a) { logf(this, "myIDDrawSurface7::GetDC"); return m_pIDDrawSurface->GetDC(a); } HRESULT __stdcall myIDDrawSurface7::GetFlipStatus(DWORD a) { logf(this, "myIDDrawSurface7::GetFlipStatus"); return m_pIDDrawSurface->GetFlipStatus(a); } HRESULT __stdcall myIDDrawSurface7::GetOverlayPosition(LPLONG a, LPLONG b) { logf(this, "myIDDrawSurface7::GetOverlayPosition"); return m_pIDDrawSurface->GetOverlayPosition(a,b); } HRESULT __stdcall myIDDrawSurface7::GetPalette(LPDIRECTDRAWPALETTE FAR*a) { logf(this, "myIDDrawSurface7::GetPalette"); return m_pIDDrawSurface->GetPalette(a); } HRESULT __stdcall myIDDrawSurface7::GetPixelFormat(LPDDPIXELFORMAT a) { logf(this, "myIDDrawSurface7::GetPixelFormat"); return m_pIDDrawSurface->GetPixelFormat(a); } HRESULT __stdcall myIDDrawSurface7::GetSurfaceDesc(LPDDSURFACEDESC2 a) { HRESULT r = m_pIDDrawSurface->GetSurfaceDesc(a); logf(this, "myIDDrawSurface7::GetSurfaceDesc([%x %x %x %x %x %x %x %x %x [%x %x %x %x %x %x %x %x] %x]) return %d", a->dwSize, a->dwFlags, a->dwWidth, a->dwHeight, a->lPitch, a->dwBackBufferCount, a->dwRefreshRate, a->dwAlphaBitDepth, a->lpSurface, a->ddpfPixelFormat.dwSize, a->ddpfPixelFormat.dwFlags, a->ddpfPixelFormat.dwFourCC, a->ddpfPixelFormat.dwRGBBitCount, a->ddpfPixelFormat.dwRBitMask, a->ddpfPixelFormat.dwGBitMask, a->ddpfPixelFormat.dwBBitMask, a->ddpfPixelFormat.dwRGBAlphaBitMask, a->ddsCaps.dwCaps, r); return r; } HRESULT __stdcall myIDDrawSurface7::Initialize(LPDIRECTDRAW a, LPDDSURFACEDESC2 b) { logf(this, "myIDDrawSurface7::Initialize"); return m_pIDDrawSurface->Initialize(a,b); } HRESULT __stdcall myIDDrawSurface7::IsLost() { logf(this, "myIDDrawSurface7::IsLost"); return m_pIDDrawSurface->IsLost(); } HRESULT __stdcall myIDDrawSurface7::Lock(LPRECT a,LPDDSURFACEDESC2 b,DWORD c,HANDLE d) { if (a) logf(this, "myIDDrawSurface7::Lock([%d,%d,%d,%d],%08x,%d,%d)",a->top,a->left,a->bottom,a->right,b,c,d); else logf(this, "myIDDrawSurface7::Lock([null],%08x,%d,%d)",b,c,d); HRESULT r = m_pIDDrawSurface->Lock(a,b,c,d); logf(this, "Locked surface data: %d,%d,%d,%d,%d,%08x,%d,%d", b->dwSize, b->dwFlags, b->dwHeight, b->dwWidth, b->lPitch, b->lpSurface, b->ddsCaps, b->ddpfPixelFormat); return r; } HRESULT __stdcall myIDDrawSurface7::ReleaseDC(HDC a) { logf(this, "myIDDrawSurface7::ReleaseDC"); return m_pIDDrawSurface->ReleaseDC(a); } HRESULT __stdcall myIDDrawSurface7::Restore() { logf(this, "myIDDrawSurface7::Restore"); return m_pIDDrawSurface->Restore(); } HRESULT __stdcall myIDDrawSurface7::SetClipper(LPDIRECTDRAWCLIPPER a) { logf(this, "myIDDrawSurface7::SetClipper"); return m_pIDDrawSurface->SetClipper(a); } HRESULT __stdcall myIDDrawSurface7::SetColorKey(DWORD a, LPDDCOLORKEY b) { logf(this, "myIDDrawSurface7::SetColorKey"); return m_pIDDrawSurface->SetColorKey(a,b); } HRESULT __stdcall myIDDrawSurface7::SetOverlayPosition(LONG a, LONG b) { logf(this, "myIDDrawSurface7::SetOverlayPosition"); return m_pIDDrawSurface->SetOverlayPosition(a,b); } HRESULT __stdcall myIDDrawSurface7::SetPalette(LPDIRECTDRAWPALETTE a) { logf(this, "myIDDrawSurface7::SetPalette(%08x)",a); if (a) a = ((myIDDrawPalette*)a)->m_pIDDrawPalette; return m_pIDDrawSurface->SetPalette(a); } HRESULT __stdcall myIDDrawSurface7::Unlock(LPRECT a) { logf(this, "myIDDrawSurface7::Unlock(%08x)",a); return m_pIDDrawSurface->Unlock(a); } HRESULT __stdcall myIDDrawSurface7::UpdateOverlay(LPRECT a, LPDIRECTDRAWSURFACE7 b,LPRECT c,DWORD d, LPDDOVERLAYFX e) { logf(this, "myIDDrawSurface7::UpdateOverlay"); return m_pIDDrawSurface->UpdateOverlay(a,((myIDDrawSurface7*)b)->m_pIDDrawSurface,c,d,e); } HRESULT __stdcall myIDDrawSurface7::UpdateOverlayDisplay(DWORD a) { logf(this, "myIDDrawSurface7::UpdateOverlayDisplay"); return m_pIDDrawSurface->UpdateOverlayDisplay(a); } HRESULT __stdcall myIDDrawSurface7::UpdateOverlayZOrder(DWORD a, LPDIRECTDRAWSURFACE7 b) { logf(this, "myIDDrawSurface7::UpdateOverlayZOrder"); return m_pIDDrawSurface->UpdateOverlayZOrder(a,((myIDDrawSurface7*)b)->m_pIDDrawSurface); } HRESULT __stdcall myIDDrawSurface7::GetDDInterface(LPVOID FAR * a) { logf(this, "myIDDrawSurface7::GetDDInterface"); return m_pIDDrawSurface->GetDDInterface(a); } HRESULT __stdcall myIDDrawSurface7::PageLock(DWORD a) { logf(this, "myIDDrawSurface7::PageLock"); return m_pIDDrawSurface->PageLock(a); } HRESULT __stdcall myIDDrawSurface7::PageUnlock(DWORD a) { logf(this, "myIDDrawSurface7::PageUnlock"); return m_pIDDrawSurface->PageUnlock(a); } HRESULT __stdcall myIDDrawSurface7::SetSurfaceDesc(LPDDSURFACEDESC2 a, DWORD b) { logf(this, "myIDDrawSurface7::SetSurfaceDesc"); return m_pIDDrawSurface->SetSurfaceDesc(a, b); } HRESULT __stdcall myIDDrawSurface7::SetPrivateData(REFGUID a, LPVOID b, DWORD c, DWORD d) { logf(this, "myIDDrawSurface7::SetPrivateData"); return m_pIDDrawSurface->SetPrivateData(a, b,c, d); } HRESULT __stdcall myIDDrawSurface7::GetPrivateData(REFGUID a, LPVOID b, LPDWORD c) { logf(this, "myIDDrawSurface7::GetPrivateData"); return m_pIDDrawSurface->GetPrivateData( a, b, c); } HRESULT __stdcall myIDDrawSurface7::FreePrivateData(REFGUID a) { logf(this, "myIDDrawSurface7::FreePrivateData"); return m_pIDDrawSurface->FreePrivateData(a); } HRESULT __stdcall myIDDrawSurface7::GetUniquenessValue(LPDWORD a) { logf(this, "myIDDrawSurface7::GetUniquenessValue"); return m_pIDDrawSurface->GetUniquenessValue(a); } HRESULT __stdcall myIDDrawSurface7::ChangeUniquenessValue() { logf(this, "myIDDrawSurface7::ChangeUniquenessValue"); return m_pIDDrawSurface->ChangeUniquenessValue(); } HRESULT __stdcall myIDDrawSurface7::SetPriority(DWORD a) { logf(this, "myIDDrawSurface7::SetPriority"); return m_pIDDrawSurface->SetPriority(a); } HRESULT __stdcall myIDDrawSurface7::GetPriority(LPDWORD a) { logf(this, "myIDDrawSurface7::GetPriority"); return m_pIDDrawSurface->GetPriority(a); } HRESULT __stdcall myIDDrawSurface7::SetLOD(DWORD a) { logf(this, "myIDDrawSurface7::SetLOD"); return m_pIDDrawSurface->SetLOD(a); } HRESULT __stdcall myIDDrawSurface7:: GetLOD(LPDWORD a) { logf(this, "myIDDrawSurface7::GetLOD"); return m_pIDDrawSurface->GetLOD(a); }
[ "[email protected]@ca3b60c3-ba86-2864-2f26-32acf34adade" ]
[ [ [ 1, 468 ] ] ]
dde3ce8bb5e4f3f2a27d36db2ed70546ad8e046b
b1d87d94202be1ce320827743461c5e9defe9948
/model_to_obj/model_to_obj/stdafx.cpp
bdd3c5e169885b061539e1715ef2e8a3e4273a4a
[]
no_license
DragonNeos/psplamb
e3a9a76af815842033e8149441506eeed8cbacc0
272c1d307a32b33504437214a1f281e6fce5f4a0
refs/heads/master
2021-01-01T17:00:43.610830
2010-11-19T14:46:04
2010-11-19T14:46:04
40,784,813
0
0
null
null
null
null
UTF-8
C++
false
false
299
cpp
// stdafx.cpp : source file that includes just the standard includes // model_to_obj.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "marcin.ploska@cbcbbe76-952c-6284-d426-79555ba45a39" ]
[ [ [ 1, 8 ] ] ]
e8f5bc87f3ff4abac8013e48751c1a99f8fc400f
76362ee1ab5097cb13c9bc045153c49863dc54a5
/category.h
18028ffa61a2cfea4ee7ace896a1f0d61ef3c34f
[]
no_license
nbigler/background_radiation
c45142727738596cb08c1739fec322ffe7c833d8
811bdd1ed5ad192fd33373d5d03b811cbb4b6059
refs/heads/master
2020-12-25T19:14:34.350872
2011-12-18T17:38:41
2011-12-18T17:38:41
2,519,498
0
0
null
null
null
null
UTF-8
C++
false
false
7,529
h
#ifndef CCATEGORY_H_ #define CCATEGORY_H_ /** * \file category.h * * \brief Implements a number of categories through an enum type and provides a counting * facility for any combination of the categories. This is useful when an entity is * assigned to more than one category at a time and, thus, intersections between the * different category sets have to be tracked. * * * Copyright (c) 2010, Eduard Glatz * * Author: Eduard Glatz ([email protected]) * * Distributed under the Gnu Public License version 2 or the modified * BSD license. */ #include <iostream> #include <string> #include <cstring> #include <vector> /** * We enclose this enum type definitin with its own name to compnesate the C++ * deficiency of a missign enum type qualifier. Doing this we can avoid name * conflicts. * The purpose of this enum type is the naming of signs that can be attributed * to a flow. Basically, every flow can be attributed a set of signs with an * arbitrary size (minimal: empty set, maximal: all defined enum values). * * We use two define statements to declare the names and the representing strings * on top of each other to be able to print enum names for given enum values. * This string print faeture is implemented in class C_Category::C_Category_set. */ namespace e_category { // The defines must match! (there is no easy way in C++ to create string from enums) #ifndef UNIT_TEST #define category_enum_vals TRWscan,TRWnom,HCscan,Backsc,GreyIP,bogon,P2P,Unreach,Retry,Onepkt,Artef,Large,PotOk,TCP,UDP,ICMP,OTHER,Unknown #define category_enum_vals_str "TRWscan,TRWnom,HCscan,Backsc,GreyIP,bogon,P2P,Unreach,Retry,Onepkt,Artef,Large,PotOk,TCP,UDP,ICMP,OTHER,Unknown" // For unit test: we must match enum code used in main() otherwise unit test code breaks #else #define category_enum_vals SweepScan,PortScan,DoS,Unknown #define category_enum_vals_str "SweepScan,PortScan,DoS,Unknown" #endif enum category_t { category_enum_vals }; // By default enum values are zero-based } // namespace /** * \class C_Category * \brief This class supports the counting of arbitray sets of signs. * For any set instance we maintain its own counter that is incremented * every time when such a set instance is associated with a flow. This * way we count the number of flows per distinct sign sets. * The sign set as a fata type is implemented by inner class C_Category_set. */ class C_Category { public: /** * \class C_Category_set * \brief This class implements a set of signs that can be associated with * a flow. For historical reasons we name such a sign set a category set. */ class C_Category_set { private: // Names of enum values as strings (for printing) std::vector<std::string> category_t_str; // Set of signs as a limited size bit set // (for a more general implementation type bitset might fit better) // Comment: the current implementation supports up to 32 signs. // Making use of the full set size would introduce 2**32 counters // in class C_Category (this does not scale anymore). unsigned int cset; // Count of unique defined enum values int ecnt; // Rules that define what signs must be present or absent // Each row represents one particular rule as follows: // Column 0: rule name // Column 1+: sign names // Note: row index represent rule number (bit position) important // for accessing the mask arrays and the rule2class map. std::vector< std::vector<std::string> > rule_set; // Contains per rule a mask that contains 1-bits for signs that must be // <<present>> in a sign set to match the rule. std::vector<unsigned int> mask_arr1; // Contains per rule a mask that contains 1-bits for signs that must be // <<absent>> in a sign set to match the rule. std::vector<unsigned int> mask_arr2; // List of all classes names to assign a number (index) to each std::vector<std::string> class_names; // Rules-to-classes mappings: index is a rule number, entry is a class number // (class number can be used as index to classes_names) std::vector<int> rule2class_map; public: C_Category_set(unsigned int c=0); // Add a sign to set. void add(e_category::category_t c) { cset |= (1<<c); } // Check if a sign is a member of the set. bool is_member(e_category::category_t c) { return (cset & (1<<c)); } // Show bitset in hexadecimal represenation on console. void show() { std::cout << std::hex << "0x" << cset << std::dec << std::endl; } // Print all names of enum type values to console (or a given stream) void print(std::ostream & outfs=std::cout); // Output a newline to console void printnl() { print(); std::cout << std::endl; } // Initialize sign set uing a given bit set. void set(unsigned int c) { cset = c; } // Get current sign set as a bit set. unsigned int get_set() { return cset; } // Read a set of rules from a text file. Every rule defines which signs // must be present or absent in a given set to match the rule. bool get_rules(std::string & rules_filename); // Show current settings of bitmasks. void show_masks(); // Get count of unique enum values int get_enum_count() { return ecnt; } // Returns the internal reference number of a rule with a given name. // This number is needed to invoke "rule_match()" on the correct rule. int get_rule_number(std::string & rule_name); // Get total count of rules. int get_rule_count() { return rule_set.size(); } // Get rule name string for a given rule number. bool get_rule_name(size_t rule_num, std::string & rule_name); // Checks if a given sign set matches a particular rule whose number is given bool rule_match(size_t rule_num, unsigned int cset); // Make sign set empty void clear() { cset = 0; } private: // Initialize bit masks from loaded rules void load_bitmasks(); // Get numeric value for a given enum value name int get_enum_by_name(std::string & sign_name); }; /** * \class C_Category_rc_signs * \brief Implements sign per rule or class accounting. */ class C_Category_rc_signs { private: std::vector<long long *> rc_signs; ///< Per rule or class sign count arrays int enum_count;///< Count of distinct sign enum values int rc_count; ///< Rule or class count public: C_Category_rc_signs(); void init(int enum_count, int rc_count); ~C_Category_rc_signs(); void reset(); // Increment enum counters for given rule or class number void increment(int rc_number, unsigned int cset); // Write enum (flow) counts for given rule or class number to csv file void write_csv(std::ofstream * outfs, int rc_number); // Write enum (flow) counts for given rule or class number to csv file // (Use fraction of all one-way flows) void write_csv(std::ofstream * outfs, int rc_number, uint32_t flows); int get_rc_count() { return rc_count; } }; private: long long * ccounters; // Counter array for all categories and any possible combination of them long long * ecounters; // Counter per enum value (ignoring combinations) int num_counters; int num_enums; public: C_Category(); ~C_Category(); void increment(C_Category_set combi); void print_counters(); void print_counters_full(); void clear(); }; #endif
[ [ [ 1, 231 ] ] ]
e44ea70619ec6f094492d7dd712272d1b89cae2f
9fb229975cc6bd01eb38c3e96849d0c36985fa1e
/Tools/Unify/Unify.cpp
4ec116866e3f23378790618587fe32a55d33e052
[]
no_license
Danewalker/ahr
3758bf3219f407ed813c2bbed5d1d86291b9237d
2af9fd5a866c98ef1f95f4d1c3d9b192fee785a6
refs/heads/master
2016-09-13T08:03:43.040624
2010-07-21T15:44:41
2010-07-21T15:44:41
56,323,321
0
0
null
null
null
null
UTF-8
C++
false
false
3,605
cpp
#pragma warning(disable : 4786) #include "unify.h" #include <algorithm> #include <set> #include <limits> using namespace Unify; const float Unify::CValue::k_fNan = std::numeric_limits<float>::quiet_NaN(); /// CNode /////////////////////////////////////////// // CNode -> ~CNode CNode::~CNode() { Clear(); } void CNode::Clear() { std::vector<CNode*>::iterator it; for(it=m_Nodes.begin();it!=m_Nodes.end();++it){ delete *it; } m_Nodes.resize(0); for(ParameterIterator it2=m_Parameters.begin();it2!=m_Parameters.end();++it2) delete it2->second; m_Parameters.clear(); } const CNode * CNode::GetChildByParamValue(const std::string& param, const std::string& value) const { for(int i = 0; i < GetChildCount(); ++i) { const CParameter * pParam = GetChild(i)->GetParameter(param); if(pParam && value == pParam->GetValue()->GetString()) { return GetChild(i); } } return 0; } CNode * CNode::GetChildByParamValue(const std::string& param, const std::string& value) { return const_cast<CNode *>(const_cast<const CNode*>(this)->GetChildByParamValue(param, value)); } // CNode -> GetParameter CParameter * CNode::GetParameter(const std::string& name){ ParameterIterator it=m_Parameters.find(name); if(it==m_Parameters.end()){ return 0; }else{ return it->second; } } const CParameter * CNode::GetParameter(const std::string& name) const { Parameters::const_iterator i = m_Parameters.find(name); if(i==m_Parameters.end()) return NULL; else return i->second; } CNode::ParameterIterator CNode::RemoveParameter(ParameterIterator i) { delete i->second; return m_Parameters.erase(i); } // CNode -> RemoveParameter void CNode::RemoveParameter(const std::string& name) { ParameterIterator i = m_Parameters.find(name); if(i!=m_Parameters.end()) RemoveParameter(i); } // Remove a parameter without deleting it Unify::CParameter * CNode::ReleaseParameter(const std::string& name) { Unify::CParameter* p=NULL; ParameterIterator i = m_Parameters.find(name); if(i!=m_Parameters.end()) { p = i->second; m_Parameters.erase(i); } return p; } // Add the node parameters from another node void CNode::AddParametersFrom(CNode* in_pNode) { for(ParameterIterator it = in_pNode->ParameterBegin(); it != in_pNode->ParameterEnd(); ++it) { (*it).second->Copy(NewParameter((*it).second->GetName())); } } // Merge the node parameters from another node void CNode::GetParameterValuesFrom(CNode* in_pNode) { for(ParameterIterator it = in_pNode->ParameterBegin(); it != in_pNode->ParameterEnd(); ++it) { Unify::CParameter * pSourceParam = (*it).second; Unify::CParameter * pExistingParam = GetParameter(pSourceParam->GetName()); if (pExistingParam) { pSourceParam->Copy(pExistingParam); } else { pSourceParam->Copy(NewParameter(pSourceParam->GetName())); } } } void CNode::Copy(Unify::CNode* target) const { target->Clear(); // Copy parameters ConstParameterIterator it; for(it=ParameterBegin();it!=ParameterEnd();++it){ (*it).second->Copy(target->NewParameter((*it).first)); } // Copy sub nodes target->m_Nodes.reserve(m_Nodes.size()); std::vector<CNode*>::const_iterator it2; for(it2=m_Nodes.begin();it2!=m_Nodes.end();++it2){ (*it2)->Copy(target->NewChild()); } } void CNode::DetachChild(CNode* node){ std::vector<CNode*>::iterator it; it=std::find(m_Nodes.begin(),m_Nodes.end(),node); if(it!=m_Nodes.end()){ m_Nodes.erase(it); } }
[ "jakesoul@c957e3ca-5ece-11de-8832-3f4c773c73ae" ]
[ [ [ 1, 165 ] ] ]
3655e881926861b1c2c67e60e520c1b5a36a5e0d
94c1c7459eb5b2826e81ad2750019939f334afc8
/source/msflexgrid.cpp
fc2e269addf8c7f37c68859f0260bae24c9bbd35
[]
no_license
wgwang/yinhustock
1c57275b4bca093e344a430eeef59386e7439d15
382ed2c324a0a657ddef269ebfcd84634bd03c3a
refs/heads/master
2021-01-15T17:07:15.833611
2010-11-27T07:06:40
2010-11-27T07:06:40
37,531,026
1
3
null
null
null
null
UTF-8
C++
false
false
29,327
cpp
// Machine generated IDispatch wrapper class(es) created by Microsoft Visual C++ // NOTE: Do not modify the contents of this file. If this class is regenerated by //tel:13366898744 #include "stdafx.h" #include "msflexgrid.h" // Dispatch interfaces referenced by this interface #include "font1.h" #include "Picture2.h" #include "rowcursor2.h" ///////////////////////////////////////////////////////////////////////////// // CMSFlexGrid IMPLEMENT_DYNCREATE(CMSFlexGrid, CWnd) ///////////////////////////////////////////////////////////////////////////// // CMSFlexGrid properties ///////////////////////////////////////////////////////////////////////////// // CMSFlexGrid operations long CMSFlexGrid::GetRows() { long result; InvokeHelper(0x4, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetRows(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x4, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } long CMSFlexGrid::GetCols() { long result; InvokeHelper(0x5, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetCols(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x5, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } long CMSFlexGrid::GetFixedRows() { long result; InvokeHelper(0x6, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetFixedRows(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x6, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } long CMSFlexGrid::GetFixedCols() { long result; InvokeHelper(0x7, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetFixedCols(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x7, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } short CMSFlexGrid::GetVersion() { short result; InvokeHelper(0x1, DISPATCH_PROPERTYGET, VT_I2, (void*)&result, NULL); return result; } CString CMSFlexGrid::GetFormatString() { CString result; InvokeHelper(0x2, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); return result; } void CMSFlexGrid::SetFormatString(LPCTSTR lpszNewValue) { static BYTE parms[] = VTS_BSTR; InvokeHelper(0x2, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, lpszNewValue); } long CMSFlexGrid::GetTopRow() { long result; InvokeHelper(0x8, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetTopRow(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x8, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } long CMSFlexGrid::GetLeftCol() { long result; InvokeHelper(0x9, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetLeftCol(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x9, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } long CMSFlexGrid::GetRow() { long result; InvokeHelper(0xa, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetRow(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0xa, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } long CMSFlexGrid::GetCol() { long result; InvokeHelper(0xb, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetCol(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0xb, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } long CMSFlexGrid::GetRowSel() { long result; InvokeHelper(0xc, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetRowSel(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0xc, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } long CMSFlexGrid::GetColSel() { long result; InvokeHelper(0xd, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetColSel(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0xd, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } CString CMSFlexGrid::GetText() { CString result; InvokeHelper(0x0, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); return result; } void CMSFlexGrid::SetText(LPCTSTR lpszNewValue) { static BYTE parms[] = VTS_BSTR; InvokeHelper(0x0, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, lpszNewValue); } unsigned long CMSFlexGrid::GetBackColor() { unsigned long result; InvokeHelper(DISPID_BACKCOLOR, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetBackColor(unsigned long newValue) { static BYTE parms[] = VTS_I4; InvokeHelper(DISPID_BACKCOLOR, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } unsigned long CMSFlexGrid::GetForeColor() { unsigned long result; InvokeHelper(DISPID_FORECOLOR, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetForeColor(unsigned long newValue) { static BYTE parms[] = VTS_I4; InvokeHelper(DISPID_FORECOLOR, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } unsigned long CMSFlexGrid::GetBackColorFixed() { unsigned long result; InvokeHelper(0xe, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetBackColorFixed(unsigned long newValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0xe, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } unsigned long CMSFlexGrid::GetForeColorFixed() { unsigned long result; InvokeHelper(0xf, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetForeColorFixed(unsigned long newValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0xf, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } unsigned long CMSFlexGrid::GetBackColorSel() { unsigned long result; InvokeHelper(0x10, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetBackColorSel(unsigned long newValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x10, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } unsigned long CMSFlexGrid::GetForeColorSel() { unsigned long result; InvokeHelper(0x11, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetForeColorSel(unsigned long newValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x11, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } unsigned long CMSFlexGrid::GetBackColorBkg() { unsigned long result; InvokeHelper(0x12, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetBackColorBkg(unsigned long newValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x12, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } BOOL CMSFlexGrid::GetWordWrap() { BOOL result; InvokeHelper(0x13, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); return result; } void CMSFlexGrid::SetWordWrap(BOOL bNewValue) { static BYTE parms[] = VTS_BOOL; InvokeHelper(0x13, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, bNewValue); } COleFont1 CMSFlexGrid::GetFont() { LPDISPATCH pDispatch; InvokeHelper(DISPID_FONT, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&pDispatch, NULL); return COleFont1(pDispatch); } void CMSFlexGrid::SetRefFont(LPDISPATCH newValue) { static BYTE parms[] = VTS_DISPATCH; InvokeHelper(DISPID_FONT, DISPATCH_PROPERTYPUTREF, VT_EMPTY, NULL, parms, newValue); } float CMSFlexGrid::GetFontWidth() { float result; InvokeHelper(0x54, DISPATCH_PROPERTYGET, VT_R4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetFontWidth(float newValue) { static BYTE parms[] = VTS_R4; InvokeHelper(0x54, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } CString CMSFlexGrid::GetCellFontName() { CString result; InvokeHelper(0x4d, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); return result; } void CMSFlexGrid::SetCellFontName(LPCTSTR lpszNewValue) { static BYTE parms[] = VTS_BSTR; InvokeHelper(0x4d, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, lpszNewValue); } float CMSFlexGrid::GetCellFontSize() { float result; InvokeHelper(0x4e, DISPATCH_PROPERTYGET, VT_R4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetCellFontSize(float newValue) { static BYTE parms[] = VTS_R4; InvokeHelper(0x4e, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } BOOL CMSFlexGrid::GetCellFontBold() { BOOL result; InvokeHelper(0x4f, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); return result; } void CMSFlexGrid::SetCellFontBold(BOOL bNewValue) { static BYTE parms[] = VTS_BOOL; InvokeHelper(0x4f, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, bNewValue); } BOOL CMSFlexGrid::GetCellFontItalic() { BOOL result; InvokeHelper(0x50, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); return result; } void CMSFlexGrid::SetCellFontItalic(BOOL bNewValue) { static BYTE parms[] = VTS_BOOL; InvokeHelper(0x50, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, bNewValue); } BOOL CMSFlexGrid::GetCellFontUnderline() { BOOL result; InvokeHelper(0x51, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); return result; } void CMSFlexGrid::SetCellFontUnderline(BOOL bNewValue) { static BYTE parms[] = VTS_BOOL; InvokeHelper(0x51, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, bNewValue); } BOOL CMSFlexGrid::GetCellFontStrikeThrough() { BOOL result; InvokeHelper(0x52, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); return result; } void CMSFlexGrid::SetCellFontStrikeThrough(BOOL bNewValue) { static BYTE parms[] = VTS_BOOL; InvokeHelper(0x52, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, bNewValue); } float CMSFlexGrid::GetCellFontWidth() { float result; InvokeHelper(0x53, DISPATCH_PROPERTYGET, VT_R4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetCellFontWidth(float newValue) { static BYTE parms[] = VTS_R4; InvokeHelper(0x53, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } long CMSFlexGrid::GetTextStyle() { long result; InvokeHelper(0x14, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetTextStyle(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x14, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } long CMSFlexGrid::GetTextStyleFixed() { long result; InvokeHelper(0x15, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetTextStyleFixed(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x15, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } BOOL CMSFlexGrid::GetScrollTrack() { BOOL result; InvokeHelper(0x16, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); return result; } void CMSFlexGrid::SetScrollTrack(BOOL bNewValue) { static BYTE parms[] = VTS_BOOL; InvokeHelper(0x16, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, bNewValue); } long CMSFlexGrid::GetFocusRect() { long result; InvokeHelper(0x17, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetFocusRect(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x17, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } long CMSFlexGrid::GetHighLight() { long result; InvokeHelper(0x18, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetHighLight(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x18, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } BOOL CMSFlexGrid::GetRedraw() { BOOL result; InvokeHelper(0x19, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); return result; } void CMSFlexGrid::SetRedraw(BOOL bNewValue) { static BYTE parms[] = VTS_BOOL; InvokeHelper(0x19, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, bNewValue); } long CMSFlexGrid::GetScrollBars() { long result; InvokeHelper(0x1a, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetScrollBars(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x1a, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } long CMSFlexGrid::GetMouseRow() { long result; InvokeHelper(0x1b, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } long CMSFlexGrid::GetMouseCol() { long result; InvokeHelper(0x1c, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } long CMSFlexGrid::GetCellLeft() { long result; InvokeHelper(0x1d, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } long CMSFlexGrid::GetCellTop() { long result; InvokeHelper(0x1e, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } long CMSFlexGrid::GetCellWidth() { long result; InvokeHelper(0x1f, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } long CMSFlexGrid::GetCellHeight() { long result; InvokeHelper(0x20, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } long CMSFlexGrid::GetRowHeightMin() { long result; InvokeHelper(0x21, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetRowHeightMin(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x21, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } long CMSFlexGrid::GetFillStyle() { long result; InvokeHelper(0xfffffe01, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetFillStyle(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0xfffffe01, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } long CMSFlexGrid::GetGridLines() { long result; InvokeHelper(0x22, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetGridLines(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x22, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } long CMSFlexGrid::GetGridLinesFixed() { long result; InvokeHelper(0x23, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetGridLinesFixed(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x23, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } unsigned long CMSFlexGrid::GetGridColor() { unsigned long result; InvokeHelper(0x24, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetGridColor(unsigned long newValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x24, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } unsigned long CMSFlexGrid::GetGridColorFixed() { unsigned long result; InvokeHelper(0x25, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetGridColorFixed(unsigned long newValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x25, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } unsigned long CMSFlexGrid::GetCellBackColor() { unsigned long result; InvokeHelper(0x26, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetCellBackColor(unsigned long newValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x26, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } unsigned long CMSFlexGrid::GetCellForeColor() { unsigned long result; InvokeHelper(0x27, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetCellForeColor(unsigned long newValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x27, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } short CMSFlexGrid::GetCellAlignment() { short result; InvokeHelper(0x28, DISPATCH_PROPERTYGET, VT_I2, (void*)&result, NULL); return result; } void CMSFlexGrid::SetCellAlignment(short nNewValue) { static BYTE parms[] = VTS_I2; InvokeHelper(0x28, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } long CMSFlexGrid::GetCellTextStyle() { long result; InvokeHelper(0x29, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetCellTextStyle(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x29, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } short CMSFlexGrid::GetCellPictureAlignment() { short result; InvokeHelper(0x2b, DISPATCH_PROPERTYGET, VT_I2, (void*)&result, NULL); return result; } void CMSFlexGrid::SetCellPictureAlignment(short nNewValue) { static BYTE parms[] = VTS_I2; InvokeHelper(0x2b, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } CString CMSFlexGrid::GetClip() { CString result; InvokeHelper(0x2d, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); return result; } void CMSFlexGrid::SetClip(LPCTSTR lpszNewValue) { static BYTE parms[] = VTS_BSTR; InvokeHelper(0x2d, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, lpszNewValue); } void CMSFlexGrid::SetSort(short nNewValue) { static BYTE parms[] = VTS_I2; InvokeHelper(0x2e, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } long CMSFlexGrid::GetSelectionMode() { long result; InvokeHelper(0x2f, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetSelectionMode(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x2f, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } long CMSFlexGrid::GetMergeCells() { long result; InvokeHelper(0x30, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetMergeCells(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x30, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } BOOL CMSFlexGrid::GetAllowBigSelection() { BOOL result; InvokeHelper(0x33, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); return result; } void CMSFlexGrid::SetAllowBigSelection(BOOL bNewValue) { static BYTE parms[] = VTS_BOOL; InvokeHelper(0x33, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, bNewValue); } long CMSFlexGrid::GetAllowUserResizing() { long result; InvokeHelper(0x34, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetAllowUserResizing(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x34, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } long CMSFlexGrid::GetBorderStyle() { long result; InvokeHelper(DISPID_BORDERSTYLE, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetBorderStyle(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(DISPID_BORDERSTYLE, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } long CMSFlexGrid::GetHWnd() { long result; InvokeHelper(DISPID_HWND, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } BOOL CMSFlexGrid::GetEnabled() { BOOL result; InvokeHelper(DISPID_ENABLED, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); return result; } void CMSFlexGrid::SetEnabled(BOOL bNewValue) { static BYTE parms[] = VTS_BOOL; InvokeHelper(DISPID_ENABLED, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, bNewValue); } long CMSFlexGrid::GetAppearance() { long result; InvokeHelper(DISPID_APPEARANCE, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetAppearance(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(DISPID_APPEARANCE, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } long CMSFlexGrid::GetMousePointer() { long result; InvokeHelper(0x35, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetMousePointer(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x35, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } CPicture1 CMSFlexGrid::GetMouseIcon() { LPDISPATCH pDispatch; InvokeHelper(0x36, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&pDispatch, NULL); return CPicture1(pDispatch); } void CMSFlexGrid::SetRefMouseIcon(LPDISPATCH newValue) { static BYTE parms[] = VTS_DISPATCH; InvokeHelper(0x36, DISPATCH_PROPERTYPUTREF, VT_EMPTY, NULL, parms, newValue); } long CMSFlexGrid::GetPictureType() { long result; InvokeHelper(0x32, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetPictureType(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x32, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } CPicture1 CMSFlexGrid::GetPicture() { LPDISPATCH pDispatch; InvokeHelper(0x31, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&pDispatch, NULL); return CPicture1(pDispatch); } CPicture1 CMSFlexGrid::GetCellPicture() { LPDISPATCH pDispatch; InvokeHelper(0x2a, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&pDispatch, NULL); return CPicture1(pDispatch); } void CMSFlexGrid::SetRefCellPicture(LPDISPATCH newValue) { static BYTE parms[] = VTS_DISPATCH; InvokeHelper(0x2a, DISPATCH_PROPERTYPUTREF, VT_EMPTY, NULL, parms, newValue); } CString CMSFlexGrid::GetTextArray(long index) { CString result; static BYTE parms[] = VTS_I4; InvokeHelper(0x37, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, parms, index); return result; } void CMSFlexGrid::SetTextArray(long index, LPCTSTR lpszNewValue) { static BYTE parms[] = VTS_I4 VTS_BSTR; InvokeHelper(0x37, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, index, lpszNewValue); } short CMSFlexGrid::GetColAlignment(long index) { short result; static BYTE parms[] = VTS_I4; InvokeHelper(0x38, DISPATCH_PROPERTYGET, VT_I2, (void*)&result, parms, index); return result; } void CMSFlexGrid::SetColAlignment(long index, short nNewValue) { static BYTE parms[] = VTS_I4 VTS_I2; InvokeHelper(0x38, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, index, nNewValue); } long CMSFlexGrid::GetColWidth(long index) { long result; static BYTE parms[] = VTS_I4; InvokeHelper(0x39, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, parms, index); return result; } void CMSFlexGrid::SetColWidth(long index, long nNewValue) { static BYTE parms[] = VTS_I4 VTS_I4; InvokeHelper(0x39, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, index, nNewValue); } long CMSFlexGrid::GetRowHeight(long index) { long result; static BYTE parms[] = VTS_I4; InvokeHelper(0x3a, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, parms, index); return result; } void CMSFlexGrid::SetRowHeight(long index, long nNewValue) { static BYTE parms[] = VTS_I4 VTS_I4; InvokeHelper(0x3a, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, index, nNewValue); } BOOL CMSFlexGrid::GetMergeRow(long index) { BOOL result; static BYTE parms[] = VTS_I4; InvokeHelper(0x3b, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, parms, index); return result; } void CMSFlexGrid::SetMergeRow(long index, BOOL bNewValue) { static BYTE parms[] = VTS_I4 VTS_BOOL; InvokeHelper(0x3b, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, index, bNewValue); } BOOL CMSFlexGrid::GetMergeCol(long index) { BOOL result; static BYTE parms[] = VTS_I4; InvokeHelper(0x3c, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, parms, index); return result; } void CMSFlexGrid::SetMergeCol(long index, BOOL bNewValue) { static BYTE parms[] = VTS_I4 VTS_BOOL; InvokeHelper(0x3c, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, index, bNewValue); } void CMSFlexGrid::SetRowPosition(long index, long nNewValue) { static BYTE parms[] = VTS_I4 VTS_I4; InvokeHelper(0x3d, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, index, nNewValue); } void CMSFlexGrid::SetColPosition(long index, long nNewValue) { static BYTE parms[] = VTS_I4 VTS_I4; InvokeHelper(0x3e, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, index, nNewValue); } long CMSFlexGrid::GetRowData(long index) { long result; static BYTE parms[] = VTS_I4; InvokeHelper(0x3f, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, parms, index); return result; } void CMSFlexGrid::SetRowData(long index, long nNewValue) { static BYTE parms[] = VTS_I4 VTS_I4; InvokeHelper(0x3f, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, index, nNewValue); } long CMSFlexGrid::GetColData(long index) { long result; static BYTE parms[] = VTS_I4; InvokeHelper(0x40, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, parms, index); return result; } void CMSFlexGrid::SetColData(long index, long nNewValue) { static BYTE parms[] = VTS_I4 VTS_I4; InvokeHelper(0x40, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, index, nNewValue); } CString CMSFlexGrid::GetTextMatrix(long Row, long Col) { CString result; static BYTE parms[] = VTS_I4 VTS_I4; InvokeHelper(0x41, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, parms, Row, Col); return result; } void CMSFlexGrid::SetTextMatrix(long Row, long Col, LPCTSTR lpszNewValue) { static BYTE parms[] = VTS_I4 VTS_I4 VTS_BSTR; InvokeHelper(0x41, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, Row, Col, lpszNewValue); } void CMSFlexGrid::AddItem(LPCTSTR Item, const VARIANT& index) { static BYTE parms[] = VTS_BSTR VTS_VARIANT; InvokeHelper(0x42, DISPATCH_METHOD, VT_EMPTY, NULL, parms, Item, &index); } void CMSFlexGrid::RemoveItem(long index) { static BYTE parms[] = VTS_I4; InvokeHelper(0x43, DISPATCH_METHOD, VT_EMPTY, NULL, parms, index); } void CMSFlexGrid::Clear() { InvokeHelper(0x44, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); } void CMSFlexGrid::Refresh() { InvokeHelper(DISPID_REFRESH, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); } CRowCursor1 CMSFlexGrid::GetDataSource() { LPDISPATCH pDispatch; InvokeHelper(0x4c, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&pDispatch, NULL); return CRowCursor1(pDispatch); } void CMSFlexGrid::SetDataSource(LPDISPATCH newValue) { static BYTE parms[] = VTS_DISPATCH; InvokeHelper(0x4c, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } BOOL CMSFlexGrid::GetRowIsVisible(long index) { BOOL result; static BYTE parms[] = VTS_I4; InvokeHelper(0x55, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, parms, index); return result; } BOOL CMSFlexGrid::GetColIsVisible(long index) { BOOL result; static BYTE parms[] = VTS_I4; InvokeHelper(0x56, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, parms, index); return result; } long CMSFlexGrid::GetRowPos(long index) { long result; static BYTE parms[] = VTS_I4; InvokeHelper(0x57, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, parms, index); return result; } long CMSFlexGrid::GetColPos(long index) { long result; static BYTE parms[] = VTS_I4; InvokeHelper(0x58, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, parms, index); return result; } short CMSFlexGrid::GetGridLineWidth() { short result; InvokeHelper(0x59, DISPATCH_PROPERTYGET, VT_I2, (void*)&result, NULL); return result; } void CMSFlexGrid::SetGridLineWidth(short nNewValue) { static BYTE parms[] = VTS_I2; InvokeHelper(0x59, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } short CMSFlexGrid::GetFixedAlignment(long index) { short result; static BYTE parms[] = VTS_I4; InvokeHelper(0x5a, DISPATCH_PROPERTYGET, VT_I2, (void*)&result, parms, index); return result; } void CMSFlexGrid::SetFixedAlignment(long index, short nNewValue) { static BYTE parms[] = VTS_I4 VTS_I2; InvokeHelper(0x5a, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, index, nNewValue); } BOOL CMSFlexGrid::GetRightToLeft() { BOOL result; InvokeHelper(0xfffffd9d, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); return result; } void CMSFlexGrid::SetRightToLeft(BOOL bNewValue) { static BYTE parms[] = VTS_BOOL; InvokeHelper(0xfffffd9d, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, bNewValue); } long CMSFlexGrid::GetOLEDropMode() { long result; InvokeHelper(0x60f, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CMSFlexGrid::SetOLEDropMode(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x60f, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } void CMSFlexGrid::OLEDrag() { InvokeHelper(0x610, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); }
[ [ [ 1, 1308 ] ] ]
ff65a188c0dd444ee4629cb6af00d41d7b4b35ed
27bde5e083cf5a32f75de64421ba541b3a23dd29
/source/AllArrows.h
cd82809829ca6dc41ab74101eea735f59486b39b
[]
no_license
jbsheblak/fatal-inflation
229fc6111039aff4fd00bb1609964cf37e4303af
5d6c0a99e8c4791336cf529ed8ce63911a297a23
refs/heads/master
2021-03-12T19:22:31.878561
2006-10-20T21:48:17
2006-10-20T21:48:17
32,184,096
0
0
null
null
null
null
UTF-8
C++
false
false
608
h
//--------------------------------------------------- // Name: Game : AllArrows // Desc: all of the game arrows // Author: John Sheblak // Contact: [email protected] //--------------------------------------------------- #ifndef _GAME_ALL_ARROWS_H_ #define _GAME_ALL_ARROWS_H_ #include "Arrow.h" namespace Game { class TimedArrow : public Arrow { public: virtual ~TimedArrow() {} TimedArrow( EntityDesc* desc ); virtual void Update( F32 curTime ); protected: F32 mLifetime; }; }; //end Game #endif // end _GAME_ALL_ARROWS_H_
[ "jbsheblak@5660b91f-811d-0410-8070-91869aa11e15" ]
[ [ [ 1, 33 ] ] ]