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
99236966f84a95c89e32f71dc625c34612316892
fb8213d7a4744087a0a1ff9b01f4ee9a1ca4be49
/Babel/QNetwork.cpp
19c276f5afb233efc8f70eb8d5a1f5ee4da02d91
[]
no_license
RemiGuillard/Babel-save-02
0efb9889eb1924e203671572f48d9cda957e1818
66ba9ed837395bae6a21ab15b5ee65aee7759a5d
refs/heads/master
2016-09-08T01:41:00.536703
2010-11-22T10:30:41
2010-11-22T10:30:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,339
cpp
#include <QTcpSocket> #include <QUdpSocket> #include <QObject> #include <QMessageBox> #include "QNetwork.h" QNetwork::QNetwork() { // QObject::connect(_sock, SIGNAL(connected()), this, SLOT(nowConnected())) } QNetwork::~QNetwork() { delete _sock; } QNetwork::QNetwork(const QNetwork &cpy) { *this = cpy; } QNetwork& QNetwork::operator=(const QNetwork &cpy) { return *this; } void QNetwork::createSocket(QAbstractSocket::SocketType sock) { if (sock == QAbstractSocket::TcpSocket) _sock = new QTcpSocket; else if (sock == QAbstractSocket::UdpSocket) { _sock = new QUdpSocket; //_sock->bind() } } void QNetwork::socketConnection(const QString & hostName, quint16 port) { _sock->connectToHost(hostName, port); QString s(0); //QMessageBox::information(NULL, "Connection Status", s.setNum(_sock->state())); if (_sock->state() == QAbstractSocket::ConnectedState) this->setSocketStatus(true); // else // QMessageBox::information(NULL, "Connection Error", s.setNum(_sock->state())); } void QNetwork::packetRcv() { } void QNetwork::packetSend() { } void QNetwork::disconnect() { QMessageBox::information(NULL, "Connection Exit", "You're now disconnected"); _sock->close(); } QAbstractSocket* QNetwork::getSocket() const { return _sock; }
[ [ [ 1, 69 ] ] ]
661361f1bfe978787c649e4362fc1de511f21aa1
974a20e0f85d6ac74c6d7e16be463565c637d135
/trunk/packages/dCompilerKit/dVirtualAssembler/dAssemblerLexical.h
4b54b8148ac9d2ddf54102b5801ef7cb94b61cd9
[]
no_license
Naddiseo/Newton-Dynamics-fork
cb0b8429943b9faca9a83126280aa4f2e6944f7f
91ac59c9687258c3e653f592c32a57b61dc62fb6
refs/heads/master
2021-01-15T13:45:04.651163
2011-11-12T04:02:33
2011-11-12T04:02:33
2,759,246
0
0
null
null
null
null
UTF-8
C++
false
false
2,015
h
/* Copyright (c) <2009> <Newton Game Dynamics> * * 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 */ // //Auto generated Lexical Analyzer class: dAssemblerLexical.h // #ifndef __dAssemblerLexical_h__ #define __dAssemblerLexical_h__ #ifdef _MSC_VER #pragma warning (disable: 4702) // warning C4702: unreachable code #pragma warning (disable: 4100) // warning C4100: unreferenced formal parameter #pragma warning (disable: 4201) // warning C4201: nonstandard extension used : nameless struct/union #endif #include <string> using namespace std; class dAssemblerLexical { public: dAssemblerLexical(const char* const data); virtual ~dAssemblerLexical(); virtual int NextToken (); const char* GetTokenString() const { return m_tokenString.c_str(); } const char* GetData() const { return m_data; } const char* GetNextBuffer() const { return &m_data[m_index]; } int GetIndex() const { return m_index; } int GetLineNumber () const { return m_lineNumber; } protected: void SetIndex(int index) { m_index = index; m_startIndex = index; m_tokenString = ""; } char NextChar () { char ch = m_data[m_index]; m_index ++; if (ch == '\n') { m_lineNumber ++; } return ch; } void UnGetChar () { m_index--; if (m_data[m_index] == '\n') { m_lineNumber --; } } void ReadBalancedExpresion (char open, char close); void GetLexString (); int GetNextStateIndex (char symbol, int count, const char* const sharacterSet) const; // local lexical variables string m_tokenString; const char* m_data; int m_index; int m_startIndex; int m_lineNumber; }; #endif
[ "[email protected]@b7a2f1d6-d59d-a8fe-1e9e-8d4888b32692" ]
[ [ [ 1, 102 ] ] ]
a6faf39a2b80b11be8a8e53ce4786a07a242c8ca
6ee200c9dba87a5d622c2bd525b50680e92b8dab
/Autumn/WrapperDX/Buffer/ConstantBuffer.h
7706d7a7e1c6dbb9924f74499591e39c676c7abd
[]
no_license
Ishoa/bizon
4dbcbbe94d1b380f213115251e1caac5e3139f4d
d7820563ab6831d19e973a9ded259d9649e20e27
refs/heads/master
2016-09-05T11:44:00.831438
2010-03-10T23:14:22
2010-03-10T23:14:22
32,632,823
0
0
null
null
null
null
UTF-8
C++
false
false
417
h
#ifndef _CONSTANT_BUFFER_ #define _CONSTANT_BUFFER_ #ifndef _BUFFER_ #include "WrapperDX/Buffer/Buffer.h" #endif class ConstantBuffer : public Buffer { private: public: ConstantBuffer(); virtual ~ConstantBuffer(); virtual HRESULT Create(unsigned int size, unsigned int nElts, const void * data, bool IsFlaggedStreamOutput = false); virtual HRESULT Destroy(); }; #endif // _CONSTANT_BUFFER_
[ "edouard.roge@ab19582e-f48f-11de-8f43-4547254af6c6" ]
[ [ [ 1, 20 ] ] ]
d5b7c61a4f9e5ff47160ea23a7d866c07cbb8169
110f8081090ba9591d295d617a55a674467d127e
/Cryptography/PureRandom.hpp
9c9bf024dc62592a0eeef59690a815a2bc8a6076
[]
no_license
rayfill/cpplib
617bcf04368a2db70aea8b9418a45d7fd187d8c2
bc37fbf0732141d0107dd93bcf5e0b31f0d078ca
refs/heads/master
2021-01-25T03:49:26.965162
2011-07-17T15:19:11
2011-07-17T15:19:11
783,979
1
0
null
null
null
null
UTF-8
C++
false
false
280
hpp
#ifndef PURERANDOM_HPP_ #define PURERANDOM_HPP_ /** * 乱数インターフェース */ class PureRandom { public: PureRandom() {} virtual ~PureRandom() {} /// バイト乱数の取得 virtual unsigned char getRandom() = 0; }; #endif /* PURERANDOM_HPP_ */
[ "bpokazakijr@287b3242-7fab-264f-8401-8509467ab285", "alfeim@287b3242-7fab-264f-8401-8509467ab285" ]
[ [ [ 1, 3 ], [ 7, 11 ], [ 13, 16 ] ], [ [ 4, 6 ], [ 12, 12 ] ] ]
a572ddbb1ac2af3a6917e80aa0bf23c201c43b78
ea313df9caa9e759b785269465871ab53b911734
/tests.cc
ed8a9692739af52aa308aab7dbd880ed179b7f0c
[]
no_license
puyo/tankdemo
ccc3127270ecf5b54b32bad5a7abad508dfa5100
9c9df4d8c094079d257271334b04b14834db91ff
refs/heads/master
2020-06-04T09:04:55.498703
2010-03-21T06:03:33
2010-03-21T06:03:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,338
cc
// 3D Tank Game 1.0 // Gregory McIntyre 1998 // test functions #include <cstdio> #include <allegro.h> #include "colours.h" #include "tank.h" #include "tests.h" /// FUNCTION DEFINITIONS ///////////////////////////////// // tank test - rotate and view a tank void tank_test() { PALETTE pal; BITMAP *buffer; MATRIX trans, cam; TANK p; int c, vc, fc; fixed dist = (128 << 16); buffer = create_bitmap(SCREEN_W, SCREEN_H); get_camera_matrix(&cam, 0, 0, 0, // eye position 0, 0, itofix(1), // front vector 0, itofix(-1), 0, // up vector itofix(32), // field of view itofix(1)); // aspect ratio for (;;) { clear(buffer); for (c = 0; c != 256; c++) putpixel(buffer, c, 0, c); get_transformation_matrix(&trans, 1<<16, p.xr, p.yr, p.zr, p.x, p.y, dist); // transform verticies for (vc = 0; vc != 3*8; vc++) { apply_matrix(&trans, p.o[vc].x, p.o[vc].y, p.o[vc].z, &p.v[vc].x, &p.v[vc].y, &p.v[vc].z); } for (fc = 0; fc != 3*6; fc++) { // cull backfaces if (polygon_z_normal(&p.v[p.f[fc].v1], &p.v[p.f[fc].v2], &p.v[p.f[fc].v3]) < 0) p.f[fc].visible = FALSE; else p.f[fc].visible = TRUE; } // 3D space coodinates -> 2D screen coodinates for (vc = 0; vc != 3*8; vc++) { apply_matrix(&cam, p.v[vc].x, p.v[vc].y, p.v[vc].z, &p.v[vc].x, &p.v[vc].y, &p.v[vc].z); persp_project(p.v[vc].x, p.v[vc].y, p.v[vc].z, &p.v[vc].x, &p.v[vc].y); } qsort(p.f, 3*6, sizeof(QUAD), quad_cmp); // draw the tank for (fc = 0; fc != 3*6; fc++) { if (p.f[fc].visible) { quad3d(buffer, POLYTYPE_GCOL, NULL, &p.v[p.f[fc].v1], &p.v[p.f[fc].v2], &p.v[p.f[fc].v3], &p.v[p.f[fc].v4]); } } // copy the buffer to the screen vsync(); blit(buffer, screen, 0, 0, 0, 0, SCREEN_W, SCREEN_H); // handle keys // tank rotation if (key[KEY_UP]) p.xr += (1 << 16); if (key[KEY_DOWN]) p.xr -= (1 << 16); if (key[KEY_LEFT]) p.yr += (1 << 16); if (key[KEY_RIGHT]) p.yr -= (1 << 16); // tank movement if (key[KEY_COMMA]) p.x -= (1 << 16); if (key[KEY_STOP]) p.x += (1 << 16); // zoom if (key[KEY_EQUALS]) dist -= (5 << 16); if (key[KEY_MINUS]) dist += (5 << 16); if (key[KEY_ESC]) goto getout; if (key[KEY_F12]) { // capture the screen to a pcx file get_palette(pal); save_bitmap("tankscrn.pcx", buffer, pal); } } getout: destroy_bitmap(buffer); } // callback for qsort() int quad_cmp(const void *e1, const void *e2) { QUAD *q1 = (QUAD *)e1; QUAD *q2 = (QUAD *)e2; fixed d1 = q1->vlist[q1->v1].z + q1->vlist[q1->v2].z + q1->vlist[q1->v3].z + q1->vlist[q1->v4].z; fixed d2 = q2->vlist[q2->v1].z + q2->vlist[q2->v2].z + q2->vlist[q2->v3].z + q2->vlist[q2->v4].z; return d2 - d1; }
[ [ [ 1, 134 ] ] ]
5df0dae2430989d013d1dc47e99080dedfc24dcb
bef7d0477a5cac485b4b3921a718394d5c2cf700
/dingus/dingus/gfx/ModelDescSerializer.cpp
223ec4f7694296b195ad84a310b8ce796785e16f
[ "MIT" ]
permissive
TomLeeLive/aras-p-dingus
ed91127790a604e0813cd4704acba742d3485400
22ef90c2bf01afd53c0b5b045f4dd0b59fe83009
refs/heads/master
2023-04-19T20:45:14.410448
2011-10-04T10:51:13
2011-10-04T10:51:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,127
cpp
// -------------------------------------------------------------------------- // Dingus project - a collection of subsystems for game/graphics applications // -------------------------------------------------------------------------- #include "stdafx.h" #include "ModelDescSerializer.h" #include "../lua/LuaSingleton.h" #include "../lua/LuaHelper.h" #include "../lua/LuaIterator.h" using namespace dingus; bool CModelDescSerializer::loadFromFile( const char* fileName, CModelDesc& desc ) { // clear desc... desc.setMeshID( "" ); desc.clearGroups(); // execute file CLuaSingleton& lua = CLuaSingleton::getInstance(); int errorCode = lua.doFile( fileName, false ); if( errorCode ) return false; // error // create desc std::string name = lua.getGlobal("name").getString(); lua.discard(); desc.setMeshID( name ); // read groups CLuaValue luaGroups = lua.getGlobal("groups"); CLuaArrayIterator itGrps( luaGroups ); while( itGrps.hasNext() ) { CLuaValue& luaGrp = itGrps.next(); // add group std::string fx = CLuaHelper::getString( luaGrp, "fx" ); int pri = (int)CLuaHelper::getNumber( luaGrp, "pri" ); desc.addGroup( pri, fx ); // group params const int grp = desc.getGroupCount() - 1; CLuaValue luaParams = luaGrp.getElement("params"); CLuaArrayIterator itParams( luaParams ); while( itParams.hasNext() ) { CLuaValue& luaPar = itParams.next(); std::string ttype = luaPar.getElement(1).getString(); std::string tname = luaPar.getElement(2).getString(); if( ttype == "tex" ) { std::string tid = luaPar.getElement(3).getString(); desc.addParamTexture( grp, tname, tid ); luaPar.discard(); } else if( ttype == "cube" ) { std::string tid = luaPar.getElement(3).getString(); desc.addParamCubemap( grp, tname, tid ); luaPar.discard(); } else if( ttype == "stex" ) { std::string tid = luaPar.getElement(3).getString(); desc.addParamSTexture( grp, tname, tid ); luaPar.discard(); } else if( ttype == "vec3" ) { SVector3 v; v.x = float( luaPar.getElement(3).getNumber() ); v.y = float( luaPar.getElement(4).getNumber() ); v.z = float( luaPar.getElement(5).getNumber() ); desc.addParamVec3( grp, tname, v ); luaPar.discard(); luaPar.discard(); luaPar.discard(); } else if( ttype == "vec4" ) { SVector4 v; v.x = float( luaPar.getElement(3).getNumber() ); v.y = float( luaPar.getElement(4).getNumber() ); v.z = float( luaPar.getElement(5).getNumber() ); v.w = float( luaPar.getElement(6).getNumber() ); desc.addParamVec4( grp, tname, v ); luaPar.discard(); luaPar.discard(); luaPar.discard(); luaPar.discard(); } else if( ttype == "flt" ) { float v = float( luaPar.getElement(3).getNumber() ); desc.addParamFloat( grp, tname, v ); luaPar.discard(); } else { ASSERT_FAIL_MSG( "Unsupported param type!" ); } luaPar.discard(); luaPar.discard(); } luaParams.discard(); } luaGroups.discard(); return true; } bool CModelDescSerializer::saveToFile( const char* fileName, const CModelDesc& desc ) { FILE *f = fopen( fileName, "wt" ); if( !f ) return false; // error! // name fprintf( f, "name = '%s'\n", desc.getMeshID().getUniqueName().c_str() ); // groups int n = desc.getGroupCount(); fprintf( f, "groups = {\n" ); for( int i = 0; i < n; ++i ) { fprintf( f, "{\n" ); // fx, priority fprintf( f, "\tfx = '%s',\n", desc.getFxID(i).getUniqueName().c_str() ); fprintf( f, "\tpri = %i,\n", desc.getRenderPriority(i) ); // params const CModelDesc::SParams& p = desc.getParams(i); fprintf( f, "\tparams = {\n" ); size_t j; for( j = 0; j < p.textures.size(); ++j ) { const CModelDesc::SParams::TNameIDPair& e = p.textures[j]; fprintf( f, "\t\t{ 'tex', '%s', '%s' },\n", e.first.c_str(), e.second.c_str() ); } for( j = 0; j < p.cubemaps.size(); ++j ) { const CModelDesc::SParams::TNameIDPair& e = p.cubemaps[j]; fprintf( f, "\t\t{ 'cube', '%s', '%s' },\n", e.first.c_str(), e.second.c_str() ); } for( j = 0; j < p.stextures.size(); ++j ) { const CModelDesc::SParams::TNameIDPair& e = p.stextures[j]; fprintf( f, "\t\t{ 'stex', '%s', '%s' },\n", e.first.c_str(), e.second.c_str() ); } for( j = 0; j < p.vectors3.size(); ++j ) { const CModelDesc::SParams::TNameVec3Pair& e = p.vectors3[j]; const SVector3& v = e.second; fprintf( f, "\t\t{ 'vec3', '%s', %g, %g, %g },\n", e.first.c_str(), v.x, v.y, v.z ); } for( j = 0; j < p.vectors4.size(); ++j ) { const CModelDesc::SParams::TNameVec4Pair& e = p.vectors4[j]; const SVector4& v = e.second; fprintf( f, "\t\t{ 'vec4', '%s', %g, %g, %g, %g },\n", e.first.c_str(), v.x, v.y, v.z, v.w ); } for( j = 0; j < p.floats.size(); ++j ) { const CModelDesc::SParams::TNameFloatPair& e = p.floats[j]; fprintf( f, "\t\t{ 'flt', '%s', %g },\n", e.first.c_str(), e.second ); } fprintf( f, "\t},\n" ); fprintf( f, "},\n" ); } fprintf( f, "}\n" ); fclose( f ); return true; }
[ [ [ 1, 149 ] ] ]
cf2797a7df468cc32e87ae2d7c120ccb578c9a41
b0fe69a13b1f10295788e8ddd243354c9cb0bfbe
/amv_int32/avm_elem.h
bb944916da6c2e0bfa6cc3f67507c1c4d3ac0f9b
[]
no_license
Surrog/avmfrandflo
d2346ce281b336eaeb4b79ec8303ed4f6c45774d
bfbaa57f7e52ff36352eaee7ca99d56ff64d16b0
refs/heads/master
2021-01-22T13:26:32.415282
2010-06-13T08:38:02
2010-06-13T08:38:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
710
h
#ifndef __AVM_ELEM_H__ #define __AVM_ELEM_H__ #include "AObj.h" class avm_elem : public AObj { int _prio; int _value; std::string _valuestr; std::string _type; public: avm_elem(void); ~avm_elem(void); IObject* Add(const IOperand &object); IObject* Subtract(const IOperand &object); IObject* Multiply(const IOperand &object); IObject* Divide(const IOperand &object); void setObj(std::string); int getprio() const; AObj* newClone() const; const std::string& ToString() const; const std::string& GetType() const; bool Equals(const IObject &value) const; IObject* Clone() const; }; #endif /* __AVM_ELEM_H__ */
[ "Florian Chanioux@localhost" ]
[ [ [ 1, 33 ] ] ]
be2ddb52aa26b56cac93e34c685cb50650780f52
804e416433c8025d08829a08b5e79fe9443b9889
/src/graphics/sprite.h
604329e2666725925eaee39884ef787c809f6905
[ "BSD-2-Clause" ]
permissive
cstrahan/argss
e77de08db335d809a482463c761fb8d614e11ba4
cc595bd9a1e4a2c079ea181ff26bdd58d9e65ace
refs/heads/master
2020-05-20T05:30:48.876372
2010-10-03T23:21:59
2010-10-03T23:21:59
1,682,890
1
0
null
null
null
null
UTF-8
C++
false
false
4,074
h
///////////////////////////////////////////////////////////////////////////// // ARGSS - Copyright (c) 2009 - 2010, Alejandro Marzini (vgvgf) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ///////////////////////////////////////////////////////////////////////////// #ifndef _SPRITE_H_ #define _SPRITE_H_ /////////////////////////////////////////////////////////// // Headers /////////////////////////////////////////////////////////// #include <string> #include "graphics/bitmap.h" #include "graphics/color.h" #include "graphics/tone.h" #include "graphics/rect.h" #include "graphics/drawable.h" /////////////////////////////////////////////////////////// /// Sprite class /////////////////////////////////////////////////////////// class Sprite : public Drawable { public: Sprite(unsigned long iid); ~Sprite(); static bool IsDisposed(unsigned long id); static void New(unsigned long id); static Sprite* Get(unsigned long id); static void Dispose(unsigned long id); void RefreshBitmaps(); void Draw(long z); void Draw(long z, Bitmap* dst_bitmap); void Flash(int duration); void Flash(Color color, int duration); void Update(); unsigned long GetViewport(); void SetViewport(unsigned long nviewport); unsigned long GetBitmap(); void SetBitmap(unsigned long nbitmap); unsigned long GetSrcRect(); void SetSrcRect(unsigned long nsrc_rect); bool GetVisible(); void SetVisible(bool nvisible); int GetX(); void SetX(int nx); int GetY(); void SetY(int ny); int GetZ(); void SetZ(int nz); int GetOx(); void SetOx(int nox); int GetOy(); void SetOy(int noy); float GetZoomX(); void SetZoomX(float nzoom_x); float GetZoomY(); void SetZoomY(float nzoom_y); float GetAngle(); void SetAngle(float nangle); bool GetFlipX(); void SetFlipX(bool nflipx); bool GetFlipY(); void SetFlipY(bool nflipy); int GetBushDepth(); void SetBushDepth(int nbush_depth); int GetOpacity(); void SetOpacity(int nopacity); int GetBlendType(); void SetBlendType(int nblend_type); unsigned long GetColor(); void SetColor(unsigned long ncolor); unsigned long GetTone(); void SetTone(unsigned long ntone); private: unsigned long id; unsigned long viewport; unsigned long bitmap; unsigned long src_rect; bool visible; int x; int y; int z; int ox; int oy; float zoom_x; float zoom_y; float angle; bool flipx; bool flipy; int bush_depth; int opacity; int blend_type; unsigned long color; unsigned long tone; GLuint flash_texture; Color flash_color; int flash_duration; int flash_frame; Bitmap* sprite; Rect src_rect_sprite; Rect src_rect_last; bool needs_refresh; bool flash_needs_refresh; void Refresh(); void RefreshFlash(); int GetWidth(); int GetHeight(); }; #endif
[ "vgvgf@a70b67f4-0116-4799-9eb2-a6e6dfe7dbda" ]
[ [ [ 1, 137 ] ] ]
e1c067201589860c2476d5da743adb6bf4142127
55d6f54f463bf0f97298eb299674e2065863b263
/donneurGraphique.h
8dcccccd2fdb867efa26f3afdac9c24d619293f8
[]
no_license
Coinche/CoinchePAV
a344e69b096ef5fd4e24c98af1b24de2a99235f0
134cac106ee8cea78abc5b29b23a32706b2aad08
refs/heads/master
2020-06-01T09:35:51.793153
2011-12-01T19:57:12
2011-12-01T19:57:12
2,729,958
0
0
null
null
null
null
ISO-8859-2
C++
false
false
1,104
h
<<<<<<< HEAD #ifndef DONNEUR_GRAPHIQUE_H #define DONNEUR_GRAPHIQUE_H #include "annonce.h" #include "carte.h" //classe virtuelle pour pouvoir bien specifier une interface entre graphique et métier indépendante de la librarie graphique //et compiler la partie metier seule (sous forme de librarie statique) class DonneurGraphique { public: virtual void afficherAnnonce(int joueur, const Annonce&) = 0; virtual void afficherCarte(int joueur, const Carte& ) = 0; virtual void ramasserPli() = 0; }; ======= #ifndef DONNEUR_GRAPHIQUE_H #define DONNEUR_GRAPHIQUE_H #include "annonce.h" #include "carte.h" //classe virtuelle pour pouvoir bien specifier une interface entre graphique et métier indépendante de la librarie graphique //et compiler la partie metier seule (sous forme de librarie statique) class DonneurGraphique { public: virtual void afficherAnnonce(int joueur, const Annonce& annonce) = 0; virtual void afficherCarte(int joueur, const Carte& carte) = 0; virtual void ramasserPli() = 0; }; >>>>>>> 724574f908be7f7cad89d404f7c1f8c54b5cda57 #endif //DONNEUR_GRAPHIQUE_H
[ "lucas@graham.(none)", "Sylvestre@PC-Perso-MS.(none)" ]
[ [ [ 1, 17 ], [ 33, 33 ] ], [ [ 18, 32 ], [ 34, 34 ] ] ]
88f2e6c48735306221645b6dd9f6a4c711cd4cd6
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/zombie/npythonserver/src/pythontest/npythonhooks.cc
41fa282d7d861b93beb1a7a8b52462bd1b3f85de
[]
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
416
cc
#include "precompiled/pchnpythonserver.h" //------------------------------------------------------------------------------ /** */ //------------------------------------------------------------------------------ #include "python/npythonserver.h" void nPythonInitializeEnvironment() { PyRun_SimpleString("from pynebula import *"); } const char* nPythonModuleName() { return "pynebula"; }
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 19 ] ] ]
23a6ed122d5bc90b35356de2b4e7d93bb99759bc
b7c505dcef43c0675fd89d428e45f3c2850b124f
/Src/SimulatorQt/Util/qt/Win32/include/Qt/qprintpreviewdialog.h
715255e1516367c0a2e69e3313ef65e6f9f62a13
[ "BSD-2-Clause" ]
permissive
pranet/bhuman2009fork
14e473bd6e5d30af9f1745311d689723bfc5cfdb
82c1bd4485ae24043aa720a3aa7cb3e605b1a329
refs/heads/master
2021-01-15T17:55:37.058289
2010-02-28T13:52:56
2010-02-28T13:52:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,646
h
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QPRINTPREVIEWDIALOG_H #define QPRINTPREVIEWDIALOG_H #include <QtGui/qdialog.h> #ifndef QT_NO_PRINTPREVIEWDIALOG QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Gui) class QGraphicsView; class QPrintPreviewDialogPrivate; class Q_GUI_EXPORT QPrintPreviewDialog : public QDialog { Q_OBJECT Q_DECLARE_PRIVATE(QPrintPreviewDialog) public: explicit QPrintPreviewDialog(QWidget *parent = 0, Qt::WindowFlags flags = 0); explicit QPrintPreviewDialog(QPrinter *printer, QWidget *parent = 0, Qt::WindowFlags flags = 0); ~QPrintPreviewDialog(); #ifdef Q_NO_USING_KEYWORD #ifndef Q_QDOC void open() { QDialog::open(); } #endif #else using QDialog::open; #endif void open(QObject *receiver, const char *member); QPrinter *printer(); void setVisible(bool visible); void done(int result); Q_SIGNALS: void paintRequested(QPrinter *printer); private: Q_PRIVATE_SLOT(d_func(), void _q_fit(QAction *action)) Q_PRIVATE_SLOT(d_func(), void _q_zoomIn()) Q_PRIVATE_SLOT(d_func(), void _q_zoomOut()) Q_PRIVATE_SLOT(d_func(), void _q_navigate(QAction *action)) Q_PRIVATE_SLOT(d_func(), void _q_setMode(QAction *action)) Q_PRIVATE_SLOT(d_func(), void _q_pageNumEdited()) Q_PRIVATE_SLOT(d_func(), void _q_print()) Q_PRIVATE_SLOT(d_func(), void _q_pageSetup()) Q_PRIVATE_SLOT(d_func(), void _q_previewChanged()) Q_PRIVATE_SLOT(d_func(), void _q_zoomFactorChanged()) QPrintPreviewDialogPrivate *d_ptr; }; QT_END_NAMESPACE QT_END_HEADER #endif // QT_NO_PRINTPREVIEWDIALOG #endif // QPRINTPREVIEWDIALOG_H
[ "alon@rogue.(none)" ]
[ [ [ 1, 107 ] ] ]
6f6b154a35f8c1c0d5096798a6e431ddd13d245f
a37df219b4a30e684db85b00dd76d4c36140f3c2
/1.7.1/tri/tri_h.h
3362c2d2c25fc62adedd774a4fb7892bacd9ce51
[]
no_license
BlackMoon/bm-net
0f79278f8709cd5d0738a6c3a27369726b0bb793
eb6414bc412a8cfc5c24622977e7fa7203618269
refs/heads/master
2020-12-25T20:20:44.843483
2011-11-29T10:33:17
2011-11-29T10:33:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,730
h
/* this ALWAYS GENERATED file contains the definitions for the interfaces */ /* File created by MIDL compiler version 6.00.0366 */ /* at Sun Jun 17 10:12:48 2007 */ /* Compiler settings for .\tri.idl: Oicf, W1, Zp8, env=Win32 (32b run) protocol : dce , ms_ext, c_ext error checks: allocation ref bounds_check enum stub_data VC __declspec() decoration level: __declspec(uuid()), __declspec(selectany), __declspec(novtable) DECLSPEC_UUID(), MIDL_INTERFACE() */ //@@MIDL_FILE_HEADING( ) #pragma warning( disable: 4049 ) /* more than 64k source lines */ /* verify that the <rpcndr.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCNDR_H_VERSION__ #define __REQUIRED_RPCNDR_H_VERSION__ 440 #endif #include "rpc.h" #include "rpcndr.h" #ifndef __tri_h_h__ #define __tri_h_h__ #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif /* Forward Declarations */ #ifndef __IApplication_FWD_DEFINED__ #define __IApplication_FWD_DEFINED__ typedef interface IApplication IApplication; #endif /* __IApplication_FWD_DEFINED__ */ #ifndef __Application_FWD_DEFINED__ #define __Application_FWD_DEFINED__ #ifdef __cplusplus typedef class Application Application; #else typedef struct Application Application; #endif /* __cplusplus */ #endif /* __Application_FWD_DEFINED__ */ #ifndef __IGraph_FWD_DEFINED__ #define __IGraph_FWD_DEFINED__ typedef interface IGraph IGraph; #endif /* __IGraph_FWD_DEFINED__ */ #ifndef __Graph_FWD_DEFINED__ #define __Graph_FWD_DEFINED__ #ifdef __cplusplus typedef class Graph Graph; #else typedef struct Graph Graph; #endif /* __cplusplus */ #endif /* __Graph_FWD_DEFINED__ */ #ifdef __cplusplus extern "C"{ #endif void * __RPC_USER MIDL_user_allocate(size_t); void __RPC_USER MIDL_user_free( void * ); #ifndef __Model_LIBRARY_DEFINED__ #define __Model_LIBRARY_DEFINED__ /* library Model */ /* [helpstring][version][uuid] */ EXTERN_C const IID LIBID_Model; #ifndef __IApplication_DISPINTERFACE_DEFINED__ #define __IApplication_DISPINTERFACE_DEFINED__ /* dispinterface IApplication */ /* [uuid] */ EXTERN_C const IID DIID_IApplication; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("69DF4038-7FDA-447B-BD0D-2E09DD5D298E") IApplication : public IDispatch { }; #else /* C style interface */ typedef struct IApplicationVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IApplication * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IApplication * This); ULONG ( STDMETHODCALLTYPE *Release )( IApplication * This); HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( IApplication * This, /* [out] */ UINT *pctinfo); HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( IApplication * This, /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo **ppTInfo); HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( IApplication * This, /* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID *rgDispId); /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( IApplication * This, /* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS *pDispParams, /* [out] */ VARIANT *pVarResult, /* [out] */ EXCEPINFO *pExcepInfo, /* [out] */ UINT *puArgErr); END_INTERFACE } IApplicationVtbl; interface IApplication { CONST_VTBL struct IApplicationVtbl *lpVtbl; }; #ifdef COBJMACROS #define IApplication_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IApplication_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IApplication_Release(This) \ (This)->lpVtbl -> Release(This) #define IApplication_GetTypeInfoCount(This,pctinfo) \ (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) #define IApplication_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) #define IApplication_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) #define IApplication_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IApplication_DISPINTERFACE_DEFINED__ */ EXTERN_C const CLSID CLSID_Application; #ifdef __cplusplus class DECLSPEC_UUID("1024D545-C833-40A5-9281-95017A384973") Application; #endif #ifndef __IGraph_DISPINTERFACE_DEFINED__ #define __IGraph_DISPINTERFACE_DEFINED__ /* dispinterface IGraph */ /* [uuid] */ EXTERN_C const IID DIID_IGraph; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("3ECB516B-24CD-494B-8676-1EB3645EDE16") IGraph : public IDispatch { }; #else /* C style interface */ typedef struct IGraphVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IGraph * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IGraph * This); ULONG ( STDMETHODCALLTYPE *Release )( IGraph * This); HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( IGraph * This, /* [out] */ UINT *pctinfo); HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( IGraph * This, /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo **ppTInfo); HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( IGraph * This, /* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID *rgDispId); /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( IGraph * This, /* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS *pDispParams, /* [out] */ VARIANT *pVarResult, /* [out] */ EXCEPINFO *pExcepInfo, /* [out] */ UINT *puArgErr); END_INTERFACE } IGraphVtbl; interface IGraph { CONST_VTBL struct IGraphVtbl *lpVtbl; }; #ifdef COBJMACROS #define IGraph_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IGraph_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IGraph_Release(This) \ (This)->lpVtbl -> Release(This) #define IGraph_GetTypeInfoCount(This,pctinfo) \ (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) #define IGraph_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) #define IGraph_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) #define IGraph_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IGraph_DISPINTERFACE_DEFINED__ */ EXTERN_C const CLSID CLSID_Graph; #ifdef __cplusplus class DECLSPEC_UUID("66FCF56C-26B5-4689-9CC0-A7AA9C78B99B") Graph; #endif #endif /* __Model_LIBRARY_DEFINED__ */ /* Additional Prototypes for ALL interfaces */ /* end of Additional Prototypes */ #ifdef __cplusplus } #endif #endif
[ "[email protected]@b6168ec3-97fc-df6f-cbe5-288b4f99fbbd" ]
[ [ [ 1, 331 ] ] ]
f4c4afa497d5fe2709e072373a378743a8ab92b1
bda7b365b5952dc48827a8e8d33d11abd458c5eb
/SignIn.h
d692b3625b0066929db943cc006ddf35a3f5064d
[]
no_license
MrColdbird/gameservice
3bc4dc3906d16713050612c1890aa8820d90272e
009d28334bdd8f808914086e8367b1eb9497c56a
refs/heads/master
2021-01-25T09:59:24.143855
2011-01-31T07:12:24
2011-01-31T07:12:24
35,889,912
3
3
null
null
null
null
UTF-8
C++
false
false
9,719
h
// ====================================================================================== // File : SignIn.h // Author : Li Chen // Last Change : 07/29/2010 | 15:48:22 PM | Thursday,July // Description : // ====================================================================================== #pragma once #ifndef SIGNIN_H #define SIGNIN_H namespace GameService { #define MAX_USER_NAME 64 class SignIn { public: // Flags that can be returned from Update() enum SIGNIN_UPDATE_FLAGS { SIGNIN_USERS_CHANGED = 0x00000001, SYSTEM_UI_CHANGED = 0x00000002, CONNECTION_CHANGED = 0x00000004 }; #if defined(_XBOX) || defined(_XENON) // Check users that are signed in static GS_DWORD GetSignedInUserCount() { return m_dwNumSignedInUsers; } static GS_DWORD GetSignedInUserMask() { return m_dwSignedInUserMask; } static GS_BOOL IsUserSignedIn( GS_DWORD dwController ) { return ( m_dwSignedInUserMask & ( 1 << dwController ) ) != 0; } static GS_BOOL AreUsersSignedIn() { // return ( m_dwNumSignedInUsers >= m_dwMinUsers ) && // ( m_dwNumSignedInUsers <= m_dwMaxUsers ); //jin yu+ change to check if the contorller user is signed in. if(XUserGetSigninState( GetActiveUserIndex() ) == eXUserSigninState_NotSignedIn ) return FALSE; else return TRUE; //jin yu- } // Get the first signed-in user static GS_DWORD GetSignedInUser() { return m_dwFirstSignedInUser; } // Check users that are signed into live static GS_DWORD GetOnlineUserMask() { return m_dwOnlineUserMask; } static GS_BOOL IsUserSignedInOnline( GS_DWORD dwController ) { return ( m_dwOnlineUserMask & ( 1 << dwController ) ) != 0; } static GS_DWORD GetActiveUserIndex() { return m_dwActiveUserIndex; } // Get the first signed-in user static GS_VOID SetActiveUserIndex(GS_DWORD user) { m_dwActiveUserIndex = user; } #elif defined(_PS3) static GS_DWORD GetActiveUserIndex() { return m_dwActiveUserIndex; } static GS_INT GetOnlineStatus() { return m_sceNPStatus; } static SceNpId& GetNpID() { return m_sceNpID; } static SceNpOnlineName& GetOnlineName() { return m_sceOnlineName; } static SceNpAvatarUrl& GetAvatarUrl() { return m_sceAvatarUrl; } static SceNpMyLanguages& GetLanguage() { return m_sceMyLang; } static SceNpCountryCode& GetCountryCode() { return m_sceCountryCode; } static GS_INT GetLangCode() { return m_sceLangCode; } #else static GS_DWORD GetActiveUserIndex() { return 0; } #endif // for local user infos: static GS_UINT GetUserNum() { return m_nNumUsers; } #if defined(_XBOX) || defined(_XENON) static XUID& GetXUID(GS_UINT iUser) { if (iUser < 0 || iUser >= XUSER_MAX_COUNT) return m_InvalidID; return m_Xuids[iUser]; } #elif defined(_PS3) #endif static GS_CHAR* GetUserNameStr(GS_UINT iUser); #if defined(_XBOX) || defined(_XENON) static XUID* GetXUIDArray() { return m_Xuids; } #elif defined(_PS3) #endif #if defined(_XBOX) || defined(_XENON) static GS_BOOL GetIsPrivate(GS_UINT iUser) { if (iUser < 0 || iUser >= XUSER_MAX_COUNT) return 0; return m_bPrivate[iUser]; } static GS_BOOL* GetIsPrivateArray() { return m_bPrivate; } static GS_BOOL IsUserOnline( GS_DWORD dwController ) { return ( m_dwOnlineUserMask & ( 1 << dwController ) ) != 0; } // Check the presence of system UI static GS_BOOL IsSystemUIShowing() { return m_bSystemUIShowing || m_bNeedToShowSignInUI; } // Function to reinvoke signin UI static GS_VOID ShowSignInUI() { m_bNeedToShowSignInUI = TRUE; } // Check privileges for a signed-in users static GS_BOOL CheckPrivilege( GS_DWORD dwController, XPRIVILEGE_TYPE priv ); static GS_BOOL NotifyNoProfileSignedIn() { GS_BOOL ret = m_bCanNotifyNoProfile; if (m_bCanNotifyNoProfile) { m_bCanNotifyNoProfile = FALSE; } return ret; } #elif defined(_PS3) static GS_BOOL StartNP(); static GS_BOOL GetNPStatus(); static void PS3_StartNP_Thread(uint64_t instance); static void TermNP(); static void SignInNP(); static GS_BOOL StartNet(); static void TermNet(); static GS_BOOL CheckConnection(); static void NpStatusNotifyCallBack(int event, int result, void* arg); static void NpManagerCallBack(int event, int result, void *arg); static int NpBasicCallBack(int event, int retCode, uint32_t reqId, void *arg); static void NetSysUtilCbInternal(uint64_t status, uint64_t param, void * userdata); static void NpBasicSendInitPresence(); static const SceNpCommunicationId* GetNpCommID() { return &m_NpCommID; } static const SceNpCommunicationSignature* GetNpCommSig() { return &m_NpCommSig; } static const SceNpCommunicationPassphrase* GetNpCommPass() { return &m_NpPassPhrase; } static const char* GetNpServiceID() { return m_NpServiceID; } static const char* GetNpProductID() { return m_NpProductID; } static GS_BOOL IsUserOnline() { return m_bIsOnline; } static int GetUserAge() { return m_UserAge; } static GS_INT IsCableConnected(); #endif static GS_VOID ShowGamerCardUI( #if defined(_XBOX) || defined(_XENON) XUID #elif defined(_PS3) SceNpId* #else int #endif id); static GS_VOID SetBeforePressStart(GS_BOOL before) { m_bBeforePressStart = before; } static GS_BOOL GetBeforePressStart() { return m_bBeforePressStart; } static GS_VOID StartGame(GS_UINT userInex); // Methods to drive autologin static GS_VOID Initialize( GS_DWORD dwMinUsers, GS_DWORD dwMaxUsers, GS_BOOL bRequireOnlineUsers, GS_DWORD dwSignInPanes ); static GS_DWORD Update(); static GS_VOID QuerySigninStatus(); // Query signed in users private: // Private constructor to prevent instantiation SignIn(); // Parameters static GS_DWORD m_dwMinUsers; // minimum users to accept as signed in static GS_DWORD m_dwMaxUsers; // maximum users to accept as signed in static GS_BOOL m_bRequireOnlineUsers; // online profiles only static GS_DWORD m_dwSignInPanes; // number of panes to show in signin UI static GS_BOOL m_bBeforePressStart; // Internal variables #if defined(_XBOX) || defined(_XENON) static HANDLE m_hNotification; // listener to accept notifications static GS_DWORD m_dwSignedInUserMask; // bitfields for signed-in users static GS_DWORD m_dwFirstSignedInUser; // first signed-in user static GS_DWORD m_dwNumSignedInUsers; // number of signed-in users static GS_DWORD m_dwOnlineUserMask; // users who are online static GS_BOOL m_bSystemUIShowing; // system UI present static GS_BOOL m_bNeedToShowSignInUI; // invoking signin UI necessary static GS_BOOL m_bMessageBoxShowing; // is retry signin message box showing? static GS_BOOL m_bSigninUIWasShown; // was the signin ui shown at least once? static XOVERLAPPED m_Overlapped; // message box overlapped struct static LPCWSTR m_pwstrButtons[2]; // message box buttons static MESSAGEBOX_RESULT m_MessageBoxResult; // message box button pressed static GS_BOOL m_bPrivate[ XUSER_MAX_COUNT ]; // Users consuming private slots static GS_BOOL m_bCanNotifyNoProfile; static GS_CHAR m_cUserName[XUSER_MAX_COUNT][MAX_USER_NAME]; static XUID m_InvalidID; //JinYu+ static GS_DWORD m_dwActiveUserIndex; static GS_DWORD m_LastSignInStateChange; static GS_BOOL m_SignInChanged; //JinYu- #elif defined(_PS3) static GS_DWORD m_dwActiveUserIndex; static GS_INT m_iCheckConnectionSlot; static GS_BOOL m_bIsOnline; static GS_INT m_sceNPStatus; static SceNpId m_sceNpID; static SceNpOnlineName m_sceOnlineName; static SceNpAvatarUrl m_sceAvatarUrl; static SceNpMyLanguages m_sceMyLang; static SceNpCountryCode m_sceCountryCode; static GS_INT m_sceLangCode; static const SceNpCommunicationSignature m_NpCommSig; static const SceNpCommunicationId m_NpCommID; static const SceNpCommunicationPassphrase m_NpPassPhrase; static const char m_NpServiceID[32]; static const char m_NpProductID[64]; static int m_UserAge; static GS_BOOL m_bStarNPInProgress; static GS_BOOL m_bIsStarNPRequestPending; #endif // Latest SignIn infos static GS_UINT m_nNumUsers; // Local users #if defined(_XBOX) || defined(_XENON) static XUID m_Xuids [ XUSER_MAX_COUNT ]; // Local XUIDs #elif defined(_PS3) #endif }; } // namespace GameService #endif // SIGNIN_H
[ "leavesmaple@383b229b-c81f-2bc2-fa3f-61d2d0c0fe69" ]
[ [ [ 1, 341 ] ] ]
ec230e78d06510a33ff3ec81039362d022185c1b
51e1cf5dc3b99e8eecffcf5790ada07b2f03f39c
/SMC/src/jpiranha.cpp
424a596c0b7e54be9688799499a78c3455a342c6
[]
no_license
jdek/jim-pspware
c3e043b59a69cf5c28daf62dc9d8dca5daf87589
fd779e1148caac2da4c590844db7235357b47f7e
refs/heads/master
2021-05-31T06:45:03.953631
2007-06-25T22:45:26
2007-06-25T22:45:26
56,973,047
2
1
null
null
null
null
UTF-8
C++
false
false
5,818
cpp
/*************************************************************************** jpiranha.cpp - jprinha,jumping piranha plant ------------------- copyright : (C) 2003-2005 by FluXy ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "include/globals.h" /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */ cjPiranha :: cjPiranha( double x, double y, ObjectDirection dir /* = DIR_UP */, unsigned int nmax_distance /* = 200 */ ) : cEnemy( x, y ) { direction = dir; if( direction == DIR_UP ) { images.push_back( GetImage( "enemy/jpiranha/c1.png" ) ); images.push_back( GetImage( "enemy/jpiranha/c2.png" ) ); images.push_back( GetImage( "enemy/jpiranha/o1.png" ) ); images.push_back( GetImage( "enemy/jpiranha/o2.png" ) ); vely = -5.8; } else if( direction == DIR_DOWN ) { images.push_back( GetImage( "enemy/jpiranha/c1.png", 180 ) ); images.push_back( GetImage( "enemy/jpiranha/c2.png", 180 ) ); images.push_back( GetImage( "enemy/jpiranha/o1.png", 180 ) ); images.push_back( GetImage( "enemy/jpiranha/o2.png", 180 ) ); vely = 5.8; } else if( direction == DIR_LEFT ) { images.push_back( GetImage( "enemy/jpiranha/c1.png", 90 ) ); images.push_back( GetImage( "enemy/jpiranha/c2.png", 90 ) ); images.push_back( GetImage( "enemy/jpiranha/o1.png", 90 ) ); images.push_back( GetImage( "enemy/jpiranha/o2.png", 90 ) ); velx = -5.8; } else if( direction == DIR_RIGHT ) { images.push_back( GetImage( "enemy/jpiranha/c1.png", 270 ) ); images.push_back( GetImage( "enemy/jpiranha/c2.png", 270 ) ); images.push_back( GetImage( "enemy/jpiranha/o1.png", 270 ) ); images.push_back( GetImage( "enemy/jpiranha/o2.png", 270 ) ); velx = 5.8; } else { dead = 1; visible = 0; printf( "jPiranha direction Error : %d\n", direction ); return; } walk_count = rand() % (8); state = FLY; max_distance = nmax_distance; wait_time = rand() % (90); type = TYPE_JPIRANHA; SetImage( 0 ); SetPos( x, y ); } cjPiranha :: ~cjPiranha( void ) { // } void cjPiranha :: Die( void ) { dead = 1; massive = 0; SetImage( 0 ); } void cjPiranha :: DieStep( void ) { visible = 0; } void cjPiranha :: Update( void ) { if( dead ) { if( visible ) { DieStep(); } return; } // update range if( posx < pPlayer->posx - 7000 || posy < pPlayer->posy - 7000 || posx > pPlayer->posx + 7000 || posy > pPlayer->posy + 7000 ) { return; } if( direction == DIR_DOWN ) { startpos = -startposy; pos = -posy; vel = -vely; } else if( direction == DIR_RIGHT ) { startpos = -startposx; pos = -posx; vel = -velx; } else if( direction == DIR_LEFT ) { startpos = startposx; pos = posx; vel = velx; } else // up { startpos = startposy; pos = posy; vel = vely; } if( startpos - pos > ( max_distance / 3 ) && startpos - pos < max_distance && vel < -0.5 ) { vel += ( -vel * 0.04 ) * Framerate.speedfactor; } else if( startpos - pos > ( max_distance - 10 ) && !wait_time ) { vel = 0.5; } else if( startpos - pos > ( max_distance / 2 ) && !wait_time ) { vel += 0.025 * Framerate.speedfactor; } else if( startpos - pos < 0 && vel > 0.3 ) { wait_time = DESIRED_FPS * 3; vel = 0; } else if( wait_time > 0 ) { wait_time -= Framerate.speedfactor; if( wait_time < 0 ) { wait_time = 0; } } else if( startpos - pos < 0 ) { SDL_Rect r2 = rect; if( direction == DIR_UP ) { r2.y -= 40; r2.h += 40; } else if( direction == DIR_DOWN ) { r2.y += 40; r2.h -= 40; } else if( direction == DIR_RIGHT ) { r2.x += 35; } else if( direction == DIR_LEFT ) { r2.x -= 35; } if( CollideBoundingBox( &pPlayer->rect, &r2 ) ) { wait_time = DESIRED_FPS * 2; } else { vel = -7; } } // set the position from the internal calculations if( direction == DIR_UP ) { startposy = startpos; posy = pos; vely = vel; } else if( direction == DIR_DOWN ) { startposy = -startpos; posy = -pos; vely = -vel; } else if( direction == DIR_RIGHT ) { startposx = -startpos; posx = -pos; velx = -vel; } else if( direction == DIR_LEFT ) { startposx = startpos; posx = pos; velx = vel; } walk_count += Framerate.speedfactor; if( walk_count > 8 ) { walk_count = -8; } if( walk_count < -4 ) { SetImage( 0 ); } else if( walk_count < 0 ) { SetImage( 1 ); } else if( walk_count < 4 ) { SetImage( 2 ); } else { SetImage( 3 ); } if( CollideMove() != DIR_NOTHING ) { Move( velx, vely, 0, 1 ); SDL_Rect r2 = Get_Collision_rect(); if( iCollisionType == 4 && massive && visible ) { PlayerCollision( col_dir ); } } if( EnemyObjects.size() && image && !dead ) { Draw( screen ); } } void cjPiranha :: PlayerCollision( ObjectDirection cdirection ) { if( cdirection != -1 ) { pPlayer->Die(); } }
[ "rinco@ff2c0c17-07fa-0310-a4bd-d48831021cb5" ]
[ [ [ 1, 275 ] ] ]
6fd0cd616a8d3439af411fb9c31e19aa59e83458
1bb21e6d6a47a9ff05b47066c9da20bc999ea8ab
/Taquin42/Taquin42/SolutionGenerator.cpp
577a1a0edf3e4e226c47485fecffa7220a92a470
[]
no_license
SouhaibDZ/taquin42
82766e89a431f47a5a0bddfe79ef4211983bf4bc
8dae0b8ff2888405e3bd1d3968ce85da78d97487
refs/heads/master
2021-01-22T04:36:40.950015
2010-12-17T15:02:29
2010-12-17T15:02:29
40,320,284
0
0
null
null
null
null
UTF-8
C++
false
false
2,892
cpp
#include "SolutionGenerator.hpp" #include <iostream> SolutionGenerator::SolutionGenerator(unsigned int Scale) { std::cout << "\tSolution Generating ....." << std::endl; this->X_min = 0; this->X_max = 0; this->X_cur = 0; this->Y_min = 0; this->Y_max = 0; this->Y_cur = 0; this->Num = 1; this->PuzzleScale = Scale; } SolutionGenerator::~SolutionGenerator() {} void SolutionGenerator::FillTop() { while (this->X_cur < this->X_max) { this->Witness[this->X_cur][this->Y_cur] = this->Num; this->X_cur++; this->Num++; } this->X_cur--; this->X_max--; this->Y_cur++; } void SolutionGenerator::FillRight() { while (this->Y_cur < this->Y_max) { this->Witness[this->X_cur][this->Y_cur] = this->Num; this->Y_cur++; this->Num++; } this->Y_cur--; this->Y_max--; this->X_cur--; } void SolutionGenerator::FillBottom() { while (this->X_cur > this->X_min - 1) { this->Witness[this->X_cur][this->Y_cur] = this->Num; this->X_cur--; this->Num++; } this->X_cur++; this->X_min++; this->Y_cur--; } void SolutionGenerator::FillLeft() { while (this->Y_cur > this->Y_min) { this->Witness[this->X_cur][this->Y_cur] = this->Num; this->Y_cur--; this->Num++; } this->Y_cur++; this->Y_min++; this->X_cur++; } void SolutionGenerator::DisplaySolution() const { std::cout << "-------------------------------------" << std::endl; for (unsigned int i = 0; i < this->PuzzleScale; ++i) { for (unsigned int j = 0; j < this->PuzzleScale; ++j) { if (this->Witness[i][j] == this->PuzzleScale * this->PuzzleScale) this->Witness[i][j] = 0; std::cout << this->Witness[j][i] << "\t"; } std::cout << std::endl; } std::cout << "-------------------------------------" << std::endl << std::endl; } bool SolutionGenerator::GenerateSolution() { if (this->PuzzleScale > 100) { std::cerr << "The taquin is too big" << std::endl; return (false); } this->X_max = this->Y_max = this->PuzzleScale; this->Witness = new unsigned int*[this->PuzzleScale]; for (unsigned int i = 0; i < this->PuzzleScale; i++) this->Witness[i] = new unsigned int[this->PuzzleScale]; while (this->X_min <= this->X_max && this->Y_min <= this->Y_max) { this->FillTop(); this->FillRight(); this->FillBottom(); this->FillLeft(); } // This part is a debug displaying , can be removed after. this->DisplaySolution(); return (true); } void SolutionGenerator::SearchNodeGoalPos(unsigned int CurrentNodeName, sPositions& pos) const { unsigned int i = 0; unsigned int j = 0; bool end = false; while (i < this->PuzzleScale && !end) { j = 0; while (j < this->PuzzleScale && !end) { if (this->Witness[i][j] == CurrentNodeName) { pos.Node_px = i; pos.Node_py = j; } ++j; } ++i; } }
[ "sikilaxx01@b4d6ab20-219d-e4c1-b8d5-e97ec591408c", "desde42@b4d6ab20-219d-e4c1-b8d5-e97ec591408c" ]
[ [ [ 1, 2 ], [ 6, 14 ], [ 17, 32 ], [ 34, 42 ], [ 44, 95 ], [ 99, 110 ] ], [ [ 3, 5 ], [ 15, 16 ], [ 33, 33 ], [ 43, 43 ], [ 96, 98 ], [ 111, 131 ] ] ]
68f03a7b768b5c5aae8593a6a9397cacf66f1d25
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Dependencies/Xerces/include/xercesc/framework/psvi/XSAttributeUse.cpp
5c25a3b39ddead00dcb37613a7737494a782e43a
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
2,065
cpp
/* * Copyright 2003,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: XSAttributeUse.cpp 191054 2005-06-17 02:56:35Z jberry $ */ #include <xercesc/framework/psvi/XSAttributeUse.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // XSAttributeUse: Constructors and Destructor // --------------------------------------------------------------------------- XSAttributeUse::XSAttributeUse(XSAttributeDeclaration* const xsAttDecl, XSModel* const xsModel, MemoryManager* const manager) : XSObject(XSConstants::ATTRIBUTE_USE, xsModel, manager) , fRequired(false) , fConstraintType(XSConstants::VALUE_CONSTRAINT_NONE) , fConstraintValue(0) , fXSAttributeDeclaration(xsAttDecl) { } XSAttributeUse::~XSAttributeUse() { // don't delete fXSAttributeDeclaration - deleted by XSModel } // --------------------------------------------------------------------------- // XSAttributeUse: helper methods // --------------------------------------------------------------------------- void XSAttributeUse::set(const bool isRequired, XSConstants::VALUE_CONSTRAINT constraintType, const XMLCh* const constraintValue) { fRequired = isRequired; fConstraintType = constraintType; fConstraintValue = constraintValue; } XERCES_CPP_NAMESPACE_END
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 60 ] ] ]
8835fa86da50687c75da622132c21406d5be7121
a0155e192c9dc2029b231829e3db9ba90861f956
/MailFilter/Libs/src/tnef/tnef-lib.cpp
17ccbf38fd9021597aed026a80f370a01975395f
[]
no_license
zeha/mailfilter
d2de4aaa79bed2073cec76c93768a42068cfab17
898dd4d4cba226edec566f4b15c6bb97e79f8001
refs/heads/master
2021-01-22T02:03:31.470739
2010-08-12T23:51:35
2010-08-12T23:51:35
81,022,257
0
0
null
null
null
null
UTF-8
C++
false
false
8,507
cpp
/* * tnef-lib.c * * based on tnef2txt, by Brandon Long. * * tnef2txt had this license header attached, and the same license applies * to tnef-lib: * * NOTE: THIS SOFTWARE IS FOR YOUR PERSONAL GRATIFICATION ONLY. I DON'T * IMPLY IN ANY LEGAL SENSE THAT THIS SOFTWARE DOES ANYTHING OR THAT IT WILL * BE USEFULL IN ANY WAY. But, you can send me fixes to it, I don't mind. */ #include <stdio.h> #include <sys/stat.h> #include <errno.h> //#include <string.h> #include "config.h" #include "tnef.h" #include "mapidefs.h" #include "tnef-lib.h" #include "mapitags.h" extern "C" { char* strncpy(char*, unsigned char*, unsigned int); void* malloc(size_t length); void free(void* p); char* strcpy(char*, char*); } //#define VERSION "tnef-lib 0.1 (based on tnef2txt/1.3)" /* Some systems don't like to read unaligned data */ static uint32 read_32(uint8 *tsp, uint8* streamsize) { uint8 a,b,c,d; uint32 ret; if ( (tsp+3) > streamsize ) { return 0; } a = *tsp; b = *(tsp+1); c = *(tsp+2); d = *(tsp+3); ret = long_little_endian(a<<24 | b<<16 | c<<8 | d); return ret; } static uint16 read_16(uint8 *tsp, uint8* streamsize) { uint8 a,b; uint16 ret; if ( (tsp+1) > streamsize ) { return 0; } a = *tsp; b = *(tsp + 1); ret = little_endian(a<<8 | b); return ret; } static char *make_string(uint8 *tsp, int size) { static char s[256] = ""; int len = (size>sizeof(s)-1) ? sizeof(s)-1 : size; strncpy(s,tsp, len); s[len] = '\0'; return s; } static int handle_props(uint8 *tsp, uint8* streamsize) { int bytes = 0; uint32 num_props = 0; uint32 x = 0; num_props = read_32(tsp,streamsize); bytes += sizeof(num_props); while (x < num_props) { uint32 prop_tag; uint32 num; // char filename[256]; static int file_num = 0; prop_tag = read_32(tsp+bytes,streamsize); bytes += sizeof(prop_tag); switch (prop_tag & PROP_TYPE_MASK) { case PT_BINARY: num = read_32(tsp+bytes,streamsize); bytes += sizeof(num); num = read_32(tsp+bytes,streamsize); bytes += sizeof(num); if (prop_tag == PR_RTF_COMPRESSED) { /* sprintf (filename, "tnef_%d_%0lx.rtf", file_num, num); file_num++; if (SaveData) { printf ("\tSaving Compressed RTF to %s\n", filename); save_attach_data(filename, tsp+bytes, num); } else { printf ("\tContains Compressed RTF MAPI property\n"); } */ } /* num + PAD */ bytes += num + ((num % 4) ? (4 - num%4) : 0); break; case PT_STRING8: /* switch (prop_tag) { case PR_CONVERSATION_TOPIC: printf ("\tConversation Topic: "); break; case PR_SENDER_ADDRTYPE: printf ("\tSender Address Type: "); break; case PR_SENDER_EMAIL_ADDRESS: printf ("\tSender Email Address: "); break; case PR_RTF_SYNC_BODY_TAG: printf ("\tRTF Sync body tag: "); break; case PR_SUBJECT_PREFIX: printf ("\tSubject Prefix: "); break; default: printf ("\tUnknown String: "); break; }*/ num = read_32(tsp+bytes,streamsize); bytes += sizeof(num); num = read_32(tsp+bytes,streamsize); bytes += sizeof(num); // printf ("%s\n", make_string(tsp+bytes,num)); bytes += num + ((num % 4) ? (4 - num%4) : 0); break; case PT_UNICODE: case PT_OBJECT: break; case PT_I2: bytes += 2; break; case PT_LONG: bytes += 4; break; case PT_R4: bytes += 4; break; case PT_DOUBLE: bytes += 8; break; case PT_CURRENCY: case PT_APPTIME: case PT_ERROR: bytes += 4; break; case PT_BOOLEAN: bytes += 4; break; case PT_I8: bytes += 8; case PT_SYSTIME: bytes += 8; break; } x++; } return 0; } //__declspec(export) LIB_EXPORT int LibTNEF_SaveAttachmentData(struct LibTNEF_ClientData* data, char* szDestinationFilename) { FILE *out; out = fopen( ( szDestinationFilename == NULL ? data->szAttachmentName : szDestinationFilename ), "w"); if (out == NULL) { // fprintf(stderr, "Error openning file %s for writing\n", filename); return -1; } fwrite(data->lAttachmentStart, sizeof(uint8), data->lAttachmentSize, out); fclose(out); return 0; } /* int default_handler(uint32 attribute, uint8 *tsp, uint32 size) { uint16 type = ATT_TYPE(attribute); switch (type) { case atpTriples: break; case atpString: case atpText: printf("Attribute %s: ", attribute_string(attribute)); printf("%s\n",make_string(tsp,size)); break; case atpDate: printf("Attribute %s: ", attribute_string(attribute)); printf("%s\n",date_string(tsp)); break; case atpShort: break; case atpLong: break; case atpByte: break; case atpWord: break; case atpDword: break; default: printf("Attribute %s: ", attribute_string(attribute)); printf("Unknown type\n"); break; } return 0; } */ //__declspec(export) LIB_EXPORT int LibTNEF_Decode(const char* szFilename, struct LibTNEF_ClientData* data /* out */) { FILE *fp; struct stat sb; int dump = 0; if (data->STRUCTSIZE != sizeof(struct LibTNEF_ClientData)) return -1; /* invalid struct */ if (stat(szFilename,&sb) == -1) { return -10; } data->size = sb.st_size; data->tnef_stream = (uint8 *)malloc(data->size); if (data->tnef_stream == NULL) { return -12; } if ((fp = fopen(szFilename,"rb")) == NULL) { return -13; } fseek(fp,SEEK_SET,0); data->nread = fread(data->tnef_stream, sizeof(uint8), data->size, fp); if (data->nread < (data->size-1)) { return -14; } data->size = data->nread; fclose(fp); data->tsp = data->tnef_stream; if (TNEF_SIGNATURE == read_32(data->tsp,data->tnef_stream+data->size)) { // printf("Good TNEF Signature\n"); } else { // printf("Bad TNEF Signature, Expecting: %lx Got: %lx\n",TNEF_SIGNATURE, read_32(data->tsp,data->tnef_stream+data->size)); return -20; } data->tsp += sizeof(TNEF_SIGNATURE); read_16(data->tsp,data->tnef_stream+data->size); // printf("TNEF Attach Key: %x\n",); data->tsp += sizeof(uint16); return 0; } LIB_EXPORT int LibTNEF_Free(struct LibTNEF_ClientData* data /* in/out */) { if (data->tnef_stream != NULL) { free(data->tnef_stream); } data->STRUCTSIZE = NULL; /* invalidate */ data->tsp = NULL; data->size = NULL; data->nread = NULL; return 0; } LIB_EXPORT int LibTNEF_ReadNextAttribute(struct LibTNEF_ClientData* data /* in/out */) { int bytes = 0, header = 0; uint32 attribute; uint8 component = 0; uint32 size = 0; uint16 checksum = 0; int rc = 0; // uint8 *ptr; // static char attach_title[256] = "default.dat"; if ( ( (data->tsp) - (data->tnef_stream) ) < (data->size) ) { component = *data->tsp; bytes += sizeof(uint8); attribute = read_32(data->tsp+bytes,data->tnef_stream+data->size); bytes += sizeof(attribute); size = read_32(data->tsp+bytes,data->tnef_stream+data->size); bytes += sizeof(size); header = bytes; bytes += (int)size; checksum = read_16(data->tsp+bytes,data->tnef_stream+data->size); bytes += sizeof(checksum); if (component != LVL_MESSAGE) { // printf("\tSize:\t\t%d\n",size); } switch (attribute) { case attAttachTitle: strcpy(data->szAttachmentName, make_string((data->tsp)+header,size)); rc = LIBTNEF_TYPE_ATTACHMENTNAME; break; case attAttachData: /* if (SaveData) { if (!save_attach_data(attach_title, tsp+header,size)) printf("Attachment saved to file %s\n", attach_title); else printf("Failure saving attachment to file %s\n", attach_title); } else { printf("TNEF Contains attached file %s\n", attach_title); }*/ data->lAttachmentStart = data->tsp+header; data->lAttachmentSize = (long)size; rc = LIBTNEF_TYPE_ATTACHMENTDATA; break; case attMAPIProps: handle_props(data->tsp+header,data->tnef_stream+data->size); rc = LIBTNEF_TYPE_MAPIPROPERTIES; break; default: // default_handler(attribute, tsp+header, size); rc = LIBTNEF_TYPE_USEMAPITYPE; break; } data->tsp += bytes; return rc; } else { return LIBTNEF_TYPE_NOMOREPARTS; } }
[ [ [ 1, 366 ] ] ]
321bb8838cd57bfdf81ed7464bdf98e15e61ef01
ea6b169a24f3584978f159ec7f44184f9e84ead8
/include/reflect/Type.hpp
fe3490049ac1de7183fc9e7e46a277a5499c46b9
[]
no_license
sparecycles/reflect
e2051e5f91a7d72375dd7bfa2635cf1d285d8ef7
bec1b6e6521080ad4d932ee940073d054c8bf57f
refs/heads/master
2020-06-05T08:34:52.453196
2011-08-18T16:33:47
2011-08-18T16:33:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,295
hpp
#ifndef REFLECT_TYPE_HPP_ #define REFLECT_TYPE_HPP_ #include <reflect/Reflection.hpp> #include <reflect/Type.h> #include <new> // for placement new namespace reflect { // TODO: some of the template/static_assert stuff here is useful, move it somewhere nice template<bool, typename iftrue, typename iffalse> struct template_if; template<typename iftrue, typename iffalse> struct template_if<true, iftrue, iffalse> : public iftrue {}; template<typename iftrue, typename iffalse> struct template_if<false, iftrue, iffalse> : public iffalse {}; template<typename T> struct AlignOf { private: struct Align { T t; char pad; }; typedef struct AlignOf<Align> next; typedef struct { enum { Result = sizeof(Align) - sizeof(T) }; } done; public: enum { Result = template_if<(sizeof(Align) > sizeof(T)), done, next>::Result }; }; template<typename Check, typename Base> struct TypeDerives { enum { Result = TypeDerives<typename Check::BaseType, Base>::Result }; }; template<typename Base> struct TypeDerives<Base, Base> { enum { Result = true }; }; template<typename Base> struct TypeDerives<Dynamic, Base> { enum { Result = false }; }; #define unique_static_assert unique_static_assert_helper(__LINE__) #define unique_static_assert_helper(line) unique_static_assert_helper_(line) #define unique_static_assert_helper_(line) static_assert_##line #define static_assert(text, expr) namespace { inline void unique_static_assert(int text##_is_wrong[(expr) ? 1 : 0]) {} } // Class: Type::DescriptionHelper // // Template base class for description helpers, used in reflection definitions. // // Features: // Concrete - Requires a default constructor, public destructor. // makes the type non-abstract. // ConversionTo<TargetType>() - declares conversion to TargetType. // ConversionToEx<TargetType, Intermediate>() - conversion to TargetType through Intermediate // ConversionFrom<SourceType>() - declares conversion from TargetType. // // See Also: // - <Type> // - <Type::ConvertValue> // - <DEFINE_REFLECTION> template<typename T> class Type::DescriptionHelper { public: struct { void operator +() const { struct Operations { static void *Construct(void *data) { typedef typename Signature<T>::ClassType ClassTypeOfType; return ClassTypeOfType::OpaqueCast(new(static_cast<T *>(data)) T); } static void *Destruct(void *data) { T *pointer = translucent_cast<T *>(data); pointer->~T(); return static_cast<void *>(pointer); } }; TypeOf<T>()->SetBasicOperations( sizeof(T), AlignOf<T>::Result, &Operations::Construct, &Operations::Destruct); } } Basic; struct { void operator +() const { typedef Type::DescriptionHelper<T> TDHT; TDHT tdht; + tdht.Basic; + typename TDHT::template ConversionFrom<T>(); } } Concrete; template<typename Target> struct ConversionTo { void operator +() const { struct Operations { static void Convert(void *target, const void *source) { *translucent_cast<Target *>(target) = Target(*translucent_cast<const T *>(source)); } }; TypeOf<Target>()->RegisterConversion(TypeOf<T>(), &Operations::Convert); } }; template<typename Target, typename As> struct ConversionToEx { void operator +() const { struct Operations { static void Convert(void *target, const void *source) { Target &target_val = *translucent_cast<Target *>(target); const T &source_val = *translucent_cast<const T *>(source); target_val = As(source_val); } }; TypeOf<Target>()->RegisterConversion(TypeOf<T>(), &Operations::Convert); } }; template<typename Source> struct ConversionFrom { void operator +() const { struct Operations { static void Convert(void *target, const void *source) { T &target_val = *translucent_cast<T *>(target); const Source &source_val = *translucent_cast<const Source *>(source); target_val = T(source_val); } }; TypeOf<T>()->RegisterConversion(TypeOf<Source>(), &Operations::Convert); } }; DescriptionHelper() {} }; } #endif
[ [ [ 1, 162 ] ] ]
6792d153d9857da035fd2977a65daa140f51709c
cd0987589d3815de1dea8529a7705caac479e7e9
/webkit/WebKit2/UIProcess/WebContext.h
5454078460424861894e7f7ddc746b2d70343551
[]
no_license
azrul2202/WebKit-Smartphone
0aab1ff641d74f15c0623f00c56806dbc9b59fc1
023d6fe819445369134dee793b69de36748e71d7
refs/heads/master
2021-01-15T09:24:31.288774
2011-07-11T11:12:44
2011-07-11T11:12:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,252
h
/* * Copyright (C) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef WebContext_h #define WebContext_h #include "APIObject.h" #include "PluginInfoStore.h" #include "ProcessModel.h" #include "VisitedLinkProvider.h" #include "WebContextInjectedBundleClient.h" #include "WebHistoryClient.h" #include "WebProcessProxy.h" #include <WebCore/LinkHash.h> #include <wtf/Forward.h> #include <wtf/HashSet.h> #include <wtf/PassRefPtr.h> #include <wtf/RefPtr.h> #include <wtf/text/StringHash.h> #include <wtf/text/WTFString.h> struct WKContextStatistics; namespace WebKit { class WebPageNamespace; class WebPageProxy; class WebPreferences; class WebContext : public APIObject { public: static const Type APIType = TypeContext; static WebContext* sharedProcessContext(); static WebContext* sharedThreadContext(); static PassRefPtr<WebContext> create(const WTF::String& injectedBundlePath); ~WebContext(); void initializeInjectedBundleClient(const WKContextInjectedBundleClient*); void initializeHistoryClient(const WKContextHistoryClient*); ProcessModel processModel() const { return m_processModel; } WebProcessProxy* process() const { return m_process.get(); } void processDidFinishLaunching(WebProcessProxy*); WebPageProxy* createWebPage(WebPageNamespace*); void reviveIfNecessary(); WebPageNamespace* createPageNamespace(); void pageNamespaceWasDestroyed(WebPageNamespace*); void setPreferences(WebPreferences*); WebPreferences* preferences() const; void preferencesDidChange(); const WTF::String& injectedBundlePath() const { return m_injectedBundlePath; } void postMessageToInjectedBundle(const WTF::String&, APIObject*); // InjectedBundle client void didReceiveMessageFromInjectedBundle(const WTF::String&, APIObject*); // History client void didNavigateWithNavigationData(WebFrameProxy*, const WebNavigationDataStore&); void didPerformClientRedirect(WebFrameProxy*, const WTF::String& sourceURLString, const WTF::String& destinationURLString); void didPerformServerRedirect(WebFrameProxy*, const WTF::String& sourceURLString, const WTF::String& destinationURLString); void didUpdateHistoryTitle(WebFrameProxy*, const WTF::String& title, const WTF::String& url); void populateVisitedLinks(); void getStatistics(WKContextStatistics* statistics); void setAdditionalPluginsDirectory(const WTF::String&); PluginInfoStore* pluginInfoStore() { return &m_pluginInfoStore; } WTF::String applicationCacheDirectory(); void registerURLSchemeAsEmptyDocument(const WTF::String&); void addVisitedLink(const WTF::String&); void addVisitedLink(WebCore::LinkHash); void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::ArgumentDecoder*); #if PLATFORM(WIN) void setShouldPaintNativeControls(bool); #endif private: WebContext(ProcessModel, const WTF::String& injectedBundlePath); virtual Type type() const { return APIType; } void ensureWebProcess(); bool hasValidProcess() const { return m_process && m_process->isValid(); } void platformSetUpWebProcess(); ProcessModel m_processModel; // FIXME: In the future, this should be one or more WebProcessProxies. RefPtr<WebProcessProxy> m_process; HashSet<WebPageNamespace*> m_pageNamespaces; RefPtr<WebPreferences> m_preferences; WTF::String m_injectedBundlePath; WebContextInjectedBundleClient m_injectedBundleClient; WebHistoryClient m_historyClient; PluginInfoStore m_pluginInfoStore; VisitedLinkProvider m_visitedLinkProvider; HashSet<WTF::String> m_schemesToRegisterAsEmptyDocument; #if PLATFORM(WIN) bool m_shouldPaintNativeControls; #endif }; } // namespace WebKit #endif // WebContext_h
[ [ [ 1, 147 ] ] ]
cc0cf321f2d9c68b4df991bd8d08de94dc67fa3a
647ea631d7a2cffa875a936a5bfbe8c8af5f906b
/PerfChart.cpp
471341bd7ed5be0db9c492ffa18851b2a3fcfdf1
[]
no_license
meloscheng/perfchart
2fc931bb185b6c4d74eebf2c0fcf4d9b72e16fb3
cd78d277d46215f3016f9d232d2d82197677ff36
refs/heads/master
2016-09-05T19:47:06.129326
2010-02-09T16:57:36
2010-02-09T16:57:36
40,610,246
0
0
null
2015-08-12T16:16:14
2015-08-12T16:01:22
C++
UTF-8
C++
false
false
7,157
cpp
#include "StdAfx.h" #include "PerfChart.h" #include "gditest.h" #include <vector> // CPerfChart() - basic constructor // // hParentDlg - handle to parent dialog holding the control // hControlID - handle to owner drawn control used for chart CPerfChart::CPerfChart(HWND hParentDlg, HWND hControlID) { m_hParentDlg = hParentDlg; m_hControlID = hControlID; m_xAxisPosition = 0; // Default chart parameters that mimick Task Manager m_nScrollIncrement = 2; m_bInMemory = TRUE; m_nGridDimension = 12; m_crGridlinePenColor = RGB(0, 128, 64); m_crChartPenColor = RGB(0, 255, 0); m_nGridlinePenSize = 1; m_nChartPenSize = 1; } // CPerfChart() - custom constructor // // hParentDlg - handle to parent dialog holding the control // hControlID - handle to owner drawn control used for chart // gridDimension - number of device units each grid should be in height and width // gridlinePenSize - width of the pen used to draw the grid lines // gridlinePenColor - color value for pen used to draw the grid lines, built with RGB() macro // chartPenSize - width of the pen used to draw the data chart // chartPenColor - color value for the pen used to draw the data chart, built with RGB() macro CPerfChart::CPerfChart(HWND hParentDlg, HWND hControlID, unsigned int gridDimension, unsigned int scrollIncrement, unsigned int gridlinePenSize, COLORREF gridlinePenColor, unsigned int chartPenSize, COLORREF chartPenColor, BOOL bInMemory) { m_hParentDlg = hParentDlg; m_hControlID = hControlID; m_xAxisPosition = 0; // Custom chart parameters m_nScrollIncrement = scrollIncrement; m_bInMemory = bInMemory; m_nGridDimension = gridDimension; m_crGridlinePenColor = gridlinePenColor; m_crChartPenColor = chartPenColor; m_nGridlinePenSize = gridlinePenSize; m_nChartPenSize = chartPenSize; } CPerfChart::~CPerfChart(void) { } // DrawGrid - Draw a Windows Task Manager "CPU Usage History"-style side-scrolling graph with gridlines // // bPaint - when true, invalidate the chart rectangle and have it redrawn // BOOL CPerfChart::DrawGrid(BOOL bPaint) { HPEN hGridlinePen; // Extraneous since the client area is typically reported with a (0, 0) origin int verticalHeight = m_DIS.rcItem.bottom - m_DIS.rcItem.top; int horizontalWidth = m_DIS.rcItem.right - m_DIS.rcItem.left; int numberOfVerticalGridlines = horizontalWidth / m_nGridDimension; int numberOfHorizontalGridlines = verticalHeight / m_nGridDimension; // Set the number of data points to be charted m_nPoints = horizontalWidth / m_nScrollIncrement; //int nSavedDC = SaveDC(m_DIS.hDC); // If BitBlt() usage is toggled then perform preliminary steps if ( m_bInMemory ) { m_hDCMem = CreateCompatibleDC( m_DIS.hDC ); m_hBMStore = CreateCompatibleBitmap( m_DIS.hDC, horizontalWidth, verticalHeight ); m_hBM = (HBITMAP)SelectObject( m_hDCMem, m_hBMStore ); } else { m_hDCMem = m_DIS.hDC; } FillRect( m_hDCMem, &m_DIS.rcItem, (HBRUSH)GetStockObject(BLACK_BRUSH) ); SetBkMode( m_hDCMem, TRANSPARENT); // Select the pen to use for the grid lines hGridlinePen = CreatePen( PS_SOLID, m_nGridlinePenSize, m_crGridlinePenColor ); SelectObject( m_hDCMem, hGridlinePen ); if (m_xAxisPosition != 0) numberOfVerticalGridlines++; // Reminder: In the GDI API the origin (0,0) is in the upper left corner and the y-axis grows descendant // Draw the vertical grid lines for(int i = 0, currentPosition = (0 - m_xAxisPosition); i < numberOfVerticalGridlines; i++) { // TODO: Catch a negative result here currentPosition += m_nGridDimension; MoveToEx( m_hDCMem, currentPosition, verticalHeight, NULL ); LineTo( m_hDCMem, currentPosition, 0 ); } // Draw the horizontal grid lines for(int i = 0, currentPosition = 0; i < numberOfHorizontalGridlines; i++) { currentPosition += m_nGridDimension; MoveToEx( m_hDCMem, horizontalWidth, currentPosition, NULL ); LineTo( m_hDCMem, 0, currentPosition ); } DeleteObject( hGridlinePen ); DrawChart( ); //RestoreDC(m_DIS.hDC, nSavedDC); // Generally, if called from a WM_DRAWITEM message do not repaint the rectangle, if called from a WM_APP // message then do repaint the rectangle if ( bPaint ) this->Paint(); return TRUE; } // Draws the actual chart by building a POINT array from the deque and calling Polyline() BOOL CPerfChart::DrawChart() { POINT *pChart = NULL; POINT *pIter = NULL; int xAxis = m_DIS.rcItem.right; pChart = new POINT[ m_dequeDataPoints.size() ]; pIter = pChart; double factor = static_cast<double>( m_DIS.rcItem.bottom / 100.0 ); std::deque<long>::reverse_iterator ril; for(ril=m_dequeDataPoints.rbegin(); ril!=m_dequeDataPoints.rend(); ril++) { pIter->x = xAxis; pIter->y = static_cast<long>( factor * (100 - *ril) ); pIter++; // TODO: Check for underflow of xAxis xAxis -= m_nScrollIncrement; } HPEN hChartPen = CreatePen( PS_SOLID, m_nChartPenSize, m_crChartPenColor ); SelectObject( m_hDCMem, hChartPen ); Polyline( m_hDCMem, pChart, m_dequeDataPoints.size() ); DeleteObject(hChartPen); delete [] pChart; if ( m_bInMemory ) { BitBlt(m_DIS.hDC, m_DIS.rcItem.left, m_DIS.rcItem.top, m_DIS.rcItem.right-m_DIS.rcItem.left, m_DIS.rcItem.bottom-m_DIS.rcItem.top, m_hDCMem, 0, 0, SRCCOPY); SelectObject(m_hDCMem, m_hBMStore); DeleteObject(m_hBM); DeleteObject(m_hBMStore); DeleteDC(m_hDCMem); } return TRUE; } // See http://msdn.microsoft.com/en-us/library/bb775802%28VS.85%29.aspx void CPerfChart::CopyDrawItemStruct(LPDRAWITEMSTRUCT lpDIS) { // Control ID from the resource file, e.g. IDC_BUTTON1 m_DIS.CtlID = lpDIS->CtlID; // Control type defined in resource file, should be ODT_BUTTON for this class m_DIS.CtlType = lpDIS->CtlType; // Device context handle for drawing region m_DIS.hDC = lpDIS->hDC; // Control handle for the button m_DIS.hwndItem = lpDIS->hwndItem; m_DIS.itemAction = lpDIS->itemAction; m_DIS.itemData = lpDIS->itemData; m_DIS.itemID = lpDIS->itemID; m_DIS.itemState = lpDIS->itemState; // Control rectangle dimensions m_DIS.rcItem = lpDIS->rcItem; return; } // Invalidates the rectangle that was updated and forces a WM_PAINT BOOL CPerfChart::Paint() { InvalidateRect( m_hControlID, &m_DIS.rcItem, FALSE ); UpdateWindow( m_hControlID ); return TRUE; } BOOL CPerfChart::AddDataPoint(unsigned int nPercentage) { if ( nPercentage > 100 ) return FALSE; unsigned long nDataPoints = static_cast<unsigned long>( m_dequeDataPoints.size() ); // Automatically grow and shrink the deque to fit the present chart dimensions if ( nDataPoints >= m_nPoints ) { for (int i = nDataPoints - m_nPoints; i != 0; i--) { m_dequeDataPoints.pop_front(); } } m_dequeDataPoints.push_back( nPercentage ); ScrollIncrement( ); DrawGrid( TRUE ); return TRUE; } BOOL CPerfChart::ScrollIncrement() { m_xAxisPosition += m_nScrollIncrement; if ( m_xAxisPosition >= m_nGridDimension ) m_xAxisPosition = 0; return TRUE; }
[ [ [ 1, 230 ] ] ]
fea3c9cb07886385bed1759aaf9e869080659057
6a2f859a41525c5512f9bf650db68bcd7d95748d
/TP2/ex2/R0/src/exceptions.cpp
e6fe9d2a8f4d59b35af0a80780fd8da31ecbb473
[]
no_license
Bengrunt/mif12-2009
21df06941a6a1e844372eb01f4911b1ef232b306
d4f02f1aab82065c8184facf859fe80233bc46b5
refs/heads/master
2021-01-23T13:48:47.238211
2009-12-04T22:52:25
2009-12-04T22:52:25
32,153,296
0
0
null
null
null
null
UTF-8
C++
false
false
362
cpp
#include "exceptions.hpp" const char* UnknownBasicTypeException::what() const throw() { return "Probleme : Type de base inconnu !"; } const char* NullPointerException::what() const throw() { return "Probleme : pointeur NULL rencontré !"; } const char* AllocationException::what() const throw() { return "Probleme rencontre lors de l'allocation !"; }
[ [ [ 1, 13 ] ] ]
33719a680d440ff996f3e43d2fb362fd1c661a99
8fc069ea952e8e1d6110104e48acce82545e58c1
/pokedex.cpp
23d99596a6ba7255c55848d6a149e17299d36f74
[]
no_license
RemiGuillard/poketroll
310673b644d7c28bc8156fda0c81b51cb6aa7b72
13ea6f1cda244dbe7acb133b92866757e6815d0d
refs/heads/master
2021-01-13T02:16:38.795527
2011-10-09T11:15:13
2011-10-09T11:15:13
32,143,539
0
0
null
null
null
null
UTF-8
C++
false
false
10,334
cpp
#include <iostream> #include <QMessageBox> #include "pokedex.h" #include "Evolution.h" #include "Stats.h" #include "Attack.h" Pokedex::Pokedex(QWidget *parent, Qt::WFlags flags) : QMainWindow(parent, flags) { ui.setupUi(this); getPokemonFile("pokedata.xml"); QObject::connect(ui.pokeList, SIGNAL(itemClicked(QListWidgetItem *)), this, SLOT(PokemonClicked(QListWidgetItem *))); QObject::connect(ui.pokeList, SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)), this, SLOT(PokemonClicked(QListWidgetItem *))); QObject::connect(ui.listEvo, SIGNAL(itemClicked(QListWidgetItem *)), this, SLOT(PokemonClicked(QListWidgetItem *))); //QObject::connect(ui.listEvo, SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)), this, SLOT(PokemonClicked(QListWidgetItem *))); QObject::connect(ui.searchButton, SIGNAL(clicked()), this, SLOT(SearchPokemon())); QObject::connect(ui.searchLine, SIGNAL(returnPressed()), this, SLOT(SearchPokemon())); //ui.pokeList->currentItem(); } Pokedex::~Pokedex() {} int Pokedex::findIdWithName(QString name) { QMapIterator<int, Pokemon *> it(this->_pokeList); while (it.hasNext()) { it.next(); if (it.value()->getName() == name) return it.value()->getId(); } return 1; } void Pokedex::PokemonClicked(QListWidgetItem *item) { /*QString tmp = item->text().toUpper(); int pos = tmp.indexOf(" ", 0); QString test(0); QMessageBox::information(this, "lol", test.setNum(pos)/*item->text());*/ pokemonDisplay(_pokeList.value(findIdWithName(item->text().toUpper()))); } void Pokedex::SearchPokemon() { //QMessageBox::information(this, "lol", ui.searchLine->displayText()); pokemonDisplay(_pokeList.value(findIdWithName(ui.searchLine->displayText().toUpper()))); } QMap<int, Pokemon *> Pokedex::getPokeList() const {return _pokeList;} void Pokedex::pokemonNameListDisplay() { QMapIterator<int, Pokemon *> it(this->_pokeList); Pokemon *poke; QString tmp; QString num(0); while (it.hasNext()) { poke = *it.next(); tmp = /*num.setNum(poke->getId()) + " " + */poke->getName(); ui.pokeList->addItem(tmp); } } void Pokedex::pokemonDisplay(const Pokemon *poke) { //QMessageBox::information(this, "lol", path); QString id(0); QString path = "Pictures/" + id.setNum(poke->getId()) + ".png"; ui.labelImg->setPixmap(QPixmap(path)); ui.labelImg->setScaledContents(true); ui.descr->setText(poke->getDescription()); ui.labelName->setText(poke->getName()); ui.textStats->setText("HP\t= " + poke->getStats().getHp()); ui.textStats->append("ATK\t= " + poke->getStats().getAtk()); ui.textStats->append("DEF\t= " + poke->getStats().getDef()); ui.textStats->append("SPD\t= " + poke->getStats().getSpd()); ui.textStats->append("SAT\t= " + poke->getStats().getSat()); ui.textStats->append("SDF\t= " + poke->getStats().getSdf()); QString tmp(0); ui.textStats->append("Height\t= " + tmp.setNum(poke->getHeight())); ui.textStats->append("Weight\t= " + tmp.setNum(poke->getWeight())); ui.textStats->append("Ratio\t= " + tmp.setNum(poke->getRatio())); writeType(poke->getTypes()); writeEgg(poke->getTypes()); ui.textStats->append("Ability\t= " + poke->getAbility()); ui.textStats->append("Exp\t= " + tmp.setNum(poke->getExp())); ui.textStats->append("Species\t= " + poke->getSpecies()); writeEvolutionList(poke->getEvolve()); writeAtkList(poke->getAttacks()); } void Pokedex::writeEgg(const QList<QString> &egglist) { QListIterator<QString> it(egglist); QString tmp = ""; while (it.hasNext()) { tmp += it.next(); } ui.textStats->append("Egg-Group\t= " + tmp); } void Pokedex::writeType(const QList<QString> &typelist) { QListIterator<QString> it(typelist); QString tmp = ""; while (it.hasNext()) { tmp += it.next(); } ui.textStats->append("type\t= " + tmp); } void Pokedex::writeEvolutionList(const QList<Evolution *> &evolist) { QListIterator<Evolution *> it(evolist); ui.listEvo->clear(); Evolution *evo; QString tmp; while (it.hasNext()) { evo = it.next(); tmp = evo->getName()/* + "\tlevel : " + evo->getRequire()*/; ui.listEvo->addItem(tmp); } } void Pokedex::writeAtkList(const QList<Attack *> &atklist) { QListIterator<Attack *> it(atklist); ui.listAttack->clear(); Attack *tmp; QString info; while (it.hasNext()) { tmp = it.next(); info = tmp->getName().toUpper(); if (tmp->getLvl() != "") info += "\tlevel : " + tmp->getLvl(); info += "\ttype : " + tmp->getType(); if (tmp->getMachine() != "") info += "\tmachine : " + tmp->getMachine(); ui.listAttack->addItem(info); } } void Pokedex::getPokemonFile(const QString &path) { QDomDocument myXml(path); QFile file(path); file.open(QFile::ReadOnly | QFile::Text); QDomDocument doc; doc.setContent(&file, false); QDomElement racine = doc.documentElement(); racine = racine.firstChildElement(); while (!racine.isNull()) { Pokemon *poke = new Pokemon(); if (racine.tagName() == "pokemon") { poke->setId(racine.attribute("id").toInt()); QDomElement Elem = racine.firstChildElement(); this->readName(Elem, poke); this->readTypes(Elem, poke); this->readAbility(Elem, poke); this->readExp(Elem, poke); this->readStats(Elem, poke); this->readEvolution(Elem, poke); this->readRatio(Elem, poke); this->readEgg(Elem, poke); this->readSpecies(Elem, poke); this->readHeight(Elem, poke); this->readWeight(Elem, poke); this->readDescription(Elem, poke); this->readAttack(Elem, poke); } this->_pokeList[poke->getId()] = poke; racine = racine.nextSiblingElement(); } //ui.pokeList->addItem(Elem.text()); } void Pokedex::readAttack(QDomElement &Elem, Pokemon *poke) { if (Elem.tagName() == "moves") { QDomElement node = Elem.firstChildElement(); QList<Attack *> atkList; atkList.clear(); while (!node.isNull()) { Attack *atk = new Attack; atk->setType(node.attribute("type")); QDomElement ssNode = node.firstChildElement(); QString mach = ""; while (!ssNode.isNull()) { if (ssNode.tagName() == "name") atk->setName(ssNode.text()); else if (ssNode.tagName() == "lvl") atk->setLvl(ssNode.text()); else if (ssNode.tagName() == "machine") mach = ssNode.text(); ssNode = ssNode.nextSiblingElement(); } atk->setMachine(mach); atkList.push_back(atk); node = node.nextSiblingElement(); } poke->setAttacks(atkList); } } void Pokedex::readDescription(QDomElement &Elem, Pokemon *poke) { if (Elem.tagName() == "description") { poke->setDescription(Elem.text()); Elem = Elem.nextSiblingElement(); } } void Pokedex::readWeight(QDomElement &Elem, Pokemon *poke) { if (Elem.tagName() == "weight") { poke->setWeight(Elem.text().toFloat()); Elem = Elem.nextSiblingElement(); } } void Pokedex::readHeight(QDomElement &Elem, Pokemon *poke) { if (Elem.tagName() == "height") { poke->setHeight(Elem.text().toFloat()); Elem = Elem.nextSiblingElement(); } } void Pokedex::readSpecies(QDomElement &Elem, Pokemon *poke) { if (Elem.tagName() == "species") { poke->setSpecies(Elem.text()); Elem = Elem.nextSiblingElement(); } } void Pokedex::readEgg(QDomElement &Elem, Pokemon *poke) { QList<QString> egg; egg.clear(); while (Elem.tagName() == "egg-group") { egg.push_back(Elem.text()); Elem = Elem.nextSiblingElement(); } poke->setEggGroup(egg); } void Pokedex::readRatio(QDomElement &Elem, Pokemon *poke) { if (Elem.tagName() == "ratio") { QDomElement node = Elem.firstChildElement(); if (node.tagName() == "male") poke->setRatio(node.text().toFloat()); else if (node.tagName() == "female") poke->setRatio(100 - node.text().toFloat()); Elem = Elem.nextSiblingElement(); } else poke->setRatio(0); } void Pokedex::readEvolution(QDomElement &Elem, Pokemon *poke) { if (Elem.tagName() == "evolutions") { QList<Evolution *> evoList; evoList.clear(); QDomElement node = Elem.firstChildElement(); while (node.tagName() == "evolution") { QDomElement ssNode = node.firstChildElement(); Evolution *evo = new Evolution; evo->setId(node.attribute("id").toInt()); QString require = "1"; while (!ssNode.isNull()) { if (ssNode.tagName() == "name") evo->setName(ssNode.text()); else if (ssNode.tagName() == "lvl" || ssNode.tagName() == "condition") require = ssNode.text(); ssNode = ssNode.nextSiblingElement(); } evo->setRequire(require); evoList.push_back(evo); node = node.nextSiblingElement(); } Elem = Elem.nextSiblingElement(); poke->setEvolve(evoList); } } void Pokedex::readName(QDomElement &Elem, Pokemon *poke) { if (Elem.tagName() == "name") { poke->setName(Elem.text()); Elem = Elem.nextSiblingElement(); } } void Pokedex::readTypes(QDomElement &Elem, Pokemon *poke) { QList<QString> type; type.clear(); while (Elem.tagName() == "type" && !Elem.isNull()) { type.push_back(Elem.text()); Elem = Elem.nextSiblingElement(); } poke->setTypes(type); } void Pokedex::readAbility(QDomElement &Elem, Pokemon *poke) { if (Elem.tagName() == "ability") { poke->setAbility(Elem.text()); Elem = Elem.nextSiblingElement(); } } void Pokedex::readExp(QDomElement &Elem, Pokemon *poke) { bool ok; if (Elem.tagName() == "exp") { poke->setExp(Elem.text().toInt(&ok, 10)); Elem = Elem.nextSiblingElement(); } } void Pokedex::readStats(QDomElement &Elem, Pokemon *poke) { if (Elem.tagName() == "stats") { Stats Statu; QDomElement node = Elem.firstChildElement(); while (!node.isNull()) { Statu.setHp(node.text()); node = node.nextSiblingElement(); Statu.setAtk(node.text()); node = node.nextSiblingElement(); Statu.setDef(node.text()); node = node.nextSiblingElement(); Statu.setSpd(node.text()); node = node.nextSiblingElement(); Statu.setSat(node.text()); node = node.nextSiblingElement(); Statu.setSdf(node.text()); node = node.nextSiblingElement(); } poke->setStats(Statu); Elem = Elem.nextSiblingElement(); } }
[ "lolokun@f8136148-a51c-7980-e803-3b4f71785a99" ]
[ [ [ 1, 382 ] ] ]
c6d9f74189d5b78038d64a24f42c796a1a91222c
c5ecda551cefa7aaa54b787850b55a2d8fd12387
/src/WorkLayer/ClientVersionInfo.h
9085736e12f6cce6062d10485b8a8c660b22d054
[]
no_license
firespeed79/easymule
b2520bfc44977c4e0643064bbc7211c0ce30cf66
3f890fa7ed2526c782cfcfabb5aac08c1e70e033
refs/heads/master
2021-05-28T20:52:15.983758
2007-12-05T09:41:56
2007-12-05T09:41:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,808
h
//this file is part of eMule //Copyright (C)2002-2006 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net ) // //This program is free software; you can redistribute it and/or //modify it under the terms of the GNU General Public License //as published by the Free Software Foundation; either //version 2 of the License, or (at your option) any later version. // //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // //You should have received a copy of the GNU General Public License //along with this program; if not, write to the Free Software #pragma once //#include "emule.h" #include "updownclient.h" // class to convert peercache Client versions to comparable values. #define CVI_IGNORED -1 // == means same client type, same or ignored version (for example eMule/0.4.* == eMule/0.4.2 ) // != means different client or different defined version (for example eMule/0.4.2 != SomeClient/0.4.2 ) // > mean _same client type_ and higher version, which therefor cannot be completely undefined ( for example eMule/1.* > eMule/0.4.2 ) // >= same as > but here the version can be undefined ( for example eMule/* >= eMule/0.4.2 ) class CClientVersionInfo{ public: CClientVersionInfo(CString strPCEncodedVersion) { m_nVerMajor = (UINT)CVI_IGNORED; m_nVerMinor = (UINT)CVI_IGNORED; m_nVerUpdate = (UINT)CVI_IGNORED; m_nVerBuild = (UINT)CVI_IGNORED; m_ClientTypeMajor = SO_UNKNOWN; m_ClientTypeMinor = SO_UNKNOWN; int posSeperator = strPCEncodedVersion.Find('/',1); if (posSeperator == (-1) || strPCEncodedVersion.GetLength() - posSeperator < 2){ // Comment UI //theApp.QueueDebugLogLine( false, _T("PeerCache Error: Bad Version info in PeerCache Descriptor found: %s"), strPCEncodedVersion); return; } CString strClientType = strPCEncodedVersion.Left(posSeperator).Trim(); CString strVersionNumber = strPCEncodedVersion.Mid(posSeperator+1).Trim(); if (strClientType.CompareNoCase(_T("eMule")) == 0) m_ClientTypeMajor = SO_EMULE; else if (strClientType.CompareNoCase(_T("eDonkey")) == 0) m_ClientTypeMajor = SO_EDONKEYHYBRID; // can add more types here else{ // Comment UI //theApp.QueueDebugLogLine(false, _T("PeerCache Warning: Unknown Clienttype in descriptor file found")); m_ClientTypeMajor = SO_UNKNOWN; } int curPos2= 0; CString strNumber = strVersionNumber.Tokenize(_T("."),curPos2); if (strNumber.IsEmpty()) return; else if (strNumber == _T("*")) m_nVerMajor = (UINT)-1; else m_nVerMajor = _tstoi(strNumber); strNumber = strVersionNumber.Tokenize(_T("."),curPos2); if (strNumber.IsEmpty()) return; else if (strNumber == _T("*")) m_nVerMinor = (UINT)-1; else m_nVerMinor = _tstoi(strNumber); strNumber = strVersionNumber.Tokenize(_T("."),curPos2); if (strNumber.IsEmpty()) return; else if (strNumber == _T("*")) m_nVerUpdate = (UINT)-1; else m_nVerUpdate = _tstoi(strNumber); strNumber = strVersionNumber.Tokenize(_T("."),curPos2); if (strNumber.IsEmpty()) return; else if (strNumber == _T("*")) m_nVerBuild = (UINT)-1; else m_nVerBuild = _tstoi(strNumber); } CClientVersionInfo(uint32 dwTagVersionInfo, UINT nClientMajor) { UINT nClientMajVersion = (dwTagVersionInfo >> 17) & 0x7f; UINT nClientMinVersion = (dwTagVersionInfo>> 10) & 0x7f; UINT nClientUpVersion = (dwTagVersionInfo >> 7) & 0x07; CClientVersionInfo(nClientMajVersion, nClientMinVersion, nClientUpVersion, (UINT)CVI_IGNORED, nClientMajor, SO_UNKNOWN); } CClientVersionInfo(uint32 nVerMajor, uint32 nVerMinor, uint32 nVerUpdate, uint32 nVerBuild, uint32 ClientTypeMajor, uint32 ClientTypeMinor = SO_UNKNOWN) { m_nVerMajor = nVerMajor; m_nVerMinor = nVerMinor; m_nVerUpdate = nVerUpdate; m_nVerBuild = nVerBuild; m_ClientTypeMajor = ClientTypeMajor; m_ClientTypeMinor = ClientTypeMinor; } CClientVersionInfo(){ CClientVersionInfo((UINT)CVI_IGNORED, (UINT)CVI_IGNORED, (UINT)CVI_IGNORED, (UINT)CVI_IGNORED, SO_UNKNOWN, SO_UNKNOWN); } CClientVersionInfo(const CClientVersionInfo& cv) {*this = cv;} CClientVersionInfo& operator=(const CClientVersionInfo& cv) { m_nVerMajor = cv.m_nVerMajor; m_nVerMinor = cv.m_nVerMinor; m_nVerUpdate = cv.m_nVerUpdate; m_nVerBuild = cv.m_nVerBuild; m_ClientTypeMajor = cv.m_ClientTypeMajor; m_ClientTypeMinor = cv.m_ClientTypeMinor; return *this; } friend bool operator==(const CClientVersionInfo& c1, const CClientVersionInfo& c2) { return ( (c1.m_nVerMajor == (-1) || c2.m_nVerMajor == (-1) || c1.m_nVerMajor == c2.m_nVerMajor) && (c1.m_nVerMinor == (-1) || c2.m_nVerMinor == (-1) || c1.m_nVerMinor == c2.m_nVerMinor) && (c1.m_nVerUpdate == (-1) || c2.m_nVerUpdate == (-1) || c1.m_nVerUpdate == c2.m_nVerUpdate) && (c1.m_nVerBuild == (-1) || c2.m_nVerBuild == (-1) || c1.m_nVerBuild == c2.m_nVerBuild) && (c1.m_ClientTypeMajor == (-1) || c2.m_ClientTypeMajor == (-1) || c1.m_ClientTypeMajor == c2.m_ClientTypeMajor) && (c1.m_ClientTypeMinor == (-1) || c2.m_ClientTypeMinor == (-1) || c1.m_ClientTypeMinor == c2.m_ClientTypeMinor) ); } friend bool operator !=(const CClientVersionInfo& c1, const CClientVersionInfo& c2) { return !(c1 == c2); } friend bool operator >(const CClientVersionInfo& c1, const CClientVersionInfo& c2) { if ( (c1.m_ClientTypeMajor == (-1) || c2.m_ClientTypeMajor == (-1) || c1.m_ClientTypeMajor != c2.m_ClientTypeMajor) || (c1.m_ClientTypeMinor != c2.m_ClientTypeMinor)) return false; if (c1.m_nVerMajor != (-1) && c2.m_nVerMajor != (-1) && c1.m_nVerMajor > c2.m_nVerMajor) return true; if (c1.m_nVerMinor != (-1) && c2.m_nVerMinor != (-1) && c1.m_nVerMinor > c2.m_nVerMinor) return true; if (c1.m_nVerUpdate != (-1) && c2.m_nVerUpdate != (-1) && c1.m_nVerUpdate > c2.m_nVerUpdate) return true; if (c1.m_nVerBuild != (-1) && c2.m_nVerBuild != (-1) && c1.m_nVerBuild > c2.m_nVerBuild) return true; return false; } friend bool operator <(const CClientVersionInfo& c1, const CClientVersionInfo& c2) { return c2 > c1; } friend bool operator <=(const CClientVersionInfo& c1, const CClientVersionInfo& c2) { return c2 > c1 || c1 == c2; } friend bool operator >=(const CClientVersionInfo& c1, const CClientVersionInfo& c2) { return c1 > c2 || c1 == c2; } UINT m_nVerMajor; UINT m_nVerMinor; UINT m_nVerUpdate; UINT m_nVerBuild; UINT m_ClientTypeMajor; UINT m_ClientTypeMinor; //unused atm };
[ "LanceFong@4a627187-453b-0410-a94d-992500ef832d" ]
[ [ [ 1, 179 ] ] ]
dcff0530359ad77552bc90c52b4b2b3c1e496c8c
0626a2ea2d9efaf12702ed1ec8683c7d9c4afe7d
/extern/sfm_rbac_lankton/src/sfm_local_chanvese_mex.cpp
d94b2e76312f5a5e238cd0362b19c2b48ceb3495
[]
no_license
zhenfeng/ktrack
4a4435d159ea8b83bd43f16dc4e6cad89c771981
86e93b11a73399e34da65de47a0da13f34f88659
refs/heads/master
2021-01-19T08:20:17.621964
2011-05-30T04:52:04
2011-05-30T04:52:04
1,820,013
0
0
null
null
null
null
UTF-8
C++
false
false
10,134
cpp
/********************************************************************* * sfm_local_chanvese_mex.cpp * * This file performs the statistical computations needed for running * the localized chan-vese active contour segmentation energy using the * Sparse Field method presented by Whitaker. * * written by: Shawn Lankton (4/17/2009) - www.shawnlankton.com * ********************************************************************/ #include "sfm_local_chanvese_mex.h" #include <iostream> #include <fstream> using std::endl; using std::cout; using std::string; //[phi C L] = ls_sparse(img,mask,iterations,display,lam,rad,dthresh); void lrbac_vessel_yz(double *img, double *phi, double *label, long *dims, LL *Lz, LL *Ln1, LL *Lp1, LL *Ln2, LL *Lp2, LL *Lin2out, LL *Lout2in, int iter, double rad, double lambda, double dthresh, short *plhs, int display){ double *F; double scale[1]; scale[0]=0; //int countdown; //initialize datastructures and statistics en_lrbac_init(Lz,img,phi,dims,rad); for(int i=0;i<iter;i++){ //compute force F = en_lrbac_vessel_yz_compute(Lz,phi,img,dims, scale,lambda,rad,dthresh); //perform iteration ls_iteration(F,phi,label,dims,Lz,Ln1,Lp1,Ln2,Lp2,Lin2out,Lout2in); //update statistics en_lrbac_vessel_yz_update(img, dims, Lin2out, Lout2in, rad,dthresh); } //destroy old datastructures en_lrbac_destroy(); } void lrbac_vessel_cv(double *img, double *phi, double *label, long *dims, LL *Lz, LL *Ln1, LL *Lp1, LL *Ln2, LL *Lp2, LL *Lin2out, LL *Lout2in, int iter, double rad, double lambda, double dthresh, short *plhs, int display){ double *F; double scale[1]; scale[0]=0; //int countdown; //initialize datastructures and statistics en_lrbac_init(Lz,img,phi,dims,rad); for(int i=0;i<iter;i++){ //compute force F = en_lrbac_vessel_cv_compute(Lz,phi,img,dims, scale,lambda,rad,dthresh); //perform iteration ls_iteration(F,phi,label,dims,Lz,Ln1,Lp1,Ln2,Lp2,Lin2out,Lout2in); //update statistics en_lrbac_vessel_cv_update(img, dims, Lin2out, Lout2in, rad,dthresh); //display stuff (maybe) // if(display) show_countdown(iter,i,&countdown,plhs); } //destroy old datastructures en_lrbac_destroy(); } void lrbac_chanvese(double *img, double *phi, double *label, long *dims, LL *Lz, LL *Ln1, LL *Lp1, LL *Ln2, LL *Lp2, LL *Lin2out, LL *Lout2in, int iter, double rad, double lambda, short *plhs,int display){ double *F; double scale[1]; scale[0]=0; //int countdown; //initialize datastructures and statistics en_lrbac_init(Lz,img,phi,dims,rad); //double Fmax; for(int i=0;i<iter;i++){ //compute force F = en_lrbac_compute(Lz,phi,img,dims, scale,lambda,rad); //perform iteration ls_iteration(F,phi,label,dims,Lz,Ln1,Lp1,Ln2,Lp2,Lin2out,Lout2in); //update statistics en_lrbac_update(img, dims, Lin2out, Lout2in, rad); //display stuff (maybe) } if( display > 0 ) std::cout << "done sfls iters: " << iter << endl; //destroy old datastructures en_lrbac_destroy(); } void chanvese(double *img, double *phi, double *label, long *dims, LL *Lz, LL *Ln1, LL *Lp1, LL *Ln2, LL *Lp2, LL *Lin2out, LL *Lout2in, int iter,double lambda, short *plhs,int display){ double *F; double scale[1]; scale[0] = 0; //int countdown; //initialize datastructures and statistics en_chanvese_init(img,phi,dims); for(int i=0;i<iter;i++){ //compute force F = en_chanvese_compute(Lz,phi,img,dims,scale,lambda); //perform iteration ls_iteration(F,phi,label,dims,Lz,Ln1,Lp1,Ln2,Lp2,Lin2out,Lout2in); //update statistics en_chanvese_update(img, dims, Lin2out, Lout2in); //display stuff (maybe) if(display){ if ( (i % display)==0) { std::cout<<"This is iteration # "<<i<<std::endl; } } } } void meanvar(double *img, double *phi, double *label, long *dims, LL *Lz, LL *Ln1, LL *Lp1, LL *Ln2, LL *Lp2, LL *Lin2out, LL *Lout2in, int iter,double lambda, short *plhs,int display){ double *F; double scale[1]; scale[0] = 0; //int countdown; //initialize datastructures and statistics en_meanvar_init(img,phi,dims); for(int i=0;i<iter;i++){ //compute force F = en_meanvar_compute(Lz,phi,img,dims,scale,lambda); //perform iteration ls_iteration(F,phi,label,dims,Lz,Ln1,Lp1,Ln2,Lp2,Lin2out,Lout2in); //update statistics en_meanvar_update(img, dims, Lin2out, Lout2in); //display stuff (maybe) // if(display) show_countdown(iter,i,&countdown,plhs); } } void bhattacharyya(double *img, double *phi, double *label, long *dims, LL *Lz, LL *Ln1, LL *Lp1, LL *Ln2, LL *Lp2, LL *Lin2out, LL *Lout2in, int iter,double lambda, short *plhs,int display){ double *F; double scale[1]; scale[0] = 0; //int countdown; //std::cout<<"Entered in Bhattacharyya"<<std::endl; //initialize datastructures and statistics en_bhattacharyya_init(img,phi,dims); for(int i=0;i<iter;i++){ //compute force F = en_bhattacharyya_compute(Lz,phi,img,dims,scale,lambda); //perform iteration ls_iteration(F,phi,label,dims,Lz,Ln1,Lp1,Ln2,Lp2,Lin2out,Lout2in); //update statistics en_bhattacharyya_update(img, dims, Lin2out, Lout2in); } en_bhattacharyya_destroy(); } void user_bhattacharyya(double *img, double *phi, double penaltyAlpha, double *seed, double *label, long *dims, LL *Lz, LL *Ln1, LL *Lp1, LL *Ln2, LL *Lp2, LL *Lin2out, LL *Lout2in, int iter,double lambda, short *plhs,int display){ double *F; double scale[1]; scale[0] = 0; //int countdown; std::cout<<"The display is set to: "<<display<<std::endl; // if(display==1){ // for (int i=0;i<dims[2];i++){ // display_slice(img,dims,i,"image"); // display_slice(phi,dims,i,"label"); // } // } std::cout<<"Entered in User Bhattacharyya"<<std::endl; //initialize datastructures and statistics en_user_bhattacharyya_init(img,phi,dims,seed); for(int i=0;i<iter;i++){ //compute force F = en_user_bhattacharyya_compute(Lz,phi,img, penaltyAlpha,dims,scale,lambda); //working here //perform iteration ls_iteration(F,phi,label,dims,Lz,Ln1,Lp1,Ln2,Lp2,Lin2out,Lout2in); //update statistics en_bhattacharyya_update(img, dims, Lin2out, Lout2in); //nothing changes in the updates from bhattacharyya } std::cout<<"Completed Segementation"<<std::endl; en_user_bhattacharyya_destroy(); } void yezzi(double *img, double *phi, double *label, long *dims, LL *Lz, LL *Ln1, LL *Lp1, LL *Ln2, LL *Lp2, LL *Lin2out, LL *Lout2in, int iter,double lambda, short *plhs,int display){ double *F; double scale[1]; scale[0]=0; //int countdown; //initialize datastructures and statistics en_yezzi_init(Lz,img,phi,dims); for(int i=0;i<iter;i++){ //compute force F = en_yezzi_compute(Lz,phi,img,dims,scale,lambda); //perform iteration ls_iteration(F,phi,label,dims,Lz,Ln1,Lp1,Ln2,Lp2,Lin2out,Lout2in); //update statistics en_yezzi_update(img, dims, Lin2out, Lout2in); //display stuff (maybe) // if(display) show_countdown(iter,i,&countdown,plhs); } } void grow(double *img, double *phi, double *label, long *dims, LL *Lz, LL *Ln1, LL *Lp1, LL *Ln2, LL *Lp2, LL *Lin2out, LL *Lout2in, int iter,double lambda, short *plhs,int display){ double *F; for(int i=0;i<iter;i++){ //compute force F = en_grow_compute(Lz, img, phi,dims,lambda, 800); //perform iteration ls_iteration(F,phi,label,dims,Lz,Ln1,Lp1,Ln2,Lp2,Lin2out,Lout2in); //update statistics en_null_update(img, dims, Lin2out, Lout2in); //display stuff (maybe) // if(display) show_countdown(iter,i,&countdown,plhs); } } void shrink(double *img, double *phi, double *label, long *dims, LL *Lz, LL *Ln1, LL *Lp1, LL *Ln2, LL *Lp2, LL *Lin2out, LL *Lout2in, int iter,double rad,double lambda, short *plhs,int display){ double *F; //int countdown; double scale[1]; scale[0] = 0; en_lrbac_init(Lz,img,phi,dims,rad); for(int i=0;i<iter;i++){ //compute force F = en_shrink_compute(Lz,img,phi,dims,rad,lambda,scale); //perform iteration ls_iteration(F,phi,label,dims,Lz,Ln1,Lp1,Ln2,Lp2,Lin2out,Lout2in); //update statistics en_lrbac_update(img, dims, Lin2out, Lout2in, rad); //display stuff (maybe) // if(display) show_countdown(iter,i,&countdown,plhs); } //destroy old datastructures en_lrbac_destroy(); } void kappa(double *img, double *phi, double *label, long *dims, LL *Lz, LL *Ln1, LL *Lp1, LL *Ln2, LL *Lp2, LL *Lin2out, LL *Lout2in, int iter,double lambda, short *plhs,int display){ double *F; //int countdown; for(int i=0;i<iter;i++){ //compute force F = en_kappa_compute(Lz,phi,dims); //perform iteration ls_iteration(F,phi,label,dims,Lz,Ln1,Lp1,Ln2,Lp2,Lin2out,Lout2in); //update statistics en_null_update(img, dims, Lin2out, Lout2in); //display stuff (maybe) // if(display) show_countdown(iter,i,&countdown,plhs); } } void prep_C_output(LL *Lz,long *dims,double *phi, short **iList, short **jList, long &lengthZLS){ int n = 0; ll_init(Lz); if(Lz==NULL){ iList=NULL; jList=NULL; lengthZLS=0; }else{ *iList=(short*) malloc(Lz->length*sizeof(short)); *jList=(short*) malloc(Lz->length*sizeof(short)); lengthZLS= (Lz->length); } while(Lz->curr != NULL){ (*iList)[n] =(short)(Lz->curr->x); (*jList)[n] =(short)(Lz->curr->y); ll_step(Lz); n++; } return; }
[ [ [ 1, 309 ] ] ]
fadfc81fae030370f1f6e256fef2912f21feed3c
d54d8b1bbc9575f3c96853e0c67f17c1ad7ab546
/hlsdk-2.3-p3/singleplayer/game_shared/vgui_checkbutton2.h
bf05da70eabcaeb7ceef202b5771c90891170994
[]
no_license
joropito/amxxgroup
637ee71e250ffd6a7e628f77893caef4c4b1af0a
f948042ee63ebac6ad0332f8a77393322157fa8f
refs/heads/master
2021-01-10T09:21:31.449489
2010-04-11T21:34:27
2010-04-11T21:34:27
47,087,485
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
2,198
h
//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============ // // Purpose: // // $NoKeywords: $ //============================================================================= #ifndef VGUI_CHECKBUTTON2_H #define VGUI_CHECKBUTTON2_H #ifdef _WIN32 #pragma once #endif #include "vgui_label.h" #include "vgui_imagepanel.h" #include "vgui_defaultinputsignal.h" namespace vgui { class CCheckButton2; class ICheckButton2Handler { public: virtual void StateChanged(CCheckButton2 *pButton) = 0; }; // VGUI checkbox class. // - Provides access to the checkbox images. // - Provides an easy callback mechanism for state changes. // - Default background is invisible, and default text color is white. class CCheckButton2 : public Panel, public CDefaultInputSignal { public: CCheckButton2(); ~CCheckButton2(); // Initialize the button with these. void SetImages(char const *pChecked, char const *pUnchecked); void SetImages(Image *pChecked, Image *pUnchecked); // If you use this, the button will never delete the images. void DeleteImages(); // The checkbox can be to the left or the right of the text (default is left). void SetCheckboxLeft(bool bLeftAlign); bool GetCheckboxLeft(); // Set the label text. void SetText(char const *pText, ...); void SetTextColor(int r, int g, int b, int a); // You can register for change notification here. void SetHandler(ICheckButton2Handler *pHandler); // Get/set the check state. bool IsChecked(); void SetChecked(bool bChecked); // Panel overrides. public: virtual void internalMousePressed(MouseCode code); protected: void SetupControls(); // InputSignal overrides. protected: virtual void mousePressed(MouseCode code,Panel* panel); public: ICheckButton2Handler *m_pHandler; bool m_bCheckboxLeft; Label m_Label; ImagePanel m_CheckboxPanel; Image *m_pChecked; Image *m_pUnchecked; bool m_bOwnImages; bool m_bChecked; }; } #endif // VGUI_CHECKBUTTON2_H
[ "joropito@23c7d628-c96c-11de-a380-73d83ba7c083" ]
[ [ [ 1, 101 ] ] ]
6dfc641618202188554bb1e9595f4f8951918c52
4d5ee0b6f7be0c3841c050ed1dda88ec128ae7b4
/src/nvcore/TextReader.cpp
790b91eb1c932870b1803a61e6638966be1c44a6
[]
no_license
saggita/nvidia-mesh-tools
9df27d41b65b9742a9d45dc67af5f6835709f0c2
a9b7fdd808e6719be88520e14bc60d58ea57e0bd
refs/heads/master
2020-12-24T21:37:11.053752
2010-09-03T01:39:02
2010-09-03T01:39:02
56,893,300
0
1
null
null
null
null
UTF-8
C++
false
false
1,411
cpp
// This code is in the public domain -- [email protected] #include <nvcore/TextReader.h> using namespace nv; /// Peek next character. char TextReader::peek() { nvDebugCheck(m_stream != NULL); nvDebugCheck(m_stream->isSeekable()); if (m_stream->isAtEnd()) { return 0; } uint pos = m_stream->tell(); char c; m_stream->serialize(&c, 1); m_stream->seek(pos); return c; } /// Read a single char. char TextReader::read() { nvDebugCheck(m_stream != NULL); char c; m_stream->serialize(&c, 1); if( m_stream->isAtEnd() ) { return 0; } return c; } /// Read from the current location to the end of the stream. const char * TextReader::readToEnd() { nvDebugCheck(m_stream != NULL); const int size = m_stream->size(); m_text.clear(); m_text.reserve(size + 1); m_text.resize(size); m_stream->serialize(m_text.mutableBuffer(), size); m_text.pushBack('\0'); return m_text.buffer(); } /// Read from the current location to the end of the line. const char * TextReader::readLine() { m_text.clear(); if (m_stream->isAtEnd()) { return NULL; } while (true) { char c = read(); if (c == 0 || c == '\n') { break; } else if (c == '\r') { if( peek() == '\n' ) { read(); } break; } m_text.pushBack(c); } m_text.pushBack('\0'); return m_text.buffer(); }
[ "castano@0f2971b0-9fc2-11dd-b4aa-53559073bf4c" ]
[ [ [ 1, 86 ] ] ]
03654ae17c1f3e6bd1890a9b5640bebf5798399c
b822313f0e48cf146b4ebc6e4548b9ad9da9a78e
/KylinSdk/Engine/Source/rRenderable.h
32c56e02f86d572590820892068e80f8c475ca41
[]
no_license
dzw/kylin001v
5cca7318301931bbb9ede9a06a24a6adfe5a8d48
6cec2ed2e44cea42957301ec5013d264be03ea3e
refs/heads/master
2021-01-10T12:27:26.074650
2011-05-30T07:11:36
2011-05-30T07:11:36
46,501,473
0
0
null
null
null
null
UTF-8
C++
false
false
240
h
#pragma once #include "rOgreRoot.h" namespace Kylin { class Renderable { public: Renderable(); ~Renderable(); virtual KVOID OnRenderStarted(KFLOAT fElapsed){} virtual KVOID OnRenderEnded(KFLOAT fElapsed){} }; }
[ [ [ 1, 16 ] ] ]
a8449a2fd04e1ee86df42857882022fb5c1ef50a
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Dependencies/Xerces/include/xercesc/dom/impl/DOMElementImpl.hpp
57bdd04bd5977755103bc84dd7c8aa7e086f78e1
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
5,021
hpp
#ifndef DOMElementImpl_HEADER_GUARD_ #define DOMElementImpl_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: DOMElementImpl.hpp 176052 2004-09-20 15:00:51Z amassari $ */ // // This file is part of the internal implementation of the C++ XML DOM. // It should NOT be included or used directly by application programs. // // Applications should include the file <xercesc/dom/DOM.hpp> for the entire // DOM API, or xercesc/dom/DOM*.hpp for individual DOM classes, where the class // name is substituded for the *. // #include <xercesc/util/XercesDefs.hpp> #include <xercesc/util/XMLString.hpp> #include <xercesc/dom/DOMElement.hpp> #include "DOMChildNode.hpp" #include "DOMNodeImpl.hpp" #include "DOMParentNode.hpp" #include "DOMAttrMapImpl.hpp" XERCES_CPP_NAMESPACE_BEGIN class DOMTypeInfo; class DOMNodeList; class DOMAttrMapImpl; class DOMDocument; class CDOM_EXPORT DOMElementImpl: public DOMElement { public: DOMNodeImpl fNode; DOMParentNode fParent; DOMChildNode fChild; DOMAttrMapImpl *fAttributes; DOMAttrMapImpl *fDefaultAttributes; const XMLCh *fName; public: DOMElementImpl(DOMDocument *ownerDoc, const XMLCh *name); DOMElementImpl(const DOMElementImpl &other, bool deep=false); virtual ~DOMElementImpl(); // Declare functions from DOMNode. They all must be implemented by this class DOMNODE_FUNCTIONS; // Functions introduced on Element... virtual const XMLCh* getAttribute(const XMLCh *name) const; virtual DOMAttr* getAttributeNode(const XMLCh *name) const; virtual DOMNodeList* getElementsByTagName(const XMLCh *tagname) const; virtual const XMLCh* getTagName() const; virtual void removeAttribute(const XMLCh *name); virtual DOMAttr* removeAttributeNode(DOMAttr * oldAttr); virtual void setAttribute(const XMLCh *name, const XMLCh *value); virtual DOMAttr* setAttributeNode(DOMAttr *newAttr); virtual void setReadOnly(bool readOnly, bool deep); //Introduced in DOM Level 2 virtual const XMLCh* getAttributeNS(const XMLCh *namespaceURI, const XMLCh *localName) const; virtual void setAttributeNS(const XMLCh *namespaceURI, const XMLCh *qualifiedName, const XMLCh *value); virtual void removeAttributeNS(const XMLCh *namespaceURI, const XMLCh *localName); virtual DOMAttr* getAttributeNodeNS(const XMLCh *namespaceURI, const XMLCh *localName) const; virtual DOMAttr* setAttributeNodeNS(DOMAttr *newAttr); virtual DOMNodeList* getElementsByTagNameNS(const XMLCh *namespaceURI, const XMLCh *localName) const; virtual bool hasAttribute(const XMLCh *name) const; virtual bool hasAttributeNS(const XMLCh *namespaceURI, const XMLCh *localName) const; //Introduced in DOM level 3 virtual void setIdAttribute(const XMLCh* name); virtual void setIdAttributeNS(const XMLCh* namespaceURI, const XMLCh* localName); virtual void setIdAttributeNode(const DOMAttr *idAttr); virtual const DOMTypeInfo * getTypeInfo() const; // for handling of default attribute virtual DOMAttr* setDefaultAttributeNode(DOMAttr *newAttr); virtual DOMAttr* setDefaultAttributeNodeNS(DOMAttr *newAttr); virtual DOMAttrMapImpl* getDefaultAttributes() const; // helper function for DOM Level 3 renameNode virtual DOMNode* rename(const XMLCh* namespaceURI, const XMLCh* name); protected: // default attribute helper functions virtual void setupDefaultAttributes(); private: // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- DOMElementImpl & operator = (const DOMElementImpl &); }; XERCES_CPP_NAMESPACE_END #endif
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 127 ] ] ]
15a2c8d40dfda9cd9be4fe550004a62077684abc
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Dependencies/Xerces/include/xercesc/util/regx/TokenFactory.cpp
8539cc54896074b7d8981f6af714922e91cf2675
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
11,525
cpp
/* * Copyright 2001,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: TokenFactory.cpp 191054 2005-06-17 02:56:35Z jberry $ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/util/regx/TokenFactory.hpp> #include <xercesc/util/regx/TokenInc.hpp> #include <xercesc/util/regx/XMLRangeFactory.hpp> #include <xercesc/util/regx/ASCIIRangeFactory.hpp> #include <xercesc/util/regx/UnicodeRangeFactory.hpp> #include <xercesc/util/regx/BlockRangeFactory.hpp> #include <xercesc/util/regx/RangeTokenMap.hpp> #include <xercesc/util/regx/RegxDefs.hpp> #include <xercesc/util/XMLRegisterCleanup.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // TokenFactory: Constructors and Destructor // --------------------------------------------------------------------------- TokenFactory::TokenFactory(MemoryManager* const manager) : fTokens(new (manager) RefVectorOf<Token> (16, true, manager)) , fEmpty(0) , fLineBegin(0) , fLineBegin2(0) , fLineEnd(0) , fStringBegin(0) , fStringEnd(0) , fStringEnd2(0) , fWordEdge(0) , fNotWordEdge(0) , fWordEnd(0) , fWordBegin(0) , fDot(0) , fCombiningChar(0) , fGrapheme(0) , fMemoryManager(manager) { } TokenFactory::~TokenFactory() { delete fTokens; fTokens = 0; } // --------------------------------------------------------------------------- // TokenFactory - Factory methods // --------------------------------------------------------------------------- Token* TokenFactory::createToken(const unsigned short tokType) { if (tokType == Token::T_EMPTY && fEmpty != 0) return fEmpty; Token* tmpTok = new (fMemoryManager) Token(tokType, fMemoryManager); if (tokType == Token::T_EMPTY) { fEmpty = tmpTok; } fTokens->addElement(tmpTok); return tmpTok; } ParenToken* TokenFactory::createLook(const unsigned short tokType, Token* const token) { ParenToken* tmpTok = new (fMemoryManager) ParenToken(tokType, token, 0, fMemoryManager); fTokens->addElement(tmpTok); return tmpTok; } ParenToken* TokenFactory::createParenthesis(Token* const token, const int noGroups) { ParenToken* tmpTok = new (fMemoryManager) ParenToken(Token::T_PAREN, token, noGroups, fMemoryManager); fTokens->addElement(tmpTok); return tmpTok; } ClosureToken* TokenFactory::createClosure(Token* const token, bool isNonGreedy) { ClosureToken* tmpTok = isNonGreedy ? new (fMemoryManager) ClosureToken(Token::T_NONGREEDYCLOSURE, token, fMemoryManager) : new (fMemoryManager) ClosureToken(Token::T_CLOSURE, token, fMemoryManager); fTokens->addElement(tmpTok); return tmpTok; } ConcatToken* TokenFactory::createConcat(Token* const token1, Token* const token2) { ConcatToken* tmpTok = new (fMemoryManager) ConcatToken(token1, token2, fMemoryManager); fTokens->addElement(tmpTok); return tmpTok; } UnionToken* TokenFactory::createUnion(const bool isConcat) { UnionToken* tmpTok = isConcat ? new (fMemoryManager) UnionToken(Token::T_CONCAT, fMemoryManager) : new (fMemoryManager) UnionToken(Token::T_UNION, fMemoryManager); fTokens->addElement(tmpTok); return tmpTok; } RangeToken* TokenFactory::createRange(const bool isNegRange){ RangeToken* tmpTok = isNegRange ? new (fMemoryManager) RangeToken(Token::T_NRANGE, fMemoryManager) : new (fMemoryManager) RangeToken(Token::T_RANGE, fMemoryManager); fTokens->addElement(tmpTok); return tmpTok; } CharToken* TokenFactory::createChar(const XMLUInt32 ch, const bool isAnchor) { CharToken* tmpTok = isAnchor ? new (fMemoryManager) CharToken(Token::T_ANCHOR, ch, fMemoryManager) : new (fMemoryManager) CharToken(Token::T_CHAR, ch, fMemoryManager); fTokens->addElement(tmpTok); return tmpTok; } StringToken* TokenFactory::createBackReference(const int noRefs) { StringToken* tmpTok = new (fMemoryManager) StringToken(Token::T_BACKREFERENCE, 0, noRefs, fMemoryManager); fTokens->addElement(tmpTok); return tmpTok; } StringToken* TokenFactory::createString(const XMLCh* const literal) { StringToken* tmpTok = new (fMemoryManager) StringToken(Token::T_STRING, literal, 0, fMemoryManager); fTokens->addElement(tmpTok); return tmpTok; } ModifierToken* TokenFactory::createModifierGroup(Token* const child, const int add, const int mask) { ModifierToken* tmpTok = new (fMemoryManager) ModifierToken(child, add, mask, fMemoryManager); fTokens->addElement(tmpTok); return tmpTok; } ConditionToken* TokenFactory::createCondition(const int refNo, Token* const condition, Token* const yesFlow, Token* const noFlow) { ConditionToken* tmpTok = new (fMemoryManager) ConditionToken(refNo, condition, yesFlow, noFlow, fMemoryManager); fTokens->addElement(tmpTok); return tmpTok; } // --------------------------------------------------------------------------- // TokenFactory - Getter methods // --------------------------------------------------------------------------- RangeToken* TokenFactory::staticGetRange(const XMLCh* const keyword, const bool complement) { return RangeTokenMap::instance()->getRange(keyword, complement); } Token* TokenFactory::getLineBegin() { if (fLineBegin == 0) fLineBegin = createChar(chCaret, true); return fLineBegin; } Token* TokenFactory::getLineBegin2() { if (fLineBegin2 == 0) fLineBegin2 = createChar(chAt, true); return fLineBegin2; } Token* TokenFactory::getLineEnd() { if (fLineEnd == 0) fLineEnd = createChar(chDollarSign, true); return fLineEnd; } Token* TokenFactory::getStringBegin() { if (fStringBegin == 0) fStringBegin = createChar(chLatin_A, true); return fStringBegin; } Token* TokenFactory::getStringEnd() { if (fStringEnd == 0) fStringEnd = createChar(chLatin_z, true); return fStringEnd; } Token* TokenFactory::getStringEnd2() { if (fStringEnd2 == 0) fStringEnd2 = createChar(chLatin_Z, true); return fStringEnd2; } Token* TokenFactory::getWordEdge() { if (fWordEdge == 0) fWordEdge = createChar(chLatin_b, true); return fWordEdge; } Token* TokenFactory::getNotWordEdge(){ if (fNotWordEdge == 0) fNotWordEdge = createChar(chLatin_B, true); return fNotWordEdge; } Token* TokenFactory::getWordBegin() { if (fWordBegin == 0) fWordBegin = createChar(chOpenAngle, true); return fWordBegin; } Token* TokenFactory::getWordEnd() { if (fWordEnd == 0) fWordEnd = createChar(chCloseAngle, true); return fWordEnd; } Token* TokenFactory::getDot() { if (fDot == 0) fDot = createToken(Token::T_DOT); return fDot; } Token* TokenFactory::getCombiningCharacterSequence() { if (fCombiningChar == 0) { Token* foo = createClosure(getRange(fgUniMark)); // \pM* foo = createConcat(getRange(fgUniMark, true), foo); // \PM + \pM* fCombiningChar = foo; } return fCombiningChar; } // static final String viramaString = Token* TokenFactory::getGraphemePattern() { if (fGrapheme == 0) { Token* base_char = createRange(); // [{ASSIGNED}]-[{M},{C}] base_char->mergeRanges(getRange(fgUniAssigned)); base_char->subtractRanges(getRange(fgUniMark)); base_char->subtractRanges(getRange(fgUniControl)); Token* virama = createRange(); virama->addRange(0x094D, 0x094D); virama->addRange(0x09CD, 0x09CD); virama->addRange(0x0A4D, 0x0A4D); virama->addRange(0x0ACD, 0x0ACD); virama->addRange(0x0B4D, 0x0B4D); virama->addRange(0x0BCD, 0x0BCD); virama->addRange(0x0C4D, 0x0C4D); virama->addRange(0x0CCD, 0x0CCD); virama->addRange(0x0D4D, 0x0D4D); virama->addRange(0x0E3A, 0x0E3A); virama->addRange(0x0F84, 0x0F84); Token* combiner_wo_virama = createRange(); combiner_wo_virama->mergeRanges(getRange(fgUniMark)); combiner_wo_virama->addRange(0x1160, 0x11FF); // hangul_medial and hangul_final combiner_wo_virama->addRange(0xFF9F, 0xFF9F); // extras Token* left = TokenFactory::createUnion(); // base_char? left->addChild(base_char, this); left->addChild(createToken(Token::T_EMPTY), this); Token* foo = createUnion(); foo->addChild(TokenFactory::createConcat(virama,getRange(fgUniLetter)), this); foo->addChild(combiner_wo_virama, this); foo = createClosure(foo); foo = createConcat(left, foo); fGrapheme = foo; } return fGrapheme; } /* #if defined (XML_USE_ICU_TRANSCODER) #include <unicode/uchar.h> #endif #include <stdio.h> void TokenFactory::printUnicode() { #if defined (XML_USE_ICU_TRANSCODER) // // Write it out to a temp file to be read back into this source later. // printf("Printing\n"); //sprintf(msg, "Printing\n"); FILE* outFl = fopen("table.out", "wt+"); fprintf(outFl, "const XMLByte fgUniCharsTable[0x10000] =\n{ "); for (unsigned int index = 0; index <= 0xFFFF; index += 16) { fprintf(outFl , " , 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X\n" , (unsigned int)u_charType(index) , (unsigned int)u_charType(index+1) , (unsigned int)u_charType(index+2) , (unsigned int)u_charType(index+3) , (unsigned int)u_charType(index+4) , (unsigned int)u_charType(index+5) , (unsigned int)u_charType(index+6) , (unsigned int)u_charType(index+7) , (unsigned int)u_charType(index+8) , (unsigned int)u_charType(index+9) , (unsigned int)u_charType(index+10) , (unsigned int)u_charType(index+11) , (unsigned int)u_charType(index+12) , (unsigned int)u_charType(index+13) , (unsigned int)u_charType(index+14) , (unsigned int)u_charType(index+15)); } fprintf(outFl, "};\n"); fclose(outFl); #endif } */ XERCES_CPP_NAMESPACE_END /** * End of file TokenFactory.cpp */
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 394 ] ] ]
4bc6812f7d722bae35efcbfdec3870140ada7b9c
00b979f12f13ace4e98e75a9528033636dab021d
/branches/ziahttpd-mod/src/include/server/modman.hh
64648524f6499bd6d8bd3648be6dd23d934c0584
[]
no_license
BackupTheBerlios/ziahttpd-svn
812e4278555fdd346b643534d175546bef32afd5
8c0b930d3f4a86f0622987776b5220564e89b7c8
refs/heads/master
2016-09-09T20:39:16.760554
2006-04-13T08:44:28
2006-04-13T08:44:28
40,819,288
0
0
null
null
null
null
UTF-8
C++
false
false
7,444
hh
// // modman.hh for in // // Made by texane // Login <[email protected]> // // Started on Fri Nov 11 15:54:10 2005 texane // Last update Fri Nov 25 15:23:33 2005 texane // #ifndef SERVER_MODMAN_HH # define SERVER_MODMAN_HH #include <list> #include <string> namespace http { class session; } namespace server { class module; } namespace server { class core; } namespace server { class modman { public: modman(); // Module loading bool is_loaded(const std::string&, std::list<module*>::iterator* = NULL); bool load_at_beginning(const std::string&, bool priviledged = false, bool activ = true); bool load_at_end(const std::string&, bool priviledged = false, bool activ = true); bool load(const std::string&, const std::string&, const std::string&, bool = false, bool = true, bool = true); bool reload(const std::string&, bool priviledged = false, bool activ = true); // Module unloading bool unload(const std::string&); // Running state management bool start(const std::string&); bool stop(const std::string&); bool state(const std::string&, int&); // Module invokation typedef enum { CREATE_CON = 0, READ_RQST_METADATA, READ_RQST_DATA, PARSE_RQST_METADATA, ALTER_RQST_DATA, BUILD_RESP_METADATA, BUILD_RESP_DATA, ALTER_RESP_DATA, ALTER_RESP_METADATA, SEND_RESP, RELEASE_CON } stageid_t; bool call_hooks(core*, stageid_t, http::session*); // Conveniences module* operator[](const std::string&); // Singleton-like behaviour static modman* instance(); // Get the next stage id static bool next_processing_stage(http::session&); private: std::list<module*> modlist_; // Singleton-like behaviour static modman* instance_; }; } //! \class server::modman //! \brief Module manager //! //! Handle module management. //! Provide methods to handle module dependencies, //! cold module reloading/unloading, running related function. //! Modules can have one of the two priviledge level. //! A priviledged module can access to the server core datas. //! Modules have to register hooks being called at different stages //! of the request processing flow. //! See the API documentation for more information on how //! a request is processed by the server core. //! <b>TODOLIST:</b> //! -# Improve the module system, in order to include list of pending //! sessions for a given module(modules have to pass information). //! -# The above problem might be solved by adding a current_operation //! attribute in the session, in order for the module to check completion //! status of the services it called. //! \fn bool server::modman::load_at_beginning(const std::string& id, //! bool priviledged = false, //! bool activ = true) //! \brief load a module at the beginning of the list. //! //! \param id Path identifying the module //! \param priviledged wether or not the module is a priviledged one //! \param activ is the module activated at loading //! \return false on error (either the module is not found, permission denied...). //! //! Load a module at the beginning of the modlist_. //! \fn bool server::modman::load_at_end(const std::string& id, //! bool priviledged = false, //! bool activ = true) //! \brief load a module at the end of the list. //! //! \param id Path identifying the module //! \param priviledged wether or not the module is a priviledged one //! \param activ is the module activated at loading //! \return false on error (either the module is not found, permission denied...). //! //! Load a module at the end of the modlist_. //! \fn bool server::modman::load(const std::string& after_id, //! const std::string& my_id, //! const std::string& before_id, //! bool priviledged = false, //! bool activ = true, //! bool load_missing = true) //! \brief load a module between two others. //! //! \param after_id path identifying the module to load after //! \param my_id path identifying the module to load //! \param before_id path identifying the module to load before //! \param priviledged wether or not the module is a priviledged one //! \param activ is the module activated at loading //! \param load_missing load the missing module //! \return false on error (either the module is not found, permission denied...). //! //! Load the module identified by my_id AFTER after_id, and BEFORE before_id. //! If the one or all module doesn't exist, the boolean load_missing decides wether //! or not to load them. //! \fn bool server::modman::reload(const std::string& id, //! bool priviledged = false, //! bool activ = true) //! \brief reload a module if it exists, preserving the position in the list. //! //! \param id Path identifying the module //! \param priviledged wether or not the module is a priviledged one //! \param activ is the module activated at loading //! \return false if the module isnot present, or cannot be accessed. //! //! Reload a module at the same place in modlist_. //! \fn bool server::modman::is_loaded(const std::string& id) const //! \brief Tell if the module is present in the list. //! //! \param id Path identifying the module //! \return false if the module isnot present //! //! Tell if the module is present in the list. //! \fn bool server::modman::unload(const std::string& id) //! \brief Unload an existing module //! //! \param id Path identifying the module //! \return false if the module isnot present. //! //! Unload the module identified by id in modlist_. //! \fn bool server::modman::start(const std::string& id) //! \brief Start the module. //! //! \param id Path identifying the module //! \return false if the module isnot present or already running. //! //! Start the module. //! \fn bool server::modman::stop(const std::string& id) //! \brief Stop the module. //! //! \param id Path identifying the module //! \return false if the module isnot present or not running. //! //! Stop the module. //! \fn bool server::modman::state(const std::string& id, int& st) //! \brief Tell why the module is in state... //! //! \param id Path identifying the module //! \param st Code of the module state //! \return false if the module isnot present. //! //! Tell why the module is in state... //! \fn bool server::modman::call_hooks(server::core* core, stageid id, http::session* session) //! \brief Call hooks registered by modules for a given stage //! //! \param core Address of the core to be passed to priviledged modules //! \param id Processing request flow stage identifier //! \param session Current session being processed by the server //! \return Always return true(improve it). //! //! Call hooks registered by modules for a given stage in //! the request processing flow. //! \see module.hh for informations about module hooks. //! \fn server::module& server::modman::operator[](const std::string& id); //! \brief Get the module identified by id. //! //! \param id Path identifying the module //! \return A reference to the module pointer contained in modlist_ //! //! Get the module identified by id. #endif // ! SERVER_MODMAN_HH
[ "texane@754ce95b-6e01-0410-81d0-8774ba66fe44" ]
[ [ [ 1, 236 ] ] ]
01b89fe165e5eeaee9d9aeb773b31db7bf4e9b3d
05869e5d7a32845b306353bdf45d2eab70d5eddc
/soft/application/CoolSimulator/StdAfx.cpp
8cc9f5c7e74bef90bdadba93665d30da8d302c68
[]
no_license
shenfahsu/sc-fix
beb9dc8034f2a8fd9feb384155fa01d52f3a4b6a
ccc96bfaa3c18f68c38036cf68d3cb34ca5b40cd
refs/heads/master
2020-07-14T16:13:47.424654
2011-07-22T16:46:45
2011-07-22T16:46:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
215
cpp
// stdafx.cpp : source file that includes just the standard includes // CoolSimulator.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
[ "windyin@2490691b-6763-96f4-2dba-14a298306784" ]
[ [ [ 1, 8 ] ] ]
2f05bf53901767249408e6aff1586cbdbe13ef67
00b979f12f13ace4e98e75a9528033636dab021d
/branches/ziis/src/core/error.cc
624c228bce1aa0e181610342d4ef844f11c80842
[]
no_license
BackupTheBerlios/ziahttpd-svn
812e4278555fdd346b643534d175546bef32afd5
8c0b930d3f4a86f0622987776b5220564e89b7c8
refs/heads/master
2016-09-09T20:39:16.760554
2006-04-13T08:44:28
2006-04-13T08:44:28
40,819,288
0
0
null
null
null
null
UTF-8
C++
false
false
1,315
cc
// // error.cc for in // // Made by texane // Login <[email protected]> // // Started on Sun Jan 22 00:20:24 2006 texane // Last update Tue Mar 21 22:43:53 2006 texane // #include <string> #include <sstream> #include <iostream> #include <ziafs_status.hh> using std::cerr; using std::endl; using std::string; using std::ostringstream; void status::debug_err_fn(error e, const char* filename, int nline) { cerr << "(@" << filename << "#" << nline << "): " << tostring(e) << endl; } void status::log_err_fn(error e, const char* filename, int nline) { cerr << "(@" << filename << "#" << nline << "): " << tostring(e) << endl; } string status::dump(error e, const char* filename, int nline) { ostringstream strm; strm << "(@" << filename << "#" << nline << "): " << tostring(e); return strm.str(); } #define on_case( e , s ) \ case e: \ str = s; \ break; string status::tostring(error e) { const char* str; switch (e) { on_case( SUCCESS, "operation success" ); on_case( NOTIMPL, "feature not implemented" ); on_case( ISNT_OPENED, "not opened"); on_case( PARTIALIMPL, "feature partially implemented" ); default: str = "unknown error"; } return string(str); }
[ "texane@754ce95b-6e01-0410-81d0-8774ba66fe44" ]
[ [ [ 1, 65 ] ] ]
647aeb08a26699185c849462484cd66e3cf5d499
acf1b4792425a2ff0565451a044f00029ccf794d
/src/scriptfile.cpp
832f3183af7f0f8d851b7e6c5f35f26c3f24f159
[]
no_license
davgit/ahk2exe-1
d36330e101dbf0f631ebcbb925635ab0631c3619
93e6af3188cff3444dc5be6ad37dd032dd3665d1
refs/heads/master
2016-09-10T22:43:59.400053
2010-07-08T07:34:46
2010-07-08T07:34:46
22,427,624
1
0
null
null
null
null
UTF-8
C++
false
false
12,448
cpp
/////////////////////////////////////////////////////////////////////////////// // // AutoIt // // Copyright (C)1999-2003: // - Jonathan Bennett <[email protected]> // - See "AUTHORS.txt" for contributors. // // 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. // /////////////////////////////////////////////////////////////////////////////// // // scriptfile.cpp // // The script file object. This object handles all requests to the script file // that was read in. // // Modified version of the AutoIt scriptfile object, not all whitespace is // stripped just trailing whitespace/newline. Leading whitespace is stored // so that when the script is decompiled the formatting is OK. // /////////////////////////////////////////////////////////////////////////////// // Includes #include "StdAfx.h" // Pre-compiled headers #ifndef _MSC_VER // Includes for non-MS compilers #include <stdio.h> #include <windows.h> #endif #include "Aut2Exe.h" #include "scriptfile.h" #include "util.h" #include "resources\resource.h" /////////////////////////////////////////////////////////////////////////////// // Constructor() /////////////////////////////////////////////////////////////////////////////// AutoIt_ScriptFile::AutoIt_ScriptFile() { m_lpScript = NULL; // Start of the linked list m_lpScriptLast = NULL; // Last node of the list m_nScriptLines = 0; // Number of lines in the list // Zero our include IDs m_nNumIncludes = 0; } // AutoIt_ScriptFile() /////////////////////////////////////////////////////////////////////////////// // AddLine() /////////////////////////////////////////////////////////////////////////////// void AutoIt_ScriptFile::AddLine(int nLineNum, const char *szLine, int nIncludeID) { LARRAY *lpTemp; char *szTemp; // if (szLine[0] == '\0') // return; // Empty, don't bother storing unless Aut2Exe // Do we need to start linked list? if ( m_lpScript == NULL ) { m_lpScript = new LARRAY; m_lpScriptLast = m_lpScript; } else { lpTemp = new LARRAY; m_lpScriptLast->lpNext = lpTemp; // Next m_lpScriptLast = lpTemp; } m_lpScriptLast->lpNext = NULL; // Next // Store our line szTemp = new char[strlen(szLine)+1]; strcpy(szTemp, szLine); m_lpScriptLast->szLine = szTemp; m_lpScriptLast->nLineNum = nLineNum; m_lpScriptLast->nIncludeID = nIncludeID; // Increase the number of lines m_nScriptLines++; } // AddLine() /////////////////////////////////////////////////////////////////////////////// // AppendLastLine() // // Same as AddLine except it adds the text onto the LAST line added /////////////////////////////////////////////////////////////////////////////// void AutoIt_ScriptFile::AppendLastLine(const char *szLine) { char *szTemp; size_t CombinedLen; // if (szLine[0] == '\0') // return; // Empty, don't bother storing unless Aut2Exe // How big are both lines added together? CombinedLen = strlen(m_lpScriptLast->szLine) + strlen(szLine); // Create a big enough space for the combined line and copy it there szTemp = new char[CombinedLen+1]; strcpy(szTemp, m_lpScriptLast->szLine); strcat(szTemp, szLine); // The appending may have gone over the max line size, so just do a dirty hack and // enforce the line size by inserting a \0 if (strlen(szTemp) > AUT_MAX_LINESIZE) szTemp[AUT_MAX_LINESIZE] = '\0'; // Now free the existing line and replace with the new one delete [] m_lpScriptLast->szLine; m_lpScriptLast->szLine = szTemp; } // AppendLastLine() /////////////////////////////////////////////////////////////////////////////// // AddIncludeName() /////////////////////////////////////////////////////////////////////////////// int AutoIt_ScriptFile::AddIncludeName(const char *szFileName) { char szFullPath[_MAX_PATH+1]; char *szTemp; if (m_nNumIncludes >= AUT_MAX_INCLUDE_IDS) return -1; GetFullPathName(szFileName, _MAX_PATH, szFullPath, &szTemp); // Does this file already exist? for (int i=0; i < m_nNumIncludes; ++i) { if (!stricmp(m_szIncludeIDs[i], szFullPath)) return i; } // New entry szTemp = new char[strlen(szFullPath)+1]; strcpy(szTemp, szFullPath); m_szIncludeIDs[m_nNumIncludes] = szTemp; ++m_nNumIncludes; return m_nNumIncludes-1; } // AddIncludeName() /////////////////////////////////////////////////////////////////////////////// // GetIncludeID() /////////////////////////////////////////////////////////////////////////////// int AutoIt_ScriptFile::GetIncludeID(int nLineNum) { int i; LARRAY *lpTemp = m_lpScript; // Do we have this many lines? if (nLineNum > m_nScriptLines || nLineNum <= 0) return -1; // Nope for (i=0; i<nLineNum-1; i++) lpTemp = lpTemp->lpNext; return lpTemp->nIncludeID; } // GetIncludeID() /////////////////////////////////////////////////////////////////////////////// // GetIncludeName() /////////////////////////////////////////////////////////////////////////////// const char * AutoIt_ScriptFile::GetIncludeName(int nIncludeID) { if (nIncludeID >= AUT_MAX_INCLUDE_IDS || nIncludeID < 0) return NULL; else return m_szIncludeIDs[nIncludeID]; } // GetIncludeName() /////////////////////////////////////////////////////////////////////////////// // UnloadScript() /////////////////////////////////////////////////////////////////////////////// void AutoIt_ScriptFile::UnloadScript(void) { LARRAY *lpTemp, *lpTemp2; // Unloading the script is simply a matter of freeing all the memory // that we allocated in the linked lists lpTemp = m_lpScript; while (lpTemp != NULL) { lpTemp2 = lpTemp->lpNext; delete [] lpTemp->szLine; // Free the string delete lpTemp; // Free the node lpTemp = lpTemp2; } // Ensure everything is zeroed in case we load another script m_lpScript = NULL; // Start of the linked list m_lpScriptLast = NULL; // Last node of the list m_nScriptLines = 0; // Number of lines in the list // Delete all our includes for (int i=0; i<m_nNumIncludes; ++i) delete [] m_szIncludeIDs[i]; m_nNumIncludes = 0; } // UnloadScript() /////////////////////////////////////////////////////////////////////////////// // GetLine() // // NOTE: Line 1 is the first line (not zero) // /////////////////////////////////////////////////////////////////////////////// const char * AutoIt_ScriptFile::GetLine(int nLineNum, int &nAutLineNum) { int i; LARRAY *lpTemp = m_lpScript; // Do we have this many lines? if (nLineNum > m_nScriptLines) return NULL; // Nope for (i=0; i<nLineNum-1; i++) lpTemp = lpTemp->lpNext; // Get the line and real line number (.aut file) nAutLineNum = lpTemp->nLineNum; return lpTemp->szLine; // Return pointer to the line } // GetLine() /////////////////////////////////////////////////////////////////////////////// // LoadScript() // // NATIVE VERSION // /////////////////////////////////////////////////////////////////////////////// bool AutoIt_ScriptFile::LoadScript(const char *szFile) { // Read in the script and any include files return Include(szFile, AddIncludeName(szFile)); } // LoadScript() /////////////////////////////////////////////////////////////////////////////// // Include() // /////////////////////////////////////////////////////////////////////////////// bool AutoIt_ScriptFile::Include(const char *szFileName, int nIncludeID) { char szBuffer[65535+1]; char szTemp[65535+1]; int nLineNum = 1; // Line# in .aut file FILE *fptr; bool bErr = true; bool bNextLineAppend = false; // If true the next line read should be appended bool bContinuationFound; int nLen; // Open a handle to the script file fptr = fopen(szFileName, "r"); // ASCII read if ( fptr == NULL ) // File error { strcpy(szBuffer, "Error reading the file:\n\n"); strcat(szBuffer, szFileName); Util_ShowError(szBuffer); return false; } // Read in lines of text until EOF is reached or error occurs while ( fgets(szBuffer, 65535, fptr) && bErr == true) { // Enforce our maximum line length (must be smaller than szBuffer!) szBuffer[AUT_MAX_LINESIZE] = '\0'; // Don't check for #include if we are continuing previous line if ( bNextLineAppend == false && IncludeParse(szBuffer, szTemp) == true ) { // Include file strcpy(szBuffer, "; <INCLUDE START: "); strcat(szBuffer, szTemp); strcat(szBuffer, ">"); AddLine(nLineNum, szBuffer, nIncludeID); bErr = Include(szTemp, AddIncludeName(szTemp)); // Get the include file strcpy(szBuffer, "; <INCLUDE END>"); AddLine(nLineNum, szBuffer, nIncludeID); } else { //StripLeading(szBuffer); // Only required in AutoIt StripTrailing(szBuffer); // Strip trailing nLen = (int)strlen(szBuffer); // Check if the last character is requesting a continuation if (nLen && szBuffer[nLen-1] == '_') { szBuffer[nLen-1] = '\0'; // Erase the continuation char bContinuationFound = true; } else bContinuationFound = false; // Was previous line a continuation? if (bNextLineAppend == true) { StripLeading(szBuffer); // Only required in Aut2Exe AppendLastLine(szBuffer); } else AddLine(nLineNum, szBuffer, nIncludeID ); if (bContinuationFound == true) bNextLineAppend = true; else bNextLineAppend = false; } nLineNum++; // Increment the line number } // End While // Close our script file fclose(fptr); return bErr; } // Include() /////////////////////////////////////////////////////////////////////////////// // IncludeParse() // // Checks a line of text to see if it is an #include directive, if so passes // back the string changed to contain the filename of the file to include /////////////////////////////////////////////////////////////////////////////// bool AutoIt_ScriptFile::IncludeParse(const char *szLine, char *szTemp) { int i,j; int nLen; nLen = (int)strlen(szLine); // Get length i = 0; // Skip whitespace while (szLine[i] == ' ' || szLine[i] == '\t') i++; // Copy until next whitespace (should be the #include word) j = 0; while (szLine [i] != ' ' && szLine[i] != '\t' && szLine[i] != '\0') szTemp[j++] = szLine[i++]; szTemp[j] = '\0'; // Terminate if (stricmp(szTemp, "#include")) return false; // No include directive // Now find " while (szLine[i] != '\"' && szLine[i] != '\0') i++; if (szLine[i++] == '\0') return false; // Didn't find " // Copy until next " (should be the filename) j = 0; while (szLine [i] != '"' && szLine[i] != '\0') szTemp[j++] = szLine[i++]; szTemp[j] = '\0'; // Terminate if (szLine[i++] == '\0') return false; // Didn't find " return true; } // IncludeParse() /////////////////////////////////////////////////////////////////////////////// // StripTrailing() /////////////////////////////////////////////////////////////////////////////// void AutoIt_ScriptFile::StripTrailing(char *szLine) { int i; int nLen; nLen = (int)strlen(szLine); // Get length if (nLen == 0) return; // Nothing to do // Strip trailing whitespace and newline i = nLen - 1; while ( i >= 0 && (szLine[i] == ' ' || szLine[i] == '\t' || szLine[i] == '\n') ) i--; // Remove trailing szLine[i+1] = '\0'; } // StripTrailing() /////////////////////////////////////////////////////////////////////////////// // StripLeading() /////////////////////////////////////////////////////////////////////////////// void AutoIt_ScriptFile::StripLeading(char *szLine) { int i, j; i = 0; while ( szLine[i] == ' ' || szLine[i] == '\t' ) i++; if (szLine[i] == '\0') return; // Nothing to do j = 0; while (szLine[i] != '\0') szLine[j++] = szLine[i++]; szLine[j] = '\0'; // Terminate } // StripLeading()
[ [ [ 1, 463 ] ] ]
76e62cd4fd377e3860cea5d927751fcfd5b26c7c
7b7a3f9e0cac33661b19bdfcb99283f64a455a13
/parser.cpp
1c1a8952073dc5a3748fbb7c0c4887e59fe8d0a0
[]
no_license
grimtraveller/fluxengine
62bc0169d90bfe656d70e68615186bd60ab561b0
8c967eca99c2ce92ca4186a9ca00c2a9b70033cd
refs/heads/master
2021-01-10T10:58:56.217357
2009-09-01T15:07:05
2009-09-01T15:07:05
55,775,414
0
0
null
null
null
null
UTF-8
C++
false
false
1,804
cpp
#include "parser.h" #include "lexer.h" #include "tree.h" Parser::Parser() { ast = new Tree<Token>; } Parser::~Parser() { } void Parser::parse() { TreeNode<Token>* root = ast->AddNode(NODE_ROOT); TreeNode<Token>* child; Lexer::getInstance()->getToken(); while(Lexer::getInstance()->getCurrentToken() != TOK_EOF) { child = parse_global_scope(); if(child != NULL) ast->AddChild(root, child); } dl_iterator<Token> it = root->m_children.getIterator(); for(it.begin(); it.valid(); it.forth()) std::cout << it.item().type; } TreeNode<Token>* Parser::parse_global_scope() { TreeNode<Token>* node = ast->AddNode(NODE_GLOBAL); if(Lexer::getInstance()->getCurrentToken() == TOK_INT) { std::cout << "Parsing Declaration Block" << std::endl; ast->AddChild(node, parse_declaration_block()); } return node; } TreeNode<Token>* Parser::parse_declaration_block() { TreeNode<Token>* node = NULL; if( Lexer::getInstance()->getCurrentToken() == TOK_INT) { TreeNode<Token>* node = ast->AddNode(NODE_DECLARATION_BLOCK); bool loop = false; do { ast->AddChild( node, parse_declaration( ) ); loop = ( Lexer::getInstance()->getCurrentToken() == TOK_COMMA ); if(loop) Lexer::getInstance()->getToken(); } while (loop); if(Lexer::getInstance()->getCurrentToken() != TOK_SEMICOLON) std::cout << "Expecting ;" << std::endl; exit(0); } Lexer::getInstance()->getToken(); return node; } TreeNode<Token>* Parser::parse_declaration() { std::cout << "Parsing declaration" << std::endl; //dummy Lexer::getInstance()->getToken(); Lexer::getInstance()->getToken(); Lexer::getInstance()->getToken(); Lexer::getInstance()->getToken(); return ast->AddNode(NODE_DECLARATION); }
[ [ [ 1, 81 ] ] ]
8a0539c7faefe50cc533cb2e586e27d7e1bb0da1
36fea6c98ecabcd5e932f2b7854b3282cdb571ee
/mainwindow.cpp
cb56f3a5a98395da470066bede382450b5584e43
[]
no_license
doomfrawen/visualcommand
976adaae69303d8b4ffc228106a1db9504e4a4e4
f7bc1d590444ff6811f84232f5c6480449228e19
refs/heads/master
2016-09-06T17:40:57.775379
2009-07-28T22:48:23
2009-07-28T22:48:23
32,345,504
0
0
null
null
null
null
UTF-8
C++
false
false
11,178
cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include "dialogsearch.h" #include "dialogupload.h" #include "dialogsettings.h" #include "dialogabout.h" #include "arguments/argtab.h" #include "arguments/argumentinterface.h" #include <qinputdialog.h> #include <QDir> #include <QPluginLoader> #include <QProcess> #include <QSettings> //Property Dialog Includes #include "qtpropertymanager.h" #include "qtvariantproperty.h" #include <QtSpinBoxFactory> #include <QtEnumEditorFactory> #include <QFileDialog> #include <QDomDocument> #include <QDomElement> #include <QDomText> #include <QTextStream> #include <QMessageBox> #include <QFile> #include "arguments/stringEditor.h" #include "arguments/numericEditor.h" #include "arguments/checkBoxEditor.h" #include "arguments/argnumericform.h" #include "arguments/argformbase.h" #include "arguments/argfileform.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), Windows(false),Mac(false),Linux(false) { QCoreApplication::setOrganizationName("ASamApplication"); QCoreApplication::setOrganizationDomain("AttackOfTheSam.com"); QCoreApplication::setApplicationName("VisualCommand"); ui->setupUi(this); int Index=0; QWidget*tab = ui->tabWidget->widget(Index); ui->tabWidget->removeTab(Index); SwitchMode(true); //ui->dockWidgetProperties->setFloating(true); ui->horizontalLayout_3->addWidget(&browser); LoadNoPlugin(); //LoadPlugins(); delete tab; read_settings(); } void MainWindow::read_settings(){ QSettings settings; settings.beginGroup("RunModes"); regularMode = settings.value("regularMode","cmd \\k").toString(); adminMode = settings.value("adminMode","sudo cmd \\k").toString(); settings.endGroup(); } void MainWindow::write_settings(){ QSettings settings; settings.beginGroup("RunModes"); settings.setValue("regularMode",regularMode); settings.setValue("adminMode",adminMode); settings.endGroup(); } void MainWindow::LoadPlugins(){ /* QDir path( "E:\\VisualCommand\\VisualCommand\\plugins\\stringEditor\\debug" ); foreach( QString filename, path.entryList(QDir::Files) ) { QPluginLoader loader( path.absoluteFilePath( filename ) ); QObject *couldBeArgument = loader.instance(); if( couldBeArgument ) { ArgumentInterface *Argument = qobject_cast<ArgumentInterface*>( couldBeArgument ); if( Argument ) { Arguments[Argument->GetName()] = Argument; ui->listWidgetArguments->addItem(Argument->GetName()); } delete couldBeArgument; } }*/ } void MainWindow::LoadNoPlugin(){ ArgumentInterface * Argument; ArgFormInterface * ArgForm; Argument = new stringEditor(); Arguments[Argument->GetName()] = Argument; ui->listWidgetArguments->addItem(Argument->GetName()); Argument = new numericEditor(); Arguments[Argument->GetName()] = Argument; ui->listWidgetArguments->addItem(Argument->GetName()); Argument = new checkBoxEditor(); Arguments[Argument->GetName()] = Argument; ui->listWidgetArguments->addItem(Argument->GetName()); //Prettier Form Versions ArgForm = new ArgNumericForm(); Argument = new ArgFormBase(ArgForm); Arguments[Argument->GetName()] = Argument; ui->listWidgetArguments->addItem(Argument->GetName()); ArgForm = new ArgFileForm(); Argument = new ArgFormBase(ArgForm); Arguments[Argument->GetName()] = Argument; ui->listWidgetArguments->addItem(Argument->GetName()); } MainWindow::~MainWindow() { delete ui; } void MainWindow::LaunchSearch(){ DialogSearch Test(this); Test.exec(); } void MainWindow::LaunchUpload(){ DialogUpload Test(this); Test.setLinux(Linux); Test.setMac(Mac); Test.setWindows(Windows); Test.setTitle(Title); Test.setAppName(AppName); Test.setAppWebsite(AppWebsite); Test.setDescription(Description); Test.exec(); Linux = Test.getLinux(); Mac = Test.getMac(); Windows = Test.getWindows(); Title = Test.getTitle(); AppName = Test.getAppName(); AppWebsite = Test.getAppWebsite(); Description = Test.getDescription(); ChangeText(); } void MainWindow::EditSettings(){ read_settings(); DialogSettings settings; settings.exec(); read_settings(); //write_settings(); } void MainWindow::EditAddWidget(QListWidgetItem* Item){ argTab* tab = dynamic_cast<argTab*>( ui->tabWidget->currentWidget()); if(tab==0) return; QString WidgetName = Item->text(); ArgumentInterface *Argument = Arguments[WidgetName]; Argument = Argument->GetNewInstance(); tab->AddWidget(Argument); ChangePropertyBrowser(Argument); } void MainWindow::EditAddTab(){ bool ok; QString text = QInputDialog::getText(this, tr("Create a tab"), tr("Tab Name"), QLineEdit::Normal, QString(""), &ok); if (ok && !text.isEmpty()){ AddTab(text); } } void MainWindow::AddTab(QString text){ argTab*tab = new argTab(text); tab->setObjectName(QString::fromUtf8("tab")); ui->tabWidget->addTab(tab,text); ui->tabWidget->setCurrentWidget(tab); QObject::connect(tab, SIGNAL(ControlChanged()),this,SLOT(ChangeText())); QObject::connect(tab, SIGNAL(ControlSelected(ArgumentInterface*)),this,SLOT(ChangePropertyBrowser(ArgumentInterface*))); } void MainWindow::EditRemoveTab(int Index){ //QWidget*tab = new QWidget(); QWidget*tab = ui->tabWidget->widget(Index); ui->tabWidget->removeTab(Index); delete tab; } void MainWindow::ChangeText(){ QString Text =this->AppName+" "; for(int x=0;x< ui->tabWidget->count();x++){ argTab * tempTab = dynamic_cast<argTab*>( ui->tabWidget->widget(x)); Text += tempTab->GetArgumentText(); } ui->plainTextEditArgumentText->setPlainText(Text); } void MainWindow::SwitchMode(bool runMode){ for(int x=0;x< ui->tabWidget->count();x++){ argTab * tempTab = dynamic_cast<argTab*>( ui->tabWidget->widget(x)); if(runMode) tempTab->setRunMode(); else tempTab->setEditMode(); } if(runMode){ ui->tabWidget->setMovable(false); ui->tabWidget->setTabsClosable(false); ui->dockWidgetProperties->setVisible(false); ui->dockWidgetControls->setVisible(false); } else{ ui->tabWidget->setMovable(true); ui->tabWidget->setTabsClosable(true); ui->dockWidgetProperties->setVisible(true); ui->dockWidgetControls->setVisible(true); } } void MainWindow::ChangePropertyBrowser(ArgumentInterface* Control){ Control->SetupBrowser(&browser); } QString MainWindow::boolToString(bool in){ if(in) return QString("True"); return QString("False"); } void MainWindow::FileSave(){ QString filename = QFileDialog::getSaveFileName(this, tr("Save Gui File"), QDir::currentPath(), tr("Gui files(*.gml)")); if(filename.isNull()) return; QDomDocument document("GUIXML"); QDomElement GuiFile = document.createElement( "VisualCommand" ); GuiFile.setAttribute("Title",this->Title); GuiFile.setAttribute("AppName",this->AppName); GuiFile.setAttribute("WebSite",this->AppWebsite); GuiFile.setAttribute("Description",this->Description); GuiFile.setAttribute("Linux",boolToString(Linux)); GuiFile.setAttribute("Mac",boolToString(Mac)); GuiFile.setAttribute("Windows",boolToString(Windows)); document.appendChild(GuiFile); for(int x=0;x< ui->tabWidget->count();x++){ argTab * tempTab = dynamic_cast<argTab*>( ui->tabWidget->widget(x)); QDomElement tag = tempTab->GetXMLElment(&document); GuiFile.appendChild(tag); } QFile file( filename ); if( !file.open( QIODevice::WriteOnly | QIODevice::Text ) ) { qDebug( "Failed to open file for writing." ); return ; } QTextStream stream( &file ); stream << document.toString(); file.close(); } void MainWindow::FileOpen(){ QString filename = QFileDialog::getOpenFileName(this, tr("Open Gui File"), QDir::currentPath(), tr("Gui files(*.gml);;All files(*.*)")); if(filename.isNull()) return; QDomDocument doc("GUIXML"); QFile file(filename); if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){ QMessageBox::information( this, "Open Error", "Unable to open the file.\n" ); return; } QString Error; int line,column; if(!doc.setContent(&file,&Error,&line,&column)){ file.close(); QMessageBox::information( this, "Open Error", "Unable to set the content of the file.\n" +Error + "\nLine "+QString::number(line)+ "\nCol"+QString::number(column) ); return; } QDomElement root = doc.documentElement(); if(root.tagName()!="VisualCommand"){ QMessageBox::information( this, "Open Error", "Unable to find VisualCommand element.\n" ); return; } ui->tabWidget->clear(); Title = root.attribute("Title",""); this->AppName=root.attribute("AppName",""); this->AppWebsite=root.attribute("WebSite",""); this->Description=root.attribute("Description",""); if(root.attribute("Linux","")=="True") Linux=true; else Linux = false; if(root.attribute("Mac","")=="True") Mac=true; else Mac = false; if(root.attribute("Windows","")=="True") Windows=true; else Windows = false; QDomNode n = root.firstChild(); while(!n.isNull()){ QDomElement e = n.toElement(); if(!e.isNull()){ AddTab(e.attribute("Name")); int count = ui->tabWidget->count()-1; argTab* tab = dynamic_cast<argTab*>(ui->tabWidget->widget(count)); tab->AddWidgets(e,Arguments); } n=n.nextSibling(); } file.close(); ChangeText(); this->SwitchMode(true); } void MainWindow::RunCommand(){ QString process = "cmd /k "+ui->plainTextEditArgumentText->toPlainText(); QProcess myProcess; myProcess.startDetached(process); } void MainWindow::LaunchAbout(){ DialogAbout about; about.exec(); }
[ "flouger@13a168e0-7ae3-11de-a146-1f7e517e55b8" ]
[ [ [ 1, 380 ] ] ]
a9b7c03c5b42adb8cd71d11b8be09935e1c52978
e92a0b984f0798ef2bba9ad4199b431b4f5eb946
/2010/software/pc/webcam_processing.hpp
ef89b40afca8559b0c2a50e49aa7ec2beea9960f
[]
no_license
AdamdbUT/mac-gyver
c09c1892080bf77c25cb4ca2a7ebaf7be3459032
32de5c0989710ccd671d46e0babb602e51bf8ff9
refs/heads/master
2021-01-23T15:53:19.383860
2010-06-21T13:33:38
2010-06-21T13:33:38
42,737,082
0
0
null
null
null
null
UTF-8
C++
false
false
3,917
hpp
#ifndef __webcam_processing__ #define __webcam_processing__ #include "webcam_common.hpp" #include <stdexcept> struct seg_decomp_t { size_t x; size_t w; inline bool intersect(const seg_decomp_t& o) const { if(x<=o.x) return o.x<(x+w); else return x<(o.x+o.w); } }; struct v_block_decomp_t { size_t y;// first y std::vector<seg_decomp_t> seg;// list of starting x's and width', one for each y }; struct h_decomp_t { std::vector<v_block_decomp_t> blocks; }; struct rgb_color_t { uint8_t r,g,b; rgb_color_t():r(0),g(0),b(0){} rgb_color_t(uint8_t r,uint8_t g,uint8_t b):r(r),g(g),b(b){} }; struct rectangle_t { size_t x,y,w,h; size_t area() const { return w*h; } rectangle_t intersect(const rectangle_t& o) const { rectangle_t res; res.x=std::max(x,o.x); res.y=std::max(y,o.y); res.w=std::max(int(std::min(x+w,o.x+o.w))-int(res.x),0); res.h=std::max(int(std::min(y+h,o.y+o.h))-int(res.y),0); return res; } }; struct __pos_t { __pos_t():x(0),y(0){} __pos_t(size_t x,size_t y):x(x),y(y){} size_t x,y; }; struct hv_segment_t { __pos_t orig; __pos_t end; enum dir_t { up,down,left,right }; dir_t dir; size_t len; }; struct edge_detection_t { std::vector<hv_segment_t> left; std::vector<hv_segment_t> right; }; struct unproject_parameters_t { size_t screen_w; double half_fov; double object_radius; }; struct unproject_result_t { double x,y; }; typedef bool (*filter_func_t)(const image_t::pixel_type_t *pix); bool filter_black(const image_t::pixel_type_t *pix); bool filter_white(const image_t::pixel_type_t *pix); bool filter_red(const image_t::pixel_type_t *pix); bool filter_green(const image_t::pixel_type_t *pix); // do a rgb to yuv conversion bool convert_rgb_to_yuv(image_t& img); bool convert_rgb_to_yuv(image_t::pixel_type_t *pix); // the inverse bool convert_yuv_to_rgb(image_t& img); bool convert_yuv_to_rgb(image_t::pixel_type_t *pix); // do standard processing on a yuv image and gives the result as a rgb image bool process_image(image_t& img,filter_func_t fn,const rgb_color_t& res); // do an horizontal lines decomposition(also eliminates some artecfacts to keeps only relevant lines) bool do_h_decomposition(image_t& img,h_decomp_t& hld,const rgb_color_t& col); // take a block and extract a rectangle(if possible) from it // delta_h is the maximum difference of x's in a border [assume 0 difference in y because of vertical decomposition] // DONT CLEAR r ON CALL, this allow to filter against already found rectangles typedef bool (*rectangle_filter_t)(const rectangle_t& r); typedef void (*rectangle_comp_t)(const rectangle_t& r1,bool& keep1,const rectangle_t& r2,bool& keep2); bool extract_rectangles(const v_block_decomp_t& block,std::vector<rectangle_t>& r,size_t delta_x, rectangle_filter_t rf,rectangle_comp_t rc); edge_detection_t do_approx_edge_detection(const v_block_decomp_t& block,size_t h_tolerance,size_t min_w); // (low-level) do an horizontal line decomposition bool do_h_line_decomposition(const image_t& img,size_t y,const rgb_color_t& col,std::vector<seg_decomp_t>& res); // (high-level) std::vector<rectangle_t> detect_rectangles(image_t& img,filter_func_t fn,size_t tolerance=10); std::vector<rectangle_t> detect_rectangles2(image_t& img,filter_func_t fn,float min_density=0.75); unproject_result_t unproject(const rectangle_t& rect,const unproject_parameters_t& param); // determine whether a rectangle region a density of pixel that satisfied <fn> that is greater than <percent>% bool is_rectangle_of_color(const image_t& img,const rectangle_t& rect,filter_func_t fn,int percent); #endif // __processing__
[ [ [ 1, 2 ], [ 4, 4 ], [ 101, 102 ] ], [ [ 3, 3 ], [ 5, 100 ], [ 103, 139 ] ] ]
6f69376e3b9d1590327798b4b5ea3cfa84e03745
5f0b8d4a0817a46a9ae18a057a62c2442c0eb17e
/Include/border/BevelBorder.cpp
19f7f6c2734fc9acb38131ac8dc10e59d2b4ee1b
[ "BSD-3-Clause" ]
permissive
gui-works/ui
3327cfef7b9bbb596f2202b81f3fc9a32d5cbe2b
023faf07ff7f11aa7d35c7849b669d18f8911cc6
refs/heads/master
2020-07-18T00:46:37.172575
2009-11-18T22:05:25
2009-11-18T22:05:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,694
cpp
/* * Copyright (c) 2003-2006, Bram Stein * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "./BevelBorder.h" #include "../Graphics.h" #include "../util/Color.h" namespace ui { namespace border { BevelBorder::BevelBorder(int type) : raisedShadow(130,130,130), raisedHighlight(255,255,255), loweredShadow(130,130,130), loweredHighlight(180,180,180) { setType(type); } BevelBorder::BevelBorder() : raisedShadow(130,130,130), raisedHighlight(255,255,255), loweredShadow(130,130,130), loweredHighlight(180,180,180) { setType(RAISED); } BevelBorder::BevelBorder(const BevelBorder& rhs) : Border(static_cast<Border>(rhs)), isRaised(rhs.isRaised) { } BevelBorder& BevelBorder::operator=(const BevelBorder &rhs) { BevelBorder temp(rhs); swap(temp); return *this; } void BevelBorder::swap(BevelBorder& rhs) throw() { std::swap(isRaised,rhs.isRaised); } void BevelBorder::setType(int type) { isRaised = type; } int BevelBorder::getType() const { return isRaised; } void BevelBorder::paintBorder(const Component* component, Graphics& g, int x, int y, int w, int h) const { if(isRaised == RAISED) { paintRaisedBorder(g,x,y,w,h); } else if(isRaised == LOWERED) { paintLoweredBorder(g,x,y,w,h); } } void BevelBorder::paintLoweredBorder(Graphics& g,int x, int y, int w,int h) const { /** * Hard BevelBorder, without soft edges. */ // adjust for opengl y += 1; //w -= 1; //h -= 1; g.setPaint(&loweredShadow); g.drawRect(x,y,w-1,h-1); g.setPaint(&loweredHighlight); g.drawRect(x+1,y+1,w-1,h-1); } void BevelBorder::paintRaisedBorder(Graphics& g, int x, int y, int w, int h) const { /** * Hard BevelBorder, without soft edges. */ // adjust for opengl y += 1; //w -= 1; //h -= 1; g.setPaint(&raisedShadow); g.drawRect(x,y,w-1,h-1); g.setPaint(&raisedHighlight); g.drawRect(x+1,y+1,w-1,h-1); } const util::Insets BevelBorder::getBorderInsets() const { return util::Insets(2,2,2,2); } } }
[ "bs@bram.(none)" ]
[ [ [ 1, 134 ] ] ]
7e32c2bcc1c4e5ba54c7767cc8fa5329a1ff5ca4
b7c505dcef43c0675fd89d428e45f3c2850b124f
/Src/SimulatorQt/Util/qt/Win32/include/Qt/qboxlayout.h
f95fe68f0aa4d29d7d750a38e1cfa0479a1e8b28
[ "BSD-2-Clause" ]
permissive
pranet/bhuman2009fork
14e473bd6e5d30af9f1745311d689723bfc5cfdb
82c1bd4485ae24043aa720a3aa7cb3e605b1a329
refs/heads/master
2021-01-15T17:55:37.058289
2010-02-28T13:52:56
2010-02-28T13:52:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,793
h
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QBOXLAYOUT_H #define QBOXLAYOUT_H #include <QtGui/qlayout.h> #ifdef QT_INCLUDE_COMPAT #include <QtGui/qwidget.h> #endif #include <limits.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Gui) class QBoxLayoutPrivate; class Q_GUI_EXPORT QBoxLayout : public QLayout { Q_OBJECT Q_DECLARE_PRIVATE(QBoxLayout) public: enum Direction { LeftToRight, RightToLeft, TopToBottom, BottomToTop, Down = TopToBottom, Up = BottomToTop }; explicit QBoxLayout(Direction, QWidget *parent = 0); #ifdef QT3_SUPPORT QT3_SUPPORT_CONSTRUCTOR QBoxLayout(QWidget *parent, Direction, int border = 0, int spacing = -1, const char *name = 0); QT3_SUPPORT_CONSTRUCTOR QBoxLayout(QLayout *parentLayout, Direction, int spacing = -1, const char *name = 0); QT3_SUPPORT_CONSTRUCTOR QBoxLayout(Direction, int spacing, const char *name = 0); #endif ~QBoxLayout(); Direction direction() const; void setDirection(Direction); void addSpacing(int size); void addStretch(int stretch = 0); void addSpacerItem(QSpacerItem *spacerItem); void addWidget(QWidget *, int stretch = 0, Qt::Alignment alignment = 0); void addLayout(QLayout *layout, int stretch = 0); void addStrut(int); void addItem(QLayoutItem *); void insertSpacing(int index, int size); void insertStretch(int index, int stretch = 0); void insertSpacerItem(int index, QSpacerItem *spacerItem); void insertWidget(int index, QWidget *widget, int stretch = 0, Qt::Alignment alignment = 0); void insertLayout(int index, QLayout *layout, int stretch = 0); int spacing() const; void setSpacing(int spacing); bool setStretchFactor(QWidget *w, int stretch); bool setStretchFactor(QLayout *l, int stretch); void setStretch(int index, int stretch); int stretch(int index) const; QSize sizeHint() const; QSize minimumSize() const; QSize maximumSize() const; bool hasHeightForWidth() const; int heightForWidth(int) const; int minimumHeightForWidth(int) const; Qt::Orientations expandingDirections() const; void invalidate(); QLayoutItem *itemAt(int) const; QLayoutItem *takeAt(int); int count() const; void setGeometry(const QRect&); #ifdef QT3_SUPPORT inline QT3_SUPPORT int findWidget(QWidget* w) {return indexOf(w);} #endif protected: // ### Qt 5: make public void insertItem(int index, QLayoutItem *); private: Q_DISABLE_COPY(QBoxLayout) }; class Q_GUI_EXPORT QHBoxLayout : public QBoxLayout { Q_OBJECT public: QHBoxLayout(); explicit QHBoxLayout(QWidget *parent); ~QHBoxLayout(); #ifdef QT3_SUPPORT QT3_SUPPORT_CONSTRUCTOR QHBoxLayout(QWidget *parent, int border, int spacing = -1, const char *name = 0); QT3_SUPPORT_CONSTRUCTOR QHBoxLayout(QLayout *parentLayout, int spacing = -1, const char *name = 0); QT3_SUPPORT_CONSTRUCTOR QHBoxLayout(int spacing, const char *name = 0); #endif private: Q_DISABLE_COPY(QHBoxLayout) }; class Q_GUI_EXPORT QVBoxLayout : public QBoxLayout { Q_OBJECT public: QVBoxLayout(); explicit QVBoxLayout(QWidget *parent); ~QVBoxLayout(); #ifdef QT3_SUPPORT QT3_SUPPORT_CONSTRUCTOR QVBoxLayout(QWidget *parent, int border, int spacing = -1, const char *name = 0); QT3_SUPPORT_CONSTRUCTOR QVBoxLayout(QLayout *parentLayout, int spacing = -1, const char *name = 0); QT3_SUPPORT_CONSTRUCTOR QVBoxLayout(int spacing, const char *name = 0); #endif private: Q_DISABLE_COPY(QVBoxLayout) }; QT_END_NAMESPACE QT_END_HEADER #endif // QBOXLAYOUT_H
[ "alon@rogue.(none)" ]
[ [ [ 1, 173 ] ] ]
8d675b8e7f7ed474bd426cc77f2b22e315232d04
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/_Common/PCBang.h
79fe9d6900e31e1f64c6fb886aa0fcf09c25ee94
[]
no_license
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UHC
C++
false
false
2,851
h
// PCBang.h: interface for the CPCBang class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_PCBANG_H__DD46F01A_2342_4D10_9A65_C6F56352353C__INCLUDED_) #define AFX_PCBANG_H__DD46F01A_2342_4D10_9A65_C6F56352353C__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #if __VER >= 14 // __PCBANG #ifdef __WORLDSERVER #include "User.h" #endif // __WORLDSERVER class CPCBangInfo { #ifdef __WORLDSERVER public: CPCBangInfo( DWORD dwPCBangClass, DWORD dwConnectTime ); ~CPCBangInfo(); void SetDisconnect( DWORD dwTime ) { m_dwDisconnectTime = dwTime; } BOOL ProcessRemove( DWORD dwPlayerId ); void UpdateInfo(); private: DWORD m_dwUnitTime; DWORD m_dwDisconnectTime; #endif // __WORLDSERVER public: DWORD GetPCBangClass() { return m_dwPCBangClass; } float GetExpFactor() { return m_fExpFactor; } float GetPieceItemDropFactor() { return m_fPieceItemDropFactor; } DWORD GetUnitTime() { return (g_tmCurrent - m_dwConnectTime)/MIN(60); } void Serialize( CAr & ar ); #ifdef __CLIENT CPCBangInfo(); ~CPCBangInfo(); static CPCBangInfo* GetInstance(); DWORD GetConnectTime() { return (g_tmCurrent - m_dwConnectTime)/SEC(1); } #endif // __CLIENT private: DWORD m_dwPCBangClass; DWORD m_dwConnectTime; float m_fExpFactor; float m_fPieceItemDropFactor; }; #ifdef __WORLDSERVER typedef map<DWORD, CPCBangInfo> MAPPBI; class CPCBang { public: CPCBang(); ~CPCBang(); static CPCBang* GetInstance(); BOOL LoadScript(); void SetPCBangPlayer( CUser* pUser, DWORD dwPCBangClass ); // PC방 유저를 목록에 추가한다. void DestroyPCBangPlayer( DWORD dwPlayerId ); // 접속해제 시간을 저장한다. DWORD GetPCBangClass( DWORD dwPlayerId ); void ProcessPCBang(); // 접속 해제 후 10분이 경과된 유저를 초기화 한다. float GetExpInfo( DWORD dwHour ); float GetExpFactor( CUser* pUser ); // 증가될 경험치를 얻어온다. float GetPartyExpFactor( CUser* apUser[], int nMemberSize ); float GetPieceItemDropInfo( DWORD dwHour ); float GetPieceItemDropFactor( CUser* pUser ); // 증가될 아이템 드롭률을 가져온다. void SetApply( BOOL bApply ); BOOL IsApply() { return m_bApply; } private: CPCBangInfo* GetPCBangInfo( DWORD dwPlayerId ); // PC방 유저인가? int GetPlayTime( DWORD dwConnectTime ) { return ( g_tmCurrent - dwConnectTime ) / MIN(60); } // 접속이후 총 플레이 시간 MAPPBI m_mapPCBang; // PC방 사용자 정보 vector<float> m_vecfExp; // 시간대별 경험치 vector<float> m_vecfDropRate; // 시간대별 아이템 드롭률 BOOL m_bApply; }; #endif // __WORLDSERVER #endif // __PCBANG #endif // !defined(AFX_PCBANG_H__DD46F01A_2342_4D10_9A65_C6F56352353C__INCLUDED_)
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 89 ] ] ]
7f3ed5b38d3e1cf5c9b28ab3e0c9b32f43d9c5e6
9fb229975cc6bd01eb38c3e96849d0c36985fa1e
/src/Lib3D2/Sort.h
bd8a366104a2dce34a96954081167fa02d6e0403
[]
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
769
h
#ifndef _SORT_H_ #define _SORT_H_ #include "Constants.h" #include "Face.h" #define MAX_SORT_COUNT 1024 // max sort polys by objects namespace Lib3D { class CBoard3D; // --------------------------------------------------------------------------- class CFSort { enum { YROW_COUNT = (FAR_CLIP_MAX * -3)>>2 // use z1+z2+z3 >> 2 sort test }; CFSort(); public: void SortFace(TFace *F); void DrawSortedList(CBoard3D&,bool envmap); // use this method if mixed type of faces are sorted (opaque + alpha) private: int Min, Max; // hach table scan range TFace* RowEntry[YROW_COUNT]; // hach table entry count }; }//namepsace #endif // _SORT_H_
[ "jakesoul@c957e3ca-5ece-11de-8832-3f4c773c73ae" ]
[ [ [ 1, 37 ] ] ]
d1486d3ab44eddfd883baa3e854434a37a895a9e
56c82f6336a2b4a4d5239a0fa677f9dde35fb853
/node.hpp
14556848c10273c2accfba2d8af4507c746a98e8
[]
no_license
aligusnet/trees
409ea75f7f7460857f9de9b87b57249fd620b0cd
258c9ffe1d3c58e5d01b75ed5d1c7134a0c429d4
refs/heads/master
2021-05-27T18:35:17.011155
2010-07-04T23:00:02
2010-07-04T23:00:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
269
hpp
#pragma once //Node template <typename T> struct Node { T data; Node *next; }; template <typename T> Node<T> *node_new() { Node<T> *node = new Node<T>(); return node; } template <typename T> void node_free(Node<T> *node) { delete node; }
[ [ [ 1, 21 ] ] ]
7246d2caa85823ca7353edeabcb69c500c15169c
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/serialization/nvp.hpp
9e220bd30df41f9a50e8cd5822ee32f84e92409b
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
4,621
hpp
#ifndef BOOST_SERIALIZATION_NVP_HPP #define BOOST_SERIALIZATION_NVP_HPP // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once #endif /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // nvp.hpp: interface for serialization system. // (C) Copyright 2002 Robert Ramey - http://www.rrsd.com . // 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 http://www.boost.org for updates, documentation, and revision history. #include <utility> #include <boost/config.hpp> #include <boost/detail/workaround.hpp> // supress noise #if BOOST_WORKAROUND(BOOST_MSVC, <= 1200) # pragma warning (disable : 4786) // too long name, harmless warning #endif #include <boost/mpl/integral_c.hpp> #include <boost/mpl/integral_c_tag.hpp> #include <boost/serialization/level.hpp> #include <boost/serialization/tracking.hpp> #include <boost/serialization/split_member.hpp> #include <boost/serialization/base_object.hpp> #include <boost/serialization/traits.hpp> namespace boost { namespace serialization { template<class T> struct nvp : public std::pair<const char *, T *>, public traits<nvp<T>, object_serializable, track_never> { explicit nvp(const char * name, T & t) : // note: redundant cast works around borland issue std::pair<const char *, T *>(name, (T*)(& t)) {} nvp(const nvp & rhs) : // note: redundant cast works around borland issue std::pair<const char *, T *>(rhs.first, (T*)rhs.second) {} const char * name() const { return this->first; } T & value() const { return *(this->second); } const T & const_value() const { return *(this->second); } // True64 compiler complains with a warning about the use of // the name "Archive" hiding some higher level usage. I'm sure this // is an error but I want to accomodated as it generates a long warning // listing and might be related to a lot of test failures. // default treatment for name-value pairs. The name is // just discarded and only the value is serialized. template<class Archivex> void save( Archivex & ar, const unsigned int /* file_version */ ) const { // CodeWarrior 8.x can't seem to resolve the << op for a rhs of "const T *" ar.operator<<(const_value()); } template<class Archivex> void load( Archivex & ar, const unsigned int /* file_version */ ){ // CodeWarrior 8.x can't seem to resolve the >> op for a rhs of "const T *" ar.operator>>(value()); } BOOST_SERIALIZATION_SPLIT_MEMBER() }; template<class T> inline #ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING const #endif nvp<T> make_nvp(const char * name, T & t){ return nvp<T>(name, t); } // to maintain efficiency and portability, we want to assign // specific serialization traits to all instances of this wrappers. // we can't strait forward method below as it depends upon // Partial Template Specialization and doing so would mean that wrappers // wouldn't be treated the same on different platforms. This would // break archive portability. Leave this here as reminder not to use it !!! #if 0 // #ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION template <class T> struct implementation_level<nvp<T> > { typedef mpl::integral_c_tag tag; typedef mpl::int_<object_serializable> type; BOOST_STATIC_CONSTANT(int, value = implementation_level::type::value); }; // nvp objects are generally created on the stack and are never tracked template<class T> struct tracking_level<nvp<T> > { typedef mpl::integral_c_tag tag; typedef mpl::int_<track_never> type; BOOST_STATIC_CONSTANT(int, value = tracking_level::type::value); }; #endif } // seralization } // boost #include <boost/preprocessor/stringize.hpp> #define BOOST_SERIALIZATION_NVP(name) \ boost::serialization::make_nvp(BOOST_PP_STRINGIZE(name), name) /**/ #define BOOST_SERIALIZATION_BASE_OBJECT_NVP(name) \ boost::serialization::make_nvp( \ BOOST_PP_STRINGIZE(name), \ boost::serialization::base_object<name >(*this) \ ) /**/ #endif // BOOST_SERIALIZATION_NVP_HPP
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 142 ] ] ]
b5c9c5f5c4a77865cd95a38740a4a95ffc53a1fe
0ee189afe953dc99825f55232cd52b94d2884a85
/mstd/threads.hpp
fc2e3df7bf75666fd86f7d605bb2cd6ac61f7f3d
[]
no_license
spolitov/lib
fed99fa046b84b575acc61919d4ef301daeed857
7dee91505a37a739c8568fdc597eebf1b3796cf9
refs/heads/master
2016-09-11T02:04:49.852151
2011-08-11T18:00:44
2011-08-11T18:00:44
2,192,752
0
0
null
null
null
null
UTF-8
C++
false
false
314
hpp
#pragma once #include "config.hpp" namespace mstd { #if defined(_MSC_VER) typedef unsigned long thread_id; #elif defined(__APPLE__) typedef size_t thread_id; #else typedef unsigned long int thread_id; #endif MSTD_DECL thread_id this_thread_id(); MSTD_DECL size_t count_process_threads(); }
[ [ [ 1, 18 ] ] ]
b4b2b9ea7d61d6c1d6338a87bb62ef85aa1128de
9f2d447c69e3e86ea8fd8f26842f8402ee456fb7
/shooting2011/shooting2011/hero.cpp
3f14cba271a189231216fd31035ff1444692778c
[]
no_license
nakao5924/projectShooting2011
f086e7efba757954e785179af76503a73e59d6aa
cad0949632cff782f37fe953c149f2b53abd706d
refs/heads/master
2021-01-01T18:41:44.855790
2011-11-07T11:33:44
2011-11-07T11:33:44
2,490,410
0
1
null
null
null
null
UTF-8
C++
false
false
2,155
cpp
#include "main.h" #include "hero.h" #include "movePattern.h" #include "firePattern.h" #include "graphicPattern.h" Hero::Hero(int _heroId, int dir){ if (_heroId == 0) hitRect = Rect( STAGE_WIDTH/2, STAGE_HEIGHT/2 - 64, 8, 8); if (_heroId == 1) hitRect = Rect( STAGE_WIDTH/2 + 64, STAGE_HEIGHT/2, 8, 8); if (_heroId == 2) hitRect = Rect( STAGE_WIDTH/2, STAGE_HEIGHT/2 + 64, 8, 8); if (_heroId == 3) hitRect = Rect( STAGE_WIDTH/2 -64, STAGE_HEIGHT/2, 8, 8); movePattern = new MovePatternHero(_heroId); //createFirePattern start/////////////////////////////////////////////////// firePattern=new FirePatternHero(5, _heroId, dir); //createFirePattern end///////////////////////////////////////////////////// string str="hero"; stringstream ss; ss<<str<<_heroId; ss>>str; this->graPattern=new GraphicPattern(str); heroId = _heroId; direction = 0; // fireWait = 0; } void Hero::add_delta(){ hitRect.x+=delta_x; hitRect.y+=delta_y; } Hero::~Hero(){ //delete movePattern; } void Hero::setDirection( int dir){ direction = dir; //firePattern=new FirePatternHero(5, _heroId, dir); FirePatternHero *temp = dynamic_cast<FirePatternHero *>(firePattern); if(temp != NULL){ temp -> setDirection(dir); } const static string direction[4] = {"up", "right", "down", "left"}; string str="hero"; stringstream ss; ss<<str<<heroId; ss<<direction[dir]<<"32"; ss>>str; this->graPattern=new GraphicPattern(str); } int Hero::getHeroId(){ return heroId; } void Hero::absorbDamage( int damage){ changeStatus( EXPLOSION); } void Hero::statusShift(){ if (status == VALID){ } else if (status == EXPLOSION){ if (frameCount > 104){ changeStatus( REBIRTH); } } else if (status == REBIRTH){ if (frameCount > 60){ changeStatus( VALID); } } } /* bool Hero::fire(){ // if( fireWait == 0 && CheckHitKey( KEY_INPUT_Z) == 1){ if( CheckHitKey( KEY_INPUT_Z) == 1){ // fireWait = 8; return true; } else{ return false; } } */ /* void Hero::transitionState(){ if( fireWait>0) fireWait--; } */
[ "[email protected]", "[email protected]", "tianyao@tianyao-PC.(none)", "[email protected]", "[email protected]" ]
[ [ [ 1, 5 ], [ 11, 11 ], [ 13, 13 ], [ 25, 26 ], [ 31, 32 ], [ 34, 35 ], [ 54, 63 ], [ 65, 67 ], [ 69, 72 ] ], [ [ 6, 10 ], [ 15, 15 ], [ 24, 24 ], [ 27, 30 ], [ 36, 53 ] ], [ [ 12, 12 ] ], [ [ 14, 14 ], [ 16, 23 ], [ 33, 33 ], [ 73, 91 ] ], [ [ 64, 64 ], [ 68, 68 ] ] ]
4b6ba50753f2036ca341a9d3f3219bb607e69983
33c05b9c833fc1b7f6807a05e94338eed6479131
/src/ProgressBar.h
94549f8ccc035cc30bbb45c8e1c84e974e816979
[]
no_license
tea/wxcocoadialog
dd9ebcc150cc7fc2556c81cc2d1c1d143d022793
6c9b4c6925c06dbe1147f2e36e5616c8b8b20cb4
refs/heads/master
2021-01-22T17:57:34.485520
2009-04-11T16:42:51
2009-04-11T16:42:51
173,613
2
0
null
null
null
null
UTF-8
C++
false
false
747
h
#ifndef __PROGRESSBAR_H__ #define __PROGRESSBAR_H__ #include "OptionDict.h" class ProgressBar : public wxDialog { public: ProgressBar(wxWindow* parent, const OptionDict& options, bool doFloat); private: // Event handlers void OnClose(wxCloseEvent& event); void OnLineRead(wxCommandEvent& event); void OnCancel(wxCommandEvent& event); DECLARE_EVENT_TABLE() class LineReaderThread : public wxThread { public: LineReaderThread(wxEvtHandler& evtHandler); virtual void *Entry(); private: wxEvtHandler& m_evtHandler; }; // Member variables const OptionDict& m_options; // Member controls wxSizer* m_mainSizer; wxStaticText* m_infoText; wxGauge* m_progressBar; }; #endif //__PROGRESSBAR_H__
[ "gcheshire@d5ffba82-4729-0410-9773-73ad8f2cc4c7", "astigsen@d5ffba82-4729-0410-9773-73ad8f2cc4c7" ]
[ [ [ 1, 7 ], [ 9, 11 ], [ 13, 34 ] ], [ [ 8, 8 ], [ 12, 12 ] ] ]
ea52691170236802fd99c74e2e0d9f32baad4a5a
a1117d878cdcbd2756512ce29ad4dfd2b5709dac
/OneSnap/SnapperOptions.cpp
ced73702ebb9078b94109d1a3bbf083bae6fe9f1
[]
no_license
nicklepede/onesnap
e423f6565fcc557af10618dc74bcaa941057f1d9
95631cb208721c97e74488d4633afaf6f63e5c00
refs/heads/master
2021-01-13T01:48:01.401096
2006-06-27T16:30:12
2006-06-27T16:30:12
102,732
1
0
null
null
null
null
UTF-8
C++
false
false
8,987
cpp
// SnapperOptions.cpp : implementation file // #include "stdafx.h" #include "OneSnap.h" #include "SnapperOptions.h" #include "SnapperConfig.h" // CSnapperOptions dialog IMPLEMENT_DYNAMIC(CSnapperOptions, CDialog) CSnapperOptions::CSnapperOptions(CWnd* pParent /*=NULL*/) : CDialog(CSnapperOptions::IDD, pParent) , m_strNotebookPath(_T("")) , m_strConfigPath(_T("")) , m_bBackground(FALSE) , m_bNavigateToPage(FALSE) , m_bUpdateHotlists(FALSE) , m_bLimitPageWidth(FALSE) , m_bIncludeShares(FALSE) , m_fMaxWidth(0) , m_bKeepSynced(FALSE) { } CSnapperOptions::~CSnapperOptions() { } void CSnapperOptions::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Text(pDX, IDED_NOTEBOOK_PATH, m_strNotebookPath); DDX_Text(pDX, IDED_CONFIG_PATH, m_strConfigPath); DDX_Check(pDX, IDCHK_BACKGROUND, m_bBackground); DDX_Check(pDX, IDCHK_NAVIGATE, m_bNavigateToPage); DDX_Check(pDX, IDCHK_UPHOT, m_bUpdateHotlists); DDX_Check(pDX, IDCHK_LIMIT_WIDTH, m_bLimitPageWidth); DDX_Check(pDX, IDCHK_INCSHARES, m_bIncludeShares); DDX_Control(pDX, IDS_WIDTH, m_sdrMaxWidth); DDX_Text(pDX, IDED_MAXWIDTH, m_fMaxWidth); DDX_Control(pDX, IDED_MAXWIDTH, m_edMaxWidth); DDX_Control(pDX, IDED_6INCH, m_edMaxWidthMin); DDX_Control(pDX, IDED_36INCH, m_edMaxWidthMax); DDX_Check(pDX, IDC_AUTOSYNC, m_bKeepSynced); } BEGIN_MESSAGE_MAP(CSnapperOptions, CDialog) ON_BN_CLICKED(IDBT_BROWSE_NOTEBOOK, &CSnapperOptions::OnBnClickedBrowseNotebook) ON_BN_CLICKED(IDBT_BROWSE_CONFIG, &CSnapperOptions::OnBnClickedBrowseConfig) ON_EN_CHANGE(IDED_CONFIG_PATH, &CSnapperOptions::OnEnChangeConfigPath) ON_BN_CLICKED(IDOK, &CSnapperOptions::OnBnClickedOk) ON_BN_CLICKED(IDC_UPDATE, &CSnapperOptions::OnBnClickedUpdate) ON_EN_CHANGE(IDED_NOTEBOOK_PATH, &CSnapperOptions::OnEnChangeNotebookPath) ON_BN_CLICKED(IDAPPLY, &CSnapperOptions::OnBnClickedApply) ON_BN_CLICKED(IDCHK_INCSHARES, &CSnapperOptions::OnBnClickedIncshares) ON_NOTIFY(NM_CUSTOMDRAW, IDS_WIDTH, &CSnapperOptions::OnNMCustomdrawWidth) ON_BN_CLICKED(IDCHK_LIMIT_WIDTH, &CSnapperOptions::OnBnClickedLimitWidth) ON_EN_CHANGE(IDED_MAXWIDTH, &CSnapperOptions::OnEnChangeMaxwidth) ON_BN_CLICKED(IDC_ADVANCED, &CSnapperOptions::OnBnClickedAdvanced) ON_BN_CLICKED(IDC_AUTOSYNC, &CSnapperOptions::OnBnClickedKeepSynced) END_MESSAGE_MAP() INT_PTR CSnapperOptions::DoModalEx(CSnapperConfig* pCfg) { ASSERT(pCfg != NULL); m_pCfg = pCfg; INT_PTR ret = DoModal(); m_pCfg = NULL; return ret; } void CSnapperOptions::InitDialog() { ASSERT(m_pCfg != NULL); m_strNotebookPath = m_pCfg->GetNotebookPath(); m_strConfigPath = m_pCfg->GetConfigFilePath(); m_bBackground = m_pCfg->GetImportAsBackground(); m_bNavigateToPage = m_pCfg->GetNavigateToPage(); m_bLimitPageWidth = m_pCfg->GetLimitPageWidth(); m_bIncludeShares = m_pCfg->GetIncludeSharedNotebooks(); m_bKeepSynced = m_pCfg->GetAutoSync(); m_fMaxWidth = m_pCfg->GetMaxPageWidth(); m_edMaxWidthMin.SetWindowTextW(L"6\""); m_edMaxWidthMax.SetWindowTextW(L"36\""); m_sdrMaxWidth.SetRange(60, 360, FALSE); m_sdrMaxWidth.SetPos((int) (m_fMaxWidth * 10)); m_sdrMaxWidth.EnableWindow(m_bLimitPageWidth); m_edMaxWidth.EnableWindow(m_bLimitPageWidth); m_edMaxWidthMin.EnableWindow(m_bLimitPageWidth); m_edMaxWidthMax.EnableWindow(m_bLimitPageWidth); } void CSnapperOptions::InitToolTips() { m_ctrlToolTips.Create(this); CWnd* pwndChild = GetWindow(GW_CHILD); CString strToolTip; while (pwndChild) { int idCtrl = pwndChild->GetDlgCtrlID(); if (strToolTip.LoadString(idCtrl)) { m_ctrlToolTips.AddTool(pwndChild, strToolTip); } pwndChild = pwndChild->GetWindow(GW_HWNDNEXT); } m_ctrlToolTips.Activate(TRUE); } BOOL CSnapperOptions::OnInitDialog() { CDialog::OnInitDialog(); InitToolTips(); InitDialog(); return TRUE; } // CSnapperOptions message handlers void CSnapperOptions::OnBnClickedBrowseNotebook() { BROWSEINFO sBi = { 0 }; /* sBi.lpszTitle = TEXT("Select Notebook(s)"); sBi.hwndOwner = m_hWndTop; sBi.iImage = */ LPITEMIDLIST pIdl = SHBrowseForFolder ( &sBi ); if ( pIdl != NULL ) { // get the name of the folder TCHAR pszNotebookPath[MAX_PATH]; if ( SHGetPathFromIDList ( pIdl, pszNotebookPath ) ) { m_strNotebookPath = pszNotebookPath; m_bUpdateHotlists = TRUE; UpdateData(FALSE); } // free memory IMalloc * piMalloc = NULL; if ( SUCCEEDED( SHGetMalloc ( &piMalloc )) ) { piMalloc->Free ( pIdl ); piMalloc->Release ( ); } } } void CSnapperOptions::OnBnClickedBrowseConfig() { CFileDialog dlgConfigFile(TRUE, TEXT("xml"), m_strConfigPath/*TEXT("OneSnap.xml")*/, OFN_CREATEPROMPT | OFN_HIDEREADONLY, TEXT("XML Files (*.xml)|*.xml|All Files (*.*)|*.*||")); if (IDOK == dlgConfigFile.DoModal()) { m_strConfigPath = dlgConfigFile.GetPathName(); UpdateData(FALSE); } // strFilepath.ReleaseBuffer(); } void CSnapperOptions::OnEnChangeConfigPath() { } void CSnapperOptions::OnBnClickedOk() { UpdateConfig(); OnOK(); } void CSnapperOptions::UpdateConfig(BOOL bFollowNetworkPaths /* = FALSE */) { UpdateData(TRUE); m_pCfg->SetConfigFilePath(m_strConfigPath); m_pCfg->SetNotebookPath(m_strNotebookPath); m_pCfg->SetIncludeSharedNotebooks(m_bIncludeShares); m_pCfg->SetAutoSync(m_bKeepSynced); if (m_bUpdateHotlists) { BeginWaitCursor(); m_pCfg->UpdateHotlists(bFollowNetworkPaths); m_bUpdateHotlists = FALSE; EndWaitCursor(); } m_pCfg->SetImportAsBackground(m_bBackground); m_pCfg->SetNavigateToPage(m_bNavigateToPage); m_pCfg->SetLimitPageWidth(m_bLimitPageWidth); m_pCfg->SetMaxPageWidth(m_fMaxWidth); m_pCfg->Save(); } void CSnapperOptions::OnBnClickedUpdate() { UpdateData(TRUE); m_bUpdateHotlists = TRUE; UpdateData(FALSE); // if we've enabled shortcuts then warn the user it may take a while... if (m_bIncludeShares) MessageBox(_T("This may take a minute if any shortcuts point to inaccessible folders/sections."), _T("Starting Update")); // update the folder/section lists, following network paths. UpdateConfig(TRUE); // just in case we've loaded a new config file... InitDialog(); UpdateData(FALSE); MessageBox(_T("Folder/section lists updated to match Notebook."), _T("Updated!")); } void CSnapperOptions::OnEnChangeNotebookPath() { UpdateData(TRUE); m_bUpdateHotlists = TRUE; UpdateData(FALSE); } void CSnapperOptions::OnBnClickedApply() { UpdateConfig(); InitDialog(); UpdateData(FALSE); } void CSnapperOptions::OnBnClickedIncshares() { UpdateData(TRUE); m_bUpdateHotlists = TRUE; if (m_bKeepSynced && m_bIncludeShares) WarnAutoSync(); UpdateData(FALSE); } void CSnapperOptions::WarnAutoSync() { MessageBox(_T("When 'auto-syncing' OneSnap will not update shortcuts to remote folders/sections. To update remote shortcuts you'll need to click 'Synchronize Now'."), _T("FYI"), MB_OK | MB_ICONWARNING ); } void CSnapperOptions::OnNMCustomdrawWidth(NMHDR *pNMHDR, LRESULT *pResult) { LPNMCUSTOMDRAW pNMCD = reinterpret_cast<LPNMCUSTOMDRAW>(pNMHDR); m_fMaxWidth = ((float) m_sdrMaxWidth.GetPos()) / 10.0f; CString strWidth; UpdateData(FALSE); *pResult = 0; } void CSnapperOptions::OnBnClickedLimitWidth() { UpdateData(TRUE); m_sdrMaxWidth.EnableWindow(m_bLimitPageWidth); m_edMaxWidth.EnableWindow(m_bLimitPageWidth); m_edMaxWidthMin.EnableWindow(m_bLimitPageWidth); m_edMaxWidthMax.EnableWindow(m_bLimitPageWidth); } void CSnapperOptions::OnEnChangeMaxwidth() { UpdateData(TRUE); int iWidth = ((int) (m_fMaxWidth * 10)); /* m_edMaxWidth.GetWindowText(strWidth); float fWidth = _tstof( strVal ); int iWidth = ((int) (fWidth * 10); */ m_sdrMaxWidth.SetPos(iWidth); } // overloaded PreTranslateMessage to handle tooltips BOOL CSnapperOptions::PreTranslateMessage(MSG *pMsg) { m_ctrlToolTips.RelayEvent(pMsg); return CDialog::PreTranslateMessage(pMsg); } void CSnapperOptions::OnBnClickedAdvanced() { // Open the OneSnap file that came w/ the plugin... // should be at <program files>\OneSnap\OneSnap.one CString strPath; // get the Program Files directory... if (!SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL, 0, strPath.GetBuffer(MAX_PATH)))) if (0 == ExpandEnvironmentStrings(L"%ProgramFiles%\\", strPath.GetBuffer(MAX_PATH), MAX_PATH)) strPath = L"C:\\Program Files\\"; // add the filename... strPath += "\\OneSnap\\OneSnap.one"; ShellExecute(NULL, L"open", L"C:\\Program Files\\OneSnap\\OneSnap.one", NULL, NULL, SW_SHOWNORMAL); } void CSnapperOptions::OnBnClickedKeepSynced() { UpdateData(TRUE); if (m_bKeepSynced && m_bIncludeShares) WarnAutoSync(); m_bUpdateHotlists = TRUE; UpdateData(FALSE); }
[ "nicklepede@2c095272-fa16-0410-abf3-d1f1c5240653" ]
[ [ [ 1, 321 ] ] ]
ebf4cfafd7733513a027c0a78190de3d45c68059
8db1c2a445f0fcb22a7cfcef9b8328b83c15bcfa
/src/Source/JSpotify/JAlbum.cpp
539840bc66a2cff956fbb6b62f6b63011685f21d
[ "Apache-2.0" ]
permissive
ngattusohw/jlibspotify
5b069fc77f8caf716dfc222d5689895d6cd02d3a
3fb825a1bc01b83e4ef52837ebe39b4b691856f9
refs/heads/master
2020-04-06T03:35:08.240919
2011-08-29T12:40:01
2011-08-29T12:40:01
40,991,877
2
0
null
null
null
null
UTF-8
C++
false
false
2,620
cpp
/* * Copyright 2011 Jim Knowler * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "JAlbum.h" #include "JImage.h" #include "JUtils.h" #include "JSession.h" #include "Spotify/Spotify_Album.h" Spotify::JAlbum* GetAlbumNativePtr( JNIEnv* env, jobject object ) { jclass cls = env->FindClass("Spotify/Album"); jfieldID fid = env->GetFieldID( cls, "m_nativePtr", "I" ); int nativePtr = env->GetIntField( object, fid ); Spotify::JAlbum* pAlbum = reinterpret_cast<Spotify::JAlbum*>( Spotify::NativePtrToPointer( nativePtr ) ); return pAlbum; } JNIEXPORT jstring JNICALL Java_Spotify_Album_GetName (JNIEnv *env, jobject object) { JSESSION_VALIDATE_THREAD(); Spotify::JAlbum* pAlbum = GetAlbumNativePtr( env, object ); jstring jstr = env->NewStringUTF( pAlbum->GetName().c_str() ); return jstr; } JNIEXPORT jboolean JNICALL Java_Spotify_Album_IsLoading (JNIEnv *env, jobject object) { JSESSION_VALIDATE_THREAD(); Spotify::JAlbum* pAlbum = GetAlbumNativePtr( env, object ); return pAlbum->IsLoading(); } JNIEXPORT jobject JNICALL Java_Spotify_Album_GetImage (JNIEnv *env, jobject object) { JSESSION_VALIDATE_THREAD(); Spotify::JAlbum* pAlbum = GetAlbumNativePtr( env, object ); Spotify::JImage* pImage = static_cast<Spotify::JImage*>( pAlbum->GetImage() ); if (pImage == NULL) { return NULL; } jclass cls = env->FindClass( "Spotify/Image" ); jmethodID cid = env->GetMethodID( cls, "<init>", "(I)V"); jobject javaObject = env->NewObject( cls, cid, PointerToNativePtr(pImage) ); return javaObject; } JNIEXPORT void JNICALL Java_Spotify_Album_Release (JNIEnv *env, jobject object) { Spotify::JAlbum* pAlbum = GetAlbumNativePtr( env, object ); pAlbum->ThreadSafeRelease(); jclass cls = env->FindClass("Spotify/Album"); jfieldID fid = env->GetFieldID( cls, "m_nativePtr", "I" ); env->SetIntField( object, fid, 0 ); } namespace Spotify { void JAlbum::ThreadSafeRelease() { static_cast<JSession*>(m_pSession)->ThreadSafeRelease( this ); } }
[ [ [ 1, 98 ] ] ]
5076e91a5318b3f866197252e89bd7300bece601
e53e3f6fac0340ae0435c8e60d15d763704ef7ec
/WDL/lice/lice_combine.h
965264e4e8171921f50ced15ad33ff816d3453e3
[]
no_license
b-vesco/vfx-wdl
906a69f647938b60387d8966f232a03ce5b87e5f
ee644f752e2174be2fefe43275aec2979f0baaec
refs/heads/master
2020-05-30T21:37:06.356326
2011-01-04T08:54:45
2011-01-04T08:54:45
848,136
2
0
null
null
null
null
UTF-8
C++
false
false
26,880
h
#ifndef _LICE_COMBINE_H_ #define _LICE_COMBINE_H_ #if defined(_MSC_VER) #pragma warning(disable:4244) // float-to-int #endif #define __LICE_BOUND(x,lo,hi) ((x)<(lo)?(lo):((x)>(hi)?(hi):(x))) #define LICE_PIXEL_HALF(x) (((x)>>1)&0x7F7F7F7F) #define LICE_PIXEL_QUARTER(x) (((x)>>2)&0x3F3F3F3F) #define LICE_PIXEL_EIGHTH(x) (((x)>>3)&0x1F1F1F1F) #if defined(_MSC_VER) && !defined(_WIN64) static inline int __LICE_TOINT(double x) // don't use this _everywhere_ since it doesnt round the same as (int) { int tmp; __asm { fld x fistp tmp }; return tmp; } #else #define __LICE_TOINT(x) ((int)(x)) #endif static inline void __LICE_BilinearFilterI(int *r, int *g, int *b, int *a, LICE_pixel_chan *pin, LICE_pixel_chan *pinnext, int xfrac, int yfrac) { int f4=((unsigned int)xfrac*(unsigned int)yfrac)/65536; int f3=yfrac-f4; // (1.0-xfrac)*yfrac; int f2=xfrac-f4; // xfrac*(1.0-yfrac); int f1=65536-yfrac-f2; // (1.0-xfrac)*(1.0-yfrac); #define DOCHAN(output, inchan) \ (output)=(pin[(inchan)]*f1 + pin[4+(inchan)]*f2 + pinnext[(inchan)]*f3 + pinnext[4+(inchan)]*f4)/65536; DOCHAN(*r,LICE_PIXEL_R) DOCHAN(*g,LICE_PIXEL_G) DOCHAN(*b,LICE_PIXEL_B) DOCHAN(*a,LICE_PIXEL_A) #undef DOCHAN } static inline void __LICE_BilinearFilterIPixOut(LICE_pixel_chan *out, LICE_pixel_chan *pin, LICE_pixel_chan *pinnext, int xfrac, int yfrac) { int f4=((unsigned int)xfrac*(unsigned int)yfrac)/65536; int f3=yfrac-f4; // (1.0-xfrac)*yfrac; int f2=xfrac-f4; // xfrac*(1.0-yfrac); int f1=65536-yfrac-f2; // (1.0-xfrac)*(1.0-yfrac); #define DOCHAN(inchan) \ (out[inchan])=(pin[(inchan)]*f1 + pin[4+(inchan)]*f2 + pinnext[(inchan)]*f3 + pinnext[4+(inchan)]*f4)/65536; DOCHAN(LICE_PIXEL_R) DOCHAN(LICE_PIXEL_G) DOCHAN(LICE_PIXEL_B) DOCHAN(LICE_PIXEL_A) #undef DOCHAN } static inline void __LICE_BilinearFilterI_2(int *r, int *g, int *b, int *a, LICE_pixel_chan *pin, LICE_pixel_chan *pinnext, int npoffs, int xfrac, int yfrac) { int f4=((unsigned int)xfrac*(unsigned int)yfrac)/65536; int f3=yfrac-f4; // (1.0-xfrac)*yfrac; int f2=xfrac-f4; // xfrac*(1.0-yfrac); int f1=65536-yfrac-f2; // (1.0-xfrac)*(1.0-yfrac); npoffs*=4; *r=(pin[LICE_PIXEL_R]*f1 + pin[npoffs+LICE_PIXEL_R]*f2 + pinnext[LICE_PIXEL_R]*f3 + pinnext[npoffs+LICE_PIXEL_R]*f4)/65536; *g=(pin[LICE_PIXEL_G]*f1 + pin[npoffs+LICE_PIXEL_G]*f2 + pinnext[LICE_PIXEL_G]*f3 + pinnext[npoffs+LICE_PIXEL_G]*f4)/65536; *b=(pin[LICE_PIXEL_B]*f1 + pin[npoffs+LICE_PIXEL_B]*f2 + pinnext[LICE_PIXEL_B]*f3 + pinnext[npoffs+LICE_PIXEL_B]*f4)/65536; *a=(pin[LICE_PIXEL_A]*f1 + pin[npoffs+LICE_PIXEL_A]*f2 + pinnext[LICE_PIXEL_A]*f3 + pinnext[npoffs+LICE_PIXEL_A]*f4)/65536; } static inline void __LICE_LinearFilterI(int *r, int *g, int *b, int *a, LICE_pixel_chan *pin, LICE_pixel_chan *pinnext, int frac) { int f=65536-frac; *r=(pin[LICE_PIXEL_R]*f + pinnext[LICE_PIXEL_R]*frac)/65536; *g=(pin[LICE_PIXEL_G]*f + pinnext[LICE_PIXEL_G]*frac)/65536; *b=(pin[LICE_PIXEL_B]*f + pinnext[LICE_PIXEL_B]*frac)/65536; *a=(pin[LICE_PIXEL_A]*f + pinnext[LICE_PIXEL_A]*frac)/65536; } static inline void __LICE_LinearFilterIPixOut(LICE_pixel_chan *out, LICE_pixel_chan *pin, LICE_pixel_chan *pinnext, int frac) { int f=65536-frac; out[LICE_PIXEL_R]=(pin[LICE_PIXEL_R]*f + pinnext[LICE_PIXEL_R]*frac)/65536; out[LICE_PIXEL_G]=(pin[LICE_PIXEL_G]*f + pinnext[LICE_PIXEL_G]*frac)/65536; out[LICE_PIXEL_B]=(pin[LICE_PIXEL_B]*f + pinnext[LICE_PIXEL_B]*frac)/65536; out[LICE_PIXEL_A]=(pin[LICE_PIXEL_A]*f + pinnext[LICE_PIXEL_A]*frac)/65536; } static void inline _LICE_MakePixelClamp(LICE_pixel_chan *out, int r, int g, int b, int a) { #define LICE_PIX_MAKECHAN(a,b) out[a] = (b&~0xff) ? (b<0?0:255) : b; LICE_PIX_MAKECHAN(LICE_PIXEL_B,b) LICE_PIX_MAKECHAN(LICE_PIXEL_G,g) LICE_PIX_MAKECHAN(LICE_PIXEL_R,r) LICE_PIX_MAKECHAN(LICE_PIXEL_A,a) #undef LICE_PIX_MAKECHAN } static void inline _LICE_MakePixelNoClamp(LICE_pixel_chan *out, LICE_pixel_chan r, LICE_pixel_chan g, LICE_pixel_chan b, LICE_pixel_chan a) { #define LICE_PIX_MAKECHAN(a,b) out[a] = b; LICE_PIX_MAKECHAN(LICE_PIXEL_B,b) LICE_PIX_MAKECHAN(LICE_PIXEL_G,g) LICE_PIX_MAKECHAN(LICE_PIXEL_R,r) LICE_PIX_MAKECHAN(LICE_PIXEL_A,a) #undef LICE_PIX_MAKECHAN } #define HSV_P v*(256-s)/256 #define HSV_Q(hval) v*(16384-(hval)*s)/16384 #define HSV_T(hval) v*(16384-(64-(hval))*s)/16384 #define HSV_X v extern unsigned short _LICE_RGB2HSV_invtab[256]; // 65536/idx - 1 #ifdef LICE_COMBINE_IMPLEMENT_HSV LICE_pixel LICE_HSV2Pix(int h, int s, int v, int alpha) #define __LICE_HSV2Pix LICE_HSV2Pix #else static inline LICE_pixel __LICE_HSV2Pix(int h, int s, int v, int alpha) #endif { if (h<192) { if (h<64) return LICE_RGBA(HSV_X,HSV_T(h),HSV_P,alpha); if (h<128) return LICE_RGBA(HSV_Q(h-64),HSV_X,HSV_P,alpha); return LICE_RGBA(HSV_P,HSV_X,HSV_T(h-128),alpha); } if (h < 256) return LICE_RGBA(HSV_P,HSV_Q(h-192),HSV_X,alpha); if (h < 320) return LICE_RGBA(HSV_T(h-256),HSV_P,HSV_X,alpha); return LICE_RGBA(HSV_X,HSV_P,HSV_Q(h-320),alpha); } #ifdef LICE_COMBINE_IMPLEMENT_HSV void LICE_HSV2RGB(int h, int s, int v, int* r, int* g, int* b) #define __LICE_HSV2RGB LICE_HSV2RGB #else static inline void __LICE_HSV2RGB(int h, int s, int v, int* r, int* g, int* b) #endif { if (h<192) { if (h<64) { *r = HSV_X; *g = HSV_T(h); *b = HSV_P; } else if (h<128) { *r = HSV_Q(h-64); *g = HSV_X; *b = HSV_P; } else { *r = HSV_P; *g = HSV_X; *b = HSV_T(h-128); } } else { if (h < 256) { *r = HSV_P; *g = HSV_Q(h-192); *b = HSV_X; } else if (h < 320) { *r = HSV_T(h-256); *g = HSV_P; *b = HSV_X; } else { *r = HSV_X; *g = HSV_P; *b = HSV_Q(h-320); } } } #define LICE_RGB2HSV_USE_TABLE // h = [0,384), s and v = [0,256) #ifdef LICE_COMBINE_IMPLEMENT_HSV void LICE_RGB2HSV(int r, int g, int b, int* h, int* s, int* v) #define __LICE_RGB2HSV LICE_RGB2HSV #else static inline void __LICE_RGB2HSV(int r, int g, int b, int* h, int* s, int* v) #endif { // this makes it just 3 conditional branches per call int df,d,maxrgb; int degoffs; if (g > r) { if (g>b) // green max { maxrgb=g; degoffs=128; df = maxrgb - min(b,r); d=b-r; } else // blue max { maxrgb=b; degoffs=256; df = maxrgb - min(g,r); d=r-g; } } else // r >= g { if (r > b) // red max { maxrgb=r; if (g<b) { degoffs=383; // not technically correct, but close enough (and simplifies the rounding case -- if you want more accuracy, set to 384, // then add a if (*h == 384) *h=0; after the *h assignment below df = maxrgb - g; } else { degoffs=0; df = maxrgb - b; } d=g-b; } else // blue max { maxrgb=b; degoffs=256; df = maxrgb - min(g,r); d=r-g; } } *v = maxrgb; #ifndef LICE_RGB2HSV_USE_TABLE // table mode doesnt need this check if (!df) { *h = *s = 0; } else #endif { #ifdef LICE_RGB2HSV_USE_TABLE *h = (d*((int)(_LICE_RGB2HSV_invtab[df]+1)))/1024 + degoffs; *s = (df*((int)_LICE_RGB2HSV_invtab[maxrgb]))/256; #else *h = ((d*64)/df) + degoffs; *s = (df*256)/(maxrgb+1); #endif } } //void doPix(LICE_pixel_chan *dest, int r, int g, int b, int a, int alpha) // alpha is ignored. // generally speaking, the "a" is 0-255, and alpha is 0-256/1-256. // Optimization when a=255 and alpha=1.0f, useful for doing a big vector drawn fill or something. // This could be called _LICE_PutPixel but that would probably be confusing. class _LICE_CombinePixelsClobberNoClamp { public: static inline void doPix(LICE_pixel_chan *dest, int r, int g, int b, int a, int alpha) // alpha is ignored. { _LICE_MakePixelNoClamp(dest, r, g, b, a); } }; class _LICE_CombinePixelsClobberClamp { public: static inline void doPix(LICE_pixel_chan *dest, int r, int g, int b, int a, int alpha) // alpha is ignored. { _LICE_MakePixelClamp(dest, r, g, b, a); } }; class _LICE_CombinePixelsClobberFAST { public: static inline void doPixFAST(LICE_pixel *dest, LICE_pixel src) // alpha is ignored. { *dest = src; } }; class _LICE_CombinePixelsHalfMixNoClamp { public: static inline void doPix(LICE_pixel_chan *dest, int r, int g, int b, int a, int alpha) { _LICE_MakePixelNoClamp(dest, (dest[LICE_PIXEL_R]+r)/2, (dest[LICE_PIXEL_G]+g)/2, (dest[LICE_PIXEL_B]+b)/2, (dest[LICE_PIXEL_A]+a)/2); } }; class _LICE_CombinePixelsHalfMixFAST { public: static inline void doPixFAST(LICE_pixel *dest, LICE_pixel src) // src is full range { *dest = ((*dest>>1) &0x7f7f7f7f) + ((src>>1)&0x7f7f7f7f); } }; class _LICE_CombinePixelsHalfMixClamp { public: static inline void doPix(LICE_pixel_chan *dest, int r, int g, int b, int a, int alpha) { _LICE_MakePixelClamp(dest, (dest[LICE_PIXEL_R]+r)/2, (dest[LICE_PIXEL_G]+g)/2, (dest[LICE_PIXEL_B]+b)/2, (dest[LICE_PIXEL_A]+a)/2); } }; class _LICE_CombinePixelsHalfMix2FAST { public: static inline void doPixFAST(LICE_pixel *dest, LICE_pixel src) // src is pre-halfed and masked { *dest = ((*dest>>1) &0x7f7f7f7f) + src; } }; class _LICE_CombinePixelsQuarterMix2FAST { public: static inline void doPixFAST(LICE_pixel *dest, LICE_pixel src) // src is pre-quartered and masked { LICE_pixel tmp = *dest; *dest = ((tmp>>1) &0x7f7f7f7f) + ((tmp>>2) &0x3f3f3f3f) + src; } }; class _LICE_CombinePixelsThreeQuarterMix2FAST { public: static inline void doPixFAST(LICE_pixel *dest, LICE_pixel src) // src is pre-quartered and masked { *dest = ((*dest>>2) &0x3f3f3f3f) + src; } }; class _LICE_CombinePixelsCopyNoClamp { public: static inline void doPix(LICE_pixel_chan *dest, int r, int g, int b, int a, int alpha) { int sc=(256-alpha); // don't check alpha=0 here, since the caller should (since alpha is usually used for static alphas) _LICE_MakePixelNoClamp(dest, r + ((dest[LICE_PIXEL_R]-r)*sc)/256, g + ((dest[LICE_PIXEL_G]-g)*sc)/256, b + ((dest[LICE_PIXEL_B]-b)*sc)/256, a + ((dest[LICE_PIXEL_A]-a)*sc)/256); } }; class _LICE_CombinePixelsCopyClamp { public: static inline void doPix(LICE_pixel_chan *dest, int r, int g, int b, int a, int alpha) { int sc=(256-alpha); // don't check alpha=0 here, since the caller should (since alpha is usually used for static alphas) _LICE_MakePixelClamp(dest, r + ((dest[LICE_PIXEL_R]-r)*sc)/256, g + ((dest[LICE_PIXEL_G]-g)*sc)/256, b + ((dest[LICE_PIXEL_B]-b)*sc)/256, a + ((dest[LICE_PIXEL_A]-a)*sc)/256); } }; class _LICE_CombinePixelsCopySourceAlphaNoClamp { public: static inline void doPix(LICE_pixel_chan *dest, int r, int g, int b, int a, int alpha) { if (a) { int sc = 256 - (alpha*(a+1))/256; _LICE_MakePixelNoClamp(dest, r + ((dest[LICE_PIXEL_R]-r)*sc)/256, g + ((dest[LICE_PIXEL_G]-g)*sc)/256, b + ((dest[LICE_PIXEL_B]-b)*sc)/256, a + ((dest[LICE_PIXEL_A]-a)*sc)/256); } } }; class _LICE_CombinePixelsCopySourceAlphaClamp { public: static inline void doPix(LICE_pixel_chan *dest, int r, int g, int b, int a, int alpha) { if (a) { int sc = 256 - (alpha*(a+1))/256; _LICE_MakePixelClamp(dest, r + ((dest[LICE_PIXEL_R]-r)*sc)/256, g + ((dest[LICE_PIXEL_G]-g)*sc)/256, b + ((dest[LICE_PIXEL_B]-b)*sc)/256, a + ((dest[LICE_PIXEL_A]-a)*sc)/256); } } }; class _LICE_CombinePixelsCopySourceAlphaIgnoreAlphaParmNoClamp { public: static inline void doPix(LICE_pixel_chan *dest, int r, int g, int b, int a, int alpha) { if (a) { if (a==255) { _LICE_MakePixelNoClamp(dest,r,g,b,a); } else { int sc=(255-a); _LICE_MakePixelNoClamp(dest, r + ((dest[LICE_PIXEL_R]-r)*sc)/256, g + ((dest[LICE_PIXEL_G]-g)*sc)/256, b + ((dest[LICE_PIXEL_B]-b)*sc)/256, a + ((dest[LICE_PIXEL_A]-a)*sc)/256); } } } }; class _LICE_CombinePixelsCopySourceAlphaIgnoreAlphaParmClamp { public: static inline void doPix(LICE_pixel_chan *dest, int r, int g, int b, int a, int alpha) { if (a) { if (a==255) { _LICE_MakePixelClamp(dest,r,g,b,a); } else { int sc=(255-a); _LICE_MakePixelClamp(dest, r + ((dest[LICE_PIXEL_R]-r)*sc)/256, g + ((dest[LICE_PIXEL_G]-g)*sc)/256, b + ((dest[LICE_PIXEL_B]-b)*sc)/256, a + ((dest[LICE_PIXEL_A]-a)*sc)/256); } } } }; #ifndef LICE_DISABLE_BLEND_ADD class _LICE_CombinePixelsAdd { public: static inline void doPix(LICE_pixel_chan *dest, int r, int g, int b, int a, int alpha) { // don't check alpha=0 here, since the caller should (since alpha is usually used for static alphas) _LICE_MakePixelClamp(dest, dest[LICE_PIXEL_R]+(r*alpha)/256, dest[LICE_PIXEL_G]+(g*alpha)/256, dest[LICE_PIXEL_B]+(b*alpha)/256, dest[LICE_PIXEL_A]+(a*alpha)/256); } }; class _LICE_CombinePixelsAddSourceAlpha { public: static inline void doPix(LICE_pixel_chan *dest, int r, int g, int b, int a, int alpha) { if (a) { alpha=(alpha*(a+1))/256; _LICE_MakePixelClamp(dest, dest[LICE_PIXEL_R]+(r*alpha)/256, dest[LICE_PIXEL_G]+(g*alpha)/256, dest[LICE_PIXEL_B]+(b*alpha)/256, dest[LICE_PIXEL_A]+(a*alpha)/256); } } }; #else // !LICE_DISABLE_BLEND_ADD #define _LICE_CombinePixelsAddSourceAlpha _LICE_CombinePixelsCopySourceAlphaClamp #define _LICE_CombinePixelsAdd _LICE_CombinePixelsCopyClamp #endif #ifndef LICE_DISABLE_BLEND_DODGE class _LICE_CombinePixelsColorDodge { public: static inline void doPix(LICE_pixel_chan *dest, int r, int g, int b, int a, int alpha) { int src_r = 256-r*alpha/256; int src_g = 256-g*alpha/256; int src_b = 256-b*alpha/256; int src_a = 256-a*alpha/256; _LICE_MakePixelClamp(dest, src_r > 1 ? 256*dest[LICE_PIXEL_R] / src_r : 256*dest[LICE_PIXEL_R], src_g > 1 ? 256*dest[LICE_PIXEL_G] / src_g : 256*dest[LICE_PIXEL_G], src_b > 1 ? 256*dest[LICE_PIXEL_B] / src_b : 256*dest[LICE_PIXEL_B], src_a > 1 ? 256*dest[LICE_PIXEL_A] / src_a : 256*dest[LICE_PIXEL_A]); } }; class _LICE_CombinePixelsColorDodgeSourceAlpha { public: static inline void doPix(LICE_pixel_chan *dest, int r, int g, int b, int a, int alpha) { alpha=(alpha*(a+1))/256; int src_r = 256-r*alpha/256; int src_g = 256-g*alpha/256; int src_b = 256-b*alpha/256; int src_a = 256-a*alpha/256; _LICE_MakePixelClamp(dest, src_r > 1 ? 256*dest[LICE_PIXEL_R] / src_r : 256*dest[LICE_PIXEL_R], src_g > 1 ? 256*dest[LICE_PIXEL_G] / src_g : 256*dest[LICE_PIXEL_G], src_b > 1 ? 256*dest[LICE_PIXEL_B] / src_b : 256*dest[LICE_PIXEL_B], src_a > 1 ? 256*dest[LICE_PIXEL_A] / src_a : 256*dest[LICE_PIXEL_A]); } }; #else // !LICE_DISABLE_BLEND_DODGE #define _LICE_CombinePixelsColorDodgeSourceAlpha _LICE_CombinePixelsCopySourceAlphaClamp #define _LICE_CombinePixelsColorDodge _LICE_CombinePixelsCopyClamp #endif #ifndef LICE_DISABLE_BLEND_MUL class _LICE_CombinePixelsMulNoClamp { public: static inline void doPix(LICE_pixel_chan *dest, int r, int g, int b, int a, int alpha) { // we could check alpha=0 here, but the caller should (since alpha is usually used for static alphas) int da=(256-alpha)*256; _LICE_MakePixelNoClamp(dest, (dest[LICE_PIXEL_R]*(da + (r*alpha)))/65536, (dest[LICE_PIXEL_G]*(da + (g*alpha)))/65536, (dest[LICE_PIXEL_B]*(da + (b*alpha)))/65536, (dest[LICE_PIXEL_A]*(da + (a*alpha)))/65536); } }; class _LICE_CombinePixelsMulClamp { public: static inline void doPix(LICE_pixel_chan *dest, int r, int g, int b, int a, int alpha) { // we could check alpha=0 here, but the caller should (since alpha is usually used for static alphas) int da=(256-alpha)*256; _LICE_MakePixelClamp(dest, (dest[LICE_PIXEL_R]*(da + (r*alpha)))/65536, (dest[LICE_PIXEL_G]*(da + (g*alpha)))/65536, (dest[LICE_PIXEL_B]*(da + (b*alpha)))/65536, (dest[LICE_PIXEL_A]*(da + (a*alpha)))/65536); } }; class _LICE_CombinePixelsMulSourceAlphaNoClamp { public: static inline void doPix(LICE_pixel_chan *dest, int r, int g, int b, int a, int alpha) { if (a) { alpha=(alpha*(a+1))/256; int da=(256-alpha)*256; _LICE_MakePixelNoClamp(dest, (dest[LICE_PIXEL_R]*(da + (r*alpha)))/65536, (dest[LICE_PIXEL_G]*(da + (g*alpha)))/65536, (dest[LICE_PIXEL_B]*(da + (b*alpha)))/65536, (dest[LICE_PIXEL_A]*(da + (a*alpha)))/65536); } } }; class _LICE_CombinePixelsMulSourceAlphaClamp { public: static inline void doPix(LICE_pixel_chan *dest, int r, int g, int b, int a, int alpha) { if (a) { alpha=(alpha*(a+1))/256; int da=(256-alpha)*256; _LICE_MakePixelClamp(dest, (dest[LICE_PIXEL_R]*(da + (r*alpha)))/65536, (dest[LICE_PIXEL_G]*(da + (g*alpha)))/65536, (dest[LICE_PIXEL_B]*(da + (b*alpha)))/65536, (dest[LICE_PIXEL_A]*(da + (a*alpha)))/65536); } } }; #else // !LICE_DISABLE_BLEND_MUL #define _LICE_CombinePixelsMulSourceAlphaNoClamp _LICE_CombinePixelsCopySourceAlphaNoClamp #define _LICE_CombinePixelsMulSourceAlphaClamp _LICE_CombinePixelsCopySourceAlphaClamp #define _LICE_CombinePixelsMulNoClamp _LICE_CombinePixelsCopyNoClamp #define _LICE_CombinePixelsMulClamp _LICE_CombinePixelsCopyClamp #endif //#define LICE_DISABLE_BLEND_OVERLAY #ifndef LICE_DISABLE_BLEND_OVERLAY class _LICE_CombinePixelsOverlay { public: static inline void doPix(LICE_pixel_chan *dest, int r, int g, int b, int a, int alpha) { // we could check alpha=0 here, but the caller should (since alpha is usually used for static alphas) int destr = dest[LICE_PIXEL_R], destg = dest[LICE_PIXEL_G], destb = dest[LICE_PIXEL_B], desta = dest[LICE_PIXEL_A]; #if 0 int srcr = r*alpha, srcg = g*alpha, srcb = b*alpha, srca = a*alpha; int da=(256-alpha)*256; int mr = (destr*(da+srcr))/65536; int mg = (destg*(da+srcg))/65536; int mb = (destb*(da+srcb))/65536; int ma = (desta*(da+srca))/65536; int sr = 256-(65536-srcr)*(256-destr)/65536; int sg = 256-(65536-srcg)*(256-destg)/65536; int sb = 256-(65536-srcb)*(256-destb)/65536; int sa = 256-(65536-srca)*(256-desta)/65536; destr = (destr*sr+(256-destr)*mr)/256; destg = (destg*sg+(256-destg)*mg)/256; destb = (destb*sb+(256-destb)*mb)/256; desta = (desta*sa+(256-desta)*ma)/256; #else // can produce slightly diff (+-1) results from above due to rounding int da=(256-alpha)*128; int srcr = r*alpha+da, srcg = g*alpha+da, srcb = b*alpha+da, srca = a*alpha + da; destr = ( destr*( (destr*(32768-srcr))/256 + srcr ) )/32768; destg = ( destg*( (destg*(32768-srcg))/256 + srcg ) )/32768; destb = ( destb*( (destb*(32768-srcb))/256 + srcb ) )/32768; desta = ( desta*( (desta*(32768-srca))/256 + srca ) )/32768; #endif _LICE_MakePixelClamp(dest, destr, destg, destb, desta); } }; class _LICE_CombinePixelsOverlaySourceAlpha { public: static inline void doPix(LICE_pixel_chan *dest, int r, int g, int b, int a, int alpha) { _LICE_CombinePixelsOverlay::doPix(dest, r, g, b, a, (alpha*(a+1))/256); } }; #else // !LICE_DISABLE_BLEND_OVERLAY #define _LICE_CombinePixelsOverlaySourceAlpha _LICE_CombinePixelsCopySourceAlphaClamp #define _LICE_CombinePixelsOverlay _LICE_CombinePixelsCopyClamp #endif //#define LICE_DISABLE_BLEND_HSVADJ #ifndef LICE_DISABLE_BLEND_HSVADJ class _LICE_CombinePixelsHSVAdjust { public: static inline void doPix(LICE_pixel_chan *dest, int r, int g, int b, int a, int alpha) { int h,s,v; __LICE_RGB2HSV(dest[LICE_PIXEL_R],dest[LICE_PIXEL_G],dest[LICE_PIXEL_B],&h,&s,&v); h+=(((r+r/2) - 192) * alpha)/256; if (h<0)h+=384; else if (h>=384) h-=384; s+=((g-128)*alpha)/128; if (s&~0xff) { if (s<0)s=0; else s=255; } v+=((b-128)*alpha)/128; if (v&~0xff) { if (v<0)v=0; else v=255; } *(LICE_pixel *)dest = __LICE_HSV2Pix(h,s,v,a); } }; class _LICE_CombinePixelsHSVAdjustSourceAlpha { public: static inline void doPix(LICE_pixel_chan *dest, int r, int g, int b, int a, int alpha) { _LICE_CombinePixelsHSVAdjust::doPix(dest, r, g, b, a, (alpha*(a+1))/256); } }; #else // !LICE_DISABLE_BLEND_HSVADJ #define _LICE_CombinePixelsHSVAdjustSourceAlpha _LICE_CombinePixelsCopySourceAlphaClamp #define _LICE_CombinePixelsHSVAdjust _LICE_CombinePixelsCopyClamp #endif // note: the "clamp" parameter would generally be false, unless you're working with // input colors that need to be clamped (i.e. if you have a r value of >255 or <0, etc. // if your input is LICE_pixel only then use false, and it will clamp as needed depending // on the blend mode.. //#define __LICE__ACTION(comb) templateclass<comb>::function(parameters) //__LICE_ACTION_SRCALPHA(mode,alpha,clamp); //#undef __LICE__ACTION // use this for paths that support LICE_BLIT_USE_ALPHA (source-alpha combining), but // otherwise have constant alpha #define __LICE_ACTION_SRCALPHA(mode,ia,clamp) \ if ((ia)!=0) switch ((mode)&(LICE_BLIT_MODE_MASK|LICE_BLIT_USE_ALPHA)) { \ case LICE_BLIT_MODE_COPY: if ((ia)>0) { \ if (clamp) { \ if ((ia)==256) { __LICE__ACTION(_LICE_CombinePixelsClobberClamp); } \ else { __LICE__ACTION(_LICE_CombinePixelsCopyClamp); } \ } else { \ if ((ia)==256) { __LICE__ACTION(_LICE_CombinePixelsClobberNoClamp); } \ else { __LICE__ACTION(_LICE_CombinePixelsCopyNoClamp); } \ } \ } \ break; \ case LICE_BLIT_MODE_ADD: __LICE__ACTION(_LICE_CombinePixelsAdd); break; \ case LICE_BLIT_MODE_DODGE: __LICE__ACTION(_LICE_CombinePixelsColorDodge); break; \ case LICE_BLIT_MODE_MUL: \ if (clamp) { __LICE__ACTION(_LICE_CombinePixelsMulClamp); } \ else { __LICE__ACTION(_LICE_CombinePixelsMulNoClamp); } \ break; \ case LICE_BLIT_MODE_OVERLAY: __LICE__ACTION(_LICE_CombinePixelsOverlay); break; \ case LICE_BLIT_MODE_HSVADJ: __LICE__ACTION(_LICE_CombinePixelsHSVAdjust); break; \ case LICE_BLIT_MODE_COPY|LICE_BLIT_USE_ALPHA: \ if (clamp) { \ if ((ia)==256) { __LICE__ACTION(_LICE_CombinePixelsCopySourceAlphaIgnoreAlphaParmClamp);} \ else { __LICE__ACTION(_LICE_CombinePixelsCopySourceAlphaClamp); } \ } else { \ if ((ia)==256) { __LICE__ACTION(_LICE_CombinePixelsCopySourceAlphaIgnoreAlphaParmNoClamp); } \ else { __LICE__ACTION(_LICE_CombinePixelsCopySourceAlphaNoClamp); } \ } \ break; \ case LICE_BLIT_MODE_ADD|LICE_BLIT_USE_ALPHA: \ __LICE__ACTION(_LICE_CombinePixelsAddSourceAlpha); \ break; \ case LICE_BLIT_MODE_DODGE|LICE_BLIT_USE_ALPHA: \ __LICE__ACTION(_LICE_CombinePixelsColorDodgeSourceAlpha); \ break; \ case LICE_BLIT_MODE_MUL|LICE_BLIT_USE_ALPHA: \ if (clamp) { __LICE__ACTION(_LICE_CombinePixelsMulSourceAlphaClamp); } \ else { __LICE__ACTION(_LICE_CombinePixelsMulSourceAlphaNoClamp); } \ break; \ case LICE_BLIT_MODE_OVERLAY|LICE_BLIT_USE_ALPHA: \ __LICE__ACTION(_LICE_CombinePixelsOverlaySourceAlpha); \ break; \ case LICE_BLIT_MODE_HSVADJ|LICE_BLIT_USE_ALPHA: \ __LICE__ACTION(_LICE_CombinePixelsHSVAdjustSourceAlpha); \ break; \ } // use this for paths that can have per pixel alpha, but calculate it themselves #define __LICE_ACTION_NOSRCALPHA(mode, ia,clamp) \ if ((ia)!=0) switch ((mode)&LICE_BLIT_MODE_MASK) { \ case LICE_BLIT_MODE_COPY: if ((ia)>0) { if (clamp) { __LICE__ACTION(_LICE_CombinePixelsCopyClamp); } else { __LICE__ACTION(_LICE_CombinePixelsCopyNoClamp); } } break; \ case LICE_BLIT_MODE_ADD: __LICE__ACTION(_LICE_CombinePixelsAdd); break; \ case LICE_BLIT_MODE_DODGE: __LICE__ACTION(_LICE_CombinePixelsColorDodge); break; \ case LICE_BLIT_MODE_MUL: if (clamp) { __LICE__ACTION(_LICE_CombinePixelsMulClamp); } else { __LICE__ACTION(_LICE_CombinePixelsMulNoClamp); } break; \ case LICE_BLIT_MODE_OVERLAY: __LICE__ACTION(_LICE_CombinePixelsOverlay); break; \ case LICE_BLIT_MODE_HSVADJ: __LICE__ACTION(_LICE_CombinePixelsHSVAdjust); break; \ } // For drawing where there is constant alpha and no per-pixel alpha. #define __LICE_ACTION_CONSTANTALPHA(mode,ia,clamp) \ if ((ia)!=0) switch ((mode)&LICE_BLIT_MODE_MASK) { \ case LICE_BLIT_MODE_COPY: \ if ((ia)==256) { if (clamp) { __LICE__ACTION(_LICE_CombinePixelsClobberClamp); } else { __LICE__ACTION(_LICE_CombinePixelsClobberNoClamp); } } \ else if ((ia)==128) { if (clamp) { __LICE__ACTION(_LICE_CombinePixelsHalfMixClamp); } else { __LICE__ACTION(_LICE_CombinePixelsHalfMixNoClamp); } } \ else if ((ia)>0) { if (clamp) { __LICE__ACTION(_LICE_CombinePixelsCopyClamp); } else { __LICE__ACTION(_LICE_CombinePixelsCopyNoClamp); } } \ break; \ case LICE_BLIT_MODE_ADD: __LICE__ACTION(_LICE_CombinePixelsAdd); break; \ case LICE_BLIT_MODE_DODGE: __LICE__ACTION(_LICE_CombinePixelsColorDodge); break; \ case LICE_BLIT_MODE_MUL: if (clamp) { __LICE__ACTION(_LICE_CombinePixelsMulClamp); } else { __LICE__ACTION(_LICE_CombinePixelsMulNoClamp); } break; \ case LICE_BLIT_MODE_OVERLAY: __LICE__ACTION(_LICE_CombinePixelsOverlay); break; \ case LICE_BLIT_MODE_HSVADJ: __LICE__ACTION(_LICE_CombinePixelsHSVAdjust); break; \ } typedef void (*LICE_COMBINEFUNC)(LICE_pixel_chan *dest, int r, int g, int b, int a, int alpha); #endif // _LICE_COMBINE_H_
[ [ [ 1, 434 ], [ 436, 440 ], [ 442, 458 ], [ 460, 464 ], [ 466, 829 ] ], [ [ 435, 435 ], [ 441, 441 ], [ 459, 459 ], [ 465, 465 ] ] ]
81e6595bc009f6c08180a3f2558bb9a5bb70dadb
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/dom/DOMTreeWalker.hpp
c18e44c80c4ed9f939820355e9d0ad86dcddc422
[ "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
11,746
hpp
#ifndef DOMTreeWalker_HEADER_GUARD_ #define DOMTreeWalker_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: DOMTreeWalker.hpp,v 1.10 2004/09/26 15:38:03 gareth Exp $ */ #include <xercesc/dom/DOMNode.hpp> #include <xercesc/dom/DOMNodeFilter.hpp> XERCES_CPP_NAMESPACE_BEGIN /** * <code>DOMTreeWalker</code> objects are used to navigate a document tree or * subtree using the view of the document defined by their * <code>whatToShow</code> flags and filter (if any). Any function which * performs navigation using a <code>DOMTreeWalker</code> will automatically * support any view defined by a <code>DOMTreeWalker</code>. * <p>Omitting nodes from the logical view of a subtree can result in a * structure that is substantially different from the same subtree in the * complete, unfiltered document. Nodes that are siblings in the * <code>DOMTreeWalker</code> view may be children of different, widely * separated nodes in the original view. For instance, consider a * <code>DOMNodeFilter</code> that skips all nodes except for DOMText nodes and * the root node of a document. In the logical view that results, all text * nodes will be siblings and appear as direct children of the root node, no * matter how deeply nested the structure of the original document. * <p>See also the <a href='http://www.w3.org/TR/2000/REC-DOM-Level-2-Traversal-Range-20001113'>Document Object Model (DOM) Level 2 Traversal and Range Specification</a>. * * @since DOM Level 2 */ class CDOM_EXPORT DOMTreeWalker { protected: // ----------------------------------------------------------------------- // Hidden constructors // ----------------------------------------------------------------------- /** @name Hidden constructors */ //@{ DOMTreeWalker() {}; //@} private: // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- /** @name Unimplemented constructors and operators */ //@{ DOMTreeWalker(const DOMTreeWalker &); DOMTreeWalker & operator = (const DOMTreeWalker &); //@} public: // ----------------------------------------------------------------------- // All constructors are hidden, just the destructor is available // ----------------------------------------------------------------------- /** @name Destructor */ //@{ /** * Destructor * */ virtual ~DOMTreeWalker() {}; //@} // ----------------------------------------------------------------------- // Virtual DOMTreeWalker interface // ----------------------------------------------------------------------- /** @name Functions introduced in DOM Level 2 */ //@{ // ----------------------------------------------------------------------- // Getter methods // ----------------------------------------------------------------------- /** * The <code>root</code> node of the <code>DOMTreeWalker</code>, as specified * when it was created. * * @since DOM Level 2 */ virtual DOMNode* getRoot() = 0; /** * This attribute determines which node types are presented via the * <code>DOMTreeWalker</code>. The available set of constants is defined in * the <code>DOMNodeFilter</code> interface. Nodes not accepted by * <code>whatToShow</code> will be skipped, but their children may still * be considered. Note that this skip takes precedence over the filter, * if any. * * @since DOM Level 2 */ virtual unsigned long getWhatToShow()= 0; /** * Return The filter used to screen nodes. * * @since DOM Level 2 */ virtual DOMNodeFilter* getFilter()= 0; /** * The value of this flag determines whether the children of entity * reference nodes are visible to the <code>DOMTreeWalker</code>. If false, * these children and their descendants will be rejected. Note that * this rejection takes precedence over <code>whatToShow</code> and the * filter, if any. * <br> To produce a view of the document that has entity references * expanded and does not expose the entity reference node itself, use * the <code>whatToShow</code> flags to hide the entity reference node * and set <code>expandEntityReferences</code> to true when creating the * <code>DOMTreeWalker</code>. To produce a view of the document that has * entity reference nodes but no entity expansion, use the * <code>whatToShow</code> flags to show the entity reference node and * set <code>expandEntityReferences</code> to false. * * @since DOM Level 2 */ virtual bool getExpandEntityReferences()= 0; /** * Return the node at which the DOMTreeWalker is currently positioned. * * @since DOM Level 2 */ virtual DOMNode* getCurrentNode()= 0; // ----------------------------------------------------------------------- // Query methods // ----------------------------------------------------------------------- /** * Moves to and returns the closest visible ancestor node of the current * node. If the search for <code>parentNode</code> attempts to step * upward from the <code>DOMTreeWalker</code>'s <code>root</code> node, or * if it fails to find a visible ancestor node, this method retains the * current position and returns <code>null</code>. * @return The new parent node, or <code>null</code> if the current node * has no parent in the <code>DOMTreeWalker</code>'s logical view. * * @since DOM Level 2 */ virtual DOMNode* parentNode()= 0; /** * Moves the <code>DOMTreeWalker</code> to the first visible child of the * current node, and returns the new node. If the current node has no * visible children, returns <code>null</code>, and retains the current * node. * @return The new node, or <code>null</code> if the current node has no * visible children in the <code>DOMTreeWalker</code>'s logical view. * * @since DOM Level 2 */ virtual DOMNode* firstChild()= 0; /** * Moves the <code>DOMTreeWalker</code> to the last visible child of the * current node, and returns the new node. If the current node has no * visible children, returns <code>null</code>, and retains the current * node. * @return The new node, or <code>null</code> if the current node has no * children in the <code>DOMTreeWalker</code>'s logical view. * * @since DOM Level 2 */ virtual DOMNode* lastChild()= 0; /** * Moves the <code>DOMTreeWalker</code> to the previous sibling of the * current node, and returns the new node. If the current node has no * visible previous sibling, returns <code>null</code>, and retains the * current node. * @return The new node, or <code>null</code> if the current node has no * previous sibling. in the <code>DOMTreeWalker</code>'s logical view. * * @since DOM Level 2 */ virtual DOMNode* previousSibling()= 0; /** * Moves the <code>DOMTreeWalker</code> to the next sibling of the current * node, and returns the new node. If the current node has no visible * next sibling, returns <code>null</code>, and retains the current node. * @return The new node, or <code>null</code> if the current node has no * next sibling. in the <code>DOMTreeWalker</code>'s logical view. * * @since DOM Level 2 */ virtual DOMNode* nextSibling()= 0; /** * Moves the <code>DOMTreeWalker</code> to the previous visible node in * document order relative to the current node, and returns the new * node. If the current node has no previous node, or if the search for * <code>previousNode</code> attempts to step upward from the * <code>DOMTreeWalker</code>'s <code>root</code> node, returns * <code>null</code>, and retains the current node. * @return The new node, or <code>null</code> if the current node has no * previous node in the <code>DOMTreeWalker</code>'s logical view. * * @since DOM Level 2 */ virtual DOMNode* previousNode()= 0; /** * Moves the <code>DOMTreeWalker</code> to the next visible node in document * order relative to the current node, and returns the new node. If the * current node has no next node, or if the search for nextNode attempts * to step upward from the <code>DOMTreeWalker</code>'s <code>root</code> * node, returns <code>null</code>, and retains the current node. * @return The new node, or <code>null</code> if the current node has no * next node in the <code>DOMTreeWalker</code>'s logical view. * * @since DOM Level 2 */ virtual DOMNode* nextNode()= 0; // ----------------------------------------------------------------------- // Setter methods // ----------------------------------------------------------------------- /** * The node at which the <code>DOMTreeWalker</code> is currently positioned. * <br>Alterations to the DOM tree may cause the current node to no longer * be accepted by the <code>DOMTreeWalker</code>'s associated filter. * <code>currentNode</code> may also be explicitly set to any node, * whether or not it is within the subtree specified by the * <code>root</code> node or would be accepted by the filter and * <code>whatToShow</code> flags. Further traversal occurs relative to * <code>currentNode</code> even if it is not part of the current view, * by applying the filters in the requested direction; if no traversal * is possible, <code>currentNode</code> is not changed. * @exception DOMException * NOT_SUPPORTED_ERR: Raised if an attempt is made to set * <code>currentNode</code> to <code>null</code>. * * @since DOM Level 2 */ virtual void setCurrentNode(DOMNode* currentNode)= 0; //@} // ----------------------------------------------------------------------- // Non-standard Extension // ----------------------------------------------------------------------- /** @name Non-standard Extension */ //@{ /** * Called to indicate that this TreeWalker is no longer in use * and that the implementation may relinquish any resources associated with it. * * Access to a released object will lead to unexpected result. */ virtual void release() = 0; //@} }; #define GetDOMTreeWalkerMemoryManager GET_INDIRECT_MM(fCurrentNode) XERCES_CPP_NAMESPACE_END #endif
[ [ [ 1, 275 ] ] ]
56de65d33f3cf40bb0ca7d7bf6b7a4b29079c997
9426ad6e612863451ad7aac2ad8c8dd100a37a98
/ULLib/src/ULRebarCtrl.cpp
2c57140dc15cb65da95626c658bf2998e35a2079
[]
no_license
piroxiljin/ullib
61f7bd176c6088d42fd5aa38a4ba5d4825becd35
7072af667b6d91a3afd2f64310c6e1f3f6a055b1
refs/heads/master
2020-12-28T19:46:57.920199
2010-02-17T01:43:44
2010-02-17T01:43:44
57,068,293
0
0
null
2016-04-25T19:05:41
2016-04-25T19:05:41
null
WINDOWS-1251
C++
false
false
3,622
cpp
///\file ULRebarCtrl.cpp ///\brief cpp файл класса ребара размещенного на плавающей панельке(31.08.2008) #include "..\..\ULLib\Include\ULRebarCtrl.h" namespace ULWnds { namespace ULWndCtrls { CULRebarCtrl::CULRebarCtrl(void):CULWndCtrl(),m_fAutoSize(false) { MessageMap.AddMessage<CULRebarCtrl>(WM_SIZE,&CULRebarCtrl::OnSize); } ///\brief Конструктор копирования CULRebarCtrl::CULRebarCtrl(CULRebarCtrl& rebarCtrl):CULWndCtrl(rebarCtrl), m_Rebar(rebarCtrl.m_Rebar), m_fAutoSize(rebarCtrl.m_fAutoSize), m_lpSubClassWndProc(rebarCtrl.m_lpSubClassWndProc) { } CULRebarCtrl::~CULRebarCtrl(void) { } ///\brief оператор копирования void CULRebarCtrl::operator=(CULRebarCtrl& rebarCtrl) { m_Rebar=rebarCtrl.m_Rebar; m_fAutoSize=rebarCtrl.m_fAutoSize; m_lpSubClassWndProc=rebarCtrl.m_lpSubClassWndProc; ULWnds::ULWndCtrls::CULWndCtrl::operator=(rebarCtrl); } LRESULT CULRebarCtrl::ClientWndProc(HWND hWnd , UINT uMsg , WPARAM wParam , LPARAM lParam) { ULBars::CULRebar* pULWnd=(ULBars::CULRebar*)CULWnd::FromHandle(hWnd); CULRebarCtrl* pRebarCtrl=(CULRebarCtrl*)pULWnd->GetProp(_T("ULRebarCtrl")); switch(uMsg) { case WM_SIZE: { RECT rect; pRebarCtrl->GetClientRect(&rect); pRebarCtrl->PostMessage(WM_SIZE, SIZE_RESTORED, MAKELPARAM(rect.right-rect.left,rect.bottom-rect.top)); } break; } return ::CallWindowProc(pRebarCtrl->m_lpSubClassWndProc,*pULWnd,uMsg,wParam,lParam); } BOOL CULRebarCtrl::CreateRebarCtrl(HWND hParentWnd, int nXPos, int nYPos, DWORD dwDockedState) { BOOL fDocked=TRUE; DWORD dwDockingStyles= dsUseBorders|dsBorderTop|dsBorderLeft| dsBorderBottom|dsBorderRight|dsAllowDockAll; ULWnds::ULBars::CULRebar::enAlignFlags rbAlignFlags=ULWnds::ULBars::CULRebar::afTop; switch(dwDockedState) { case ULWnds::ULWndCtrls::CULWndCtrl::dsAllowDockTop: rbAlignFlags=ULWnds::ULBars::CULRebar::afTop; break; case ULWnds::ULWndCtrls::CULWndCtrl::dsAllowDockBottom: rbAlignFlags=ULWnds::ULBars::CULRebar::afBottom; break; case ULWnds::ULWndCtrls::CULWndCtrl::dsAllowDockLeft: rbAlignFlags=ULWnds::ULBars::CULRebar::afLeft; break; case ULWnds::ULWndCtrls::CULWndCtrl::dsAllowDockRight: rbAlignFlags=ULWnds::ULBars::CULRebar::afRight; break; } m_Rebar.Create(hParentWnd,0,rbAlignFlags); if(!m_Rebar) return FALSE; m_Rebar.SetProp(_T("ULRebarCtrl"),(HANDLE)this); m_lpSubClassWndProc=(WNDPROC)(LONG_PTR)m_Rebar.SetWindowLong(GWL_WNDPROC,(LONG)(LONG_PTR)ClientWndProc); RECT rcRebar; m_Rebar.GetWindowRect(&rcRebar); POINT ptLT={rcRebar.left,rcRebar.top}; ::ScreenToClient(m_Rebar,&ptLT); POINT ptRB={rcRebar.right,rcRebar.bottom}; ::ScreenToClient(m_Rebar,&ptRB); Create(NULL,nXPos,nYPos,ptRB.x-ptLT.x,ptRB.y-ptLT.y, hParentWnd,dwDockedState,fDocked,dwDockingStyles); if(!*this) return FALSE; m_Rebar.SetParent(*this); return TRUE; } LRESULT CULRebarCtrl::OnSize(WPARAM /*nType*/,LPARAM /*size*/) { if(!m_fAutoSize) { m_Rebar.AutoSize(); m_fAutoSize=true; return TRUE; } else m_fAutoSize=false; RECT rcRebar; m_Rebar.GetWindowRect(&rcRebar); m_FloatingSize.cy=m_nDockedSize=rcRebar.bottom-rcRebar.top-2; m_FloatingSize.cx=rcRebar.right-rcRebar.left; ResizeAllWndCtrls(); return TRUE; } } }
[ "UncleLab@a8b69a72-a546-0410-9fb4-5106a01aa11f" ]
[ [ [ 1, 117 ] ] ]
8649b19f33aa010550614cb2d2ba692827b5adde
5e61787e7adba6ed1c2b5e40d38098ebdf9bdee8
/sans/models/c_models/multishell.cpp
e9d4220a3d8ed8047bb0d8fba5b453239a7a8356
[]
no_license
mcvine/sansmodels
4dcba43d18c930488b0e69e8afb04139e89e7b21
618928810ee7ae58ec35bbb839eba2a0117c4611
refs/heads/master
2021-01-22T13:12:22.721492
2011-09-30T14:01:06
2011-09-30T14:01:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,780
cpp
/** This software was developed by the University of Tennessee as part of the Distributed Data Analysis of Neutron Scattering Experiments (DANSE) project funded by the US National Science Foundation. If you use DANSE applications to do scientific research that leads to publication, we ask that you acknowledge the use of the software with the following sentence: "This work benefited from DANSE software developed under NSF award DMR-0520547." copyright 2008, University of Tennessee */ /** * Scattering model classes * The classes use the IGOR library found in * sansmodels/src/libigor * */ #include <math.h> #include "models.hh" #include "parameters.hh" #include <stdio.h> using namespace std; extern "C" { #include "libSphere.h" #include "multishell.h" } MultiShellModel :: MultiShellModel() { scale = Parameter(1.0); core_radius = Parameter(60.0, true); core_radius.set_min(0.0); s_thickness = Parameter(10.0, true); s_thickness.set_min(0.0); w_thickness = Parameter(10.0, true); w_thickness.set_min(0.0); core_sld = Parameter(6.4e-6); shell_sld = Parameter(4.0e-7); n_pairs = Parameter(2); background = Parameter(0.0); } /** * Function to evaluate 1D scattering function * The NIST IGOR library is used for the actual calculation. * @param q: q-value * @return: function value */ double MultiShellModel :: operator()(double q) { double dp[8]; // Fill parameter array for IGOR library // Add the background after averaging dp[0] = scale(); dp[1] = core_radius(); dp[2] = s_thickness(); dp[3] = w_thickness(); dp[4] = core_sld(); dp[5] = shell_sld(); dp[6] = n_pairs(); dp[7] = 0.0; // Get the dispersion points for the core radius vector<WeightPoint> weights_core_radius; core_radius.get_weights(weights_core_radius); // Get the dispersion points for the s_thickness vector<WeightPoint> weights_s_thickness; s_thickness.get_weights(weights_s_thickness); // Get the dispersion points for the w_thickness vector<WeightPoint> weights_w_thickness; w_thickness.get_weights(weights_w_thickness); // Perform the computation, with all weight points double sum = 0.0; double norm = 0.0; double vol = 0.0; // Loop over radius weight points for(int i=0; i< (int)weights_core_radius.size(); i++) { dp[1] = weights_core_radius[i].value; for(int j=0; j< (int)weights_s_thickness.size(); j++){ dp[2] = weights_s_thickness[j].value; for(int k=0; k< (int)weights_w_thickness.size(); k++){ dp[3] = weights_w_thickness[k].value; //Un-normalize SphereForm by volume sum += weights_core_radius[i].weight*weights_s_thickness[j].weight *weights_w_thickness[k].weight* MultiShell(dp, q) *pow(weights_core_radius[i].value+dp[6]*weights_s_thickness[j].value+(dp[6]-1)*weights_w_thickness[k].value,3); //Find average volume vol += weights_core_radius[i].weight*weights_s_thickness[j].weight *weights_w_thickness[k].weight *pow(weights_core_radius[i].value+dp[6]*weights_s_thickness[j].value+(dp[6]-1)*weights_w_thickness[k].value,3); norm += weights_core_radius[i].weight*weights_s_thickness[j].weight *weights_w_thickness[k].weight; } } } if (vol != 0.0 && norm != 0.0) { //Re-normalize by avg volume sum = sum/(vol/norm);} return sum/norm + background(); } /** * Function to evaluate 2D scattering function * @param q_x: value of Q along x * @param q_y: value of Q along y * @return: function value */ double MultiShellModel :: operator()(double qx, double qy) { double q = sqrt(qx*qx + qy*qy); return (*this).operator()(q); } /** * Function to evaluate 2D scattering function * @param pars: parameters of the multishell * @param q: q-value * @param phi: angle phi * @return: function value */ double MultiShellModel :: evaluate_rphi(double q, double phi) { return (*this).operator()(q); } /** * Function to calculate effective radius * @return: effective radius value */ double MultiShellModel :: calculate_ER() { MultiShellParameters dp; dp.core_radius = core_radius(); dp.s_thickness = s_thickness(); dp.w_thickness = w_thickness(); dp.n_pairs = n_pairs(); double rad_out = 0.0; // Perform the computation, with all weight points double sum = 0.0; double norm = 0.0; if (dp.n_pairs <= 0.0 ){ dp.n_pairs = 0.0; } // Get the dispersion points for the core radius vector<WeightPoint> weights_core_radius; core_radius.get_weights(weights_core_radius); // Get the dispersion points for the s_thickness vector<WeightPoint> weights_s_thickness; s_thickness.get_weights(weights_s_thickness); // Get the dispersion points for the w_thickness vector<WeightPoint> weights_w_thickness; w_thickness.get_weights(weights_w_thickness); // Loop over major shell weight points for(int i=0; i< (int)weights_s_thickness.size(); i++) { dp.s_thickness = weights_s_thickness[i].value; for(int j=0; j< (int)weights_w_thickness.size(); j++) { dp.w_thickness = weights_w_thickness[j].value; for(int k=0; k< (int)weights_core_radius.size(); k++) { dp.core_radius = weights_core_radius[k].value; sum += weights_s_thickness[i].weight*weights_w_thickness[j].weight * weights_core_radius[k].weight*(dp.core_radius+dp.n_pairs*dp.s_thickness+(dp.n_pairs-1.0)*dp.w_thickness); norm += weights_s_thickness[i].weight*weights_w_thickness[j].weight* weights_core_radius[k].weight; } } } if (norm != 0){ //return the averaged value rad_out = sum/norm;} else{ //return normal value rad_out = (dp.core_radius+dp.n_pairs*dp.s_thickness+(dp.n_pairs-1.0)*dp.w_thickness);} return rad_out; }
[ [ [ 1, 29 ], [ 31, 36 ], [ 41, 64 ], [ 66, 70 ], [ 79, 81 ], [ 83, 86 ], [ 103, 103 ], [ 107, 130 ] ], [ [ 30, 30 ], [ 37, 40 ], [ 65, 65 ], [ 71, 78 ], [ 82, 82 ], [ 87, 102 ], [ 104, 106 ], [ 131, 185 ] ] ]
f9a81ba4fccb289e333c0a2c8dd77749afd341b0
38664d844d9fad34e88160f6ebf86c043db9f1c5
/branches/initialize/skin/src/controls/ipadress.h
0a07b7d66e744c4cf73f71b1ba784795965984bd
[]
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,052
h
#pragma once #include "../base/skinctrl.h" namespace Skin { template<class BaseT = CIPAddressCtrl> struct SkinIpAddress : public SkinControlImpl<SkinIpAddress, BaseT> { SkinIpAddress() { _nPart = EP_EDITTEXT; _classid = IPADDRESS; } void OnFirstMessage() { } typedef SkinIpAddress<BaseT> this_type; typedef SkinControlImpl<SkinIpAddress, BaseT> base_type; BEGIN_MSG_MAP(this_type) MESSAGE_HANDLER(WM_NCPAINT, OnNcPaint) END_MSG_MAP() 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)) { WTL::CRect rcw; GetWindowRect(&rcw); rcw.right -= rcw.left; rcw.bottom -= rcw.top; rcw.top = rcw.left = 0; HDC hdc = GetWindowDC( ); // »æÖÆÍâ¿ò WTL::CBrush brBorder; int nState = GetState(); COLORREF cr; _scheme->GetColor(_classid, _nPart, nState, TMT_BORDERCOLOR, &cr); brBorder.CreateSolidBrush( cr ); FrameRect(hdc, WTL::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(); WTL::CBrush brBorder; _scheme->GetColor(_classid, _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 _nPart; }; }; // namespace
[ "zhongzeng@ba8f1dc9-3c1c-0410-9eed-0f8a660c14bd" ]
[ [ [ 1, 88 ] ] ]
0ec4aa238caa9686b7c0882f783256ced72d0311
28b097d96e87de603d75faf24e56394ac16d239f
/logger/myIDDraw7.cpp
73b3fb4b52e6006cbc502be0541e32a1cbe4401e
[]
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
6,536
cpp
#include "StdAfx.h" #include <varargs.h> myIDDraw7::myIDDraw7(LPDIRECTDRAW7 pOriginal) { logf(this, "myIDDraw7 Constructor"); m_pIDDraw = pOriginal; } myIDDraw7::~myIDDraw7(void) { logf(this, "myIDDraw7 Destructor"); } HRESULT __stdcall myIDDraw7::QueryInterface (REFIID a, LPVOID FAR * b) { char *iid = "?"; if (a == IID_IDirectDraw) iid = "IID_IDirectDraw"; if (a == IID_IDirectDraw2) iid = "IID_IDirectDraw2"; if (a == IID_IDirectDraw4) iid = "IID_IDirectDraw4"; if (a == IID_IDirectDraw7) iid = "IID_IDirectDraw7"; logf(this, "myIDDraw7::QueryInterface(%s,%08x)",iid,b); *b = NULL; // call this to increase AddRef at original object // and to check if such an interface is there HRESULT hRes = m_pIDDraw->QueryInterface(a, b); if (hRes == NOERROR) // if OK, send our "fake" address { if (a == IID_IDirectDraw7) *b = this; } return hRes; } ULONG __stdcall myIDDraw7::AddRef(void) { logf(this, "myIDDraw7::AddRef"); return(m_pIDDraw->AddRef()); } ULONG __stdcall myIDDraw7::Release(void) { logf(this, "myIDDraw7::Release"); // call original routine ULONG count = m_pIDDraw->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_pIDDraw = NULL; delete(this); } return(count); } HRESULT __stdcall myIDDraw7::Compact(void) { logf(this, "myIDDraw7::Compact"); return(m_pIDDraw->Compact()); } HRESULT __stdcall myIDDraw7::CreateClipper(DWORD a, LPDIRECTDRAWCLIPPER FAR* b, IUnknown FAR* c) { logf(this, "myIDDraw7::CreateClipper"); return(m_pIDDraw->CreateClipper(a, b, c)); } HRESULT __stdcall myIDDraw7::CreatePalette(DWORD a, LPPALETTEENTRY b, LPDIRECTDRAWPALETTE FAR* c, IUnknown FAR* d) { HRESULT r = m_pIDDraw->CreatePalette(a, b, c, d); *c = new myIDDrawPalette(*c); logf(this, "myIDDraw7::CreatePalette(%d,%08x,%08x,%08x) return %d",a,b,c,d,r); return r; } HRESULT __stdcall myIDDraw7::CreateSurface(LPDDSURFACEDESC2 a, LPDIRECTDRAWSURFACE7 FAR* b, IUnknown FAR* c) { HRESULT r = m_pIDDraw->CreateSurface(a, b, c); logf(this, "myIDDraw7::CreateSurface([%d,0x%x,%d,%d,%d,%d,%d], %08x, %08x) return %d", a->dwSize, a->dwFlags, a->dwWidth, a->dwHeight, a->lPitch, a->dwBackBufferCount, a->ddsCaps, b, c, r); *b = new myIDDrawSurface7(*b); return r; } HRESULT __stdcall myIDDraw7::DuplicateSurface(LPDIRECTDRAWSURFACE7 a, LPDIRECTDRAWSURFACE7 FAR* b) { logf(this, "myIDDraw7::DuplicateSurface"); return(m_pIDDraw->DuplicateSurface(a, b)); } HRESULT __stdcall myIDDraw7::EnumDisplayModes(DWORD a, LPDDSURFACEDESC2 b, LPVOID c, LPDDENUMMODESCALLBACK2 d) { logf(this, "myIDDraw7::EnumDisplayModes"); return(m_pIDDraw->EnumDisplayModes(a, b, c, d)); } HRESULT __stdcall myIDDraw7::EnumSurfaces(DWORD a, LPDDSURFACEDESC2 b, LPVOID c, LPDDENUMSURFACESCALLBACK7 d) { logf(this, "myIDDraw7::EnumSurfaces"); return(m_pIDDraw->EnumSurfaces(a, b, c, d)); } HRESULT __stdcall myIDDraw7::FlipToGDISurface(void) { logf(this, "myIDDraw7::FlipToGDISurface"); return(m_pIDDraw->FlipToGDISurface()); } HRESULT __stdcall myIDDraw7::GetCaps(LPDDCAPS a, LPDDCAPS b) { logf(this, "myIDDraw7::GetCaps"); return(m_pIDDraw->GetCaps(a, b)); } HRESULT __stdcall myIDDraw7::GetDisplayMode(LPDDSURFACEDESC2 a) { logf(this, "myIDDraw7::GetDisplayMode"); return(m_pIDDraw->GetDisplayMode(a)); } HRESULT __stdcall myIDDraw7::GetFourCCCodes(LPDWORD a, LPDWORD b) { logf(this, "myIDDraw7::GetFourCCCodes"); return(m_pIDDraw->GetFourCCCodes(a, b)); } HRESULT __stdcall myIDDraw7::GetGDISurface(LPDIRECTDRAWSURFACE7 FAR * a) { logf(this, "myIDDraw7::GetGDISurface"); return(m_pIDDraw->GetGDISurface(a)); } HRESULT __stdcall myIDDraw7::GetMonitorFrequency(LPDWORD a) { logf(this, "myIDDraw7::GetMonitorFrequency"); return(m_pIDDraw->GetMonitorFrequency(a)); } HRESULT __stdcall myIDDraw7::GetScanLine(LPDWORD a) { logf(this, "myIDDraw7::GetScanLine"); return(m_pIDDraw->GetScanLine(a)); } HRESULT __stdcall myIDDraw7::GetVerticalBlankStatus(LPBOOL a) { logf(this, "myIDDraw7::GetVerticalBlankStatus"); return(m_pIDDraw->GetVerticalBlankStatus(a)); } HRESULT __stdcall myIDDraw7::Initialize(GUID FAR* a) { logf(this, "myIDDraw7::Initialize"); return(m_pIDDraw->Initialize(a)); } HRESULT __stdcall myIDDraw7::RestoreDisplayMode(void) { logf(this, "myIDDraw7::RestoreDisplayMode"); return(m_pIDDraw->RestoreDisplayMode()); } HRESULT __stdcall myIDDraw7::SetCooperativeLevel(HWND a, DWORD b) { HRESULT h = m_pIDDraw->SetCooperativeLevel(a, b); logf(this, "myIDDraw7::SetCooperativeLevel(%08x, %d) return %d", a, b, h); return(h); } HRESULT __stdcall myIDDraw7::SetDisplayMode(DWORD a, DWORD b, DWORD c, DWORD d, DWORD e) { HRESULT h = m_pIDDraw->SetDisplayMode(a, b, c, d, e); logf(this, "myIDDraw7::SetDisplayMode(%d, %d, %d, %d, %d) return %d",a,b,c,d,e,h); return(h); } HRESULT __stdcall myIDDraw7::WaitForVerticalBlank(DWORD a, HANDLE b) { logf(this, "myIDDraw7::WaitForVerticalBlank(%d,%d)",a,b); return(m_pIDDraw->WaitForVerticalBlank(a, b)); } HRESULT __stdcall myIDDraw7::GetAvailableVidMem(LPDDSCAPS2 a, LPDWORD b, LPDWORD c) { logf(this, "myIDDraw7::GetAvailableVidMem"); return(m_pIDDraw->GetAvailableVidMem(a, b, c)); } HRESULT __stdcall myIDDraw7::GetSurfaceFromDC(HDC a, LPDIRECTDRAWSURFACE7 * b) { logf(this, "myIDDraw7::GetSurfaceFromDC"); return(m_pIDDraw->GetSurfaceFromDC(a, b)); } HRESULT __stdcall myIDDraw7::RestoreAllSurfaces(void) { logf(this, "myIDDraw7::RestoreAllSurfaces"); return(m_pIDDraw->RestoreAllSurfaces()); } HRESULT __stdcall myIDDraw7::TestCooperativeLevel(void) { logf(this, "myIDDraw7::TestCooperativeLevel"); return(m_pIDDraw->TestCooperativeLevel()); } HRESULT __stdcall myIDDraw7::GetDeviceIdentifier(LPDDDEVICEIDENTIFIER2 a, DWORD b) { logf(this, "myIDDraw7::GetDeviceIdentifier"); return(m_pIDDraw->GetDeviceIdentifier(a, b)); } HRESULT __stdcall myIDDraw7::StartModeTest(LPSIZE a, DWORD b, DWORD c) { logf(this, "myIDDraw7::StartModeTest"); return(m_pIDDraw->StartModeTest(a, b, c)); } HRESULT __stdcall myIDDraw7::EvaluateMode(DWORD a, DWORD * b) { logf(this, "myIDDraw7::EvaluateMode"); return(m_pIDDraw->EvaluateMode(a, b)); }
[ "[email protected]@ca3b60c3-ba86-2864-2f26-32acf34adade" ]
[ [ [ 1, 272 ] ] ]
744163baaa45e07bede704e39eedb9aeabf8611e
9590b067bcd6087a7ae97a77788818562649bd02
/Sources/Internal/Scene3D/Frustum.h
a097fa62bca56b6f6a2020fb985c0a515952c593
[]
no_license
vaad2/dava.framework
b2ce2ad737c374a28e9d13112db1951a965870e5
bc0589048287a9b303b794854b75c98eb61baa8e
refs/heads/master
2020-11-27T05:12:12.268778
2011-12-01T13:09:34
2011-12-01T13:09:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,847
h
/*================================================================================== Copyright (c) 2008, DAVA Consulting, LLC All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the DAVA Consulting, LLC nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE DAVA CONSULTING, LLC AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DAVA CONSULTING, LLC BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Revision History: * Created by Vitaliy Borodovsky =====================================================================================*/ #ifndef __DAVAENGINE_FRUSTUM_H__ #define __DAVAENGINE_FRUSTUM_H__ #include "Base/BaseTypes.h" #include "Base/BaseObject.h" #include "Base/BaseMath.h" #include "Render/RenderManager.h" #include "Math/AABBox3.h" #include "Math/Plane.h" namespace DAVA { /** \brief Frustum class to detect objects visibility This class is supposed for testing objects for visibility This class is multiplane frustum Main logical question is why frustum is related to render, and not in Math or Scene3D. The answer is simple: I assume that culling code can differ for OGL, DX matrices. Let's see when we'll add DirectX am I right. */ class Frustum : public BaseObject { enum eFrustumPlane { EFP_LEFT = 0, EFP_RIGHT, EFP_BOTTOM, EFP_TOP, EFP_NEAR, EFP_FAR, }; public: enum eFrustumResult { EFR_INSIDE = 0x0, EFR_OUTSIDE = 0x1, EFR_INTERSECT = 0x2, }; Frustum(); ~Frustum(); //! \brief Set view frustum from matrix information //! \param viewProjection view * projection matrix void Set(const Matrix4 & viewProjection); // from active model view projection void Set(); //! \brief Check axial aligned bounding box visibility //! \param min bounding box minimum point //! \param max bounding box maximum point //! \return true if inside bool IsInside(const Vector3 & min, const Vector3 &max) const; //! \brief Check axial aligned bounding box visibility //! \param box bounding box bool IsInside(const AABBox3 & box)const; //! \brief Check axial aligned bounding box visibility //! \param box bounding box bool IsFullyInside(const AABBox3 & box)const; // ********************************************* // All above require detailed testing !!! Never tested in real project!!! // ********************************************* //! \brief Check axial aligned bounding box visibility //! \param min bounding box minimum point //! \param max bounding box maximum point //! \return \ref eFrustumResult to classify intersection eFrustumResult Classify(const Vector3 & min, const Vector3 &max) const; //! \brief Check axial aligned bounding box visibility //! \param min bounding box minimum point //! \param max bounding box maximum point //! \return \ref eFrustumResult to classify intersection eFrustumResult Classify(const AABBox3 & box) const; //! \brief check bounding sphere visibility against frustum //! \param point sphere center point //! \param radius sphere radius bool IsInside(const Vector3 & point, const float32 radius) const; //! \brief function return real plane count in this frustum inline int32 GetPlaneCount(); //! \brief function return plane with index //! \param i index of plane we want to get inline Plane & GetPlane(int32 i); // void DebugDraw(); private: int32 planeCount; Vector<Plane> planeArray; }; }; #endif // __DAVAENGINE_FRUSTUM_H__
[ [ [ 1, 141 ] ] ]
1341ec0dcd75573f6ee2e8a4fe0edcab6f6706e9
b5ad65ebe6a1148716115e1faab31b5f0de1b493
/src/pymuscle/rs/pymrscore.cpp
d1d7be52bd632d2182e8c1326d7e3eb604922431
[]
no_license
gasbank/aran
4360e3536185dcc0b364d8de84b34ae3a5f0855c
01908cd36612379ade220cc09783bc7366c80961
refs/heads/master
2021-05-01T01:16:19.815088
2011-03-01T05:21:38
2011-03-01T05:21:38
1,051,010
1
0
null
null
null
null
UTF-8
C++
false
false
12,855
cpp
#include "PymRsPch.h" #include "PrsGraphCapi.h" #include "PymStruct.h" #include "PymBiped.h" #include "RigidBody.h" #include "MuscleFiber.h" #include "ConvexHullCapi.h" #include "PymuscleConfig.h" #include "StateDependents.h" #include "Config.h" #include "DebugPrintDef.h" #include "Optimize.h" #include "PymJointAnchor.h" #include "PymDebugMessageFlags.h" #include "TrajParser.h" #include "PhysicsThreadMain.h" #include "PymCmdLineParser.h" #include "MathUtil.h" #include "pymrscore.h" #ifdef WIN32 #define PATH_SEPARATOR '\\' #else #define PATH_SEPARATOR '/' #endif static FILE *devnull; FILE *PymGetDevnull() { return devnull; } void PrintCmdLineHelp(int argc, char *argv[]) { printf(" Usage:\n"); printf(" %s config_file <simulation conf file> [Options]\n", strrchr(argv[0], PATH_SEPARATOR) + 1); printf("\n"); printf(" Options:\n"); printf(" --test simulator test mode (no simulation conf file needed)\n"); printf("\n"); } void pym_update_debug_msg_streams(int *dmflags, FILE *dmstreams[]) { int i; #ifdef WIN32 devnull = fopen("nul", "w"); #else devnull = fopen("/dev/null", "w"); #endif assert(devnull); FOR_0(i, PDMTE_COUNT) { if (dmflags[i]) dmstreams[i] = stdout; else dmstreams[i] = devnull; } } void pym_init_debug_msg_streams(FILE *dmstreams[]) { int dmflags[PDMTE_COUNT] = {0,}; dmflags[PDMTE_INIT_MF_FOR_EACH_RB] = 1; dmflags[PDMTE_INIT_RB_CORRESPONDENCE_1] = 1; dmflags[PDMTE_INIT_RB_CORRESPONDENCE_2] = 1; dmflags[PDMTE_INIT_JOINT_ANCHOR_ATTACH_REPORT] = 1; pym_update_debug_msg_streams(dmflags, dmstreams); } void pym_compute_reference_com( const pym_config_t *const pymCfg, pym_traj_t * pymTraj ) { const int nd = 6; double tot_mass = 0; for (int j = 0; j < pymCfg->nBody; ++j) { tot_mass += pymCfg->body[j].b.m; } pymTraj->comTrajData = new double[3*pymTraj->nBlenderFrame]; for (int i = 0; i < pymTraj->nBlenderFrame; ++i) { double comref[3] = {0,}; for (int j = 0; j < pymCfg->nBody; ++j) { const double *const ref = pymTraj->trajData + (i+0)*pymTraj->nBlenderBody*nd + pymTraj->corresMapIndex[j]*nd; for (int k = 0; k < 3; ++k) { comref[k] += pymCfg->body[j].b.m * ref[k]; } } for (int j = 0; j < 3; ++j) { comref[j] /= tot_mass; pymTraj->comTrajData[3 * i + j] = comref[j]; } } } int pym_init_global(int argc, char *argv[], pym_config_t *pymCfg, pym_traj_t *pymTraj, pym_cmdline_options_t *cmdopt, FILE** _outputFile, FILE *dmstreams[]) { int ret = 0; if ( argc < 2 || (argc == 2 && strcmp(argv[1], "--help") == 0) ) { PrintCmdLineHelp(argc, argv); return 1; } ret = PymParseCmdlineOptions(cmdopt, argc, argv); if (ret < 0) { printf("Failed.\n"); return -2; } /* Initialize debug message flags (dmflags) */ pym_init_debug_msg_streams(dmstreams); /* Construct pymCfg structure */ ret = PymConstructConfig(cmdopt->simconf, pymCfg, dmstreams[PDMTE_INIT_MF_FOR_EACH_RB]); if (ret < 0) { printf("PymConstructConfig() Failed.\n"); return -1; } PymConvertRotParamInPlace(pymCfg, pymCfg->rotparam); const char *t1 = strrchr(cmdopt->trajconf, '/') + 1; const char *t2 = strchr(t1, '.'); size_t tlen = t2-t1; strncpy(pymCfg->trajName, t1, tlen); pymCfg->trajName[tlen] = 0; printf("trajName = %s\n", pymCfg->trajName); int i; FOR_0(i, pymCfg->nBody) pymTraj->corresMapIndex[i] = -1; if (cmdopt->trajconf) { char fnJaCfg[128] = {0}; int parseRet = PymParseTrajectoryFile(pymTraj, cmdopt->trajconf, cmdopt->trajdata); if (parseRet) { /* from now on, we should not refer 'pymTraj' variable in this case. */ printf("Warn - trajectory data file not exists.\n"); /* No trajconf provided. */ PymSetPymCfgChiRefToCurrentState(pymCfg); } else { assert(pymTraj->nCorresMap > 0); /* The simulation time step defined in simconf and * the frame time (reciprocal of FPS) in trajdata * should have the same value. If mismatch happens * we ignore simulation time step in simconf. */ if (fabs(1.0/pymTraj->exportFps - pymCfg->h) > 1e-6) { printf("Warning - simulation time step defined in simconf and\n"); printf(" trajectory data do not match.\n"); printf(" simconf : %3d FPS (%lf sec per frame)\n", (int)ceil(1.0/pymCfg->h), pymCfg->h); printf(" trajconf : %3d FPS (%lf sec per frame)\n", pymTraj->exportFps, 1.0/pymTraj->exportFps); printf(" simconf's value will be ignored.\n"); pymCfg->h = 1.0/pymTraj->exportFps; } PymCorresMapIndexFromCorresMap(pymTraj, pymCfg, dmstreams); /* * We need at least three frames of trajectory data * to follow one or more reference trajectory frames since * the first (frame 0) is used as previous step and * the second (frame 1) is used as current step and * the third (frame 2) is used as the reference trajectory for next step * * We need (nBlenderFrame-2) simulation iteration to complete * following the trajectory entirely. So the following assertion helds: */ assert(pymTraj->nBlenderFrame >= 3); PymSetInitialStateUsingTrajectory(pymCfg, pymTraj); pym_compute_reference_com(pymCfg, pymTraj); } PymInferJointAnchorConfFileName(fnJaCfg, cmdopt->trajconf); const size_t num_joint_anchor = sizeof(pymCfg->pymJa)/sizeof(pym_joint_anchor_t); pymCfg->na = PymParseJointAnchorFile(pymCfg->pymJa, num_joint_anchor, fnJaCfg); if (pymCfg->na < 0) { /* Joint anchor conf file parse failure. Ignore joint anchors happily. */ pymCfg->na = 0; } printf("Info - # of joint anchors = %d\n", pymCfg->na); PymInitJointAnchors(pymCfg, dmstreams); PymConstructAnchoredJointList(pymCfg); if (pymCfg->joint_constraints) { printf("Fibers for joint constraints (joint muscles) are created automatically.\n"); for (int i = 0; i < pymCfg->nJoint; ++i) { const int ai = pymCfg->anchoredJoints[i].aIdx; const int bi = pymCfg->anchoredJoints[i].bIdx; pym_rb_named_t *rbA = &pymCfg->body[ai].b; pym_rb_named_t *rbB = &pymCfg->body[bi].b; double *a_apos = pymCfg->body[ai].b.jointAnchors[ pymCfg->anchoredJoints[i].aAnchorIdx ]; double *b_apos = pymCfg->body[bi].b.jointAnchors[ pymCfg->anchoredJoints[i].bAnchorIdx ]; pym_mf_named_t *mf = &pymCfg->fiber [ pymCfg->nFiber ].b; mf->A = 0; mf->b = 1; memcpy(mf->fibb_org, a_apos, sizeof(double)*3); memcpy(mf->fibb_ins, b_apos, sizeof(double)*3); mf->org = ai; mf->ins = bi; mf->kpe = 1; mf->kse = 1; mf->mType = PMT_JOINT_MUSCLE; mf->T = 0; mf->xrest = 1.0; mf->xrest_lower = 0.0; mf->xrest_upper = 10.0; strcpy(mf->name, "joint muscle fiber"); rbA->fiber[ rbA->nFiber ] = pymCfg->nFiber; rbB->fiber[ rbB->nFiber ] = pymCfg->nFiber; ++rbA->nFiber; ++rbB->nFiber; ++pymCfg->nFiber; } } } else { /* No trajconf provided. */ PymSetPymCfgChiRefToCurrentState(pymCfg); } pymCfg->real_muscle = false; pymCfg->zero_cost_func = false; pymCfg->temp_ref_mode = false; pymCfg->render_hud = true; pymCfg->freeze_pose = false; pymCfg->support_polygon_constraint = false; if (cmdopt->frame >= 0) { /* Total simulation frame set by user */ pymCfg->nSimFrame = cmdopt->frame; } else if (cmdopt->trajconf && pymTraj->trajData) { pymCfg->nSimFrame = pymTraj->nBlenderFrame - 2; } else { /* if no traj conf data provided */ pymCfg->nSimFrame = 100; } assert(pymCfg->nSimFrame >= 1); FILE *outputFile = fopen(cmdopt->output, "w"); if (!outputFile) { printf("Error: Opening the output file %s failed.\n", cmdopt->output); return -3; } fprintf(outputFile, "%d %d\n", pymCfg->nSimFrame, pymCfg->nBody); *_outputFile = outputFile; /* Let's start the simulation happily :) */ printf("Starting the simulation...\n"); return 0; } void pym_init_phy_thread_ctx(pym_physics_thread_context_t* cxt, pym_config_t *pymCfg, pym_cmdline_options_t *cmdopt, pym_traj_t *pymTraj, FILE *outputFile, FILE *dmstreams[]) { pym_physics_thread_context_t phyCon; cxt->pymCfg = pymCfg; cxt->cmdopt = cmdopt; cxt->pymTraj = pymTraj; cxt->outputFile = outputFile; cxt->dmstreams = dmstreams; cxt->totalPureOptTime = 0; cxt->stop = 0; cxt->trunkExternalForce[0] = 0; cxt->trunkExternalForce[1] = 0; cxt->trunkExternalForce[2] = 0; cxt->comZGraph = PrsGraphNew("COM Z"); cxt->comDevGraph = PrsGraphNew("COM Z Dev."); cxt->exprotGraph.resize(pymCfg->nBody); for (int i = 0; i < pymCfg->nBody; ++i) cxt->exprotGraph[i] = PrsGraphNew("Body Rot"); cxt->actGraph = PrsGraphNew("Act"); cxt->ligGraph = PrsGraphNew("Lig"); cxt->sd = (pym_rb_statedep_t *)malloc(sizeof(pym_rb_statedep_t) * pymCfg->nBody); for (int i = 0; i < pymCfg->nBody; ++i) pym_init_statedep(cxt->sd[i]); } pym_rs_t *PymRsInitContext(int argc, char *argv[]) { printf("Pymuscle realtime simulator -- 2010 Geoyeob Kim\n"); pym_rs_t *rs = new pym_rs_t; int ret = pym_init_global(argc, argv, &rs->pymCfg, &rs->pymTraj, &rs->cmdopt, &rs->outputFile, rs->dmstreams); if (ret) { /* something goes wrong */ return 0; } rs->drawing_options = 0; /* Initialize the physics thread context */ pym_init_phy_thread_ctx(&rs->phyCon, &rs->pymCfg, &rs->cmdopt, &rs->pymTraj, rs->outputFile, rs->dmstreams); /* comZGraph */ PrsGraphSetMaxY(rs->phyCon.comZGraph, 4.0); PRSGRAPHDATA simComGd = PrsGraphDataNew(rs->pymCfg.nSimFrame); PrsGraphDataSetLineColor(simComGd, 0, 1, 0); PrsGraphAttach(rs->phyCon.comZGraph, PCG_SIM_COMZ, simComGd); PRSGRAPHDATA refComGd = PrsGraphDataNew(rs->pymCfg.nSimFrame); PrsGraphDataSetLineColor(refComGd, 1, 0, 0); PrsGraphAttach(rs->phyCon.comZGraph, PCG_REF_COMZ, refComGd); /* comDevGraph */ PrsGraphSetMaxY(rs->phyCon.comDevGraph, 2.0); PRSGRAPHDATA comDevGd = PrsGraphDataNew(rs->pymCfg.nSimFrame); PrsGraphDataSetLineColor(comDevGd, 0, 1, 0); PrsGraphAttach(rs->phyCon.comDevGraph, PCG_COMDEV, comDevGd); PrsGraphAddGuideY(rs->phyCon.comDevGraph, 0.01, 1, 1, 0); /* actGraph */ PrsGraphSetMaxY(rs->phyCon.actGraph, 10000); PRSGRAPHDATA actActGd = PrsGraphDataNew(rs->pymCfg.nSimFrame); PrsGraphDataSetLineColor(actActGd, 1, 0, 0); PrsGraphAttach(rs->phyCon.actGraph, PCG_ACT_ACT, actActGd); PRSGRAPHDATA actTenGd = PrsGraphDataNew(rs->pymCfg.nSimFrame); PrsGraphDataSetLineColor(actTenGd, 0, 1, 0); PrsGraphAttach(rs->phyCon.actGraph, PCG_ACT_TEN, actTenGd); /* ligGraph */ PrsGraphSetMaxY(rs->phyCon.ligGraph, 10000); PRSGRAPHDATA ligActGd = PrsGraphDataNew(rs->pymCfg.nSimFrame); PrsGraphDataSetLineColor(ligActGd, 1, 0, 0); PrsGraphAttach(rs->phyCon.ligGraph, PCG_LIG_ACT, ligActGd); PRSGRAPHDATA ligTenGd = PrsGraphDataNew(rs->pymCfg.nSimFrame); PrsGraphDataSetLineColor(ligTenGd, 0, 1, 0); PrsGraphAttach(rs->phyCon.ligGraph, PCG_LIG_TEN, ligTenGd); /* exprotGraph */ for (std::vector<PRSGRAPH>::iterator i = rs->phyCon.exprotGraph.begin(); i != rs->phyCon.exprotGraph.end(); ++i) { PrsGraphSetMaxY(*i, 2*M_PI); PRSGRAPHDATA d = PrsGraphDataNew(rs->pymCfg.nSimFrame); PrsGraphDataSetLineColor(d, 1, 0, 0); PrsGraphAttach(*i, 0, d); } return rs; } void PymRsDestroyContext(pym_rs_t *rs) { printf("Accumulated pure MOSEK optimizer time : %lf s\n", rs->phyCon.totalPureOptTime); fclose(rs->outputFile); printf("Output written to %s\n", rs->cmdopt.output); PymDestoryConfig(&rs->pymCfg); PrsGraphDelete(rs->phyCon.comZGraph); PrsGraphDelete(rs->phyCon.comDevGraph); PrsGraphDelete(rs->phyCon.actGraph); PrsGraphDelete(rs->phyCon.ligGraph); for (std::vector<PRSGRAPH>::iterator i = rs->phyCon.exprotGraph.begin(); i != rs->phyCon.exprotGraph.end(); ++i) { PrsGraphDelete(*i); } free(rs->pymTraj.trajData); free(rs->phyCon.sd); if (rs->cmdopt.freeTrajStrings) { free(rs->cmdopt.trajconf); free(rs->cmdopt.trajdata); } if (rs->cmdopt.freeOutputStrings) { free(rs->cmdopt.output); } delete rs; }
[ "Dan@Dan-PC.(none)", "[email protected]" ]
[ [ [ 1, 1 ], [ 3, 3 ] ], [ [ 2, 2 ], [ 4, 363 ] ] ]
41a8b9ead55cff52bad1574406f2f999dff226c6
cd0987589d3815de1dea8529a7705caac479e7e9
/webkit/WebKitTools/QtTestBrowser/urlloader.h
2ded5e96dff6ed1e95b037cef19af6978b3830c3
[]
no_license
azrul2202/WebKit-Smartphone
0aab1ff641d74f15c0623f00c56806dbc9b59fc1
023d6fe819445369134dee793b69de36748e71d7
refs/heads/master
2021-01-15T09:24:31.288774
2011-07-11T11:12:44
2011-07-11T11:12:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,980
h
/* * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies) * Copyright (C) 2009 University of Szeged * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef urlloader_h #define urlloader_h #include "qwebframe.h" #include <QTextStream> #include <QVector> class UrlLoader : public QObject { Q_OBJECT public: UrlLoader(QWebFrame* frame, const QString& inputFileName); public slots: void loadNext(); private: void init(const QString& inputFileName); bool getUrl(QString& qstr); private: QVector<QString> m_urls; int m_index; QWebFrame* m_frame; QTextStream m_stdOut; int m_loaded; }; #endif
[ [ [ 1, 58 ] ] ]
02e9c7a35e4496a5052689762d8b187ea55f4031
4aadb120c23f44519fbd5254e56fc91c0eb3772c
/Source/opensteer/src/Obstacle.cpp
356e59f6457d0ebdaa77600d1db089c8f5dbacac
[ "MIT" ]
permissive
janfietz/edunetgames
d06cfb021d8f24cdcf3848a59cab694fbfd9c0ba
04d787b0afca7c99b0f4c0692002b4abb8eea410
refs/heads/master
2016-09-10T19:24:04.051842
2011-04-17T11:00:09
2011-04-17T11:00:09
33,568,741
0
0
null
null
null
null
UTF-8
C++
false
false
13,301
cpp
//----------------------------------------------------------------------------- // // // OpenSteer -- Steering Behaviors for Autonomous Characters // // Copyright (c) 2002-2004, Sony Computer Entertainment America // Original author: Craig Reynolds <[email protected]> // // 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. // // //----------------------------------------------------------------------------- // // // OpenSteer Obstacle classes // // 10-28-04 cwr: split off from Obstacle.h // // //----------------------------------------------------------------------------- #include "OpenSteer/Obstacle.h" //----------------------------------------------------------------------------- // Obstacle // compute steering for a vehicle to avoid this obstacle, if needed OpenSteer::Vec3 OpenSteer::Obstacle::steerToAvoid (const AbstractVehicle& vehicle, const float minTimeToCollision) const { // find nearest intersection with this obstacle along vehicle's path PathIntersection pi; findIntersectionWithVehiclePath (vehicle, pi); // return steering for vehicle to avoid intersection, or zero if non found return pi.steerToAvoidIfNeeded (vehicle, minTimeToCollision); } //----------------------------------------------------------------------------- // Obstacle // static method to apply steerToAvoid to nearest obstacle in an ObstacleGroup OpenSteer::Vec3 OpenSteer::Obstacle:: steerToAvoidObstacles (const AbstractVehicle& vehicle, const float minTimeToCollision, const ObstacleGroup& obstacles) { PathIntersection nearest, next; // test all obstacles in group for an intersection with the vehicle's // future path, select the one whose point of intersection is nearest firstPathIntersectionWithObstacleGroup (vehicle, obstacles, nearest, next); // if nearby intersection found, steer away from it, otherwise no steering return nearest.steerToAvoidIfNeeded (vehicle, minTimeToCollision); } //----------------------------------------------------------------------------- // Obstacle // static method to find first vehicle path intersection in an ObstacleGroup // // returns its results in the PathIntersection argument "nearest", // "next" is used to store internal state. void OpenSteer::Obstacle:: firstPathIntersectionWithObstacleGroup (const AbstractVehicle& vehicle, const ObstacleGroup& obstacles, PathIntersection& nearest, PathIntersection& next) { // test all obstacles in group for an intersection with the vehicle's // future path, select the one whose point of intersection is nearest next.intersect = false; nearest.intersect = false; for (ObstacleIterator o = obstacles.begin(); o != obstacles.end(); o++) { // find nearest point (if any) where vehicle path intersects obstacle // o, storing the results in PathIntersection object "next" (**o).findIntersectionWithVehiclePath (vehicle, next); // if this is the first intersection found, or it is the nearest found // so far, store it in PathIntersection object "nearest" const bool firstFound = !nearest.intersect; const bool nearestFound = (next.intersect && (next.distance < nearest.distance)); if (firstFound || nearestFound) nearest = next; } } //----------------------------------------------------------------------------- // PathIntersection // determine steering once path intersections have been found OpenSteer::Vec3 OpenSteer::Obstacle::PathIntersection:: steerToAvoidIfNeeded (const AbstractVehicle& vehicle, const float minTimeToCollision) const { // if nearby intersection found, steer away from it, otherwise no steering const float minDistanceToCollision = minTimeToCollision * vehicle.speed(); if (intersect && (distance < minDistanceToCollision)) { // compute avoidance steering force: take the component of // steerHint which is lateral (perpendicular to vehicle's // forward direction), set its length to vehicle's maxForce Vec3 lateral = steerHint.perpendicularComponent (vehicle.forward ()); return lateral.normalized () * vehicle.maxForce (); } else { return Vec3::zero; } } //----------------------------------------------------------------------------- // SphereObstacle // find first intersection of a vehicle's path with this obstacle void OpenSteer:: SphereObstacle:: findIntersectionWithVehiclePath (const AbstractVehicle& vehicle, PathIntersection& pi) const { // This routine is based on the Paul Bourke's derivation in: // Intersection of a Line and a Sphere (or circle) // http://www.swin.edu.au/astronomy/pbourke/geometry/sphereline/ // But the computation is done in the vehicle's local space, so // the line in question is the Z (Forward) axis of the space which // simplifies some of the calculations. float b, c, d, p, q, s; Vec3 lc; // initialize pathIntersection object to "no intersection found" pi.intersect = false; // find sphere's "local center" (lc) in the vehicle's coordinate space lc = vehicle.localizePosition (center); pi.vehicleOutside = lc.length () > radius; // if obstacle is seen from inside, but vehicle is outside, must avoid // (noticed once a vehicle got outside it ignored the obstacle 2008-5-20) if (pi.vehicleOutside && (seenFrom () == inside)) { pi.intersect = true; pi.distance = 0.0f; pi.steerHint = (center - vehicle.position()).normalized(); return; } // compute line-sphere intersection parameters const float r = radius + vehicle.radius(); b = -2 * lc.z; c = square (lc.x) + square (lc.y) + square (lc.z) - square (r); d = (b * b) - (4 * c); // when the path does not intersect the sphere if (d < 0) return; // otherwise, the path intersects the sphere in two points with // parametric coordinates of "p" and "q". (If "d" is zero the two // points are coincident, the path is tangent) s = sqrtXXX (d); p = (-b + s) / 2; q = (-b - s) / 2; // both intersections are behind us, so no potential collisions if ((p < 0) && (q < 0)) return; // at least one intersection is in front, so intersects our forward // path pi.intersect = true; pi.obstacle = this; pi.distance = ((p > 0) && (q > 0)) ? // both intersections are in front of us, find nearest one ((p < q) ? p : q) : // otherwise one is ahead and one is behind: we are INSIDE obstacle (seenFrom () == outside ? // inside a solid obstacle, so distance to obstacle is zero 0.0f : // hollow obstacle (or "both"), pick point that is in front ((p > 0) ? p : q)); pi.surfacePoint = vehicle.position() + (vehicle.forward() * pi.distance); pi.surfaceNormal = (pi.surfacePoint-center).normalized(); switch (seenFrom ()) { case outside: pi.steerHint = pi.surfaceNormal; break; case inside: pi.steerHint = -pi.surfaceNormal; break; case both: pi.steerHint = pi.surfaceNormal * (pi.vehicleOutside ? 1.0f : -1.0f); break; } } //----------------------------------------------------------------------------- // BoxObstacle // find first intersection of a vehicle's path with this obstacle void OpenSteer:: BoxObstacle:: findIntersectionWithVehiclePath (const AbstractVehicle& vehicle, PathIntersection& pi) const { // abbreviations const float w = width; // dimensions const float h = height; const float d = depth; const Vec3 s = side (); // local space const Vec3 u = up (); const Vec3 f = forward (); const Vec3 p = position (); const Vec3 hw = s * (0.5f * width); // offsets for face centers const Vec3 hh = u * (0.5f * height); const Vec3 hd = f * (0.5f * depth); const seenFromState sf = seenFrom (); // the box's six rectangular faces RectangleObstacle r1 (w, h, s, u, f, p + hd, sf); // front RectangleObstacle r2 (w, h, -s, u, -f, p - hd, sf); // back RectangleObstacle r3 (d, h, -f, u, s, p + hw, sf); // side RectangleObstacle r4 (d, h, f, u, -s, p - hw, sf); // other side RectangleObstacle r5 (w, d, s, -f, u, p + hh, sf); // top RectangleObstacle r6 (w, d, -s, -f, -u, p - hh, sf); // bottom // group the six RectangleObstacle faces together ObstacleGroup faces; faces.push_back (&r1); faces.push_back (&r2); faces.push_back (&r3); faces.push_back (&r4); faces.push_back (&r5); faces.push_back (&r6); // find first intersection of vehicle path with group of six faces PathIntersection next; firstPathIntersectionWithObstacleGroup (vehicle, faces, pi, next); // when intersection found, adjust PathIntersection for the box case if (pi.intersect) { pi.obstacle = this; pi.steerHint = ((pi.surfacePoint - position ()).normalized () * (pi.vehicleOutside ? 1.0f : -1.0f)); } } //----------------------------------------------------------------------------- // PlaneObstacle // find first intersection of a vehicle's path with this obstacle void OpenSteer:: PlaneObstacle:: findIntersectionWithVehiclePath (const AbstractVehicle& vehicle, PathIntersection& pi) const { // initialize pathIntersection object to "no intersection found" pi.intersect = false; const Vec3 lp = localizePosition (vehicle.position ()); const Vec3 ld = localizeDirection (vehicle.forward ()); // no obstacle intersection if path is parallel to XY (side/up) plane if (ld.dot (Vec3::forward) == 0.0f) return; // no obstacle intersection if vehicle is heading away from the XY plane if ((lp.z > 0.0f) && (ld.z > 0.0f)) return; if ((lp.z < 0.0f) && (ld.z < 0.0f)) return; // no obstacle intersection if obstacle "not seen" from vehicle's side if ((seenFrom () == outside) && (lp.z < 0.0f)) return; if ((seenFrom () == inside) && (lp.z > 0.0f)) return; // find intersection of path with rectangle's plane (XY plane) const float ix = lp.x - (ld.x * lp.z / ld.z); const float iy = lp.y - (ld.y * lp.z / ld.z); const Vec3 planeIntersection (ix, iy, 0.0f); // no obstacle intersection if plane intersection is outside 2d shape if (!xyPointInsideShape (planeIntersection, vehicle.radius ())) return; // otherwise, the vehicle path DOES intersect this rectangle const Vec3 localXYradial = planeIntersection.normalized (); const Vec3 radial = globalizeDirection (localXYradial); const float sideSign = (lp.z > 0.0f) ? +1.0f : -1.0f; const Vec3 opposingNormal = forward () * sideSign; pi.intersect = true; pi.obstacle = this; pi.distance = (lp - planeIntersection).length (); pi.steerHint = opposingNormal + radial; // should have "toward edge" term? pi.surfacePoint = globalizePosition (planeIntersection); pi.surfaceNormal = opposingNormal; pi.vehicleOutside = lp.z > 0.0f; } //----------------------------------------------------------------------------- // RectangleObstacle // determines if a given point on XY plane is inside obstacle shape bool OpenSteer:: RectangleObstacle:: xyPointInsideShape (const Vec3& point, float radius) const { const float w = radius + (width * 0.5f); const float h = radius + (height * 0.5f); return !((point.x > w) || (point.x < -w) || (point.y > h) || (point.y < -h)); } //-----------------------------------------------------------------------------
[ "janfietz@localhost" ]
[ [ [ 1, 355 ] ] ]
3cb0dbe8c74ee6f8e47df24589041f02f9788631
968aa9bac548662b49af4e2b873b61873ba6f680
/imgtools/romtools/rofsbuild/r_romnode.h
bffc5d89667dfdf7ebc410e242d6620e7a4fb6e0
[]
no_license
anagovitsyn/oss.FCL.sftools.dev.build
b3401a1ee3fb3c8f3d5caae6e5018ad7851963f3
f458a4ce83f74d603362fe6b71eaa647ccc62fee
refs/heads/master
2021-12-11T09:37:34.633852
2010-12-01T08:05:36
2010-12-01T08:05:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,098
h
/* * Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of the License "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ #ifndef __R_ROMNODE_H__ #define __R_ROMNODE_H__ #include <fstream> #include <e32std.h> #include <vector> #include <string> #include "rofs.h" #include "e32image.h" #include "h_utl.h" const TUint KOverrideStack = 0x01; const TUint KOverrideHeapMin = 0x02; const TUint KOverrideHeapMax = 0x04; const TUint KOverrideRelocationAddress = 0x08; const TUint KOverrideUid1 = 0x10; const TUint KOverrideUid2 = 0x20; const TUint KOverrideUid3 = 0x40; const TUint KOverrideCallEntryPoint = 0x80; const TUint KOverrideNoCallEntryPoint = 0x100; const TUint KOverridePriority = 0x200; const TUint KOverrideStackReserve = 0x400; const TUint KOverrideKeepIAT = 0x800; const TUint KOverrideCapability = 0x1000; const TUint KOverrideFixed = 0x2000; const TUint KOverrideDllData = 0x4000; const TUint KOverrideCodeUnpaged = 0x8000; const TUint KOverrideCodePaged = 0x10000; const TUint KOverrideDataUnpaged = 0x20000; const TUint KOverrideDataPaged = 0x40000; enum ECompression{ ECompressionUnknown=0, ECompressionCompress=1, ECompressionUncompress=2 }; const TInt KFileHidden = 0xFFFFFFFF; class TRomBuilderEntry; class RomFileStructure; class TRomNode { public: TRomNode(const char* aName, TRomBuilderEntry* aEntry = 0); ~TRomNode(); void Destroy(); static inline TRomNode* FirstNode() { return TheFirstNode; }; inline TRomNode* NextNode() { return iNextNode; }; inline void SetNextNode(TRomNode* aNode) { iNextNode = aNode; }; inline TRomNode* Currentchild() const { return iChild; }; inline TRomNode* Currentsibling() const { return iSibling; }; void DisplayStructure(ostream* aOut); TRomNode* FindInDirectory(const char *aName) const; void AddFile(TRomNode *aChild); TRomNode* NewSubDir(const char *aName); TInt SetAtt(char *anAttWord); TInt SetAttExtra(char *anAttWord, TRomBuilderEntry* aFile, enum EKeyword aKeyword); inline void SetStackSize(TInt aValue); inline void SetHeapSizeMin(TInt aValue); inline void SetHeapSizeMax(TInt aValue); inline void SetCapability(SCapabilitySet& aCapability); inline void SetUid1(TInt aValue); inline void SetUid2(TInt aValue); inline void SetUid3(TInt aValue); inline void SetPriority(TProcessPriority aValue); inline void SetFixed(); inline void SetDllData(); TBool IsDirectory() const { return 0 == iEntry; }; TBool IsFile() const { return 0!=iEntry; }; TInt CalculateDirectoryEntrySize( TInt& aDirectoryBlockSize, TInt& aFileBlockSize ); TInt CountFileAndDir(TInt& aFileCount, TInt& aDirCount); TInt PlaceFile( TUint8* &aDest, TUint aOffset, TUint aMaxSize, CBytePair *aBPE ); TInt Place( TUint8* aDestBase ); TInt NameCpy(char* aDest, TUint8& aUnicodeLength ); TInt NameLengthUnicode() const; void Rename(TRomNode *aOldParent, TRomNode* aNewParent, const char* aNewName); TRofsEntry* RofsEntry() const { return iRofsEntry; }; void SetRofsEntry(TRofsEntry* aEntry); inline void SetImagePosition( TInt aPosition ) { iImagePosition = aPosition; }; inline void SetFileBlockPosition( TInt aPosition ) { iFileBlockPosition = aPosition; }; void AddNodeForSameFile(TRomNode* aPreviousNode, TRomBuilderEntry* aFile); void CountDirectory(TInt& aFileCount, TInt& aDirCount); TInt ProcessDirectory(RomFileStructure* aRFS); TRomNode* CopyDirectory(TRomNode*& aLastExecutable); void Alias(TRomNode* aNode); static void deleteTheFirstNode(); static void displayFlatList(); TInt FullNameLength(TBool aIgnoreHiddenAttrib = EFalse) const; TInt GetFullName(char* aBuf, TBool aIgnoreHiddenAttrib = EFalse) const; static void InitializeCount(); // Accessor Function. inline TRomNode* GetParent() const { return iParent; } void FlushLogMessages(); private: void Remove(TRomNode* aChild); void Add(TRomNode* aChild); void Clone(TRomNode* aOriginal); TInt CalculateEntrySize() const; private: static TInt Count; // seed for unique identifiers // Flat linked list of TRomNode structures static TRomNode* TheFirstNode; static TRomNode* TheLastNode; TRomNode* iNextNode; TRomNode* iParent; TRomNode* iSibling; TRomNode* iChild; TRomNode* iNextNodeForSameFile; protected: TInt iIdentifier; TRofsEntry* iRofsEntry; // in ROM image buffer TInt iTotalDirectoryBlockSize; // calculated size of directory block TInt iTotalFileBlockSize; // calculated size of file block TInt iImagePosition; // position of directory entry in image TInt iFileBlockPosition; // position of directory file block in image friend class FileEntry; public: char* iName; TUint8 iAtt; TUint8 iAttExtra; TBool iHidden; TRomBuilderEntry* iEntry; // represents file data TUint iFileStartOffset; // position in image of start of file TInt iSize; // size of associated file // Override values TInt iStackSize; TInt iHeapSizeMin; TInt iHeapSizeMax; SCapabilitySet iCapability; TInt iUid1; TInt iUid2; TInt iUid3; TProcessPriority iPriority; TInt iOverride; TBool iFileUpdate; bool iAlias; // for a ROM image, all the files have a default read-only attribute, but in data drive, files's default attribute should be 0 static TUint8 sDefaultInitialAttr ; }; class DllDataEntry; struct TLogItem { TPrintType iPrintType; std::string iLogMessage; }; typedef vector<TLogItem> LogVector; class TRomBuilderEntry { public: TRomBuilderEntry(const char *aFileName, const char *aName); ~TRomBuilderEntry(); void SetRomNode(TRomNode* aNode); TRofsEntry* RofsEntry() const {return iRomNode->RofsEntry(); }; TInt PlaceFile( TUint8* &aDest, TUint aMaxSize, CBytePair *aBPE ); inline TInt RealFileSize() const { return iRealFileSize; }; inline void SetRealFileSize(TInt aFileSize) { iRealFileSize=aFileSize;}; void DisplaySize(TPrintType aWhere); char* GetSystemFullName(); private: TRomBuilderEntry(); TRomBuilderEntry(const TRomBuilderEntry&); const TRomBuilderEntry& operator==(const TRomBuilderEntry &); DllDataEntry* iFirstDllDataEntry; public: char *iName; char *iFileName; TRomBuilderEntry* iNext; TRomBuilderEntry* iNextInArea; TBool iExecutable; TBool iFileOffset; // offset of the file in ROM TUint iCompressEnabled; TUint8 iUids[sizeof(TCheckedUid)]; TBool iHidden; LogVector iLogMessages; DllDataEntry* GetFirstDllDataEntry() const; void SetFirstDllDataEntry(DllDataEntry *aDllDataEntry); private: TRomNode *iRomNode; TInt iRealFileSize; }; inline void TRomNode::SetStackSize(TInt aValue) { iStackSize = aValue; iOverride |= KOverrideStack; } inline void TRomNode::SetHeapSizeMin(TInt aValue) { iHeapSizeMin = aValue; iOverride |= KOverrideHeapMin; } inline void TRomNode::SetHeapSizeMax(TInt aValue) { iHeapSizeMax = aValue; iOverride |= KOverrideHeapMax; } inline void TRomNode::SetCapability(SCapabilitySet& aCapability) { iCapability = aCapability; iOverride |= KOverrideCapability; } inline void TRomNode::SetUid1(TInt aValue) { iUid1 = aValue; iOverride |= KOverrideUid1; } inline void TRomNode::SetUid2(TInt aValue) { iUid2 = aValue; iOverride |= KOverrideUid2; } inline void TRomNode::SetUid3(TInt aValue) { iUid3 = aValue; iOverride |= KOverrideUid3; } inline void TRomNode::SetPriority(TProcessPriority aValue) { iPriority = aValue; iOverride |= KOverridePriority; } inline void TRomNode::SetFixed() { iOverride |= KOverrideFixed; } inline void TRomNode::SetDllData() { iOverride |= KOverrideDllData; } #endif
[ "none@none", "[email protected]" ]
[ [ [ 1, 23 ], [ 26, 127 ], [ 130, 192 ], [ 199, 210 ], [ 212, 229 ], [ 231, 297 ] ], [ [ 24, 25 ], [ 128, 129 ], [ 193, 198 ], [ 211, 211 ], [ 230, 230 ] ] ]
02ff62af1df16dbfba9b4be5c47b99a1055c7299
019f72b2dde7d0b9ab0568dc23ae7a0f4a41b2d1
/jot/Template.h
222b3a1fd767ca1c960a4239a37229567d6c049c
[]
no_license
beketa/jot-for-X01SC
7bb74051f494172cb18b0f6afa5df055646eed25
5158fde188bec3aea4f5495da0dc5dfcd4c1663b
refs/heads/master
2020-04-05T06:29:04.125514
2010-07-10T05:36:49
2010-07-10T05:36:49
1,416,589
0
0
null
null
null
null
UTF-8
C++
false
false
648
h
#pragma once class CTemplate { private: class Temp { public: CString name; CString temp; Temp(CString &t){ int f = t.Find( _T("=") ); if ( f!= -1 ){ name = t.Left( f ).Trim(); temp = t.Mid( f+1 ); } } }; CArray<Temp*> m_list; int m_max; CString m_filename ; public: CTemplate(int max , const TCHAR *filename); virtual ~CTemplate(void); int GetCount(){ return m_list.GetCount(); } const TCHAR *GetName(int i){ if ( i< m_list.GetCount() ){ return m_list.GetAt(i)->name; } return _T(""); } CString ProcTemplate( int idx , CString src , int &caret ); };
[ [ [ 1, 41 ] ] ]
25d439c473b7e6efce67214b0fd7938fa065d5a3
bdb8fc8eb5edc84cf92ba80b8541ba2b6c2b0918
/TPs CPOO/Gareth & Maxime/Projet/CanonNoir_Moteur_C++/fichiers/Radeau.h
3b4e0bbbdaa1465e6c86917500671bbf5ae1902f
[]
no_license
Issam-Engineer/tp4infoinsa
3538644b40d19375b6bb25f030580004ed4a056d
1576c31862ffbc048890e72a81efa11dba16338b
refs/heads/master
2021-01-10T17:53:31.102683
2011-01-27T07:46:51
2011-01-27T07:46:51
55,446,817
0
0
null
null
null
null
UTF-8
C++
false
false
954
h
/** *\file Radeau.h *\brief file which contains the attributes and function declarations of the Radeau class *\author Maxime HAVEZ *\author Gareth THIVEUX *\version 1.0 */ #ifndef RADEAU_H #define RADEAU_H #include "Bateau.h" class Radeau : public Bateau { public : /** * \fn char typeBateau() * \brief Inherited function which gives the name of the class * \return char the name of the class */ char type(); /** * \fn void init() * \brief Inherited function which initialises the Radeau virtual void init();*/ /** * \fn Radeau() * \brief Default constructor */ Radeau(); /** *\fn void setATresor() *\brief redefines the heritated function */ void setATresor(bool b); }; inline char Radeau::type(){ return 'R';} inline void Radeau::setATresor(bool b){ aTresor=false; cout<<"Radeau.h : un radeau ne peut pas prendre de trésor !"<<endl; } #endif
[ "havez.maxime.01@9f3b02c3-fd90-5378-97a3-836ae78947c6", "garethiveux@9f3b02c3-fd90-5378-97a3-836ae78947c6" ]
[ [ [ 1, 1 ], [ 7, 8 ], [ 12, 19 ], [ 21, 25 ], [ 27, 30 ], [ 32, 33 ], [ 40, 43 ] ], [ [ 2, 6 ], [ 9, 11 ], [ 20, 20 ], [ 26, 26 ], [ 31, 31 ], [ 34, 39 ], [ 44, 49 ] ] ]
3756b9f0223f4dab4e40c81502c3d3a41a7c9153
fc2f53c62ab435998421e2b26305e9fd963f79b3
/src/Texture.h
91ba9bf6c82d8791932110fcde161ef0337cbb17
[]
no_license
hrehfeld/ezrgraphicsdemo
64446583c0d7ea4c89806be536ee02b76255a8b5
04e477f1fca28ee3c5216384e9757e75dda21f18
refs/heads/master
2020-05-18T00:44:54.669110
2009-07-13T18:31:03
2009-07-13T18:31:03
197,796
5
1
null
null
null
null
UTF-8
C++
false
false
646
h
#ifndef _TEXTURE_H_ #define _TEXTURE_H_ #include <string> namespace Ezr { class Image; class Texture { public: Texture(const Image& img); Texture(int width, int height, unsigned int internalFormat, unsigned int format, unsigned int type); virtual ~Texture(); void setAnisotropicFiltering(int anisotropic); void bind() const; /** * Get the ogl texture id */ unsigned int getId() { return _id; } private: void init(int width, int height, unsigned int internalFormat, unsigned int format, unsigned int type, unsigned char* data); unsigned int _id; }; } #endif /* _TEXTURE_H_ */
[ [ [ 1, 29 ] ] ]
19b08928660cb7f7edab0180384a507fadcf6557
0c930838cc851594c9eceab6d3bafe2ceb62500d
/include/jflib/linalg/lapack/linalg.hpp
d74731222c09989fde2842f384999d1f29622e0a
[ "BSD-3-Clause" ]
permissive
quantmind/jflib
377a394c17733be9294bbf7056dd8082675cc111
cc240d2982f1f1e7e9a8629a5db3be434d0f207d
refs/heads/master
2021-01-19T07:42:43.692197
2010-04-19T22:04:51
2010-04-19T22:04:51
439,289
4
3
null
null
null
null
UTF-8
C++
false
false
313
hpp
#include <boost/numeric/ublas/banded.hpp> #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/symmetric.hpp> #include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/operation.hpp> #include <boost/numeric/ublas/lu.hpp> #include <boost/numeric/ublas/vector_proxy.hpp>
[ [ [ 1, 9 ] ] ]
a2e31d26ad108a9b5ebec478a8c928ae991bae24
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/tools/NLS/Xlat/Xlat_Formatter.hpp
36a5a655721609059e8933a14b666347a9c4d10b
[ "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,748
hpp
/* * Copyright 1999-2000,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Log: Xlat_Formatter.hpp,v $ * Revision 1.5 2004/09/08 13:57:07 peiyongz * Apache License Version 2.0 * * Revision 1.4 2000/03/02 19:55:53 roddey * This checkin includes many changes done while waiting for the * 1.1.0 code to be finished. I can't list them all here, but a list is * available elsewhere. * * Revision 1.3 2000/02/06 07:48:41 rahulj * Year 2K copyright swat. * * Revision 1.2 2000/01/05 20:24:58 roddey * Some changes to simplify life for the Messge Catalog message loader. The formatter * for the message loader now spits out a simple header of ids that allows the loader to * be independent of hard coded set numbers. * * Revision 1.1.1.1 1999/11/09 01:01:22 twl * Initial checkin * * Revision 1.3 1999/11/08 20:42:06 rahul * Swat for adding in Product name and CVS comment log variable. * */ // --------------------------------------------------------------------------- // This is a simple abstract API that each formatter must provide. This is // how the main program logic calls out with all of the needed information // and events needed to create the output. // --------------------------------------------------------------------------- class XlatFormatter { public : // ----------------------------------------------------------------------- // Public Constructors and Destructor // ----------------------------------------------------------------------- virtual ~XlatFormatter() { } // ----------------------------------------------------------------------- // Virtual formatter interface // ----------------------------------------------------------------------- virtual void endDomain ( const XMLCh* const domainName , const unsigned int msgCount ) = 0; virtual void endMsgType ( const MsgTypes type ) = 0; virtual void endOutput() = 0; virtual void nextMessage ( const XMLCh* const msgText , const XMLCh* const msgId , const unsigned int messageId , const unsigned int curId ) = 0; virtual void startDomain ( const XMLCh* const domainName , const XMLCh* const nameSpace ) = 0; virtual void startMsgType ( const MsgTypes type ) = 0; virtual void startOutput ( const XMLCh* const locale , const XMLCh* const outPath ) = 0; protected : // ----------------------------------------------------------------------- // Hidden constructors // ----------------------------------------------------------------------- XlatFormatter() { } private : // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- XlatFormatter(const XlatFormatter&); void operator=(const XlatFormatter&); };
[ [ [ 1, 117 ] ] ]
7c68943daf9039df182f648d4bcd12d30a6ef0ba
804e416433c8025d08829a08b5e79fe9443b9889
/src/argss/classes/arect.cpp
05e639fed9913ce881c57058bbccbc42a3be873d
[ "BSD-2-Clause" ]
permissive
cstrahan/argss
e77de08db335d809a482463c761fb8d614e11ba4
cc595bd9a1e4a2c079ea181ff26bdd58d9e65ace
refs/heads/master
2020-05-20T05:30:48.876372
2010-10-03T23:21:59
2010-10-03T23:21:59
1,682,890
1
0
null
null
null
null
UTF-8
C++
false
false
6,130
cpp
///////////////////////////////////////////////////////////////////////////// // ARGSS - Copyright (c) 2009 - 2010, Alejandro Marzini (vgvgf) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // Headers /////////////////////////////////////////////////////////// #include "argss/classes/arect.h" /////////////////////////////////////////////////////////// // Global Variables /////////////////////////////////////////////////////////// VALUE ARGSS::ARect::id; /////////////////////////////////////////////////////////// // ARGSS Rect instance methods /////////////////////////////////////////////////////////// VALUE ARGSS::ARect::rinitialize(VALUE self, VALUE x, VALUE y, VALUE w, VALUE h) { Check_Kind(x, rb_cNumeric); Check_Kind(y, rb_cNumeric); Check_Kind(w, rb_cNumeric); Check_Kind(h, rb_cNumeric); rb_iv_set(self, "@x", x); rb_iv_set(self, "@y", y); rb_iv_set(self, "@width", w); rb_iv_set(self, "@height", h); return self; } VALUE ARGSS::ARect::rset(VALUE self, VALUE x, VALUE y, VALUE w, VALUE h) { Check_Kind(x, rb_cNumeric); Check_Kind(y, rb_cNumeric); Check_Kind(w, rb_cNumeric); Check_Kind(h, rb_cNumeric); rb_iv_set(self, "@x", x); rb_iv_set(self, "@y", y); rb_iv_set(self, "@width", w); rb_iv_set(self, "@height", h); return self; } VALUE ARGSS::ARect::rx(VALUE self) { return rb_iv_get(self, "@x"); } VALUE ARGSS::ARect::rxE(VALUE self, VALUE x) { Check_Kind(x, rb_cNumeric); return rb_iv_set(self, "@x", x); } VALUE ARGSS::ARect::ry(VALUE self) { return rb_iv_get(self, "@y"); } VALUE ARGSS::ARect::ryE(VALUE self, VALUE y) { Check_Kind(y, rb_cNumeric); return rb_iv_set(self, "@y", y); } VALUE ARGSS::ARect::rwidth(VALUE self) { return rb_iv_get(self, "@width"); } VALUE ARGSS::ARect::rwidthE(VALUE self, VALUE w) { Check_Kind(w, rb_cNumeric); return rb_iv_set(self, "@width", w); } VALUE ARGSS::ARect::rheight(VALUE self) { return rb_iv_get(self, "@height"); } VALUE ARGSS::ARect::rheightE(VALUE self, VALUE h) { Check_Kind(h, rb_cNumeric); return rb_iv_set(self, "@height", h); } VALUE ARGSS::ARect::rempty(VALUE self) { rb_iv_set(self, "@x", INT2NUM(0)); rb_iv_set(self, "@y", INT2NUM(0)); rb_iv_set(self, "@width", INT2NUM(0)); rb_iv_set(self, "@height", INT2NUM(0)); return self; } VALUE ARGSS::ARect::rinspect(VALUE self) { char str[255]; long str_size = sprintf( str, "(%i, %i, %i, %i)", NUM2INT(rb_iv_get(self, "@x")), NUM2INT(rb_iv_get(self, "@y")), NUM2INT(rb_iv_get(self, "@width")), NUM2INT(rb_iv_get(self, "@height")) ); return rb_str_new(str, str_size); } VALUE ARGSS::ARect::rdump(int argc, VALUE* argv, VALUE self) { if (argc > 1) raise_argn(argc, 1); VALUE arr = rb_ary_new3(4, rb_iv_get(self, "@x"), rb_iv_get(self, "@y"), rb_iv_get(self, "@width"), rb_iv_get(self, "@height")); return rb_funcall(arr, rb_intern("pack"), 1, rb_str_new2("l4")); } /////////////////////////////////////////////////////////// // ARGSS Rect class methods /////////////////////////////////////////////////////////// VALUE ARGSS::ARect::rload(VALUE self, VALUE str) { VALUE arr = rb_funcall(str, rb_intern("unpack"), 1, rb_str_new2("l4")); VALUE args[4] = {rb_ary_entry(arr, 0), rb_ary_entry(arr, 1), rb_ary_entry(arr, 2), rb_ary_entry(arr, 3)}; VALUE rect = rb_class_new_instance(4, args, ARGSS::ARect::id); return rect; } /////////////////////////////////////////////////////////// // ARGSS Rect initialize /////////////////////////////////////////////////////////// void ARGSS::ARect::Init() { id = rb_define_class("Rect", rb_cObject); rb_define_method(id, "initialize", (rubyfunc)rinitialize, 4); rb_define_method(id, "set", (rubyfunc)rset, 4); rb_define_method(id, "x", (rubyfunc)rx, 0); rb_define_method(id, "x=", (rubyfunc)rxE, 1); rb_define_method(id, "y", (rubyfunc)ry, 0); rb_define_method(id, "y=", (rubyfunc)ryE, 1); rb_define_method(id, "width", (rubyfunc)rwidth, 0); rb_define_method(id, "width=", (rubyfunc)rwidthE, 1); rb_define_method(id, "height", (rubyfunc)rheight, 0); rb_define_method(id, "height=", (rubyfunc)rheightE, 1); rb_define_method(id, "empty", (rubyfunc)rempty, 0); rb_define_method(id, "inspect", (rubyfunc)rinspect, 0); rb_define_method(id, "_dump", (rubyfunc)rdump, -1); rb_define_singleton_method(id, "_load", (rubyfunc)rload, 1); } /////////////////////////////////////////////////////////// // ARGSS Rect new instance /////////////////////////////////////////////////////////// VALUE ARGSS::ARect::New(double x, double y, double width, double height) { VALUE args[4] = {rb_float_new(x), rb_float_new(y), rb_float_new(width), rb_float_new(height)}; return rb_class_new_instance(4, args, id); }
[ "vgvgf@a70b67f4-0116-4799-9eb2-a6e6dfe7dbda" ]
[ [ [ 1, 152 ] ] ]
cbd3edbc0da548963ab31fb753ef9b77ae753db6
9f2d447c69e3e86ea8fd8f26842f8402ee456fb7
/shooting2011/shooting2011/connect_test.cpp
10002a1b170a48b73a9bef94dd27a0b3383e522a
[]
no_license
nakao5924/projectShooting2011
f086e7efba757954e785179af76503a73e59d6aa
cad0949632cff782f37fe953c149f2b53abd706d
refs/heads/master
2021-01-01T18:41:44.855790
2011-11-07T11:33:44
2011-11-07T11:33:44
2,490,410
0
1
null
null
null
null
SHIFT_JIS
C++
false
false
2,315
cpp
/* #include "main.h" #include <cassert> #include "shooting.h" #include "server.h" #include "client.h" #include "msgdump.h" using namespace std; //void dumpDummyPipe(); // WinMain関数 int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { // 画面モードの設定 ChangeWindowMode(true); SetGraphMode( WINDOW_WIDTH, WINDOW_HEIGHT, 16 ) ; // DXライブラリ初期化処理 if( DxLib_Init() == -1 ) return -1; // グラフィックの描画先を裏画面にセット SetDrawScreen( DX_SCREEN_BACK ); string buf; IPDATA ip = {127, 0, 0, 1}; / * Connection c1(0), c2(0); c1.send("c1: hello, c2."); c2.receive(buf); c2.send("c2: hello, c1!!"); c1.receive(buf); c1.send("c1: test message1"); c1.send("c1: test message2"); c2.send("c2: test message1"); c2.send("c2: test message2"); c1.receive(buf); c1.receive(buf); c2.receive(buf); c2.receive(buf); * / ServerConnection server(12345); ClientConnection client(12345, ip); server.startListen(); bool connect = client.connect(); assert(connect); server.action(); server.endListen(); assert(server.size() == 1); dxout << server.send(0, "server: hello, client!!") << dxendl; dxout << client.receive(buf) << dxendl; dxout << buf << dxendl; dxout << client.send("client: hello, server!!") << dxendl; dxout << server.receive(0, buf) << dxendl; dxout << buf << dxendl; dxout << client.receive(buf) << dxendl; dxout << buf << dxendl; dxout << server.receive(0, buf) << dxendl; dxout << buf << dxendl; dxout << server.send(0, "server: test message1") << dxendl; dxout << server.send(0, "server: test message2") << dxendl; dxout << client.receive(buf) << dxendl; dxout << buf << dxendl; dxout << client.receive(buf) << dxendl; dxout << buf << dxendl; dxout << client.send("client: test message1") << dxendl; dxout << client.send("client: test message2") << dxendl; dxout << server.receive(0, buf) << dxendl; dxout << buf << dxendl; dxout << server.receive(0, buf) << dxendl; dxout << buf << dxendl; ScreenFlip(); WaitKey(); DxLib_End(); // DXライブラリ使用の終了処理 return 0; // ソフトの終了 } */
[ [ [ 1, 26 ], [ 49, 61 ], [ 63, 91 ], [ 93, 99 ] ], [ [ 27, 48 ], [ 62, 62 ], [ 92, 92 ], [ 100, 100 ] ] ]
ff22b7857d12894115b128f1c3cc5da660aaa966
ee065463a247fda9a1927e978143186204fefa23
/Src/Engine/GameState/GameStateManager.h
830ebd7512471a6b5c805a4acfcc7d6f2728b53b
[]
no_license
ptrefall/hinsimviz
32e9a679170eda9e552d69db6578369a3065f863
9caaacd39bf04bbe13ee1288d8578ece7949518f
refs/heads/master
2021-01-22T09:03:52.503587
2010-09-26T17:29:20
2010-09-26T17:29:20
32,448,374
1
0
null
null
null
null
UTF-8
C++
false
false
886
h
#pragma once #include <ClanLib/core.h> #include <vector> namespace Engine { namespace Core { class CoreManager; } namespace GameState { class IGameState; class GameStateFactory; class GameStateManager { public: GameStateManager(Core::CoreManager *coreMgr); virtual ~GameStateManager(); virtual int init(); virtual unsigned int genGameStateId(); virtual IGameState *getGameState(unsigned int id) const; virtual IGameState *getCurrentState() const; virtual int changeState(unsigned int id); virtual int pushState(unsigned int id); virtual int popState(); virtual IGameState *create(const CL_String &name); private: Core::CoreManager *coreMgr; GameStateFactory *factory; unsigned int gameStateIds; std::vector<IGameState*> gameStates; IGameState *currentState; std::vector<IGameState*> gameStateStackHistory; }; } }
[ "[email protected]@28a56cb3-1e7c-bc60-7718-65c159e1d2df" ]
[ [ [ 1, 45 ] ] ]
cb9eca7abe7d48d92eb45b5d872e2475a4f5cf5e
502efe97b985c69d6378d9c428c715641719ee03
/src/moaicore/MOAITransformBase.h
42c81cec17a90656248b1e46ac2694023f32a1d3
[]
no_license
neojjang/moai-beta
c3933bca2625bca4f4da26341de6b855e41b9beb
6bc96412d35192246e35bff91df101bd7c7e41e1
refs/heads/master
2021-01-16T20:33:59.443558
2011-09-19T23:45:06
2011-09-19T23:45:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,624
h
// Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved. // http://getmoai.com #ifndef MOAITRANSFORMBASE_H #define MOAITRANSFORMBASE_H #include <moaicore/MOAITraits.h> //================================================================// // MOAITransformBase //================================================================// /** @name MOAITransformBase @text Base class for 2D affine transforms. @attr ATTR_WORLD_X_LOC @attr ATTR_WORLD_Y_LOC @attr ATTR_WORLD_Z_ROT @attr ATTR_WORLD_X_SCL @attr ATTR_WORLD_Y_SCL */ class MOAITransformBase : public virtual MOAITraits { protected: USAffine2D mLocalToWorldMtx; USAffine2D mWorldToLocalMtx; //----------------------------------------------------------------// static int _getWorldDir ( lua_State* L ); static int _getWorldLoc ( lua_State* L ); static int _getWorldRot ( lua_State* L ); static int _getWorldScl ( lua_State* L ); public: DECL_ATTR_HELPER ( MOAITransformBase ) enum { ATTR_WORLD_X_LOC, ATTR_WORLD_Y_LOC, ATTR_WORLD_Z_ROT, ATTR_WORLD_X_SCL, ATTR_WORLD_Y_SCL, TOTAL_ATTR, }; //----------------------------------------------------------------// bool ApplyAttrOp ( u32 attrID, USAttrOp& attrOp ); const USAffine2D& GetLocalToWorldMtx (); const USAffine2D* GetTransformTrait (); const USAffine2D& GetWorldToLocalMtx (); MOAITransformBase (); ~MOAITransformBase (); void RegisterLuaClass ( USLuaState& state ); void RegisterLuaFuncs ( USLuaState& state ); STLString ToString (); }; #endif
[ "Patrick@agile.(none)", "[email protected]" ]
[ [ [ 1, 16 ], [ 20, 59 ] ], [ [ 17, 19 ] ] ]
aa2776c8900c94380060f77a7828a221fcf37e0c
ef23e388061a637f82b815d32f7af8cb60c5bb1f
/src/mame/includes/crospang.h
6b8e4a6295f011b2b168ccc4e9adbaddeefe3e0f
[]
no_license
marcellodash/psmame
76fd877a210d50d34f23e50d338e65a17deff066
09f52313bd3b06311b910ed67a0e7c70c2dd2535
refs/heads/master
2021-05-29T23:57:23.333706
2011-06-23T20:11:22
2011-06-23T20:11:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,371
h
/************************************************************************* Cross Pang *************************************************************************/ class crospang_state : public driver_device { public: crospang_state(running_machine &machine, const driver_device_config_base &config) : driver_device(machine, config) { } /* memory pointers */ UINT16 * m_bg_videoram; UINT16 * m_fg_videoram; UINT16 * m_spriteram; // UINT16 * m_paletteram; // currently this uses generic palette handling size_t m_spriteram_size; /* video-related */ tilemap_t *m_bg_layer; tilemap_t *m_fg_layer; int m_xsproff; int m_ysproff; int m_bestri_tilebank; /* devices */ device_t *m_audiocpu; }; /*----------- defined in video/crospang.c -----------*/ VIDEO_START( crospang ); SCREEN_UPDATE( crospang ); WRITE16_HANDLER ( crospang_fg_scrolly_w ); WRITE16_HANDLER ( crospang_bg_scrolly_w ); WRITE16_HANDLER ( crospang_fg_scrollx_w ); WRITE16_HANDLER ( crospang_bg_scrollx_w ); WRITE16_HANDLER ( bestri_fg_scrolly_w ); WRITE16_HANDLER ( bestri_bg_scrolly_w ); WRITE16_HANDLER ( bestri_fg_scrollx_w ); WRITE16_HANDLER ( bestri_bg_scrollx_w ); WRITE16_HANDLER ( crospang_fg_videoram_w ); WRITE16_HANDLER ( crospang_bg_videoram_w ); WRITE16_HANDLER ( bestri_tilebank_w );
[ "Mike@localhost" ]
[ [ [ 1, 49 ] ] ]
18912ecad8fce4721d66bc456e0f956196066f23
968aa9bac548662b49af4e2b873b61873ba6f680
/imgtools/imgcheck/libimgutils/src/rofsimage.cpp
334a1f9529a4febddf035c169c1031601ef612b6
[]
no_license
anagovitsyn/oss.FCL.sftools.dev.build
b3401a1ee3fb3c8f3d5caae6e5018ad7851963f3
f458a4ce83f74d603362fe6b71eaa647ccc62fee
refs/heads/master
2021-12-11T09:37:34.633852
2010-12-01T08:05:36
2010-12-01T08:05:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,284
cpp
/* * Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of the License "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ /** @file @internalComponent @released */ #include "typedefs.h" #include "rofsimage.h" /** Constructor. @internalComponent @released @param aReader - image reader pointer */ RofsImage::RofsImage(RCoreImageReader *aReader) : CCoreImage(aReader) , iRofsHeader(0), iRofsExtnHeader(0),iAdjustment(0), iImageType((RCoreImageReader::TImageType)0) { } /** Destructor deletes iRofsHeader and iRofsExtnHeader. @internalComponent @released @param aReader - image reader pointer */ RofsImage::~RofsImage() { DELETE(iRofsHeader); DELETE(iRofsExtnHeader); } /** Function responsible to read the ROFS image and to construct the tree for the elements available in Directory section. @internalComponent @released @return - returns the error code */ TInt RofsImage::ProcessImage() { int result = CreateRootDir(); if (result == KErrNone) { if (iReader->Open()) { iImageType = iReader->ReadImageType(); if (iImageType == RCoreImageReader::E_ROFS) { iRofsHeader = new TRofsHeader; result = iReader->ReadCoreHeader(*iRofsHeader); if (result != KErrNone){ cerr << "error is :"<< result << endl; return result; } SaveDirInfo(*iRofsHeader); result = ProcessDirectory(0); } else if (iImageType == RCoreImageReader::E_ROFX) { iRofsExtnHeader = new TExtensionRofsHeader ; result = iReader->ReadExtensionHeader(*iRofsExtnHeader); if(result != KErrNone) return result; long filePos = iReader->FilePosition(); iAdjustment = iRofsExtnHeader->iDirTreeOffset - filePos; SaveDirInfo(*iRofsExtnHeader); result = ProcessDirectory(iAdjustment); } else { result = KErrNotSupported; } } else { result = KErrGeneral; } } return result; }
[ "none@none" ]
[ [ [ 1, 102 ] ] ]
67812b97126aa0e7a62b4b7ab0d1c22879abf204
6406ffa37fd4b705e61b79312f0ebe1035228365
/src/common/HorizonScheduler.h
96d77b75dae12acf8b8b55948fdff9a308c2b51b
[]
no_license
kitakita/omnetpp_obs
65904d4e37637706a385476f7c33656c491e2fbd
19e7c8f0eafcd293d381e733712ecbb2a3564b08
refs/heads/master
2021-01-02T12:55:37.328995
2011-01-30T10:42:56
2011-01-30T10:42:56
1,189,202
0
1
null
null
null
null
UTF-8
C++
false
false
1,686
h
// // This program 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. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // #ifndef __OMNETPP_OBS_HORIZONSCHEDULER_H_ #define __OMNETPP_OBS_HORIZONSCHEDULER_H_ #include <omnetpp.h> #include "IBurstScheduler.h" #include "WDMTable.h" struct Schedule { simtime_t horizon; simtime_t tail; cMessage *burst; }; struct ScheduleResult { int channel; simtime_t offset; simtime_t droppedHead; simtime_t droppedTail; }; class HorizonScheduler : public cSimpleModule, public IBurstScheduler { protected: WDMTable *wdm; bool droppable; bool waveConversion; typedef std::vector<Schedule *> ScheduleTable; typedef std::vector<ScheduleTable> ScheduleTables; ScheduleTables scheduleTables; virtual void initialize(); virtual void handleMessage(cMessage *msg); virtual void finish(); virtual void printSchedule(int outPort); virtual void updateDisplayString(); virtual ScheduleResult trySchedule(cMessage *msg, int port, int channel); public: virtual int schedule(cMessage *msg, int port); }; #endif
[ [ [ 1, 62 ] ] ]
2dfa5f44f9602e67238c7affc2b4961c7a677705
cfa667b1f83649600e78ea53363ee71dfb684d81
/code/render/coregraphics/win360/d3d9memoryindexbufferloader.cc
40008aff5c333a69f5dfcbc3c84b6e6e7278a35d
[]
no_license
zhouxh1023/nebuladevice3
c5f98a9e2c02828d04fb0e1033f4fce4119e1b9f
3a888a7c6e6d1a2c91b7ebd28646054e4c9fc241
refs/heads/master
2021-01-23T08:56:15.823698
2011-08-26T02:22:25
2011-08-26T02:22:25
32,018,644
0
1
null
null
null
null
UTF-8
C++
false
false
2,328
cc
//------------------------------------------------------------------------------ // d3d9memoryindexbufferloader.cc // (C) 2007 Radon Labs GmbH //------------------------------------------------------------------------------ #include "stdneb.h" #include "coregraphics/win360/d3d9memoryindexbufferloader.h" #include "coregraphics/indexbuffer.h" namespace Win360 { __ImplementClass(Win360::D3D9MemoryIndexBufferLoader, 'DMIL', Base::MemoryIndexBufferLoaderBase); using namespace Resources; using namespace CoreGraphics; //------------------------------------------------------------------------------ /** This will create a D3D9 IndexBuffer using the data provided by our Setup() method and set our resource object (which must be a D3D9IndexBuffer object). */ bool D3D9MemoryIndexBufferLoader::OnLoadRequested() { n_assert(this->GetState() == Resource::Initial); n_assert(this->resource.isvalid()); n_assert(!this->resource->IsAsyncEnabled()); n_assert(this->indexType != IndexType::None); n_assert(this->numIndices > 0); if (IndexBuffer::UsageImmutable == this->usage) { n_assert(this->indexDataSize == (this->numIndices * IndexType::SizeOf(this->indexType))); n_assert(0 != this->indexDataPtr); n_assert(0 < this->indexDataSize); } // create a D3D9 index buffer object const Ptr<IndexBuffer>& res = this->resource.downcast<IndexBuffer>(); n_assert(!res->IsLoaded()); res->SetUsage(this->usage); res->SetAccess(this->access); res->SetIndexType(this->indexType); res->SetNumIndices(this->numIndices); res->Setup(); IDirect3DIndexBuffer9* d3dIndexBuffer = res->GetD3D9IndexBuffer(); // setup initial data if provided if (0 != this->indexDataPtr) { // copy data to d3d9 index buffer void* dstPtr = 0; HRESULT hr = d3dIndexBuffer->Lock(0, 0, &dstPtr, D3DLOCK_NOSYSLOCK); n_assert(SUCCEEDED(hr)); n_assert(0 != dstPtr); Memory::CopyToGraphicsMemory(this->indexDataPtr, dstPtr, this->indexDataSize); hr = d3dIndexBuffer->Unlock(); n_assert(SUCCEEDED(hr)); } // invalidate setup data (because we don't own our data) this->indexDataPtr = 0; this->indexDataSize = 0; this->SetState(Resource::Loaded); return true; } } // namespace Win360
[ [ [ 1, 68 ] ] ]
d81e1f84c429d8af59fb4ac3c1cfca795b7ebb1c
3276915b349aec4d26b466d48d9c8022a909ec16
/c++/异常处理机制/异常的多态实现/myexception.cpp
18633c29e62ad58d5a9fba64df781fc7549aa9be
[]
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
UTF-8
C++
false
false
141
cpp
#include"myexception.h" void e_int:: disp() { cout<<"int"<<endl; } void e_char::disp() { cout<<"char"<<endl; }
[ [ [ 1, 14 ] ] ]
7e3b2663d116c6085c25abb1f8ddaa6ed959e62e
81a38f1f0e77081746812a7f76a52dd0290fde81
/minicurso-glsl/06.Extensoes2/src/Modelo.h
910692e250fd692ffe7942633a6cdaca60a976a3
[]
no_license
tamiresharumi/cg_project
500f437977465264460cd345f484c83feae95454
5c4027b3ae749f57f676ae830f2140cd72b51898
refs/heads/master
2021-01-20T12:16:41.916754
2011-06-20T02:00:23
2011-06-20T02:00:23
1,761,107
0
0
null
null
null
null
UTF-8
C++
false
false
424
h
#ifndef MODELO_H #define MODELO_H #include <cml/cml.h> struct Vertice { cml::vector3f posicao; cml::vector3f normal; cml::vector2f texCoord; }; class Modelo { public: typedef std::vector<Vertice> Vertices; typedef std::vector<unsigned> Indices; void carrega(const Vertices &vertices, const Indices &indices); void desenha(); private: Vertices m_vertices; Indices m_indices; }; #endif
[ [ [ 1, 26 ] ] ]
dbed4610980f04e63eb780da1af85b39c704c836
9176b0fd29516d34cfd0b143e1c5c0f9e665c0ed
/CS_153_Data_Structures/assignment6/bst.h
16cb99b3b00fae3e3ecf8957791ee4e2dbd91a76
[]
no_license
Mr-Anderson/james_mst_hw
70dbde80838e299f9fa9c5fcc16f4a41eec8263a
83db5f100c56e5bb72fe34d994c83a669218c962
refs/heads/master
2020-05-04T13:15:25.694979
2011-11-30T20:10:15
2011-11-30T20:10:15
2,639,602
2
0
null
null
null
null
UTF-8
C++
false
false
3,418
h
#ifndef BST_H #define BST_H ////////////////////////////////////////////////////////////////////// /// @file bst.h /// @author James Anderson CS 153 Section A /// @brief Heder file for binary search tree class for assignment 6 ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// @fn Bst<generic>::insert (generic x) /// @brief inserts value into the Bst /// @post inserts value into corect place in the Bst and incresses size /// @param x holds the variable value to be removed ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// @fn Bst<generic>::remove (generic x) /// @brief removes all values mathing the specivied value /// @post removes all values and decreses size of bst /// @param x holds the variable value to be removed ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// @fn PreOrder<generic>::pre_search (generic x) /// @brief returns an iterator starting at the value specified /// @post returns iterator starting at the search /// @return returns iterator starting at the search /// @param x holds the variable value to be searched for ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// @fn InOrder<generic>::pin_search (generic x) /// @brief returns an iterator starting at the value specified /// @post returns iterator starting at the search /// @return returns iterator starting at the search /// @param x holds the variable value to be searched for ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// @fn PostOrder<generic>::post_search (generic x) /// @brief returns an iterator starting at the value specified /// @post returns iterator starting at the search /// @return returns iterator starting at the search /// @param x holds the variable value to be searched for ////////////////////////////////////////////////////////////////////// #include "bt.h" #include "btn.h" #include "exception.h" #include "iostream" using std::cout; using std::cerr; using std::endl; using std::cin; template <class generic> class Bst : public BT<generic> { public: void insert (generic); void remove (generic); typedef BTPreorderIterator<generic> PreOrder; typedef BTInorderIterator<generic> InOrder; typedef BTPostorderIterator<generic> PostOrder; PreOrder pre_search (generic); InOrder in_search (generic); PostOrder post_search (generic); private: void swap ( Btn<generic> *, Btn<generic> *); void delete_leaf ( Btn<generic> * ); void delete_link ( Btn<generic> * ); using BT<generic>:: m_size; using BT<generic>:: m_root; protected: //returns a pointer to the parent of the inserted node Btn<generic> * p_insert (generic); //returns a pointer to the parent of the deleted node Btn<generic> * p_remove (generic); //returns a pointer to the node containing the found data Btn<generic> * p_search (generic); }; #include "bst.hpp" #endif
[ [ [ 1, 87 ] ] ]
ca346013465880f96fb20189bba1ab584517142f
04fec4cbb69789d44717aace6c8c5490f2cdfa47
/include/wx/hash.h
f5cd926412c5e604c68324690b3c7107bba84faa
[]
no_license
aaryanapps/whiteTiger
04f39b00946376c273bcbd323414f0a0b675d49d
65ed8ffd530f20198280b8a9ea79cb22a6a47acd
refs/heads/master
2021-01-17T12:07:15.264788
2010-10-11T20:20:26
2010-10-11T20:20:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
24,000
h
///////////////////////////////////////////////////////////////////////////// // Name: wx/hash.h // Purpose: wxHashTable class // Author: Julian Smart // Modified by: VZ at 25.02.00: type safe hashes with WX_DECLARE_HASH() // Created: 01/02/97 // RCS-ID: $Id: hash.h 49563 2007-10-31 20:46:21Z VZ $ // Copyright: (c) Julian Smart // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #ifndef _WX_HASH_H__ #define _WX_HASH_H__ #include "wx/defs.h" #if !wxUSE_STL && WXWIN_COMPATIBILITY_2_4 #define wxUSE_OLD_HASH_TABLE 1 #else #define wxUSE_OLD_HASH_TABLE 0 #endif #if !wxUSE_STL #include "wx/object.h" #else class WXDLLIMPEXP_BASE wxObject; #endif #if wxUSE_OLD_HASH_TABLE #include "wx/list.h" #endif #if WXWIN_COMPATIBILITY_2_4 #include "wx/dynarray.h" #endif // the default size of the hash #define wxHASH_SIZE_DEFAULT (1000) /* * A hash table is an array of user-definable size with lists * of data items hanging off the array positions. Usually there'll * be a hit, so no search is required; otherwise we'll have to run down * the list to find the desired item. */ // ---------------------------------------------------------------------------- // this is the base class for object hashes: hash tables which contain // pointers to objects // ---------------------------------------------------------------------------- #if wxUSE_OLD_HASH_TABLE class WXDLLIMPEXP_BASE wxHashTableBase : public wxObject { public: wxHashTableBase(); void Create(wxKeyType keyType = wxKEY_INTEGER, size_t size = wxHASH_SIZE_DEFAULT); void Destroy(); size_t GetSize() const { return m_hashSize; } size_t GetCount() const { return m_count; } void DeleteContents(bool flag); protected: // find the node for (key, value) wxNodeBase *GetNode(long key, long value) const; // the array of lists in which we store the values for given key hash wxListBase **m_hashTable; // the size of m_lists array size_t m_hashSize; // the type of indexing we use wxKeyType m_keyType; // the total number of elements in the hash size_t m_count; // should we delete our data? bool m_deleteContents; private: // no copy ctor/assignment operator (yet) DECLARE_NO_COPY_CLASS(wxHashTableBase) }; #else // if !wxUSE_OLD_HASH_TABLE #if !defined(wxENUM_KEY_TYPE_DEFINED) #define wxENUM_KEY_TYPE_DEFINED enum wxKeyType { wxKEY_NONE, wxKEY_INTEGER, wxKEY_STRING }; #endif union wxHashKeyValue { long integer; wxChar *string; }; // for some compilers (AIX xlC), defining it as friend inside the class is not // enough, so provide a real forward declaration class WXDLLIMPEXP_FWD_BASE wxHashTableBase; class WXDLLIMPEXP_BASE wxHashTableBase_Node { friend class WXDLLIMPEXP_FWD_BASE wxHashTableBase; typedef class WXDLLIMPEXP_FWD_BASE wxHashTableBase_Node _Node; public: wxHashTableBase_Node( long key, void* value, wxHashTableBase* table ); wxHashTableBase_Node( const wxChar* key, void* value, wxHashTableBase* table ); ~wxHashTableBase_Node(); long GetKeyInteger() const { return m_key.integer; } const wxChar* GetKeyString() const { return m_key.string; } void* GetData() const { return m_value; } void SetData( void* data ) { m_value = data; } protected: _Node* GetNext() const { return m_next; } protected: // next node in the chain wxHashTableBase_Node* m_next; // key wxHashKeyValue m_key; // value void* m_value; // pointer to the hash containing the node, used to remove the // node from the hash when the user deletes the node iterating // through it // TODO: move it to wxHashTable_Node (only wxHashTable supports // iteration) wxHashTableBase* m_hashPtr; }; class WXDLLIMPEXP_BASE wxHashTableBase #if !wxUSE_STL : public wxObject #endif { friend class WXDLLIMPEXP_FWD_BASE wxHashTableBase_Node; public: typedef wxHashTableBase_Node Node; wxHashTableBase(); virtual ~wxHashTableBase() { } void Create( wxKeyType keyType = wxKEY_INTEGER, size_t size = wxHASH_SIZE_DEFAULT ); void Clear(); void Destroy(); size_t GetSize() const { return m_size; } size_t GetCount() const { return m_count; } void DeleteContents( bool flag ) { m_deleteContents = flag; } static long MakeKey(const wxChar *string); protected: void DoPut( long key, long hash, void* data ); void DoPut( const wxChar* key, long hash, void* data ); void* DoGet( long key, long hash ) const; void* DoGet( const wxChar* key, long hash ) const; void* DoDelete( long key, long hash ); void* DoDelete( const wxChar* key, long hash ); private: // Remove the node from the hash, *only called from // ~wxHashTable*_Node destructor void DoRemoveNode( wxHashTableBase_Node* node ); // destroys data contained in the node if appropriate: // deletes the key if it is a string and destrys // the value if m_deleteContents is true void DoDestroyNode( wxHashTableBase_Node* node ); // inserts a node in the table (at the end of the chain) void DoInsertNode( size_t bucket, wxHashTableBase_Node* node ); // removes a node from the table (fiven a pointer to the previous // but does not delete it (only deletes its contents) void DoUnlinkNode( size_t bucket, wxHashTableBase_Node* node, wxHashTableBase_Node* prev ); // unconditionally deletes node value (invoking the // correct destructor) virtual void DoDeleteContents( wxHashTableBase_Node* node ) = 0; protected: // number of buckets size_t m_size; // number of nodes (key/value pairs) size_t m_count; // table Node** m_table; // key typ (INTEGER/STRING) wxKeyType m_keyType; // delete contents when hash is cleared bool m_deleteContents; private: DECLARE_NO_COPY_CLASS(wxHashTableBase) }; #endif // wxUSE_OLD_HASH_TABLE #if !wxUSE_STL #if WXWIN_COMPATIBILITY_2_4 // ---------------------------------------------------------------------------- // a hash table which stores longs // ---------------------------------------------------------------------------- class WXDLLIMPEXP_BASE wxHashTableLong : public wxObject { public: wxHashTableLong(size_t size = wxHASH_SIZE_DEFAULT) { Init(size); } virtual ~wxHashTableLong(); void Create(size_t size = wxHASH_SIZE_DEFAULT); void Destroy(); size_t GetSize() const { return m_hashSize; } size_t GetCount() const { return m_count; } void Put(long key, long value); long Get(long key) const; long Delete(long key); protected: void Init(size_t size); private: wxArrayLong **m_values, **m_keys; // the size of array above size_t m_hashSize; // the total number of elements in the hash size_t m_count; // not implemented yet DECLARE_NO_COPY_CLASS(wxHashTableLong) }; // ---------------------------------------------------------------------------- // wxStringHashTable: a hash table which indexes strings with longs // ---------------------------------------------------------------------------- class WXDLLIMPEXP_BASE wxStringHashTable : public wxObject { public: wxStringHashTable(size_t sizeTable = wxHASH_SIZE_DEFAULT); virtual ~wxStringHashTable(); // add a string associated with this key to the table void Put(long key, const wxString& value); // get the string from the key: if not found, an empty string is returned // and the wasFound is set to false if not NULL wxString Get(long key, bool *wasFound = NULL) const; // remove the item, returning true if the item was found and deleted bool Delete(long key) const; // clean up void Destroy(); private: wxArrayLong **m_keys; wxArrayString **m_values; // the size of array above size_t m_hashSize; DECLARE_NO_COPY_CLASS(wxStringHashTable) }; #endif // WXWIN_COMPATIBILITY_2_4 #endif // !wxUSE_STL // ---------------------------------------------------------------------------- // for compatibility only // ---------------------------------------------------------------------------- #if !wxUSE_OLD_HASH_TABLE class WXDLLIMPEXP_BASE wxHashTable_Node : public wxHashTableBase_Node { friend class WXDLLIMPEXP_BASE wxHashTable; public: wxHashTable_Node( long key, void* value, wxHashTableBase* table ) : wxHashTableBase_Node( key, value, table ) { } wxHashTable_Node( const wxChar* key, void* value, wxHashTableBase* table ) : wxHashTableBase_Node( key, value, table ) { } wxObject* GetData() const { return (wxObject*)wxHashTableBase_Node::GetData(); } void SetData( wxObject* data ) { wxHashTableBase_Node::SetData( data ); } wxHashTable_Node* GetNext() const { return (wxHashTable_Node*)wxHashTableBase_Node::GetNext(); } }; // should inherit protectedly, but it is public for compatibility in // order to publicly inherit from wxObject class WXDLLIMPEXP_BASE wxHashTable : public wxHashTableBase { typedef wxHashTableBase hash; public: typedef wxHashTable_Node Node; typedef wxHashTable_Node* compatibility_iterator; public: wxHashTable( wxKeyType keyType = wxKEY_INTEGER, size_t size = wxHASH_SIZE_DEFAULT ) : wxHashTableBase() { Create( keyType, size ); BeginFind(); } wxHashTable( const wxHashTable& table ); virtual ~wxHashTable() { Destroy(); } const wxHashTable& operator=( const wxHashTable& ); // key and value are the same void Put(long value, wxObject *object) { DoPut( value, value, object ); } void Put(long lhash, long value, wxObject *object) { DoPut( value, lhash, object ); } void Put(const wxChar *value, wxObject *object) { DoPut( value, MakeKey( value ), object ); } void Put(long lhash, const wxChar *value, wxObject *object) { DoPut( value, lhash, object ); } // key and value are the same wxObject *Get(long value) const { return (wxObject*)DoGet( value, value ); } wxObject *Get(long lhash, long value) const { return (wxObject*)DoGet( value, lhash ); } wxObject *Get(const wxChar *value) const { return (wxObject*)DoGet( value, MakeKey( value ) ); } wxObject *Get(long lhash, const wxChar *value) const { return (wxObject*)DoGet( value, lhash ); } // Deletes entry and returns data if found wxObject *Delete(long key) { return (wxObject*)DoDelete( key, key ); } wxObject *Delete(long lhash, long key) { return (wxObject*)DoDelete( key, lhash ); } wxObject *Delete(const wxChar *key) { return (wxObject*)DoDelete( key, MakeKey( key ) ); } wxObject *Delete(long lhash, const wxChar *key) { return (wxObject*)DoDelete( key, lhash ); } // Construct your own integer key from a string, e.g. in case // you need to combine it with something long MakeKey(const wxChar *string) const { return wxHashTableBase::MakeKey(string); } // Way of iterating through whole hash table (e.g. to delete everything) // Not necessary, of course, if you're only storing pointers to // objects maintained separately void BeginFind() { m_curr = NULL; m_currBucket = 0; } Node* Next(); void Clear() { wxHashTableBase::Clear(); } size_t GetCount() const { return wxHashTableBase::GetCount(); } protected: // copy helper void DoCopy( const wxHashTable& copy ); // searches the next node starting from bucket bucketStart and sets // m_curr to it and m_currBucket to its bucket void GetNextNode( size_t bucketStart ); private: virtual void DoDeleteContents( wxHashTableBase_Node* node ); // current node Node* m_curr; // bucket the current node belongs to size_t m_currBucket; }; #else // if wxUSE_OLD_HASH_TABLE class WXDLLIMPEXP_BASE wxHashTable : public wxObject { public: typedef wxNode Node; typedef wxNode* compatibility_iterator; int n; int current_position; wxNode *current_node; unsigned int key_type; wxList **hash_table; wxHashTable(int the_key_type = wxKEY_INTEGER, int size = wxHASH_SIZE_DEFAULT); virtual ~wxHashTable(); // copy ctor and assignment operator wxHashTable(const wxHashTable& table) : wxObject() { DoCopy(table); } wxHashTable& operator=(const wxHashTable& table) { Clear(); DoCopy(table); return *this; } void DoCopy(const wxHashTable& table); void Destroy(); bool Create(int the_key_type = wxKEY_INTEGER, int size = wxHASH_SIZE_DEFAULT); // Note that there are 2 forms of Put, Get. // With a key and a value, the *value* will be checked // when a collision is detected. Otherwise, if there are // 2 items with a different value but the same key, // we'll retrieve the WRONG ONE. So where possible, // supply the required value along with the key. // In fact, the value-only versions make a key, and still store // the value. The use of an explicit key might be required // e.g. when combining several values into one key. // When doing that, it's highly likely we'll get a collision, // e.g. 1 + 2 = 3, 2 + 1 = 3. // key and value are NOT necessarily the same void Put(long key, long value, wxObject *object); void Put(long key, const wxChar *value, wxObject *object); // key and value are the same void Put(long value, wxObject *object); void Put(const wxChar *value, wxObject *object); // key and value not the same wxObject *Get(long key, long value) const; wxObject *Get(long key, const wxChar *value) const; // key and value are the same wxObject *Get(long value) const; wxObject *Get(const wxChar *value) const; // Deletes entry and returns data if found wxObject *Delete(long key); wxObject *Delete(const wxChar *key); wxObject *Delete(long key, int value); wxObject *Delete(long key, const wxChar *value); // Construct your own integer key from a string, e.g. in case // you need to combine it with something long MakeKey(const wxChar *string) const; // Way of iterating through whole hash table (e.g. to delete everything) // Not necessary, of course, if you're only storing pointers to // objects maintained separately void BeginFind(); Node* Next(); void DeleteContents(bool flag); void Clear(); // Returns number of nodes size_t GetCount() const { return m_count; } private: size_t m_count; // number of elements in the hashtable bool m_deleteContents; DECLARE_DYNAMIC_CLASS(wxHashTable) }; #endif // wxUSE_OLD_HASH_TABLE #if !wxUSE_OLD_HASH_TABLE // defines a new type safe hash table which stores the elements of type eltype // in lists of class listclass #define _WX_DECLARE_HASH(eltype, dummy, hashclass, classexp) \ classexp hashclass : public wxHashTableBase \ { \ public: \ hashclass(wxKeyType keyType = wxKEY_INTEGER, \ size_t size = wxHASH_SIZE_DEFAULT) \ : wxHashTableBase() { Create(keyType, size); } \ \ virtual ~hashclass() { Destroy(); } \ \ void Put(long key, eltype *data) { DoPut(key, key, (void*)data); } \ void Put(long lhash, long key, eltype *data) \ { DoPut(key, lhash, (void*)data); } \ eltype *Get(long key) const { return (eltype*)DoGet(key, key); } \ eltype *Get(long lhash, long key) const \ { return (eltype*)DoGet(key, lhash); } \ eltype *Delete(long key) { return (eltype*)DoDelete(key, key); } \ eltype *Delete(long lhash, long key) \ { return (eltype*)DoDelete(key, lhash); } \ private: \ virtual void DoDeleteContents( wxHashTableBase_Node* node ) \ { delete (eltype*)node->GetData(); } \ \ DECLARE_NO_COPY_CLASS(hashclass) \ } #else // if wxUSE_OLD_HASH_TABLE #define _WX_DECLARE_HASH(eltype, listclass, hashclass, classexp) \ classexp hashclass : public wxHashTableBase \ { \ public: \ hashclass(wxKeyType keyType = wxKEY_INTEGER, \ size_t size = wxHASH_SIZE_DEFAULT) \ { Create(keyType, size); } \ \ virtual ~hashclass() { Destroy(); } \ \ void Put(long key, long val, eltype *data) { DoPut(key, val, data); } \ void Put(long key, eltype *data) { DoPut(key, key, data); } \ \ eltype *Get(long key, long value) const \ { \ wxNodeBase *node = GetNode(key, value); \ return node ? ((listclass::Node *)node)->GetData() : (eltype *)0; \ } \ eltype *Get(long key) const { return Get(key, key); } \ \ eltype *Delete(long key, long value) \ { \ eltype *data; \ \ wxNodeBase *node = GetNode(key, value); \ if ( node ) \ { \ data = ((listclass::Node *)node)->GetData(); \ \ delete node; \ m_count--; \ } \ else \ { \ data = (eltype *)0; \ } \ \ return data; \ } \ eltype *Delete(long key) { return Delete(key, key); } \ \ protected: \ void DoPut(long key, long value, eltype *data) \ { \ size_t slot = (size_t)abs((int)(key % (long)m_hashSize)); \ \ if ( !m_hashTable[slot] ) \ { \ m_hashTable[slot] = new listclass(m_keyType); \ if ( m_deleteContents ) \ m_hashTable[slot]->DeleteContents(true); \ } \ \ ((listclass *)m_hashTable[slot])->Append(value, data); \ m_count++; \ } \ \ DECLARE_NO_COPY_CLASS(hashclass) \ } #endif // wxUSE_OLD_HASH_TABLE // this macro is to be used in the user code #define WX_DECLARE_HASH(el, list, hash) \ _WX_DECLARE_HASH(el, list, hash, class) // and this one does exactly the same thing but should be used inside the // library #define WX_DECLARE_EXPORTED_HASH(el, list, hash) \ _WX_DECLARE_HASH(el, list, hash, class WXDLLEXPORT) #define WX_DECLARE_USER_EXPORTED_HASH(el, list, hash, usergoo) \ _WX_DECLARE_HASH(el, list, hash, class usergoo) // delete all hash elements // // NB: the class declaration of the hash elements must be visible from the // place where you use this macro, otherwise the proper destructor may not // be called (a decent compiler should give a warning about it, but don't // count on it)! #define WX_CLEAR_HASH_TABLE(hash) \ { \ (hash).BeginFind(); \ wxHashTable::compatibility_iterator it = (hash).Next(); \ while( it ) \ { \ delete it->GetData(); \ it = (hash).Next(); \ } \ (hash).Clear(); \ } #endif // _WX_HASH_H__
[ [ [ 1, 630 ] ] ]
2443a967a29fbdc2b7afd68ec4faa09d8b94aad8
9566086d262936000a914c5dc31cb4e8aa8c461c
/EnigmaServer/Application.hpp
8429f99d09b86ae7da5e98624e88bc6e93143be5
[]
no_license
pazuzu156/Enigma
9a0aaf0cd426607bb981eb46f5baa7f05b66c21f
b8a4dfbd0df206e48072259dbbfcc85845caad76
refs/heads/master
2020-06-06T07:33:46.385396
2011-12-19T03:14:15
2011-12-19T03:14:15
3,023,618
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
3,426
hpp
#ifndef APPLICATION_HPP_INCLUDED #define APPLICATION_HPP_INCLUDED /* Copyright © 2009 Christopher Joseph Dean Schaefer (disks86) 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. */ #include "ServerTransmissionManager.hpp" #include "IApplicationEventListener.hpp" #include "DataAccessListener.hpp" namespace Enigma { class Application : public IApplicationEventListener { private: bool mIsUnloaded; bool mIsStopped; ServerTransmissionManager mServerTransmissionManager; DataAccessListener mDataAccessListener; protected: /* * Initialize variables to null or other default values. * This should not result in an exception. */ void PreInit(); /* * Initialize variables to sane and useable values. * Can cause exceptions. */ void Init(int argc, Enigma::c8** argv); /* * Load all required resources for execution. * Can result in an exception if resources cannot be loaded. */ void Load(); void LoadUnsafely(); /* * Unload or release all resources loaded during the load part of the life cycle. * */ void Unload(); /* * Steps through the object life cycle can starts calling poll until stopped. (This is a thread entry point if applicable.) * May result in an exception if any portion of the object life cycle results in an exception. */ void EnterLoop(int argc, Enigma::c8** argv); /* * Performs executions processes. * May result in an exception if any of those processes fail. */ void Poll(); bool PollSafe(); public: Application(); ~Application(); /* * Start execution of the application by stepping through object life cycle and calling the entry point. * May result in an exception at multiple stages. */ void Start(int argc, Enigma::c8** argv); /* * Stop execution of the application by halting the progression through the object life cycle and skipping to unloading. * May result in an exception if execution cannot be stopped or unloading results in an exception. */ void Stop(); void DoApplicationEvents(); void DoAudioEvents(); void DoChatEvents(); void DoSceneEvents(); virtual void onExit(); virtual void onChangeGameMode(size_t gameMode); virtual void onLog(const std::string& message); virtual void onOpenBrowserWindow(const std::string& url); virtual void onOpenVideoWindow(const std::string& url); virtual void onReceivedCharacterList(const std::vector<std::string>& characters){} }; }; #endif // APPLICATION_HPP_INCLUDED
[ [ [ 1, 102 ] ] ]
982235557bb1e07d001a9230d9f78f55fc8f09ce
b4f709ac9299fe7a1d3fa538eb0714ba4461c027
/trunk/alternateending.cpp
f63e2877d5943522ce0eb8a3d733cb3e271ecb86
[]
no_license
BackupTheBerlios/ptparser-svn
d953f916eba2ae398cc124e6e83f42e5bc4558f0
a18af9c39ed31ef5fd4c5e7b69c3768c5ebb7f0c
refs/heads/master
2020-05-27T12:26:21.811820
2005-11-06T14:23:18
2005-11-06T14:23:18
40,801,514
0
0
null
null
null
null
UTF-8
C++
false
false
7,719
cpp
///////////////////////////////////////////////////////////////////////////// // Name: alternateending.cpp // Purpose: Stores and renders alternate ending symbols // Author: Brad Larsen // Modified by: // Created: Dec 3, 2004 // RCS-ID: // Copyright: (c) Brad Larsen // License: wxWindows license ///////////////////////////////////////////////////////////////////////////// #include "stdwx.h" #include "alternateending.h" #include <math.h> // Needed for pow function #ifdef _DEBUG #define new DEBUG_NEW #endif // Constructor/Destructor /// Default Constructor AlternateEnding::AlternateEnding() { //------Last Checked------// // - Dec 4, 2004 } /// Primary Constructor /// @param system Zero-based index of the system where the alternate ending is anchored /// @param position Zero-based index of the position within the system where the alternate ending is anchored /// @param numbers Bits indicating which numbers are to be set (1st bit = 1., 2nd bit = 2., etc.) AlternateEnding::AlternateEnding(wxUint32 system, wxUint32 position, wxWord numbers) { //------Last Checked------// // - Dec 4, 2004 SetSystem(system); SetPosition(position); SetNumbers(numbers); } /// Copy Constructor AlternateEnding::AlternateEnding(const AlternateEnding& alternateEnding) { //------Last Checked------// // - Dec 3, 2004 *this = alternateEnding; } /// Destructor AlternateEnding::~AlternateEnding() { //------Last Checked------// // - Dec 3, 2004 } // Operators /// Assignment Operator const AlternateEnding& AlternateEnding::operator=(const AlternateEnding& alternateEnding) { //------Last Checked------// // - Dec 3, 2004 // Check for assignment to self if (this != &alternateEnding) SystemSymbol::operator=(alternateEnding); return (*this); } /// Equality Operator bool AlternateEnding::operator==(const AlternateEnding& alternateEnding) const { //------Last Checked------// // - Jan 12, 2005 return (SystemSymbol::operator==(alternateEnding)); } /// Inequality Operator bool AlternateEnding::operator!=(const AlternateEnding& alternateEnding) const { //------Last Checked------// // - Jan 5, 2005 return (!operator==(alternateEnding)); } // Serialize Functions /// Performs serialization for the class /// @param stream Power Tab output stream to serialize to /// @return True if the object was serialized, false if not bool AlternateEnding::DoSerialize(PowerTabOutputStream& stream) { //------Last Checked------// // - Dec 27, 2004 return (SystemSymbol::DoSerialize(stream)); } /// Performs deserialization for the class /// @param stream Power Tab input stream to load from /// @param version File version /// @return True if the object was deserialized, false if not bool AlternateEnding::DoDeserialize(PowerTabInputStream& stream, wxWord version) { //------Last Checked------// // - Dec 27, 2004 return (SystemSymbol::DoDeserialize(stream, version)); } // Number Functions /// Sets the numbers using a bit map /// @param numbers Bit map of the numbers to set (bit 0 = 1, bit 1 = 2, bit 2 = 3, etc.) /// @return True if the numbers were set, false if not bool AlternateEnding::SetNumbers(wxWord numbers) { //------Last Checked------// // - Jan 12, 2005 wxCHECK(IsValidNumbers(numbers), false); m_data = MAKELONG(0, numbers); return (true); } /// Gets a bit map representing the numbers /// @return Bit map representing the numbers wxWord AlternateEnding::GetNumbers() const { //------Last Checked------// // - Jan 12, 2005 return (HIWORD(m_data)); } /// Sets a number /// @param number The number to set (one based) /// @return True if the number was set, false if not bool AlternateEnding::SetNumber(wxUint32 number) { //------Last Checked------// // - Jan 12, 2005 wxCHECK(IsValidNumber(number), false); // Note: Numbers are stored in zero-based form wxWord numbers = GetNumbers(); numbers |= (wxWord)(pow(2, (number - 1))); return (SetNumbers(numbers)); } /// Determines if a number is set /// @param number A one-based index of the number to test /// @return True if the number is set, false if not bool AlternateEnding::IsNumberSet(wxUint32 number) const { //------Last Checked------// // - Jan 12, 2005 wxCHECK(IsValidNumber(number), false); // Number is one based, so subtract one number--; // Determine if bit is set wxWord numbers = GetNumbers(); wxWord power = (wxWord)pow(2, number); return ((numbers & power) == power); } /// Clears a number /// @param number The number to clear (one based) /// @return True if the number was cleared, false if not bool AlternateEnding::ClearNumber(wxUint32 number) { //------Last Checked------// // - Jan 12, 2005 wxCHECK(IsValidNumber(number), false); wxWord numbers = GetNumbers(); numbers &= ~(wxWord)(pow(2, (number - 1))); SetNumbers(numbers); return (true); } /// Gets the alternate ending text (numbers + D.C./D.S./D.S.S.) /// @return Text representation of the alternate ending wxString AlternateEnding::GetText() const { //------Last Checked------// // - Dec 3, 2004 wxString returnValue; wxInt32 groupStart = -1; wxInt32 groupEnd = -1; // Construct the numbers wxUint32 i = 1; wxUint32 lastNumber = 8; for (; i <= lastNumber; i++) { bool numberSet = IsNumberSet(i); if (numberSet) { // Starting a new group of numbers if (groupStart == -1) groupStart = groupEnd = i; // Continuing existing group else groupEnd = i; } // Always treat the last number like the end of a group if (i == lastNumber) numberSet = false; // We've reached the end of a group, if groupStart != -1, then we have a group if (!numberSet && groupStart != -1) { // Add a separator if (!returnValue.IsEmpty()) returnValue += wxT(", "); wxString temp; // Single number if (groupStart == groupEnd) temp = wxString::Format(wxT("%s."), GetNumberText(groupStart).c_str()); // 2 numbers else if (groupStart == (groupEnd - 1)) temp = wxString::Format(wxT("%s., %s."), GetNumberText(groupStart).c_str(), GetNumberText(groupEnd).c_str()); // > 2 numbers else temp = wxString::Format(wxT("%s.-%s."), GetNumberText(groupStart).c_str(), GetNumberText(groupEnd).c_str()); returnValue += temp; // Reset the group data groupStart = groupEnd = -1; } } // Construct the special symbols i = daCapo; for (; i <= dalSegnoSegno; i++) { if (IsNumberSet(i)) { if (!returnValue.IsEmpty()) returnValue += wxT(", "); returnValue += GetNumberText(i).c_str(); } } return (returnValue); } /// Gets the text for a number /// @param number Number to get the text for (one based) /// @return Text representation of the number wxString AlternateEnding::GetNumberText(wxUint32 number) { //------Last Checked------// // - Dec 3, 2004 wxCHECK(IsValidNumber(number), wxT("")); if (number == daCapo) return wxT("D.C."); else if (number == dalSegno) return wxT("D.S."); else if (number == dalSegnoSegno) return wxT("D.S.S."); return (wxString::Format(wxT("%d"), number)); }
[ "blarsen@8c24db97-d402-0410-b267-f151a046c31a" ]
[ [ [ 1, 268 ] ] ]
b57751926943d844d14a50fd0405d3403a087204
d0cf8820b4ad21333e15f7cec1e4da54efe1fdc5
/DES_GOBSTG/DES_GOBSTG/Process/processInit.cpp
0af3152e6d105c9cf5431e5327fc998cd830c7e3
[]
no_license
CBE7F1F65/c1bf2614b1ec411ee7fe4eb8b5cfaee6
296b31d342e39d1d931094c3dfa887dbb2143e54
09ed689a34552e62316e0e6442c116bf88a5a88b
refs/heads/master
2020-05-30T14:47:27.645751
2010-10-12T16:06:11
2010-10-12T16:06:11
32,192,658
0
0
null
null
null
null
UTF-8
C++
false
false
12,338
cpp
#include "processPrep.h" int Process::processInit() { bool rebuilddone = false; if(_access(CONFIG_STR_FILENAME, 00) == -1) { rebuild: if (rebuilddone) { errorcode = PROC_ERROR_INIFILE; return PQUIT; } DeleteFile(CONFIG_STR_FILENAME); hge-> Ini_SetInt(data.translateSection(data.sLinkType(DATAS_HEADER)), data.translateName(data.nLinkType(DATAN_GAMEVERSION)), GAME_VERSION); hge-> Ini_SetString(data.translateSection(data.sLinkType(DATAS_HEADER)), data.translateName(data.nLinkType(DATAN_SIGNATURE)), GAME_SIGNATURE); hge-> Ini_SetString(RESCONFIGS_RESOURCE, RESCONFIGN_RESOURCEFILE, RESCONFIGDEFAULT_RESOURCEFILE); hge-> Ini_SetString(RESCONFIGS_RESOURCE, RESCONFIGN_RESBINNAME, RESCONFIGDEFAULT_RESBINNAME); hge-> Ini_SetString(RESCONFIGS_RESOURCE, RESCONFIGN_PASSWORD, RESCONFIGDEFAULT_PASSWORD); hge-> Ini_SetInt(RESCONFIGS_KEYSETTING, RESCONFIGN_KEYUP, RESCONFIGDEFAULT_KEYUP); hge-> Ini_SetInt(RESCONFIGS_KEYSETTING, RESCONFIGN_KEYDOWN, RESCONFIGDEFAULT_KEYDOWN); hge-> Ini_SetInt(RESCONFIGS_KEYSETTING, RESCONFIGN_KEYLEFT, RESCONFIGDEFAULT_KEYLEFT); hge-> Ini_SetInt(RESCONFIGS_KEYSETTING, RESCONFIGN_KEYRIGHT, RESCONFIGDEFAULT_KEYRIGHT); hge-> Ini_SetInt(RESCONFIGS_KEYSETTING, RESCONFIGN_KEYFIRE, RESCONFIGDEFAULT_KEYFIRE); hge-> Ini_SetInt(RESCONFIGS_KEYSETTING, RESCONFIGN_KEYBOMB, RESCONFIGDEFAULT_KEYBOMB); hge-> Ini_SetInt(RESCONFIGS_KEYSETTING, RESCONFIGN_KEYSLOW, RESCONFIGDEFAULT_KEYSLOW); hge-> Ini_SetInt(RESCONFIGS_KEYSETTING, RESCONFIGN_KEYCIRCLE, RESCONFIGDEFAULT_KEYCIRCLE); hge-> Ini_SetInt(RESCONFIGS_KEYSETTING, RESCONFIGN_KEYPAUSE, RESCONFIGDEFAULT_KEYPAUSE); hge-> Ini_SetInt(RESCONFIGS_KEYSETTING, RESCONFIGN_KEYSKIP, RESCONFIGDEFAULT_KEYSKIP); hge-> Ini_SetInt(RESCONFIGS_KEYSETTING, RESCONFIGN_KEYENTER, RESCONFIGDEFAULT_KEYENTER); hge-> Ini_SetInt(RESCONFIGS_KEYSETTING, RESCONFIGN_KEYESCAPE, RESCONFIGDEFAULT_KEYESCAPE); hge-> Ini_SetInt(RESCONFIGS_KEYSETTING, RESCONFIGN_KEYCAPTURE, RESCONFIGDEFAULT_KEYCAPTURE); hge-> Ini_SetInt(RESCONFIGS_JOYSETTING, RESCONFIGN_JOYFIRE, RESCONFIGDEFAULT_JOYFIRE); hge-> Ini_SetInt(RESCONFIGS_JOYSETTING, RESCONFIGN_JOYBOMB, RESCONFIGDEFAULT_JOYBOMB); hge-> Ini_SetInt(RESCONFIGS_JOYSETTING, RESCONFIGN_JOYSLOW, RESCONFIGDEFAULT_JOYSLOW); hge-> Ini_SetInt(RESCONFIGS_JOYSETTING, RESCONFIGN_JOYCIRCLE, RESCONFIGDEFAULT_JOYCIRCLE); hge-> Ini_SetInt(RESCONFIGS_JOYSETTING, RESCONFIGN_JOYPAUSE, RESCONFIGDEFAULT_JOYPAUSE); hge-> Ini_SetInt(RESCONFIGS_VOLUME, RESCONFIGN_VOLMUSIC, RESCONFIGDEFAULT_VOLMUSIC); hge-> Ini_SetInt(RESCONFIGS_VOLUME, RESCONFIGN_VOLSE, RESCONFIGDEFAULT_VOLSE); hge-> Ini_SetInt(RESCONFIGS_CUSTOM, RESCONFIGN_MAXPLAYER, RESCONFIGDEFAULT_MAXPLAYER); hge-> Ini_SetInt(RESCONFIGS_CUSTOM, RESCONFIGN_SCREENMODE, RESCONFIGDEFAULT_SCREENMODE); hge-> Ini_SetInt(RESCONFIGS_CUSTOM, RESCONFIGN_DEFAULTLEVEL, RESCONFIGDEFAULT_DEFAULTLV); hge-> Ini_SetString(RESCONFIGS_CUSTOM, RESCONFIGN_USERNAME, RESCONFIGDEFAULT_USERNAME); hge-> Ini_SetInt(RESCONFIGS_CUSTOM, RESCONFIGN_RENDERSKIP, RESCONFIGDEFAULT_RENDERSKIP); hge-> Ini_SetInt(RESCONFIGS_CUSTOMWINDOW, RESCONFIGN_DEFAULTWINDOW, RESCONFIGDEFAULT_DEFAULTWINDOW); hge-> Ini_SetInt(RESCONFIGS_CUSTOMWINDOW, RESCONFIGN_WINDOWLEFT, RESCONFIGDEFAULT_WINDOWLEFT); hge-> Ini_SetInt(RESCONFIGS_CUSTOMWINDOW, RESCONFIGN_WINDOWTOP, RESCONFIGDEFAULT_WINDOWTOP); hge-> Ini_SetInt(RESCONFIGS_CUSTOMWINDOW, RESCONFIGN_WINDOWWIDTH, RESCONFIGDEFAULT_WINDOWWIDTH); hge-> Ini_SetInt(RESCONFIGS_CUSTOMWINDOW, RESCONFIGN_WINDOWHEIGHT, RESCONFIGDEFAULT_WINDOWHEIGHT); hge-> Ini_SetInt(RESCONFIGS_CUSTOMWINDOW, RESCONFIGN_WINDOWTOPMOST, RESCONFIGDEFAULT_WINDOWTOPMOST); #ifdef __DEBUG hge-> Ini_SetInt(RESCONFIGS_JOYSETTING, RESCONFIGN_DEBUG_JOYSPEEDUP, RESCONFIGDEFAULT_DEBUG_JOYSPEEDUP); HGELOG("Config File rebuilt"); rebuilddone = true; #endif } keyUp = hge->Ini_GetInt(RESCONFIGS_KEYSETTING, RESCONFIGN_KEYUP, RESCONFIGDEFAULT_KEYUP); keyDown = hge->Ini_GetInt(RESCONFIGS_KEYSETTING, RESCONFIGN_KEYDOWN, RESCONFIGDEFAULT_KEYDOWN); keyLeft = hge->Ini_GetInt(RESCONFIGS_KEYSETTING, RESCONFIGN_KEYLEFT, RESCONFIGDEFAULT_KEYLEFT); keyRight = hge->Ini_GetInt(RESCONFIGS_KEYSETTING, RESCONFIGN_KEYRIGHT, RESCONFIGDEFAULT_KEYRIGHT); keyFire = hge->Ini_GetInt(RESCONFIGS_KEYSETTING, RESCONFIGN_KEYFIRE, RESCONFIGDEFAULT_KEYFIRE); keyBomb = hge->Ini_GetInt(RESCONFIGS_KEYSETTING, RESCONFIGN_KEYBOMB, RESCONFIGDEFAULT_KEYBOMB); keySlow = hge->Ini_GetInt(RESCONFIGS_KEYSETTING, RESCONFIGN_KEYSLOW, RESCONFIGDEFAULT_KEYSLOW); keyCircle = hge->Ini_GetInt(RESCONFIGS_KEYSETTING, RESCONFIGN_KEYCIRCLE, RESCONFIGDEFAULT_KEYCIRCLE); keyPause = hge->Ini_GetInt(RESCONFIGS_KEYSETTING, RESCONFIGN_KEYPAUSE, RESCONFIGDEFAULT_KEYPAUSE); keySkip = hge->Ini_GetInt(RESCONFIGS_KEYSETTING, RESCONFIGN_KEYSKIP, RESCONFIGDEFAULT_KEYSKIP); keyEnter = hge->Ini_GetInt(RESCONFIGS_KEYSETTING, RESCONFIGN_KEYENTER, RESCONFIGDEFAULT_KEYENTER); keyEscape = hge->Ini_GetInt(RESCONFIGS_KEYSETTING, RESCONFIGN_KEYESCAPE, RESCONFIGDEFAULT_KEYESCAPE); keyCapture = hge->Ini_GetInt(RESCONFIGS_KEYSETTING, RESCONFIGN_KEYCAPTURE, RESCONFIGDEFAULT_KEYCAPTURE); joyFire = hge->Ini_GetInt(RESCONFIGS_JOYSETTING, RESCONFIGN_JOYFIRE, RESCONFIGDEFAULT_JOYFIRE); joyBomb = hge->Ini_GetInt(RESCONFIGS_JOYSETTING, RESCONFIGN_JOYBOMB, RESCONFIGDEFAULT_JOYBOMB); joySlow = hge->Ini_GetInt(RESCONFIGS_JOYSETTING, RESCONFIGN_JOYSLOW, RESCONFIGDEFAULT_JOYSLOW); joyCircle = hge->Ini_GetInt(RESCONFIGS_JOYSETTING, RESCONFIGN_JOYCIRCLE, RESCONFIGDEFAULT_JOYCIRCLE); joyPause = hge->Ini_GetInt(RESCONFIGS_JOYSETTING, RESCONFIGN_JOYPAUSE, RESCONFIGDEFAULT_JOYPAUSE); #ifdef __DEBUG debug_joySpeedUp = hge->Ini_GetInt(RESCONFIGS_JOYSETTING, RESCONFIGN_DEBUG_JOYSPEEDUP, RESCONFIGDEFAULT_DEBUG_JOYSPEEDUP); #endif bgmvol = hge->Ini_GetInt(RESCONFIGS_VOLUME, RESCONFIGN_VOLMUSIC, RESCONFIGDEFAULT_VOLMUSIC); sevol = hge->Ini_GetInt(RESCONFIGS_VOLUME, RESCONFIGN_VOLSE, RESCONFIGDEFAULT_VOLSE); maxplayer = hge->Ini_GetInt(RESCONFIGS_CUSTOM, RESCONFIGN_MAXPLAYER, RESCONFIGDEFAULT_MAXPLAYER); screenmode = hge->Ini_GetInt(RESCONFIGS_CUSTOM, RESCONFIGN_SCREENMODE, RESCONFIGDEFAULT_SCREENMODE); defaultdifflv = hge->Ini_GetInt(RESCONFIGS_CUSTOM, RESCONFIGN_DEFAULTLEVEL, RESCONFIGDEFAULT_DEFAULTLV); strcpy(username, hge->Ini_GetString(RESCONFIGS_CUSTOM, RESCONFIGN_USERNAME, RESCONFIGDEFAULT_USERNAME)); hge->renderSkip = hge->Ini_GetInt(RESCONFIGS_CUSTOM, RESCONFIGN_RENDERSKIP, RESCONFIGDEFAULT_RENDERSKIP); circlearound = hge->Ini_GetInt(RESCONFIGS_CUSTOM, RESCONFIGN_CIRCLEAROUND, RESCONFIGDEFAULT_CIRCLEAROUND); bool binmode = Export::GetResourceFile(); data.GetIni(); // if(hge->Ini_GetInt(data.translateSection(data.sLinkType(DATAS_HEADER)), data.translateName(data.nLinkType(DATAN_GAMEVERSION)), -1) != GAME_VERSION) goto rebuild; for (int i=0; i<13; i++) { if (keyKey[i] < 0 || keyKey[i] >= M_KEYKEYMAX) { goto rebuild; } } for (int i=0; i<5; i++) { if(joyKey[i] < 0 || joyKey[i] >= M_JOYKEYMAX) { goto rebuild; } } #ifdef __DEBUG if(debug_joySpeedUp < 0 || debug_joySpeedUp >= M_JOYKEYMAX) goto rebuild; #endif if(maxplayer < 0 || maxplayer > M_PL_PLAYERMAX - 1) goto rebuild; if(screenmode < 0 || screenmode > 1) goto rebuild; if(defaultdifflv < 0 || defaultdifflv > M_DIFFI_EXTRA) goto rebuild; if(bgmvol < 0 || bgmvol > 100) goto rebuild; if(sevol < 0 || sevol > 100) goto rebuild; if (hge->renderSkip < 0 || hge->renderSkip > 3) { goto rebuild; } #ifdef __DEBUG HGELOG("Gained data from Config File."); #endif if(binmode) { data.binmode = true; scr.binmode = true; #ifdef __RELEASE // hge->System_SetState(HGE_LOGFILE, ""); #endif // __RELEASE } else { if(!res.Fill()) { #ifdef __DEBUG HGELOG("Error in Filling Resource Data."); #endif errorcode = PROC_ERROR_RESOURCE; return PQUIT; } if(!scr.LoadAll()) { errorcode = PROC_ERROR_SCRIPT; return PQUIT; } if(!res.Pack(strdesc, scr.customconstName)) { #ifdef __DEBUG HGELOG("Error in Packing Resource Data."); #endif errorcode = PROC_ERROR_TRANSLATE; return PQUIT; } if(!res.SetDataFile()) { errorcode = PROC_ERROR_DATA; return PQUIT; } } if(!res.Gain(strdesc, scr.customconstName)) { #ifdef __DEBUG HGELOG("Error in Gaining Resource Data."); #endif errorcode = PROC_ERROR_DATA; return PQUIT; } if(scr.binmode && !scr.LoadAll()) { errorcode = PROC_ERROR_SCRIPT; return PQUIT; } if(!data.SetFile(Export::resourcefilename, DATA_RESOURCEFILE)) { #ifdef __DEBUG HGELOG("Error in Setting Resource File"); #endif errorcode = PROC_ERROR_DATA; return PQUIT; } if(!res.LoadPackage()) { errorcode = PROC_ERROR_PACKAGE; return PQUIT; } BGLayer::Init(); SE::vol = sevol; if(!SE::Initial()) { errorcode = PROC_ERROR_SOUND; return PQUIT; } if(FPS_font) delete FPS_font; FPS_font = new hgeFont(res.resdata.normalfontfilename); #ifdef __DEBUG if(FPS_font == NULL) { HGELOG("%s\nFailed in loading Font File %s.", HGELOG_ERRSTR, res.resdata.normalfontfilename); errorcode = PROC_ERROR_FONT; return PQUIT; } else { HGELOG("Gained data from Font File %s.", res.resdata.normalfontfilename); } #endif FPS_font->SetColor(0xffffffff); if(info_font) { delete info_font; } info_font = new hgeFont(res.resdata.normalfontfilename); info_font->SetColor(0xceffffff); info_font->SetScale(1.5f); if(chat_font) hge->Font_Free(chat_font); chat_font = hge->Font_Load(res.resdata.widefontname, 20); Fontsys::font = chat_font; char tnbuffer[M_STRMAX]; for(int i=1;i<TEXMAX;i++) { if(tex[i]) hge->Texture_Free(tex[i]); tex[i] = NULL; strcpy(tnbuffer, res.resdata.texfilename[i]); if(!strlen(tnbuffer)) { if(i < TEX_FREEBEGIN) strcpy(tnbuffer, res.resdata.texfilename[TEX_WHITE]); else continue; } tex[i] = hge->Texture_Load(tnbuffer); #ifdef __DEBUG if(tex[i] == NULL) { HGELOG("%s\nFailed in loading Texture File %s.(To be assigned to Index %d)", HGELOG_ERRSTR, tnbuffer, i); errorcode = PROC_ERROR_TEXTURE; return PQUIT; } else { HGELOG("Texture File %s loaded.(Assigned to Index %d)", tnbuffer, i); } #endif } tex[TEX_WORD] = hge->Texture_Load(res.resdata.texfilename[TEX_WORD]); #ifdef __DEBUG if(tex[TEX_WORD] == NULL) { HGELOG("%s\nFailed in loading Texture File %s.(To be assigned to Index %d)", HGELOG_ERRSTR, res.resdata.texfilename[TEX_WORD], TEX_WORD); errorcode = PROC_ERROR_TEXTURE; return PQUIT; } else { HGELOG("Texture File %s loaded.(Assigned to Index %d)", res.resdata.texfilename[TEX_WORD], TEX_WORD); } #endif Fontsys::Init(); //Heatup Fontsys::HeatUp(); /* hgeQuad quad; quad.blend = BLEND_DEFAULT; quad.v[0].tx = 0; quad.v[0].ty = 0; quad.v[1].tx = 1; quad.v[1].ty = 0; quad.v[2].tx = 1; quad.v[2].ty = 1; quad.v[3].tx = 0; quad.v[3].ty = 1; quad.v[0].x = M_CLIENT_LEFT; quad.v[0].y = M_CLIENT_TOP; quad.v[1].x = M_CLIENT_RIGHT; quad.v[1].y = M_CLIENT_TOP; quad.v[2].x = M_CLIENT_RIGHT; quad.v[2].y = M_CLIENT_BOTTOM; quad.v[3].x = M_CLIENT_RIGHT; quad.v[3].y = M_CLIENT_BOTTOM; quad.v[0].z = quad.v[1].z = quad.v[2].z = quad.v[3].z = 0; quad.v[0].col = quad.v[1].col = quad.v[2].col = quad.v[3].col = 0xffffffff; hge->Gfx_BeginScene(); for (int i=0; i<TEXMAX; i++) { if (tex[i]) { quad.tex = tex[i]; hge->Gfx_RenderQuad(&quad); } } hge->Gfx_EndScene(); */ Selector::Clear(); pauseret = false; luchara = 0; nowdifflv = defaultdifflv; randi = 0; // hge->System_SetState(HGE_WINDOWED, !(bool)screenmode); hge->System_SetState(HGE_HIDEMOUSE, (bool)screenmode); if(!screenmode) { Export::clientAdjustWindow(); } #ifdef __DEBUG HGELOG("All resources loaded.\n"); #endif errorcode = PROC_ERROR_NONE; // titleselect = 0; replaymode = false; practicemode = false; rangemode = false; playing = false; playtimeStart = 0; time = 0; state = STATE_TITLE; return PTURN; }
[ "CBE7F1F65@e00939f0-95ee-11de-8df0-bd213fda01be" ]
[ [ [ 1, 359 ] ] ]
cd77321ccd54c8be30c18654ad356986a537cbbe
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/Modules/UiCtrl/RoutePositionData.h
d39fb8219dde6e60e8ebed24191767c290517292
[ "BSD-3-Clause" ]
permissive
ravustaja/Wayfinder-S60-Navigator
ef506c418b8c2e6498ece6dcae67e583fb8a4a95
14d1b729b2cea52f726874687e78f17492949585
refs/heads/master
2021-01-16T20:53:37.630909
2010-06-28T09:51:10
2010-06-28T09:51:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,909
h
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef ROUTEPOSITIONDATA_H #define ROUTEPOSITIONDATA_H namespace isab { class PositionObject { public: PositionObject(); PositionObject(uint8 type, int32 lat, int32 lon, const char *id, const char *name); ~PositionObject(); uint8 getType() { return m_type; } int32 getLat() { return m_lat; } int32 getLon() { return m_lon; } const char *getName() { return m_name; } const char *getId() { return m_id; } void setType(uint8 type) { m_type = type; } void setLat(int32 lat) { m_lat=lat; } void setLon(int32 lon) { m_lon=lon; } void setName(const char *name); void setId(const char *id); void setPositionOk(uint8 ok) { m_position_set = ok; } uint8 positionOk() { return m_position_set; } uint8 m_position_set; uint8 m_type; int32 m_lat; int32 m_lon; char *m_id; char *m_name; }; class RoutePositionData { public: RoutePositionData(); RoutePositionData(const char *destName, int32 orig_lat, int32 orig_lon, int32 dest_lat, int32 dest_lon); ~RoutePositionData(); int32 getoLat() { return m_origin->getLat(); } int32 getoLon() { return m_origin->getLon(); } int32 getdLat() { return m_dest->getLat(); } int32 getdLon() { return m_dest->getLon(); } const char *getDestinationName() { return m_dest->getName(); } void setoType(uint8 type) { m_origin->setType(type); } void setdType(uint8 type) { m_dest->setType(type); } void setoLat(int32 lat) { m_origin->setLat(lat); } void setoLon(int32 lon) { m_origin->setLon(lon); } void setdLat(int32 lat) { m_dest->setLat(lat); } void setdLon(int32 lon) { m_dest->setLon(lon); } void setoName(const char *name) { m_origin->setName(name); } void setdName(const char *name) { m_dest->setName(name); } void setoId(const char *id) { m_origin->setId(id); } void setdId(const char *id) { m_dest->setId(id); } void setoPositionOk(uint8 ok) { m_origin->setPositionOk(ok); } void setdPositionOk(uint8 ok) { m_dest->setPositionOk(ok); } uint8 getoPositionOk() { return m_origin->positionOk(); } uint8 getdPositionOk() { return m_dest->positionOk(); } uint16 m_req_type; uint16 m_req_id; PositionObject *m_origin; PositionObject *m_dest; }; } #endif /* ROUTEPOSITIONDATA_H */
[ [ [ 1, 90 ] ] ]
7cbd0611ccfa47d5acf0e336401bed10f28a743c
bf9e82f027caeff04cca5c16b327f33e59bfaf7a
/fce360/fceux/fceux/fceu.cpp
1c55b22e24c63376e89042914a208edebdb6c88c
[]
no_license
Miitumrow27/fce360
654de5d31223564a16299cfb84a2a4a7031791c3
fe388a88c18ea4c460f5aecb9c26bf6f13544e79
refs/heads/master
2020-05-05T02:01:05.998655
2011-01-24T20:05:22
2011-01-24T20:05:22
40,433,229
0
0
null
null
null
null
UTF-8
C++
false
false
25,660
cpp
/* FCE Ultra - NES/Famicom Emulator * * Copyright notice for this file: * Copyright (C) 2003 Xodnizel * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <string> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <time.h> #include "types.h" #include "x6502.h" #include "fceu.h" #include "ppu.h" #include "sound.h" #include "netplay.h" #include "file.h" #include "utils/endian.h" #include "utils/memory.h" #include "utils/crc32.h" #include "cart.h" #include "nsf.h" #include "fds.h" #include "ines.h" #include "unif.h" #include "cheat.h" #include "palette.h" #include "state.h" #include "movie.h" #include "video.h" #include "input.h" #include "file.h" #include "vsuni.h" #include "ines.h" #ifdef WIN32 #include "drivers/win/pref.h" #endif #include <fstream> #include <sstream> #ifdef _S9XLUA_H #include "fceulua.h" #endif //TODO - we really need some kind of global platform-specific options api #ifdef WIN32 #include "drivers/win/main.h" #include "drivers/win/cheat.h" #include "drivers/win/texthook.h" #include "drivers/win/ram_search.h" #include "drivers/win/ramwatch.h" #include "drivers/win/memwatch.h" #include "drivers/win/tracer.h" #else #ifdef GEKKO #include "driver.h" #elif _XBOX #include "driver.h" #else #include "drivers/sdl/sdl.h" #endif #endif using namespace std; int AFon = 1, AFoff = 1, AutoFireOffset = 0; //For keeping track of autofire settings bool justLagged = false; bool frameAdvanceLagSkip = false; //If this is true, frame advance will skip over lag frame (i.e. it will emulate 2 frames instead of 1) bool AutoSS = false; //Flagged true when the first auto-savestate is made while a game is loaded, flagged false on game close bool movieSubtitles = true; //Toggle for displaying movie subtitles bool DebuggerWasUpdated = false; //To prevent the debugger from updating things without being updated. FCEUGI::FCEUGI() : filename(0) , archiveFilename(0) { printf("%08x",opsize); } FCEUGI::~FCEUGI() { if(filename) delete filename; if(archiveFilename) delete archiveFilename; } bool CheckFileExists(const char* filename) { //This function simply checks to see if the given filename exists if (!filename) return false; fstream test; test.open(filename,fstream::in); if (test.fail()) { test.close(); return false; } else { test.close(); return true; } } void FCEU_TogglePPU(void) { newppu ^= 1; if (newppu) { FCEU_DispMessage("New PPU loaded", 0); FCEUI_printf("New PPU loaded"); } else { FCEU_DispMessage("Old PPU loaded", 0); FCEUI_printf("Old PPU loaded"); } } static void FCEU_CloseGame(void) { if(GameInfo) { #ifdef WIN32 //SP CODE extern char LoadedRomFName[2048]; if (storePreferences(LoadedRomFName)) { FCEUD_PrintError("Couldn't store debugging data"); } #endif if(FCEUnetplay) { FCEUD_NetworkClose(); } if(GameInfo->name) { free(GameInfo->name); GameInfo->name=0; } if(GameInfo->type!=GIT_NSF) { FCEU_FlushGameCheats(0,0); } GameInterface(GI_CLOSE); FCEUI_StopMovie(); ResetExState(0,0); //clear screen when game is closed extern uint8 *XBuf; if(XBuf) memset(XBuf,0,256*256); CloseGenie(); delete GameInfo; GameInfo = 0; currFrameCounter = 0; //Reset flags for Undo/Redo/Auto Savestating //adelikat: TODO: maybe this stuff would be cleaner as a struct or class lastSavestateMade[0] = 0; undoSS = false; redoSS = false; lastLoadstateMade[0] = 0; undoLS = false; redoLS = false; AutoSS = false; } } uint64 timestampbase; FCEUGI *GameInfo = 0; void (*GameInterface)(GI h); void (*GameStateRestore)(int version); readfunc ARead[0x10000]; writefunc BWrite[0x10000]; static readfunc *AReadG; static writefunc *BWriteG; static int RWWrap=0; //mbg merge 7/18/06 docs //bit0 indicates whether emulation is paused //bit1 indicates whether emulation is in frame step mode int EmulationPaused=0; bool frameAdvanceRequested=false; int frameAdvanceDelay; //indicates that the emulation core just frame advanced (consumed the frame advance state and paused) bool JustFrameAdvanced=false; static int *AutosaveStatus; //is it safe to load Auto-savestate static int AutosaveIndex = 0; //which Auto-savestate we're on int AutosaveQty = 4; // Number of Autosaves to store int AutosaveFrequency = 256; // Number of frames between autosaves // Flag that indicates whether the Auto-save option is enabled or not int EnableAutosave = 0; ///a wrapper for unzip.c extern "C" FILE *FCEUI_UTF8fopen_C(const char *n, const char *m) { return ::FCEUD_UTF8fopen(n,m); } static DECLFW(BNull) { } static DECLFR(ANull) { return(X.DB); } int AllocGenieRW(void) { if(!(AReadG=(readfunc *)FCEU_malloc(0x8000*sizeof(readfunc)))) return 0; if(!(BWriteG=(writefunc *)FCEU_malloc(0x8000*sizeof(writefunc)))) return 0; RWWrap=1; return 1; } void FlushGenieRW(void) { int32 x; if(RWWrap) { for(x=0;x<0x8000;x++) { ARead[x+0x8000]=AReadG[x]; BWrite[x+0x8000]=BWriteG[x]; } free(AReadG); free(BWriteG); AReadG=0; BWriteG=0; RWWrap=0; } } readfunc GetReadHandler(int32 a) { if(a>=0x8000 && RWWrap) return AReadG[a-0x8000]; else return ARead[a]; } void SetReadHandler(int32 start, int32 end, readfunc func) { int32 x; if(!func) func=ANull; if(RWWrap) for(x=end;x>=start;x--) { if(x>=0x8000) AReadG[x-0x8000]=func; else ARead[x]=func; } else for(x=end;x>=start;x--) ARead[x]=func; } writefunc GetWriteHandler(int32 a) { if(RWWrap && a>=0x8000) return BWriteG[a-0x8000]; else return BWrite[a]; } void SetWriteHandler(int32 start, int32 end, writefunc func) { int32 x; if(!func) func=BNull; if(RWWrap) for(x=end;x>=start;x--) { if(x>=0x8000) BWriteG[x-0x8000]=func; else BWrite[x]=func; } else for(x=end;x>=start;x--) BWrite[x]=func; } uint8 *GameMemBlock; uint8 *RAM; //--------- //windows might need to allocate these differently, so we have some special code static void AllocBuffers() { #ifdef _USE_SHARED_MEMORY_ void win_AllocBuffers(uint8 **GameMemBlock, uint8 **RAM); win_AllocBuffers(&GameMemBlock, &RAM); #else GameMemBlock = (uint8*)FCEU_gmalloc(GAME_MEM_BLOCK_SIZE); RAM = (uint8*)FCEU_gmalloc(0x800); #endif } static void FreeBuffers() { #ifdef _USE_SHARED_MEMORY_ void win_FreeBuffers(uint8 *GameMemBlock, uint8 *RAM); win_FreeBuffers(GameMemBlock, RAM); #else FCEU_free(GameMemBlock); FCEU_free(RAM); #endif } //------ uint8 PAL=0; static DECLFW(BRAML) { RAM[A]=V; #ifdef _S9XLUA_H CallRegisteredLuaMemHook(A, 1, V, LUAMEMHOOK_WRITE); #endif } static DECLFW(BRAMH) { RAM[A&0x7FF]=V; #ifdef _S9XLUA_H CallRegisteredLuaMemHook(A&0x7FF, 1, V, LUAMEMHOOK_WRITE); #endif } static DECLFR(ARAML) { return RAM[A]; } static DECLFR(ARAMH) { return RAM[A&0x7FF]; } void ResetGameLoaded(void) { if(GameInfo) FCEU_CloseGame(); EmulationPaused = 0; //mbg 5/8/08 - loading games while paused was bad news. maybe this fixes it GameStateRestore=0; PPU_hook=0; GameHBIRQHook=0; FFCEUX_PPURead = 0; FFCEUX_PPUWrite = 0; if(GameExpSound.Kill) GameExpSound.Kill(); memset(&GameExpSound,0,sizeof(GameExpSound)); MapIRQHook=0; MMC5Hack=0; PAL&=1; pale=0; } int UNIFLoad(const char *name, FCEUFILE *fp); int iNESLoad(const char *name, FCEUFILE *fp, int OverwriteVidMode); int FDSLoad(const char *name, FCEUFILE *fp); int NSFLoad(const char *name, FCEUFILE *fp); //char lastLoadedGameName [2048] = {0,}; // hack for movie WRAM clearing on record from poweron FCEUGI *FCEUI_LoadGameVirtual(const char *name, int OverwriteVidMode) { //mbg merge 7/17/07 - why is this here //#ifdef WIN32 // StopSound(); //#endif //---------- //attempt to open the files FCEUFILE *fp; FCEU_printf("Loading %s...\n\n",name); const char* romextensions[] = {"nes","fds",0}; fp=FCEU_fopen(name,0,"rb",0,-1,romextensions); if(!fp) { return 0; } GetFileBase(fp->filename.c_str()); if(!fp) { FCEU_PrintError("Error opening \"%s\"!",name); return 0; } //--------- //file opened ok. start loading. ResetGameLoaded(); if (!AutosaveStatus) AutosaveStatus = (int*)FCEU_dmalloc(sizeof(int)*AutosaveQty); for (AutosaveIndex=0; AutosaveIndex<AutosaveQty; ++AutosaveIndex) AutosaveStatus[AutosaveIndex] = 0; FCEU_CloseGame(); GameInfo = new FCEUGI(); memset(GameInfo, 0, sizeof(FCEUGI)); GameInfo->filename = strdup(fp->filename.c_str()); if(fp->archiveFilename != "") GameInfo->archiveFilename = strdup(fp->archiveFilename.c_str()); GameInfo->archiveCount = fp->archiveCount; GameInfo->soundchan = 0; GameInfo->soundrate = 0; GameInfo->name=0; GameInfo->type=GIT_CART; GameInfo->vidsys=GIV_USER; GameInfo->input[0]=GameInfo->input[1]=SI_UNSET; GameInfo->inputfc=SIFC_UNSET; GameInfo->cspecial=SIS_NONE; //try to load each different format bool FCEUXLoad(const char *name, FCEUFILE *fp); /*if(FCEUXLoad(name,fp)) goto endlseq;*/ if(iNESLoad(name,fp,OverwriteVidMode)) goto endlseq; if(NSFLoad(name,fp)) goto endlseq; if(UNIFLoad(name,fp)) goto endlseq; if(FDSLoad(name,fp)) goto endlseq; FCEU_PrintError("An error occurred while loading the file."); FCEU_fclose(fp); delete GameInfo; GameInfo = 0; return 0; endlseq: FCEU_fclose(fp); #ifdef WIN32 // ################################## Start of SP CODE ########################### extern char LoadedRomFName[2048]; extern int loadDebugDataFailed; if ((loadDebugDataFailed = loadPreferences(LoadedRomFName))) { FCEUD_PrintError("Couldn't load debugging data"); } // ################################## End of SP CODE ########################### #endif FCEU_ResetVidSys(); if(GameInfo->type!=GIT_NSF) if(FSettings.GameGenie) OpenGenie(); PowerNES(); if(GameInfo->type!=GIT_NSF) FCEU_LoadGamePalette(); FCEU_ResetPalette(); FCEU_ResetMessages(); // Save state, status messages, etc. if(GameInfo->type!=GIT_NSF) FCEU_LoadGameCheats(0); #if defined (WIN32) || defined (WIN64) DoDebuggerDataReload(); // Reloads data without reopening window #endif return GameInfo; } FCEUGI *FCEUI_LoadGame(const char *name, int OverwriteVidMode) { return FCEUI_LoadGameVirtual(name,OverwriteVidMode); } //Return: Flag that indicates whether the function was succesful or not. bool FCEUI_Initialize() { srand(time(0)); if(!FCEU_InitVirtualVideo()) { return false; } AllocBuffers(); // Initialize some parts of the settings structure //mbg 5/7/08 - I changed the ntsc settings to match pal. //this is more for precision emulation, instead of entertainment, which is what fceux is all about nowadays memset(&FSettings,0,sizeof(FSettings)); //FSettings.UsrFirstSLine[0]=8; FSettings.UsrFirstSLine[0]=0; FSettings.UsrFirstSLine[1]=0; //FSettings.UsrLastSLine[0]=231; FSettings.UsrLastSLine[0]=239; FSettings.UsrLastSLine[1]=239; FSettings.SoundVolume=150; //0-150 scale FSettings.TriangleVolume=256; //0-256 scale (256 is max volume) FSettings.Square1Volume=256; //0-256 scale (256 is max volume) FSettings.Square2Volume=256; //0-256 scale (256 is max volume) FSettings.NoiseVolume=256; //0-256 scale (256 is max volume) FSettings.PCMVolume=256; //0-256 scale (256 is max volume) FCEUPPU_Init(); X6502_Init(); return true; } void FCEUI_Kill(void) { #ifdef _S9XLUA_H FCEU_LuaStop(); #endif FCEU_KillVirtualVideo(); FCEU_KillGenie(); FreeBuffers(); } int rapidAlternator = 0; int AutoFirePattern[8] = {1,0,0,0,0,0,0,0}; int AutoFirePatternLength = 2; void SetAutoFirePattern(int onframes, int offframes) { int i; for(i = 0; i < onframes && i < 8; i++) { AutoFirePattern[i] = 1; } for(;i < 8; i++) { AutoFirePattern[i] = 0; } if(onframes + offframes < 2) { AutoFirePatternLength = 2; } else if(onframes + offframes > 8) { AutoFirePatternLength = 8; } else { AutoFirePatternLength = onframes + offframes; } AFon = onframes; AFoff = offframes; } void SetAutoFireOffset(int offset) { if(offset < 0 || offset > 8) return; AutoFireOffset = offset; } void AutoFire(void) { static int counter = 0; if (justLagged == false) counter = (counter + 1) % (8*7*5*3); //If recording a movie, use the frame # for the autofire so the offset //doesn't get screwed up when loading. if(FCEUMOV_Mode(MOVIEMODE_RECORD | MOVIEMODE_PLAY)) { rapidAlternator= AutoFirePattern[(AutoFireOffset + FCEUMOV_GetFrame())%AutoFirePatternLength]; //adelikat: TODO: Think through this, MOVIEMODE_FINISHED should not use movie data for auto-fire? } else { rapidAlternator= AutoFirePattern[(AutoFireOffset + counter)%AutoFirePatternLength]; } } void UpdateAutosave(void); ///Emulates a single frame. ///Skip may be passed in, if FRAMESKIP is #defined, to cause this to emulate more than one frame void FCEUI_Emulate(uint8 **pXBuf, int32 **SoundBuf, int32 *SoundBufSize, int skip) { //skip initiates frame skip if 1, or frame skip and sound skip if 2 int r,ssize; JustFrameAdvanced = false; if (frameAdvanceRequested) { if (frameAdvanceDelay==0 || frameAdvanceDelay>=10) EmulationPaused = 3; if (frameAdvanceDelay==0 || frameAdvanceDelay < 10) frameAdvanceDelay++; } if(EmulationPaused&2) EmulationPaused &= ~1; // clear paused flag temporarily (frame advance) else if((EmulationPaused&1)) { memcpy(XBuf, XBackBuf, 256*256); FCEU_PutImage(); *pXBuf=XBuf; *SoundBuf=WaveFinal; *SoundBufSize=0; return; } AutoFire(); UpdateAutosave(); #ifdef _S9XLUA_H FCEU_LuaFrameBoundary(); #endif FCEU_UpdateInput(); lagFlag = 1; #ifdef _S9XLUA_H CallRegisteredLuaFunctions(LUACALL_BEFOREEMULATION); #endif if(geniestage!=1) FCEU_ApplyPeriodicCheats(); r = FCEUPPU_Loop(skip); if (skip != 2) ssize=FlushEmulateSound(); //If skip = 2 we are skipping sound processing #ifdef _S9XLUA_H CallRegisteredLuaFunctions(LUACALL_AFTEREMULATION); #endif #ifdef WIN32 //These Windows only dialogs need to be updated only once per frame so they are included here UpdateCheatList(); // CaH4e3: can't see why, this is only cause problems with selection - adelikat: selection is only a problem when not paused, it shoudl be paused to select, we want to see the values update UpdateTextHooker(); Update_RAM_Search(); // Update_RAM_Watch() is also called. RamChange(); UpdateLogWindow(); //FCEUI_AviVideoUpdate(XBuf); extern int KillFCEUXonFrame; if (KillFCEUXonFrame && (FCEUMOV_GetFrame() >= KillFCEUXonFrame)) DoFCEUExit(); #endif timestampbase += timestamp; timestamp = 0; *pXBuf=skip?0:XBuf; if (skip == 2) //If skip = 2, then bypass sound { *SoundBuf=0; *SoundBufSize=0; } else { *SoundBuf=WaveFinal; *SoundBufSize=ssize; } if (EmulationPaused&2 && ( !frameAdvanceLagSkip || !lagFlag) ) //Lots of conditions here. EmulationPaused&2 must be true. In addition frameAdvanceLagSkip or lagFlag must be false { EmulationPaused = 1; // restore paused flag JustFrameAdvanced = true; #ifdef WIN32 if(soundoptions&SO_MUTEFA) //mute the frame advance if the user requested it *SoundBufSize=0; //keep sound muted #endif } currMovieData.TryDumpIncremental(); if (lagFlag) { lagCounter++; justLagged = true; } else justLagged = false; if (movieSubtitles) ProcessSubtitles(); } void FCEUI_CloseGame(void) { if(!FCEU_IsValidUI(FCEUI_CLOSEGAME)) return; FCEU_CloseGame(); } void ResetNES(void) { FCEUMOV_AddCommand(FCEUNPCMD_RESET); if(!GameInfo) return; GameInterface(GI_RESETM2); FCEUSND_Reset(); FCEUPPU_Reset(); X6502_Reset(); // clear back baffer extern uint8 *XBackBuf; memset(XBackBuf,0,256*256); } void FCEU_MemoryRand(uint8 *ptr, uint32 size) { int x=0; while(size) { *ptr=(x&4)?0xFF:0x00; x++; size--; ptr++; } } void hand(X6502 *X, int type, unsigned int A) { } int suppressAddPowerCommand=0; // hack... yeah, I know... void PowerNES(void) { //void MapperInit(); //MapperInit(); if(!suppressAddPowerCommand) FCEUMOV_AddCommand(FCEUNPCMD_POWER); if(!GameInfo) return; FCEU_CheatResetRAM(); FCEU_CheatAddRAM(2,0,RAM); GeniePower(); FCEU_MemoryRand(RAM,0x800); //memset(RAM,0xFF,0x800); SetReadHandler(0x0000,0xFFFF,ANull); SetWriteHandler(0x0000,0xFFFF,BNull); SetReadHandler(0,0x7FF,ARAML); SetWriteHandler(0,0x7FF,BRAML); SetReadHandler(0x800,0x1FFF,ARAMH); // Part of a little SetWriteHandler(0x800,0x1FFF,BRAMH); //hack for a small speed boost. InitializeInput(); FCEUSND_Power(); FCEUPPU_Power(); //Have the external game hardware "powered" after the internal NES stuff. Needed for the NSF code and VS System code. GameInterface(GI_POWER); if(GameInfo->type==GIT_VSUNI) FCEU_VSUniPower(); //if we are in a movie, then reset the saveram extern int disableBatteryLoading; if(disableBatteryLoading) GameInterface(GI_RESETSAVE); timestampbase=0; LagCounterReset(); X6502_Power(); FCEU_PowerCheats(); // clear back baffer extern uint8 *XBackBuf; memset(XBackBuf,0,256*256); } void FCEU_ResetVidSys(void) { int w; if(GameInfo->vidsys==GIV_NTSC) w=0; else if(GameInfo->vidsys==GIV_PAL) w=1; else w=FSettings.PAL; PAL=w?1:0; FCEUPPU_SetVideoSystem(w); SetSoundVariables(); } FCEUS FSettings; void FCEU_printf(char *format, ...) { char temp[2048]; va_list ap; va_start(ap,format); vsnprintf(temp,sizeof(temp),format,ap); FCEUD_Message(temp); va_end(ap); } void FCEU_PrintError(char *format, ...) { char temp[2048]; va_list ap; va_start(ap,format); vsnprintf(temp,sizeof(temp),format,ap); FCEUD_PrintError(temp); va_end(ap); } void FCEUI_SetRenderedLines(int ntscf, int ntscl, int palf, int pall) { FSettings.UsrFirstSLine[0]=ntscf; FSettings.UsrLastSLine[0]=ntscl; FSettings.UsrFirstSLine[1]=palf; FSettings.UsrLastSLine[1]=pall; if(PAL) { FSettings.FirstSLine=FSettings.UsrFirstSLine[1]; FSettings.LastSLine=FSettings.UsrLastSLine[1]; } else { FSettings.FirstSLine=FSettings.UsrFirstSLine[0]; FSettings.LastSLine=FSettings.UsrLastSLine[0]; } } void FCEUI_SetVidSystem(int a) { FSettings.PAL=a?1:0; if(GameInfo) { FCEU_ResetVidSys(); FCEU_ResetPalette(); FCEUD_VideoChanged(); } } int FCEUI_GetCurrentVidSystem(int *slstart, int *slend) { if(slstart) *slstart=FSettings.FirstSLine; if(slend) *slend=FSettings.LastSLine; return(PAL); } //Enable or disable Game Genie option. void FCEUI_SetGameGenie(bool a) { FSettings.GameGenie = a; } //this variable isn't used at all, snap is always name-based //void FCEUI_SetSnapName(bool a) //{ // FSettings.SnapName = a; //} int32 FCEUI_GetDesiredFPS(void) { if(PAL) return(838977920); // ~50.007 else return(1008307711); // ~60.1 } int FCEUI_EmulationPaused(void) { return (EmulationPaused&1); } int FCEUI_EmulationFrameStepped() { return (EmulationPaused&2); } void FCEUI_ClearEmulationFrameStepped() { EmulationPaused &=~2; } //mbg merge 7/18/06 added //ideally maybe we shouldnt be using this, but i need it for quick merging void FCEUI_SetEmulationPaused(int val) { EmulationPaused = val; } void FCEUI_ToggleEmulationPause(void) { EmulationPaused = (EmulationPaused&1)^1; DebuggerWasUpdated = false; } void FCEUI_FrameAdvanceEnd(void) { frameAdvanceRequested = false; } void FCEUI_FrameAdvance(void) { frameAdvanceRequested = true; frameAdvanceDelay = 0; } static int AutosaveCounter = 0; void UpdateAutosave(void) { if(!EnableAutosave || turbo) return; char * f; if(++AutosaveCounter >= AutosaveFrequency) { AutosaveCounter = 0; AutosaveIndex = (AutosaveIndex + 1) % AutosaveQty; f = strdup(FCEU_MakeFName(FCEUMKF_AUTOSTATE,AutosaveIndex,0).c_str()); FCEUSS_Save(f); AutoSS = true; //Flag that an auto-savestate was made free(f); AutosaveStatus[AutosaveIndex] = 1; } } void FCEUI_Autosave(void) { if(!EnableAutosave || !AutoSS || FCEUMOV_Mode(MOVIEMODE_TASEDIT)) return; if(AutosaveStatus[AutosaveIndex] == 1) { char * f; f = strdup(FCEU_MakeFName(FCEUMKF_AUTOSTATE,AutosaveIndex,0).c_str()); FCEUSS_Load(f); free(f); //Set pointer to previous available slot if(AutosaveStatus[(AutosaveIndex + AutosaveQty-1)%AutosaveQty] == 1) { AutosaveIndex = (AutosaveIndex + AutosaveQty-1)%AutosaveQty; } //Reset time to next Auto-save AutosaveCounter = 0; } } int FCEU_TextScanlineOffset(int y) { return FSettings.FirstSLine*256; } int FCEU_TextScanlineOffsetFromBottom(int y) { return (FSettings.LastSLine-y)*256; } bool FCEU_IsValidUI(EFCEUI ui) { switch(ui) { case FCEUI_OPENGAME: case FCEUI_CLOSEGAME: if(FCEUMOV_Mode(MOVIEMODE_TASEDIT)) return false; break; case FCEUI_RECORDMOVIE: case FCEUI_PLAYMOVIE: case FCEUI_QUICKSAVE: case FCEUI_QUICKLOAD: case FCEUI_SAVESTATE: case FCEUI_LOADSTATE: case FCEUI_NEXTSAVESTATE: case FCEUI_PREVIOUSSAVESTATE: case FCEUI_VIEWSLOTS: if(!GameInfo) return false; if(FCEUMOV_Mode(MOVIEMODE_TASEDIT)) return false; break; case FCEUI_STOPMOVIE: case FCEUI_PLAYFROMBEGINNING: return (FCEUMOV_Mode(MOVIEMODE_PLAY|MOVIEMODE_RECORD|MOVIEMODE_FINISHED)); case FCEUI_STOPAVI: return FCEUI_AviIsRecording(); case FCEUI_TASEDIT: if(!GameInfo) return false; break; case FCEUI_RESET: if(!GameInfo) return false; if(FCEUMOV_Mode(MOVIEMODE_FINISHED|MOVIEMODE_TASEDIT|MOVIEMODE_PLAY)) return false; break; case FCEUI_POWER: if(!GameInfo) return false; if(FCEUMOV_Mode(MOVIEMODE_RECORD)) return true; if(!FCEUMOV_Mode(MOVIEMODE_INACTIVE)) return false; break; } return true; } //--------------------- //experimental new mapper and ppu system follows class FCEUXCart { public: int mirroring; int chrPages, prgPages; uint32 chrSize, prgSize; char* CHR, *PRG; FCEUXCart() : CHR(0) , PRG(0) {} ~FCEUXCart() { if(CHR) delete[] CHR; if(PRG) delete[] PRG; } virtual void Power() { } protected: //void SetReadHandler(int32 start, int32 end, readfunc func) { }; FCEUXCart* cart = 0; //uint8 Read_ByteFromRom(uint32 A) { // if(A>=cart->prgSize) return 0xFF; // return cart->PRG[A]; //} // //uint8 Read_Unmapped(uint32 A) { // return 0xFF; //} class NROM : FCEUXCart { public: virtual void Power() { SetReadHandler(0x8000,0xFFFF,CartBR); setprg16(0x8000,0); setprg16(0xC000,~0); setchr8(0); vnapage[0] = NTARAM; vnapage[2] = NTARAM; vnapage[1] = NTARAM+0x400; vnapage[3] = NTARAM+0x400; PPUNTARAM=0xF; } }; void FCEUXGameInterface(GI command) { switch(command) { case GI_POWER: cart->Power(); } } bool FCEUXLoad(const char *name, FCEUFILE *fp) { //read ines header iNES_HEADER head; if(FCEU_fread(&head,1,16,fp)!=16) return false; //validate header if(memcmp(&head,"NES\x1a",4)) return 0; int mapper = (head.ROM_type>>4); mapper |= (head.ROM_type2&0xF0); //choose what kind of cart to use. cart = (FCEUXCart*)new NROM(); //fceu ines loading code uses 256 here when the romsize is 0. cart->prgPages = head.ROM_size; if(cart->prgPages == 0) { printf("FCEUX: received zero prgpages\n"); cart->prgPages = 256; } cart->chrPages = head.VROM_size; cart->mirroring = (head.ROM_type&1); if(head.ROM_type&8) cart->mirroring=2; //skip trainer bool hasTrainer = (head.ROM_type&4)!=0; if(hasTrainer) { FCEU_fseek(fp,512,SEEK_CUR); } //load data cart->prgSize = cart->prgPages*16*1024; cart->chrSize = cart->chrPages*8*1024; cart->PRG = new char[cart->prgSize]; cart->CHR = new char[cart->chrSize]; FCEU_fread(cart->PRG,1,cart->prgSize,fp); FCEU_fread(cart->CHR,1,cart->chrSize,fp); //setup the emulator GameInterface=FCEUXGameInterface; ResetCartMapping(); SetupCartPRGMapping(0,(uint8*)cart->PRG,cart->prgSize,0); SetupCartCHRMapping(0,(uint8*)cart->CHR,cart->chrSize,0); return true; } uint8 FCEU_ReadRomByte(uint32 i) { extern iNES_HEADER head; if(i < 16) return *((unsigned char *)&head+i); if(i < 16+PRGsize[0])return PRGptr[0][i-16]; if(i < 16+PRGsize[0]+CHRsize[0])return CHRptr[0][i-16-PRGsize[0]]; return 0; }
[ "Ced2911@1f2d827f-b39e-40f8-2521-43ba25b7e373" ]
[ [ [ 1, 1203 ] ] ]
11b1b3d818662efc8706369bac22464da7bbfd53
3532ae25961855b20635decd1481ed7def20c728
/app/CamDriver/cameranotconnectedblocker.h
1e381fbb68442bff45bd2bbdd7d65b6673fe4970
[]
no_license
mcharmas/Bazinga
121645a0c7bc8bd6a91322c2a7ecc56a5d3f71b7
1d35317422c913f28710b3182ee0e03822284ba3
refs/heads/master
2020-05-18T05:48:32.213937
2010-03-22T17:13:09
2010-03-22T17:13:09
577,323
1
0
null
null
null
null
UTF-8
C++
false
false
711
h
#ifndef CAMERANOTCONNECTEDBLOCKER_H #define CAMERANOTCONNECTEDBLOCKER_H #include <bconnectionblocker.h> class ConfigDialog; /*! \brief Obiekt blokujący jeżeli nie podpięta kamera */ class CameraNotConnectedBlocker : public BConnectionBlocker { public: /*! \brief To jest konstruktor, jeśli by ktoś nie wiedział @param cdialog wskaźnik na config dialog */ CameraNotConnectedBlocker(ConfigDialog * cdialog); /*! \brief Pozwala na połączenie jeśli podłączona jest kamera */ bool canConnect(); /*! \brief Zwraca w stringu informację o popełnionym przestępstwie */ QString toString(); private: ConfigDialog * cdialog; }; #endif // CAMERANOTCONNECTEDBLOCKER_H
[ "santamon@ffdda973-792b-4bce-9e62-2343ac01ffa1" ]
[ [ [ 1, 26 ] ] ]
75419431018f7d7055437e5d8f1d21aa1758e078
93088fe67401f51470ea3f9d55d12e0b40f04450
/jni/src/PlayState.cpp
f7b48aa03045805dbb354a621336697bbb253836
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
4nakin/canabalt-bluegin
f9967891418e07690c270075a1de0386b1d9a456
c68dc378d420e271dd7faa49b89e30c7c87c7233
refs/heads/master
2021-01-24T03:08:39.081279
2011-04-17T06:05:57
2011-04-17T06:05:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
21,032
cpp
#include "bluegin/resourcemanager.h" #include "flx/flxG.h" #include "PlayState.h" #include "Hall.h" #include "HUD.h" #include "Jet.h" #include "Sequence.h" #include "Shard.h" #include "Smoke.h" #include "Walker.h" using namespace ci; using namespace bluegin; using namespace flx; extern FlxGlobal FlxG; static const char* MusicRun = "run"; static const char* SndCrumble = "crumble"; static const char* ImgMidground1 = "midground1-trimmed"; static const char* ImgMidground2 = "midground2-trimmed"; static const char* ImgBackground = "background-trimmed"; static const char* ImgMidground1IPad = "midground1-trimmed.ipad"; static const char* ImgMidground2IPad = "midground2-trimmed.ipad"; static const char* ImgBackgroundIPad = "background-trimmed.ipad"; static const char* ImgMothership = "mothership-filled"; static const char* ImgDarkTower = "dark_tower-filled"; static const char* ImgGirder1 = "girder-tall"; static const char* ImgGameOver = "gameover"; static const char* ImgPauseButton = "pause"; static const char* ImgPaused = "paused"; static const char* ImgExitOn = "gameover_exit_on"; static const char* ImgExitOff = "gameover_exit_off"; #define GLASS_SHARDS #define SMOKE static int frameCount = 0; static float fpsElapsed = 0; // quake compensation const int QUAKE_OVERHANG = 10; void PlayState::doPause() { paused = true; fadedSprite->visible = true; pausedSprite->visible = true; pauseButton->visible = false; // FlxG.pauseMusic(); } void PlayState::setPaused(bool gamePaused) { if (gamePaused) { doPause(); //maybe do this on the next iteration? // FlxG.pauseFollow = true; // player.pause = true; } } void PlayState::create() { // XXX one-off initialization, can we put it outside of create??? // Order of initialization is significant (!) Hall::initialize(); Building::initialize(); Sequence::initialize(); bgColor = FlxU::color(0xffb0b0bf); FlxG.score = 0; ResourceManager& res = *(FlxG.resources); firstTimeThroughUpdateLoop = true; reallyJustPaused = false; pauseVisibility = true; int i; //Far BG 'Easter Egg' objects SpritePtr s = Sprite::create(0, 0, res.graphic(ImgMothership)); // s->enableBlend = false; s->x = 900; s->scrollFactor = Vec2f(0.015, 0); add(s); s = Sprite::create(0, 0, res.graphic(ImgDarkTower)); // s.enableBlend = false; s->x = 1700; s->scrollFactor = Vec2f(0.015,0); add(s); EmitterPtr e; #ifdef SMOKE vector<EmitterPtr> smoke; if (!FlxG.iPhone1G && !FlxG.iPodTouch1G) { int numSmokes = 8; // int numSmokes = 4; if (FlxG.iPad) numSmokes = 8; if (FlxG.iPhone3G) numSmokes = 1; for (i=0; i<numSmokes; ++i) { // int num_clouds = 15; int num_clouds = 25; if (FlxG.iPad) num_clouds = 25; if (FlxG.iPhone3G) num_clouds = 7; e = SmokeEmitterPtr(new SmokeEmitter(num_clouds)); for (vector<ObjectPtr>::iterator it = e->members.begin(); it != e->members.end(); ++it) { Sprite& s = static_cast<Sprite&>(**it); s.randomFrame(); s.scrollFactor = Vec2f(0.1, 0.05); add(*it); } e->delay = 0.6; e->minParticleSpeed = Vec2f(-3,-15); e->maxParticleSpeed = Vec2f(3,-15); if(FlxG.iPhone3G || FlxG.iPhone1G || FlxG.iPodTouch1G) { e->minRotation = 0; e->maxRotation = 0; } else { e->minRotation = -30; e->maxRotation = 30; } e->gravity = 0; e->particleDrag = Vec2f(0,0); add(e); smoke.push_back(e); } add(Walker::create(smoke)); if (!FlxG.iPhone3G) add(Walker::create(smoke)); } #endif BGPtr mg; SpritePtr bg; //for solid background rectangle... if (FlxG.iPad) mg = BGPtr(new BG(0, 0, res.graphic(ImgBackgroundIPad))); else mg = BGPtr(new BG(0, 0, res.graphic(ImgBackground))); mg->x = 0; mg->y = 30; mg->scrollFactor = Vec2f(0.15, 0.25); mg->y += 36; add(mg); background = mg; if (FlxG.iPad) mg = BGPtr(new BG(0, 0, res.graphic(ImgBackgroundIPad))); else mg = BGPtr(new BG(0, 0, res.graphic(ImgBackground))); mg->x = FlxG.width; mg->y = 30; mg->y += 36; mg->scrollFactor = Vec2f(0.15, 0.25); add(mg); //add below - since these are trimmed images bg = Sprite::create(0, 30+36+48); bg->x -= QUAKE_OVERHANG; if (FlxG.iPad) bg->createGraphic(FlxG.width + 2*QUAKE_OVERHANG, 156, FlxU::color(0x868696)); else bg->createGraphic(FlxG.width + 2*QUAKE_OVERHANG, 76+12, FlxU::color(0x868696)); bg->scrollFactor = Vec2f(0, 0.25); //don't scroll in the x direction at all! // bg->enableBlend = false; add(bg); backgroundRect = bg; if (FlxG.iPad) mg = BGPtr(new BG(0, 0, res.graphic(ImgMidground1))); else mg = BGPtr(new BG(0, 0, res.graphic(ImgMidground1))); mg->x = 0; mg->y = 104+8; mg->scrollFactor = Vec2f(0.4, 0.5); add(mg); midground = mg; if (FlxG.iPad) mg = BGPtr(new BG(0, 0, res.graphic(ImgMidground2IPad))); else mg = BGPtr(new BG(0, 0, res.graphic(ImgMidground2))); if (FlxG.iPad) mg->x = 512; else mg->x = 480; mg->y = 104+8; mg->scrollFactor = Vec2f(0.4, 0.5); add(mg); bg = Sprite::create(0, 104+8+97); bg->x -= QUAKE_OVERHANG; bg->createGraphic(FlxG.width+2*QUAKE_OVERHANG, 223, FlxU::color(0x646a7d)); bg->scrollFactor = Vec2f(0, 0.5); //don't scroll in the x direction at all! // bg->enableBlend = false; add(bg); // [self add:[Jet jet]]; add(JetPtr(new Jet(res.graphic("jet")))); focus = Sprite::create(); FlxG.follow(focus, 15); FlxG.followBounds(0, 0, INT_MAX, 480); FlxG.followAdjust(1.5, 0); player = PlayerPtr(new Player()); // player->play("run1"); //Infinite level sequence objects #ifdef GLASS_SHARDS // int numShards = 40; int numShards = 80; if (FlxG.iPad /*|| FlxG.retinaDisplay*/) numShards = 80; if (FlxG.iPhone1G) numShards = 20; #else int numShards = 0; #endif // shardsA = [ShardEmitter shardEmitterWithShardCount:numShards]; // shardsB = [ShardEmitter shardEmitterWithShardCount:numShards]; shardsA = EmitterPtr(new ShardEmitter(numShards)); shardsB = EmitterPtr(new ShardEmitter(numShards)); // XXX shard placeholders using gib emitters // shardsA = EmitterPtr(new Emitter()); // shardsA->createSprites(res.graphic("shard"), numShards, 0, false, 0.5f); // for (vector<ObjectPtr>::iterator it = shardsA->members.begin(); // it != shardsA->members.end(); ++it) { // Sprite& sp = static_cast<Sprite&>(**it); // sp.scale = Vec2f(1.25f - FlxU::random(), 1.25f - FlxU::random()); // sp.offset.set(0,-1); // } // shardsB = EmitterPtr(new Emitter()); // shardsB->createSprites(res.graphic("shard"), numShards, 0, false, 0.6f); // for (vector<ObjectPtr>::iterator it = shardsB->members.begin(); // it != shardsB->members.end(); ++it) { // Sprite& sp = static_cast<Sprite&>(**it); // sp.scale = Vec2f(1.25f - FlxU::random(), 1.25f - FlxU::random()); // sp.offset.set(0,-1); // } Sequence::setCurIndex(0); Sequence::setNextIndex((int)(FlxU::random()*3+3)); Sequence::setNextType(1); seqA = Sequence::get(player.get(), shardsA, shardsB); seqB = Sequence::get(player.get(), shardsA, shardsB); add(seqA); add(seqB); seqA->initSequence(seqB.get()); seqB->initSequence(seqA.get()); add(shardsA); add(shardsB); add(player); if (!(FlxG.iPhone3G || FlxG.iPhone1G || FlxG.iPodTouch1G)) { mg = BGPtr(new BG(0, 0, res.graphic(ImgGirder1))); mg->random = true; mg->x = 3000; mg->y = 0; mg->scrollFactor = Vec2f(3, 0); add(mg); } mg = BGPtr(new BG(0, 0, Graphic())); mg->createGraphic(32, FlxG.height, FlxU::color(0x35353d)); // mg->enableBlend = false; mg->random = true; mg->x = 3000; mg->y = 0; mg->scrollFactor = Vec2f(4, 0); add(mg); dist = HUDPtr(new HUD(Rect(FlxG.width-80-5,2+3,80,16))); dist->scrollFactor = Vec2f(0, 0); dist->setDistance(0); add(dist); //need this to be above everything else // pauseButton = [FlxSprite spriteWithGraphic:ImgPauseButton]; // pauseButton.x = 8; // pauseButton.y = 6; // pauseButton.scrollFactor = CGPointMake(0, 0); // if (pauseVisibility == false) // pauseButton.visible = false; // [self add:pauseButton]; // // fadedSprite = [FlxSprite spriteWithX:0 y:0 graphic:nil]; // [fadedSprite createGraphicWithWidth:FlxG.width height:FlxG.height color:0xffffff]; // fadedSprite.scrollFactor = CGPointMake(0, 0); // fadedSprite.alpha = 0.5; // fadedSprite.visible = false; // [self add:fadedSprite]; // pausedSprite = [FlxSprite spriteWithGraphic:ImgPaused]; // pausedSprite.x = ([FlxG width]-pausedSprite.width)/2; // pausedSprite.y = ([FlxG height]-pausedSprite.height)/2; // pausedSprite.scrollFactor = CGPointMake(0, 0); // pausedSprite.visible = false; // [self add:pausedSprite]; paused = false; if (FlxG.iPad) FlxG.quake.start(0.007, 3.1); else FlxG.quake.start(0.0065, 2.5); gameover = 0; bluegin_music_volume(0.8f, 0.8f); FlxG.playMusic(res.sound(MusicRun)); FlxG.play(res.sound(SndCrumble)); } void PlayState::update() { ResourceManager& res = *(FlxG.resources); fpsElapsed += FlxG.elapsed; frameCount++; if (fpsElapsed > 1.0f) { Log("FPS: %d", frameCount); fpsElapsed = 0; frameCount = 0; } if (reallyJustPaused) { doPause(); } reallyJustPaused = false; //check for pause touch // if (gameover == 0) { // if (!paused) { // if (FlxG.touches.touchesBegan && // CGRectContainsPoint(pauseRect, FlxG.touches.screenTouchBeganPoint) && // !firstTimeThroughUpdateLoop) { // justPaused = true; // reallyJustPaused = true; // FlxG.pauseFollow = true; // player.pause = true; // } // } else { // if (FlxG.touches.touchesEnded) { // if (justPaused) { // justPaused = false; // } else { // player.pause = false; // paused = false; // fadedSprite.visible = false; // pausedSprite.visible = false; // if (pauseVisibility == true) // pauseButton.visible = true; // //start following again // FlxG.pauseFollow = false; // [FlxG unpauseMusic]; // } // } // } // } // if (pressedExit) { // //still touching? // //released in bounds? // if (FlxG.touches.touchesEnded) { // //switch state // FlxG.state = [[[MenuState alloc] init] autorelease]; // return; // } // } // pressedExit = false; if (exitOn && exitOff) { exitOff->visible = true; exitOn->visible = false; } if (gameover > 0) gameover += FlxG.elapsed; if (gameover > 0.35 && FlxG.touch.pressed()) { bool switchState = true; // if (exitOn && exitOff) { // if (CGRectContainsPoint(CGRectInset(CGRectMake(exitOff.x, exitOff.y, exitOff.width, exitOff.height), -20, -20), FlxG.touches.screenTouchPoint)) { // //pressing button // exitOff.visible = false; // exitOn.visible = true; // pressedExit = true; // switchState = false; // } // } if (switchState) { FlxG.stopMusic(); FlxG.setState(StatePtr(new PlayState())); return; } } focus->x = player->x + FlxG.width*0.5; focus->y = player->y + FlxG.height*0.18 + (player->onFloor ? 0 : 20); bool wasDead = player->dead; //only do this if we aren't paused... if (!paused) State::update(); FlxU::collide(*player, *(seqA->blocks)); FlxU::collide(*player, *(seqB->blocks)); FlxU::collide(*(seqA->blocks), *shardsA); FlxU::collide(*(seqA->blocks), *shardsB); FlxU::collide(*(seqB->blocks), *shardsA); FlxU::collide(*(seqB->blocks), *shardsB); // if(FlxG.iPad) // { // [FlxU alternateCollideWithParam1:seqA.blocks param2:shardsA]; // [FlxU alternateCollideWithParam1:seqA.blocks param2:shardsB]; // [FlxU alternateCollideWithParam1:seqB.blocks param2:shardsA]; // [FlxU alternateCollideWithParam1:seqB.blocks param2:shardsB]; // } // else // { // Sequence* sq = (seqA.x < seqB.x)?seqA:seqB; // FlxEmitter* sh; // if(shardsA.exists && shardsB.exists) // sh = (shardsA.x > shardsB.x)?shardsA:shardsB; // else if(shardsB.exists) // sh = shardsB; // else // sh = shardsA; // [FlxU alternateCollideWithParam1:sq.blocks param2:sh]; // } dist->setDistance((int)(player->x/10)); if (player->dead && !wasDead) { // //hide pause button // // pausedSprite.visible = false; // // fadedSprite.visible = false; // // pauseButton.visible = false; distance = player->x/10; //Write player's epitaph based on special events and/or the environmental context if(player->epitaph.compare("bomb") == 0) player->epitaph = "\nturning into a fine mist."; else if(player->epitaph.compare("hit") == 0) { if (distance < 105) { player->epitaph = "just barely\nstumbling out of the first hallway."; } else { //ran into the front of the sequence in question Sequence& s = (seqA->x < seqB->x) ? *seqA : *seqB; // int type = s.getType(); int type = s.type; switch(type) { case 1: //hallway player->epitaph = "\nmissing another window."; break; case 2: //collapse player->epitaph = "\nknocking a building down."; break; case 4: //crane player->epitaph = "somehow\nhitting the edge of a crane."; break; case 5: //billboard player->epitaph = "somehow\nhitting the edge of a billboard."; break; case 6: //leg player->epitaph = "colliding\nwith some enormous obstacle."; break; default: //basic wallcase player->epitaph = "hitting\na wall and tumbling to your death."; break; } } } else { //fell off the screen int preType = seqA->getLastType(); //These are static, player-dependent values int type = seqA->getThisType(); if(type > 0) { switch(type) { case 1: //hallway player->epitaph = "completely\n missing the entire hallway."; break; case 4: //crane player->epitaph = "\nmissing a crane completely."; break; case 5: //billboard player->epitaph = "not\nquite reaching a billboard."; break; case 6: //leg player->epitaph = "landing\nwhere a building used to be."; break; default: //basic fall case player->epitaph = "\nfalling to your death."; break; } } else { switch(preType) { case 1: //hallway player->epitaph = "\nfalling out of a hallway."; break; case 2: //collapse player->epitaph = "riding\na falling building all the way down."; break; case 3: //bomb player->epitaph = "dodging\n a bomb only to miss the next roof."; break; case 4: //crane player->epitaph = "\nfalling off a crane."; break; case 5: //billboard player->epitaph = "\nstumbling off the edge of a billboard."; break; case 6: //leg player->epitaph = "jumping\nclear over...something."; break; default: //basic fall case player->epitaph = "\nfalling to your death."; break; } } } //End epitaph decision tree // //show exit button // exitOn = [FlxSprite spriteWithGraphic:ImgExitOn]; // exitOff = [FlxSprite spriteWithGraphic:ImgExitOff]; // exitOn.x = FlxG.width-62; // exitOn.y = 0; // exitOn.scrollFactor = CGPointMake(0, 0); // exitOff.x = exitOn.x; // exitOff.y = exitOn.y; // exitOff.scrollFactor = exitOn.scrollFactor; // [self add:exitOn]; // [self add:exitOff]; // exitOff.visible = true; // exitOn.visible = false; gameover = 0.01; int h = 88; SpritePtr bigGray = Sprite::create(); bigGray->createGraphic(FlxG.width+2*QUAKE_OVERHANG, 64, FlxU::color(0xff35353d)); bigGray->x = 0-QUAKE_OVERHANG; bigGray->y = h+35; bigGray->width = FlxG.width+2*QUAKE_OVERHANG; bigGray->height = 64; bigGray->scrollFactor = Vec2f(0, 0); add(bigGray); SpritePtr littleWhite = Sprite::create(); littleWhite->createGraphic(FlxG.width+2*QUAKE_OVERHANG, 2, FlxU::color(0xffffffff)); littleWhite->x = 0-QUAKE_OVERHANG; littleWhite->y = h+35+64; littleWhite->width = FlxG.width+2*QUAKE_OVERHANG; littleWhite->height = 2; littleWhite->scrollFactor = Vec2f(0, 0); add(littleWhite); SpritePtr s = Sprite::create(); s->createGraphic(FlxG.width+2*QUAKE_OVERHANG, 30+QUAKE_OVERHANG, FlxU::color(0xff35353d)); s->x = 0 - QUAKE_OVERHANG; s->y = FlxG.height-30; s->width = FlxG.width+2*QUAKE_OVERHANG; s->height = 30 + QUAKE_OVERHANG; s->scrollFactor = Vec2f(0, 0); add(s); SpritePtr gameOver = Sprite::create(0, 0, res.graphic(ImgGameOver)); gameOver->x = (FlxG.width-390)/2.0; gameOver->y = h; gameOver->scrollFactor = Vec2f(0, 0); add(gameOver); const float margin = 30.0f; TextPtr epitaphText = Text::create(0+margin, h+50+5, FlxG.width-2*margin, epitaph); epitaphText->setAlignment(ALIGN_CENTER); epitaphText->setColor(FlxU::color(0xffffffff)); epitaphText->scrollFactor = Vec2f(0, 0); epitaphText->setSize(18.0f); epitaphText->printf("You ran %dm before %s", distance, player->epitaph.c_str()); add(epitaphText); TextPtr t = Text::create(0, FlxG.height-27+4, FlxG.width-3, string("Tap to retry your daring escape")); t->setSize(18.0f); t->setAlignment(ALIGN_RIGHT); t->setColor(FlxU::color(0xffffffff)); t->scrollFactor = Vec2f(0,0); add(t); dist->visible = false; } if (firstTimeThroughUpdateLoop) { //don't set to false unless we aren't touching the screen // if (FlxG.touches.touching == false) // firstTimeThroughUpdateLoop = false; } }
[ [ [ 1, 630 ] ] ]
1cb5aff461d7be5cef3e7f72a5d36db3c600d885
3c22e8879c8060942ad1ba4a28835d7963e10bce
/trunk/scintilla/win32/PlatWin.cxx
8217cabe75e4b0ab79138c070ed37af135b662a2
[ "LicenseRef-scancode-scintilla" ]
permissive
svn2github/NotepadPlusPlus
b17f159f9fe6d8d650969b0555824d259d775d45
35b5304f02aaacfc156269c4b894159de53222ef
refs/heads/master
2021-01-22T09:05:19.267064
2011-01-31T01:46:36
2011-01-31T01:46:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
66,693
cxx
// Scintilla source code edit control /** @file PlatWin.cxx ** Implementation of platform facilities on Windows. **/ // Copyright 1998-2003 by Neil Hodgson <[email protected]> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <time.h> #undef _WIN32_WINNT #define _WIN32_WINNT 0x0500 #include <windows.h> #include <commctrl.h> #include <richedit.h> #include <windowsx.h> #include "Platform.h" #include "PlatformRes.h" #include "UniConversion.h" #include "XPM.h" #include "FontQuality.h" // We want to use multi monitor functions, but via LoadLibrary etc // Luckily microsoft has done the heavy lifting for us, so we'll just use their stub functions! #if (defined(_MSC_VER) && (MSC_VER > 1200)) || defined(__BORLANDC__) #define COMPILE_MULTIMON_STUBS #include "MultiMon.h" #endif #ifndef IDC_HAND #define IDC_HAND MAKEINTRESOURCE(32649) #endif // Take care of 32/64 bit pointers #ifdef GetWindowLongPtr static void *PointerFromWindow(HWND hWnd) { return reinterpret_cast<void *>(::GetWindowLongPtr(hWnd, 0)); } static void SetWindowPointer(HWND hWnd, void *ptr) { ::SetWindowLongPtr(hWnd, 0, reinterpret_cast<LONG_PTR>(ptr)); } #else static void *PointerFromWindow(HWND hWnd) { return reinterpret_cast<void *>(::GetWindowLong(hWnd, 0)); } static void SetWindowPointer(HWND hWnd, void *ptr) { ::SetWindowLong(hWnd, 0, reinterpret_cast<LONG>(ptr)); } #ifndef GWLP_USERDATA #define GWLP_USERDATA GWL_USERDATA #endif #ifndef GWLP_WNDPROC #define GWLP_WNDPROC GWL_WNDPROC #endif #ifndef LONG_PTR #define LONG_PTR LONG #endif static LONG_PTR SetWindowLongPtr(HWND hWnd, int nIndex, LONG_PTR dwNewLong) { return ::SetWindowLong(hWnd, nIndex, dwNewLong); } static LONG_PTR GetWindowLongPtr(HWND hWnd, int nIndex) { return ::GetWindowLong(hWnd, nIndex); } #endif typedef BOOL (WINAPI *AlphaBlendSig)(HDC, int, int, int, int, HDC, int, int, int, int, BLENDFUNCTION); static CRITICAL_SECTION crPlatformLock; static HINSTANCE hinstPlatformRes = 0; static bool onNT = false; static HMODULE hDLLImage = 0; static AlphaBlendSig AlphaBlendFn = 0; bool IsNT() { return onNT; } #ifdef SCI_NAMESPACE using namespace Scintilla; #endif Point Point::FromLong(long lpoint) { return Point(static_cast<short>(LOWORD(lpoint)), static_cast<short>(HIWORD(lpoint))); } static RECT RectFromPRectangle(PRectangle prc) { RECT rc = {prc.left, prc.top, prc.right, prc.bottom}; return rc; } Palette::Palette() { used = 0; allowRealization = false; hpal = 0; size = 100; entries = new ColourPair[size]; } Palette::~Palette() { Release(); delete []entries; entries = 0; } void Palette::Release() { used = 0; if (hpal) ::DeleteObject(hpal); hpal = 0; delete []entries; size = 100; entries = new ColourPair[size]; } /** * This method either adds a colour to the list of wanted colours (want==true) * or retrieves the allocated colour back to the ColourPair. * This is one method to make it easier to keep the code for wanting and retrieving in sync. */ void Palette::WantFind(ColourPair &cp, bool want) { if (want) { for (int i=0; i < used; i++) { if (entries[i].desired == cp.desired) return; } if (used >= size) { int sizeNew = size * 2; ColourPair *entriesNew = new ColourPair[sizeNew]; for (int j=0; j<size; j++) { entriesNew[j] = entries[j]; } delete []entries; entries = entriesNew; size = sizeNew; } entries[used].desired = cp.desired; entries[used].allocated.Set(cp.desired.AsLong()); used++; } else { for (int i=0; i < used; i++) { if (entries[i].desired == cp.desired) { cp.allocated = entries[i].allocated; return; } } cp.allocated.Set(cp.desired.AsLong()); } } void Palette::Allocate(Window &) { if (hpal) ::DeleteObject(hpal); hpal = 0; if (allowRealization) { char *pal = new char[sizeof(LOGPALETTE) + (used-1) * sizeof(PALETTEENTRY)]; LOGPALETTE *logpal = reinterpret_cast<LOGPALETTE *>(pal); logpal->palVersion = 0x300; logpal->palNumEntries = static_cast<WORD>(used); for (int iPal=0;iPal<used;iPal++) { ColourDesired desired = entries[iPal].desired; logpal->palPalEntry[iPal].peRed = static_cast<BYTE>(desired.GetRed()); logpal->palPalEntry[iPal].peGreen = static_cast<BYTE>(desired.GetGreen()); logpal->palPalEntry[iPal].peBlue = static_cast<BYTE>(desired.GetBlue()); entries[iPal].allocated.Set( PALETTERGB(desired.GetRed(), desired.GetGreen(), desired.GetBlue())); // PC_NOCOLLAPSE means exact colours allocated even when in background this means other windows // are less likely to get their colours and also flashes more when switching windows logpal->palPalEntry[iPal].peFlags = PC_NOCOLLAPSE; // 0 allows approximate colours when in background, yielding moe colours to other windows //logpal->palPalEntry[iPal].peFlags = 0; } hpal = ::CreatePalette(logpal); delete []pal; } } #ifndef CLEARTYPE_QUALITY #define CLEARTYPE_QUALITY 5 #endif static BYTE Win32MapFontQuality(int extraFontFlag) { switch (extraFontFlag & SC_EFF_QUALITY_MASK) { case SC_EFF_QUALITY_NON_ANTIALIASED: return NONANTIALIASED_QUALITY; case SC_EFF_QUALITY_ANTIALIASED: return ANTIALIASED_QUALITY; case SC_EFF_QUALITY_LCD_OPTIMIZED: return CLEARTYPE_QUALITY; default: return SC_EFF_QUALITY_DEFAULT; } } static void SetLogFont(LOGFONTA &lf, const char *faceName, int characterSet, int size, bool bold, bool italic, int extraFontFlag) { memset(&lf, 0, sizeof(lf)); // The negative is to allow for leading lf.lfHeight = -(abs(size)); lf.lfWeight = bold ? FW_BOLD : FW_NORMAL; lf.lfItalic = static_cast<BYTE>(italic ? 1 : 0); lf.lfCharSet = static_cast<BYTE>(characterSet); lf.lfQuality = Win32MapFontQuality(extraFontFlag); strncpy(lf.lfFaceName, faceName, sizeof(lf.lfFaceName)); } /** * Create a hash from the parameters for a font to allow easy checking for identity. * If one font is the same as another, its hash will be the same, but if the hash is the * same then they may still be different. */ static int HashFont(const char *faceName, int characterSet, int size, bool bold, bool italic, int extraFontFlag) { return size ^ (characterSet << 10) ^ ((extraFontFlag & SC_EFF_QUALITY_MASK) << 9) ^ (bold ? 0x10000000 : 0) ^ (italic ? 0x20000000 : 0) ^ faceName[0]; } class FontCached : Font { FontCached *next; int usage; LOGFONTA lf; int hash; FontCached(const char *faceName_, int characterSet_, int size_, bool bold_, bool italic_, int extraFontFlag_); ~FontCached() {} bool SameAs(const char *faceName_, int characterSet_, int size_, bool bold_, bool italic_, int extraFontFlag_); virtual void Release(); static FontCached *first; public: static FontID FindOrCreate(const char *faceName_, int characterSet_, int size_, bool bold_, bool italic_, int extraFontFlag_); static void ReleaseId(FontID fid_); }; FontCached *FontCached::first = 0; FontCached::FontCached(const char *faceName_, int characterSet_, int size_, bool bold_, bool italic_, int extraFontFlag_) : next(0), usage(0), hash(0) { SetLogFont(lf, faceName_, characterSet_, size_, bold_, italic_, extraFontFlag_); hash = HashFont(faceName_, characterSet_, size_, bold_, italic_, extraFontFlag_); fid = ::CreateFontIndirectA(&lf); usage = 1; } bool FontCached::SameAs(const char *faceName_, int characterSet_, int size_, bool bold_, bool italic_, int extraFontFlag_) { return (lf.lfHeight == -(abs(size_))) && (lf.lfWeight == (bold_ ? FW_BOLD : FW_NORMAL)) && (lf.lfItalic == static_cast<BYTE>(italic_ ? 1 : 0)) && (lf.lfCharSet == characterSet_) && (lf.lfQuality == Win32MapFontQuality(extraFontFlag_)) && 0 == strcmp(lf.lfFaceName,faceName_); } void FontCached::Release() { if (fid) ::DeleteObject(fid); fid = 0; } FontID FontCached::FindOrCreate(const char *faceName_, int characterSet_, int size_, bool bold_, bool italic_, int extraFontFlag_) { FontID ret = 0; ::EnterCriticalSection(&crPlatformLock); int hashFind = HashFont(faceName_, characterSet_, size_, bold_, italic_, extraFontFlag_); for (FontCached *cur=first; cur; cur=cur->next) { if ((cur->hash == hashFind) && cur->SameAs(faceName_, characterSet_, size_, bold_, italic_, extraFontFlag_)) { cur->usage++; ret = cur->fid; } } if (ret == 0) { FontCached *fc = new FontCached(faceName_, characterSet_, size_, bold_, italic_, extraFontFlag_); if (fc) { fc->next = first; first = fc; ret = fc->fid; } } ::LeaveCriticalSection(&crPlatformLock); return ret; } void FontCached::ReleaseId(FontID fid_) { ::EnterCriticalSection(&crPlatformLock); FontCached **pcur=&first; for (FontCached *cur=first; cur; cur=cur->next) { if (cur->fid == fid_) { cur->usage--; if (cur->usage == 0) { *pcur = cur->next; cur->Release(); cur->next = 0; delete cur; } break; } pcur=&cur->next; } ::LeaveCriticalSection(&crPlatformLock); } Font::Font() { fid = 0; } Font::~Font() { } #define FONTS_CACHED void Font::Create(const char *faceName, int characterSet, int size, bool bold, bool italic, int extraFontFlag) { Release(); #ifndef FONTS_CACHED LOGFONT lf; SetLogFont(lf, faceName, characterSet, size, bold, italic, extraFontFlag); fid = ::CreateFontIndirect(&lf); #else if (faceName) fid = FontCached::FindOrCreate(faceName, characterSet, size, bold, italic, extraFontFlag); #endif } void Font::Release() { #ifndef FONTS_CACHED if (fid) ::DeleteObject(fid); #else if (fid) FontCached::ReleaseId(fid); #endif fid = 0; } #ifdef SCI_NAMESPACE namespace Scintilla { #endif class SurfaceImpl : public Surface { bool unicodeMode; HDC hdc; bool hdcOwned; HPEN pen; HPEN penOld; HBRUSH brush; HBRUSH brushOld; HFONT font; HFONT fontOld; HBITMAP bitmap; HBITMAP bitmapOld; HPALETTE paletteOld; int maxWidthMeasure; int maxLenText; int codePage; // If 9x OS and current code page is same as ANSI code page. bool win9xACPSame; void BrushColor(ColourAllocated back); void SetFont(Font &font_); // Private so SurfaceImpl objects can not be copied SurfaceImpl(const SurfaceImpl &); SurfaceImpl &operator=(const SurfaceImpl &); public: SurfaceImpl(); virtual ~SurfaceImpl(); void Init(WindowID wid); void Init(SurfaceID sid, WindowID wid); void InitPixMap(int width, int height, Surface *surface_, WindowID wid); void Release(); bool Initialised(); void PenColour(ColourAllocated fore); int LogPixelsY(); int DeviceHeightFont(int points); void MoveTo(int x_, int y_); void LineTo(int x_, int y_); void Polygon(Point *pts, int npts, ColourAllocated fore, ColourAllocated back); void RectangleDraw(PRectangle rc, ColourAllocated fore, ColourAllocated back); void FillRectangle(PRectangle rc, ColourAllocated back); void FillRectangle(PRectangle rc, Surface &surfacePattern); void RoundedRectangle(PRectangle rc, ColourAllocated fore, ColourAllocated back); void AlphaRectangle(PRectangle rc, int cornerSize, ColourAllocated fill, int alphaFill, ColourAllocated outline, int alphaOutline, int flags); void Ellipse(PRectangle rc, ColourAllocated fore, ColourAllocated back); void Copy(PRectangle rc, Point from, Surface &surfaceSource); void DrawTextCommon(PRectangle rc, Font &font_, int ybase, const char *s, int len, UINT fuOptions); void DrawTextNoClip(PRectangle rc, Font &font_, int ybase, const char *s, int len, ColourAllocated fore, ColourAllocated back); void DrawTextClipped(PRectangle rc, Font &font_, int ybase, const char *s, int len, ColourAllocated fore, ColourAllocated back); void DrawTextTransparent(PRectangle rc, Font &font_, int ybase, const char *s, int len, ColourAllocated fore); void MeasureWidths(Font &font_, const char *s, int len, int *positions); int WidthText(Font &font_, const char *s, int len); int WidthChar(Font &font_, char ch); int Ascent(Font &font_); int Descent(Font &font_); int InternalLeading(Font &font_); int ExternalLeading(Font &font_); int Height(Font &font_); int AverageCharWidth(Font &font_); int SetPalette(Palette *pal, bool inBackGround); void SetClip(PRectangle rc); void FlushCachedState(); void SetUnicodeMode(bool unicodeMode_); void SetDBCSMode(int codePage_); }; #ifdef SCI_NAMESPACE } //namespace Scintilla #endif SurfaceImpl::SurfaceImpl() : unicodeMode(false), hdc(0), hdcOwned(false), pen(0), penOld(0), brush(0), brushOld(0), font(0), fontOld(0), bitmap(0), bitmapOld(0), paletteOld(0) { // Windows 9x has only a 16 bit coordinate system so break after 30000 pixels maxWidthMeasure = IsNT() ? 1000000 : 30000; // There appears to be a 16 bit string length limit in GDI on NT and a limit of // 8192 characters on Windows 95. maxLenText = IsNT() ? 65535 : 8192; codePage = 0; win9xACPSame = false; } SurfaceImpl::~SurfaceImpl() { Release(); } void SurfaceImpl::Release() { if (penOld) { ::SelectObject(reinterpret_cast<HDC>(hdc), penOld); ::DeleteObject(pen); penOld = 0; } pen = 0; if (brushOld) { ::SelectObject(reinterpret_cast<HDC>(hdc), brushOld); ::DeleteObject(brush); brushOld = 0; } brush = 0; if (fontOld) { // Fonts are not deleted as they are owned by a Font object ::SelectObject(reinterpret_cast<HDC>(hdc), fontOld); fontOld = 0; } font = 0; if (bitmapOld) { ::SelectObject(reinterpret_cast<HDC>(hdc), bitmapOld); ::DeleteObject(bitmap); bitmapOld = 0; } bitmap = 0; if (paletteOld) { // Palettes are not deleted as they are owned by a Palette object ::SelectPalette(reinterpret_cast<HDC>(hdc), reinterpret_cast<HPALETTE>(paletteOld), TRUE); paletteOld = 0; } if (hdcOwned) { ::DeleteDC(reinterpret_cast<HDC>(hdc)); hdc = 0; hdcOwned = false; } } bool SurfaceImpl::Initialised() { return hdc != 0; } void SurfaceImpl::Init(WindowID) { Release(); hdc = ::CreateCompatibleDC(NULL); hdcOwned = true; ::SetTextAlign(reinterpret_cast<HDC>(hdc), TA_BASELINE); } void SurfaceImpl::Init(SurfaceID sid, WindowID) { Release(); hdc = reinterpret_cast<HDC>(sid); ::SetTextAlign(reinterpret_cast<HDC>(hdc), TA_BASELINE); } void SurfaceImpl::InitPixMap(int width, int height, Surface *surface_, WindowID) { Release(); hdc = ::CreateCompatibleDC(static_cast<SurfaceImpl *>(surface_)->hdc); hdcOwned = true; bitmap = ::CreateCompatibleBitmap(static_cast<SurfaceImpl *>(surface_)->hdc, width, height); bitmapOld = static_cast<HBITMAP>(::SelectObject(hdc, bitmap)); ::SetTextAlign(reinterpret_cast<HDC>(hdc), TA_BASELINE); } void SurfaceImpl::PenColour(ColourAllocated fore) { if (pen) { ::SelectObject(hdc, penOld); ::DeleteObject(pen); pen = 0; penOld = 0; } pen = ::CreatePen(0,1,fore.AsLong()); penOld = static_cast<HPEN>(::SelectObject(reinterpret_cast<HDC>(hdc), pen)); } void SurfaceImpl::BrushColor(ColourAllocated back) { if (brush) { ::SelectObject(hdc, brushOld); ::DeleteObject(brush); brush = 0; brushOld = 0; } // Only ever want pure, non-dithered brushes ColourAllocated colourNearest = ::GetNearestColor(hdc, back.AsLong()); brush = ::CreateSolidBrush(colourNearest.AsLong()); brushOld = static_cast<HBRUSH>(::SelectObject(hdc, brush)); } void SurfaceImpl::SetFont(Font &font_) { if (font_.GetID() != font) { if (fontOld) { ::SelectObject(hdc, font_.GetID()); } else { fontOld = static_cast<HFONT>(::SelectObject(hdc, font_.GetID())); } font = reinterpret_cast<HFONT>(font_.GetID()); } } int SurfaceImpl::LogPixelsY() { return ::GetDeviceCaps(hdc, LOGPIXELSY); } int SurfaceImpl::DeviceHeightFont(int points) { return ::MulDiv(points, LogPixelsY(), 72); } void SurfaceImpl::MoveTo(int x_, int y_) { ::MoveToEx(hdc, x_, y_, 0); } void SurfaceImpl::LineTo(int x_, int y_) { ::LineTo(hdc, x_, y_); } void SurfaceImpl::Polygon(Point *pts, int npts, ColourAllocated fore, ColourAllocated back) { PenColour(fore); BrushColor(back); ::Polygon(hdc, reinterpret_cast<POINT *>(pts), npts); } void SurfaceImpl::RectangleDraw(PRectangle rc, ColourAllocated fore, ColourAllocated back) { PenColour(fore); BrushColor(back); ::Rectangle(hdc, rc.left, rc.top, rc.right, rc.bottom); } void SurfaceImpl::FillRectangle(PRectangle rc, ColourAllocated back) { // Using ExtTextOut rather than a FillRect ensures that no dithering occurs. // There is no need to allocate a brush either. RECT rcw = RectFromPRectangle(rc); ::SetBkColor(hdc, back.AsLong()); ::ExtTextOut(hdc, rc.left, rc.top, ETO_OPAQUE, &rcw, TEXT(""), 0, NULL); } void SurfaceImpl::FillRectangle(PRectangle rc, Surface &surfacePattern) { HBRUSH br; if (static_cast<SurfaceImpl &>(surfacePattern).bitmap) br = ::CreatePatternBrush(static_cast<SurfaceImpl &>(surfacePattern).bitmap); else // Something is wrong so display in red br = ::CreateSolidBrush(RGB(0xff, 0, 0)); RECT rcw = RectFromPRectangle(rc); ::FillRect(hdc, &rcw, br); ::DeleteObject(br); } void SurfaceImpl::RoundedRectangle(PRectangle rc, ColourAllocated fore, ColourAllocated back) { PenColour(fore); BrushColor(back); ::RoundRect(hdc, rc.left + 1, rc.top, rc.right - 1, rc.bottom, 8, 8); } // Plot a point into a DWORD buffer symetrically to all 4 qudrants static void AllFour(DWORD *pixels, int width, int height, int x, int y, DWORD val) { pixels[y*width+x] = val; pixels[y*width+width-1-x] = val; pixels[(height-1-y)*width+x] = val; pixels[(height-1-y)*width+width-1-x] = val; } #ifndef AC_SRC_OVER #define AC_SRC_OVER 0x00 #endif #ifndef AC_SRC_ALPHA #define AC_SRC_ALPHA 0x01 #endif static DWORD dwordFromBGRA(byte b, byte g, byte r, byte a) { union { byte pixVal[4]; DWORD val; } converter; converter.pixVal[0] = b; converter.pixVal[1] = g; converter.pixVal[2] = r; converter.pixVal[3] = a; return converter.val; } void SurfaceImpl::AlphaRectangle(PRectangle rc, int cornerSize, ColourAllocated fill, int alphaFill, ColourAllocated outline, int alphaOutline, int /* flags*/ ) { if (AlphaBlendFn && rc.Width() > 0) { HDC hMemDC = ::CreateCompatibleDC(reinterpret_cast<HDC>(hdc)); int width = rc.Width(); int height = rc.Height(); // Ensure not distorted too much by corners when small cornerSize = Platform::Minimum(cornerSize, (Platform::Minimum(width, height) / 2) - 2); BITMAPINFO bpih = {sizeof(BITMAPINFOHEADER), width, height, 1, 32, BI_RGB, 0, 0, 0, 0, 0}; void *image = 0; HBITMAP hbmMem = CreateDIBSection(reinterpret_cast<HDC>(hMemDC), &bpih, DIB_RGB_COLORS, &image, NULL, 0); HBITMAP hbmOld = SelectBitmap(hMemDC, hbmMem); DWORD valEmpty = dwordFromBGRA(0,0,0,0); DWORD valFill = dwordFromBGRA( static_cast<byte>(GetBValue(fill.AsLong()) * alphaFill / 255), static_cast<byte>(GetGValue(fill.AsLong()) * alphaFill / 255), static_cast<byte>(GetRValue(fill.AsLong()) * alphaFill / 255), static_cast<byte>(alphaFill)); DWORD valOutline = dwordFromBGRA( static_cast<byte>(GetBValue(outline.AsLong()) * alphaOutline / 255), static_cast<byte>(GetGValue(outline.AsLong()) * alphaOutline / 255), static_cast<byte>(GetRValue(outline.AsLong()) * alphaOutline / 255), static_cast<byte>(alphaOutline)); DWORD *pixels = reinterpret_cast<DWORD *>(image); for (int y=0; y<height; y++) { for (int x=0; x<width; x++) { if ((x==0) || (x==width-1) || (y == 0) || (y == height-1)) { pixels[y*width+x] = valOutline; } else { pixels[y*width+x] = valFill; } } } for (int c=0;c<cornerSize; c++) { for (int x=0;x<c+1; x++) { AllFour(pixels, width, height, x, c-x, valEmpty); } } for (int x=1;x<cornerSize; x++) { AllFour(pixels, width, height, x, cornerSize-x, valOutline); } BLENDFUNCTION merge = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA }; AlphaBlendFn(reinterpret_cast<HDC>(hdc), rc.left, rc.top, width, height, hMemDC, 0, 0, width, height, merge); SelectBitmap(hMemDC, hbmOld); ::DeleteObject(hbmMem); ::DeleteDC(hMemDC); } else { BrushColor(outline); RECT rcw = RectFromPRectangle(rc); FrameRect(hdc, &rcw, brush); } } void SurfaceImpl::Ellipse(PRectangle rc, ColourAllocated fore, ColourAllocated back) { PenColour(fore); BrushColor(back); ::Ellipse(hdc, rc.left, rc.top, rc.right, rc.bottom); } void SurfaceImpl::Copy(PRectangle rc, Point from, Surface &surfaceSource) { ::BitBlt(hdc, rc.left, rc.top, rc.Width(), rc.Height(), static_cast<SurfaceImpl &>(surfaceSource).hdc, from.x, from.y, SRCCOPY); } // Buffer to hold strings and string position arrays without always allocating on heap. // May sometimes have string too long to allocate on stack. So use a fixed stack-allocated buffer // when less than safe size otherwise allocate on heap and free automatically. template<typename T, int lengthStandard> class VarBuffer { T bufferStandard[lengthStandard]; public: T *buffer; VarBuffer(size_t length) : buffer(0) { if (length > lengthStandard) { buffer = new T[length]; } else { buffer = bufferStandard; } } ~VarBuffer() { if (buffer != bufferStandard) { delete []buffer; buffer = 0; } } }; const int stackBufferLength = 10000; class TextWide : public VarBuffer<wchar_t, stackBufferLength> { public: int tlen; TextWide(const char *s, int len, bool unicodeMode, int codePage=0) : VarBuffer<wchar_t, stackBufferLength>(len) { if (unicodeMode) { tlen = UTF16FromUTF8(s, len, buffer, len); } else { // Support Asian string display in 9x English tlen = ::MultiByteToWideChar(codePage, 0, s, len, buffer, len); } } }; typedef VarBuffer<int, stackBufferLength> TextPositions; void SurfaceImpl::DrawTextCommon(PRectangle rc, Font &font_, int ybase, const char *s, int len, UINT fuOptions) { SetFont(font_); RECT rcw = RectFromPRectangle(rc); SIZE sz={0,0}; int pos = 0; int x = rc.left; // Text drawing may fail if the text is too big. // If it does fail, slice up into segments and draw each segment. const int maxSegmentLength = 0x200; if ((!unicodeMode) && (IsNT() || (codePage==0) || win9xACPSame)) { // Use ANSI calls int lenDraw = Platform::Minimum(len, maxLenText); if (!::ExtTextOutA(hdc, x, ybase, fuOptions, &rcw, s, lenDraw, NULL)) { while (lenDraw > pos) { int seglen = Platform::Minimum(maxSegmentLength, lenDraw - pos); if (!::ExtTextOutA(hdc, x, ybase, fuOptions, &rcw, s+pos, seglen, NULL)) { PLATFORM_ASSERT(false); return; } ::GetTextExtentPoint32A(hdc, s+pos, seglen, &sz); x += sz.cx; pos += seglen; } } } else { // Use Unicode calls const TextWide tbuf(s, len, unicodeMode, codePage); if (!::ExtTextOutW(hdc, x, ybase, fuOptions, &rcw, tbuf.buffer, tbuf.tlen, NULL)) { while (tbuf.tlen > pos) { int seglen = Platform::Minimum(maxSegmentLength, tbuf.tlen - pos); if (!::ExtTextOutW(hdc, x, ybase, fuOptions, &rcw, tbuf.buffer+pos, seglen, NULL)) { PLATFORM_ASSERT(false); return; } ::GetTextExtentPoint32W(hdc, tbuf.buffer+pos, seglen, &sz); x += sz.cx; pos += seglen; } } } } void SurfaceImpl::DrawTextNoClip(PRectangle rc, Font &font_, int ybase, const char *s, int len, ColourAllocated fore, ColourAllocated back) { ::SetTextColor(hdc, fore.AsLong()); ::SetBkColor(hdc, back.AsLong()); DrawTextCommon(rc, font_, ybase, s, len, ETO_OPAQUE); } void SurfaceImpl::DrawTextClipped(PRectangle rc, Font &font_, int ybase, const char *s, int len, ColourAllocated fore, ColourAllocated back) { ::SetTextColor(hdc, fore.AsLong()); ::SetBkColor(hdc, back.AsLong()); DrawTextCommon(rc, font_, ybase, s, len, ETO_OPAQUE | ETO_CLIPPED); } void SurfaceImpl::DrawTextTransparent(PRectangle rc, Font &font_, int ybase, const char *s, int len, ColourAllocated fore) { // Avoid drawing spaces in transparent mode for (int i=0;i<len;i++) { if (s[i] != ' ') { ::SetTextColor(hdc, fore.AsLong()); ::SetBkMode(hdc, TRANSPARENT); DrawTextCommon(rc, font_, ybase, s, len, 0); ::SetBkMode(hdc, OPAQUE); return; } } } int SurfaceImpl::WidthText(Font &font_, const char *s, int len) { SetFont(font_); SIZE sz={0,0}; if ((!unicodeMode) && (IsNT() || (codePage==0) || win9xACPSame)) { ::GetTextExtentPoint32A(hdc, s, Platform::Minimum(len, maxLenText), &sz); } else { const TextWide tbuf(s, len, unicodeMode, codePage); ::GetTextExtentPoint32W(hdc, tbuf.buffer, tbuf.tlen, &sz); } return sz.cx; } void SurfaceImpl::MeasureWidths(Font &font_, const char *s, int len, int *positions) { SetFont(font_); SIZE sz={0,0}; int fit = 0; if (unicodeMode) { const TextWide tbuf(s, len, unicodeMode, codePage); TextPositions poses(tbuf.tlen); fit = tbuf.tlen; if (!::GetTextExtentExPointW(hdc, tbuf.buffer, tbuf.tlen, maxWidthMeasure, &fit, poses.buffer, &sz)) { // Likely to have failed because on Windows 9x where function not available // So measure the character widths by measuring each initial substring // Turns a linear operation into a qudratic but seems fast enough on test files for (int widthSS=0; widthSS < tbuf.tlen; widthSS++) { ::GetTextExtentPoint32W(hdc, tbuf.buffer, widthSS+1, &sz); poses.buffer[widthSS] = sz.cx; } } // Map the widths given for UTF-16 characters back onto the UTF-8 input string int ui=0; const unsigned char *us = reinterpret_cast<const unsigned char *>(s); int i=0; while (ui<fit) { unsigned char uch = us[i]; unsigned int lenChar = 1; if (uch >= (0x80 + 0x40 + 0x20 + 0x10)) { lenChar = 4; ui++; } else if (uch >= (0x80 + 0x40 + 0x20)) { lenChar = 3; } else if (uch >= (0x80)) { lenChar = 2; } for (unsigned int bytePos=0; (bytePos<lenChar) && (i<len); bytePos++) { positions[i++] = poses.buffer[ui]; } ui++; } int lastPos = 0; if (i > 0) lastPos = positions[i-1]; while (i<len) { positions[i++] = lastPos; } } else if (IsNT() || (codePage==0) || win9xACPSame) { // Zero positions to avoid random behaviour on failure. memset(positions, 0, len * sizeof(*positions)); // len may be larger than platform supports so loop over segments small enough for platform int startOffset = 0; while (len > 0) { int lenBlock = Platform::Minimum(len, maxLenText); if (!::GetTextExtentExPointA(hdc, s, lenBlock, maxWidthMeasure, &fit, positions, &sz)) { // Eeek - a NULL DC or other foolishness could cause this. return; } else if (fit < lenBlock) { // For some reason, such as an incomplete DBCS character // Not all the positions are filled in so make them equal to end. for (int i=fit;i<lenBlock;i++) positions[i] = positions[fit-1]; } else if (startOffset > 0) { for (int i=0;i<lenBlock;i++) positions[i] += startOffset; } startOffset = positions[lenBlock-1]; len -= lenBlock; positions += lenBlock; s += lenBlock; } } else { // Support Asian string display in 9x English const TextWide tbuf(s, len, unicodeMode, codePage); TextPositions poses(tbuf.tlen); for (int widthSS=0; widthSS<tbuf.tlen; widthSS++) { ::GetTextExtentPoint32W(hdc, tbuf.buffer, widthSS+1, &sz); poses.buffer[widthSS] = sz.cx; } int ui = 0; for (int i=0;i<len;) { if (::IsDBCSLeadByteEx(codePage, s[i])) { positions[i] = poses.buffer[ui]; positions[i+1] = poses.buffer[ui]; i += 2; } else { positions[i] = poses.buffer[ui]; i++; } ui++; } } } int SurfaceImpl::WidthChar(Font &font_, char ch) { SetFont(font_); SIZE sz; ::GetTextExtentPoint32A(hdc, &ch, 1, &sz); return sz.cx; } int SurfaceImpl::Ascent(Font &font_) { SetFont(font_); TEXTMETRIC tm; ::GetTextMetrics(hdc, &tm); return tm.tmAscent; } int SurfaceImpl::Descent(Font &font_) { SetFont(font_); TEXTMETRIC tm; ::GetTextMetrics(hdc, &tm); return tm.tmDescent; } int SurfaceImpl::InternalLeading(Font &font_) { SetFont(font_); TEXTMETRIC tm; ::GetTextMetrics(hdc, &tm); return tm.tmInternalLeading; } int SurfaceImpl::ExternalLeading(Font &font_) { SetFont(font_); TEXTMETRIC tm; ::GetTextMetrics(hdc, &tm); return tm.tmExternalLeading; } int SurfaceImpl::Height(Font &font_) { SetFont(font_); TEXTMETRIC tm; ::GetTextMetrics(hdc, &tm); return tm.tmHeight; } int SurfaceImpl::AverageCharWidth(Font &font_) { SetFont(font_); TEXTMETRIC tm; ::GetTextMetrics(hdc, &tm); return tm.tmAveCharWidth; } int SurfaceImpl::SetPalette(Palette *pal, bool inBackGround) { if (paletteOld) { ::SelectPalette(hdc, paletteOld, TRUE); } paletteOld = 0; int changes = 0; if (pal->allowRealization) { paletteOld = ::SelectPalette(hdc, reinterpret_cast<HPALETTE>(pal->hpal), inBackGround); changes = ::RealizePalette(hdc); } return changes; } void SurfaceImpl::SetClip(PRectangle rc) { ::IntersectClipRect(hdc, rc.left, rc.top, rc.right, rc.bottom); } void SurfaceImpl::FlushCachedState() { pen = 0; brush = 0; font = 0; } void SurfaceImpl::SetUnicodeMode(bool unicodeMode_) { unicodeMode=unicodeMode_; } void SurfaceImpl::SetDBCSMode(int codePage_) { // No action on window as automatically handled by system. codePage = codePage_; win9xACPSame = !IsNT() && ((unsigned int)codePage == ::GetACP()); } Surface *Surface::Allocate() { return new SurfaceImpl; } Window::~Window() { } void Window::Destroy() { if (wid) ::DestroyWindow(reinterpret_cast<HWND>(wid)); wid = 0; } bool Window::HasFocus() { return ::GetFocus() == wid; } PRectangle Window::GetPosition() { RECT rc; ::GetWindowRect(reinterpret_cast<HWND>(wid), &rc); return PRectangle(rc.left, rc.top, rc.right, rc.bottom); } void Window::SetPosition(PRectangle rc) { ::SetWindowPos(reinterpret_cast<HWND>(wid), 0, rc.left, rc.top, rc.Width(), rc.Height(), SWP_NOZORDER|SWP_NOACTIVATE); } void Window::SetPositionRelative(PRectangle rc, Window w) { LONG style = ::GetWindowLong(reinterpret_cast<HWND>(wid), GWL_STYLE); if (style & WS_POPUP) { RECT rcOther; ::GetWindowRect(reinterpret_cast<HWND>(w.GetID()), &rcOther); rc.Move(rcOther.left, rcOther.top); // This #ifdef is for VC 98 which has problems with MultiMon.h under some conditions. #ifdef MONITOR_DEFAULTTONULL // We're using the stub functionality of MultiMon.h to decay gracefully on machines // (ie, pre Win2000, Win95) that do not support the newer functions. RECT rcMonitor; memcpy(&rcMonitor, &rc, sizeof(rcMonitor)); // RECT and Rectangle are the same really. MONITORINFO mi = {0}; mi.cbSize = sizeof(mi); HMONITOR hMonitor = ::MonitorFromRect(&rcMonitor, MONITOR_DEFAULTTONEAREST); // If hMonitor is NULL, that's just the main screen anyways. ::GetMonitorInfo(hMonitor, &mi); // Now clamp our desired rectangle to fit inside the work area // This way, the menu will fit wholly on one screen. An improvement even // if you don't have a second monitor on the left... Menu's appears half on // one screen and half on the other are just U.G.L.Y.! if (rc.right > mi.rcWork.right) rc.Move(mi.rcWork.right - rc.right, 0); if (rc.bottom > mi.rcWork.bottom) rc.Move(0, mi.rcWork.bottom - rc.bottom); if (rc.left < mi.rcWork.left) rc.Move(mi.rcWork.left - rc.left, 0); if (rc.top < mi.rcWork.top) rc.Move(0, mi.rcWork.top - rc.top); #endif } SetPosition(rc); } PRectangle Window::GetClientPosition() { RECT rc={0,0,0,0}; if (wid) ::GetClientRect(reinterpret_cast<HWND>(wid), &rc); return PRectangle(rc.left, rc.top, rc.right, rc.bottom); } void Window::Show(bool show) { if (show) ::ShowWindow(reinterpret_cast<HWND>(wid), SW_SHOWNOACTIVATE); else ::ShowWindow(reinterpret_cast<HWND>(wid), SW_HIDE); } void Window::InvalidateAll() { ::InvalidateRect(reinterpret_cast<HWND>(wid), NULL, FALSE); } void Window::InvalidateRectangle(PRectangle rc) { RECT rcw = RectFromPRectangle(rc); ::InvalidateRect(reinterpret_cast<HWND>(wid), &rcw, FALSE); } static LRESULT Window_SendMessage(Window *w, UINT msg, WPARAM wParam=0, LPARAM lParam=0) { return ::SendMessage(reinterpret_cast<HWND>(w->GetID()), msg, wParam, lParam); } void Window::SetFont(Font &font) { Window_SendMessage(this, WM_SETFONT, reinterpret_cast<WPARAM>(font.GetID()), 0); } void Window::SetCursor(Cursor curs) { switch (curs) { case cursorText: ::SetCursor(::LoadCursor(NULL,IDC_IBEAM)); break; case cursorUp: ::SetCursor(::LoadCursor(NULL,IDC_UPARROW)); break; case cursorWait: ::SetCursor(::LoadCursor(NULL,IDC_WAIT)); break; case cursorHoriz: ::SetCursor(::LoadCursor(NULL,IDC_SIZEWE)); break; case cursorVert: ::SetCursor(::LoadCursor(NULL,IDC_SIZENS)); break; case cursorHand: ::SetCursor(::LoadCursor(NULL,IDC_HAND)); break; case cursorReverseArrow: { if (!hinstPlatformRes) hinstPlatformRes = ::GetModuleHandle(TEXT("Scintilla")); if (!hinstPlatformRes) hinstPlatformRes = ::GetModuleHandle(TEXT("SciLexer")); if (!hinstPlatformRes) hinstPlatformRes = ::GetModuleHandle(NULL); HCURSOR hcursor = ::LoadCursor(hinstPlatformRes, MAKEINTRESOURCE(IDC_MARGIN)); if (hcursor) ::SetCursor(hcursor); else ::SetCursor(::LoadCursor(NULL,IDC_ARROW)); } break; case cursorArrow: case cursorInvalid: // Should not occur, but just in case. ::SetCursor(::LoadCursor(NULL,IDC_ARROW)); break; } } void Window::SetTitle(const char *s) { ::SetWindowTextA(reinterpret_cast<HWND>(wid), s); } /* Returns rectangle of monitor pt is on, both rect and pt are in Window's coordinates */ PRectangle Window::GetMonitorRect(Point pt) { #ifdef MONITOR_DEFAULTTONULL // MonitorFromPoint and GetMonitorInfo are not available on Windows 95 so are not used. // There could be conditional code and dynamic loading in a future version // so this would work on those platforms where they are available. PRectangle rcPosition = GetPosition(); POINT ptDesktop = {pt.x + rcPosition.left, pt.y + rcPosition.top}; HMONITOR hMonitor = ::MonitorFromPoint(ptDesktop, MONITOR_DEFAULTTONEAREST); MONITORINFO mi = {0}; memset(&mi, 0, sizeof(mi)); mi.cbSize = sizeof(mi); if (::GetMonitorInfo(hMonitor, &mi)) { PRectangle rcMonitor( mi.rcWork.left - rcPosition.left, mi.rcWork.top - rcPosition.top, mi.rcWork.right - rcPosition.left, mi.rcWork.bottom - rcPosition.top); return rcMonitor; } else { return PRectangle(); } #else return PRectangle(); #endif } struct ListItemData { const char *text; int pixId; }; #define _ROUND2(n,pow2) \ ( ( (n) + (pow2) - 1) & ~((pow2) - 1) ) class LineToItem { char *words; int wordsCount; int wordsSize; ListItemData *data; int len; int count; private: void FreeWords() { delete []words; words = NULL; wordsCount = 0; wordsSize = 0; } char *AllocWord(const char *word); public: LineToItem() : words(NULL), wordsCount(0), wordsSize(0), data(NULL), len(0), count(0) { } ~LineToItem() { Clear(); } void Clear() { FreeWords(); delete []data; data = NULL; len = 0; count = 0; } ListItemData *Append(const char *text, int value); ListItemData Get(int index) const { if (index >= 0 && index < count) { return data[index]; } else { ListItemData missing = {"", -1}; return missing; } } int Count() const { return count; } ListItemData *AllocItem(); void SetWords(char *s) { words = s; // N.B. will be deleted on destruction } }; char *LineToItem::AllocWord(const char *text) { int chars = strlen(text) + 1; int newCount = wordsCount + chars; if (newCount > wordsSize) { wordsSize = _ROUND2(newCount * 2, 8192); char *wordsNew = new char[wordsSize]; memcpy(wordsNew, words, wordsCount); int offset = wordsNew - words; for (int i=0; i<count; i++) data[i].text += offset; delete []words; words = wordsNew; } char *s = &words[wordsCount]; wordsCount = newCount; strncpy(s, text, chars); return s; } ListItemData *LineToItem::AllocItem() { if (count >= len) { int lenNew = _ROUND2((count+1) * 2, 1024); ListItemData *dataNew = new ListItemData[lenNew]; memcpy(dataNew, data, count * sizeof(ListItemData)); delete []data; data = dataNew; len = lenNew; } ListItemData *item = &data[count]; count++; return item; } ListItemData *LineToItem::Append(const char *text, int imageIndex) { ListItemData *item = AllocItem(); item->text = AllocWord(text); item->pixId = imageIndex; return item; } const TCHAR ListBoxX_ClassName[] = TEXT("ListBoxX"); ListBox::ListBox() { } ListBox::~ListBox() { } class ListBoxX : public ListBox { int lineHeight; FontID fontCopy; XPMSet xset; LineToItem lti; HWND lb; bool unicodeMode; int desiredVisibleRows; unsigned int maxItemCharacters; unsigned int aveCharWidth; Window *parent; int ctrlID; CallBackAction doubleClickAction; void *doubleClickActionData; const char *widestItem; unsigned int maxCharWidth; int resizeHit; PRectangle rcPreSize; Point dragOffset; Point location; // Caret location at which the list is opened HWND GetHWND() const; void AppendListItem(const char *startword, const char *numword); void AdjustWindowRect(PRectangle *rc) const; int ItemHeight() const; int MinClientWidth() const; int TextOffset() const; Point GetClientExtent() const; POINT MinTrackSize() const; POINT MaxTrackSize() const; void SetRedraw(bool on); void OnDoubleClick(); void ResizeToCursor(); void StartResize(WPARAM); int NcHitTest(WPARAM, LPARAM) const; void CentreItem(int); void Paint(HDC); static LRESULT PASCAL ControlWndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam); static const Point ItemInset; // Padding around whole item static const Point TextInset; // Padding around text static const Point ImageInset; // Padding around image public: ListBoxX() : lineHeight(10), fontCopy(0), lb(0), unicodeMode(false), desiredVisibleRows(5), maxItemCharacters(0), aveCharWidth(8), parent(NULL), ctrlID(0), doubleClickAction(NULL), doubleClickActionData(NULL), widestItem(NULL), maxCharWidth(1), resizeHit(0) { } virtual ~ListBoxX() { if (fontCopy) { ::DeleteObject(fontCopy); fontCopy = 0; } } virtual void SetFont(Font &font); virtual void Create(Window &parent, int ctrlID, Point location_, int lineHeight_, bool unicodeMode_); virtual void SetAverageCharWidth(int width); virtual void SetVisibleRows(int rows); virtual int GetVisibleRows() const; virtual PRectangle GetDesiredRect(); virtual int CaretFromEdge(); virtual void Clear(); virtual void Append(char *s, int type = -1); virtual int Length(); virtual void Select(int n); virtual int GetSelection(); virtual int Find(const char *prefix); virtual void GetValue(int n, char *value, int len); virtual void RegisterImage(int type, const char *xpm_data); virtual void ClearRegisteredImages(); virtual void SetDoubleClickAction(CallBackAction action, void *data) { doubleClickAction = action; doubleClickActionData = data; } virtual void SetList(const char *list, char separator, char typesep); void Draw(DRAWITEMSTRUCT *pDrawItem); LRESULT WndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam); static LRESULT PASCAL StaticWndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam); }; const Point ListBoxX::ItemInset(0, 0); const Point ListBoxX::TextInset(2, 0); const Point ListBoxX::ImageInset(1, 0); ListBox *ListBox::Allocate() { ListBoxX *lb = new ListBoxX(); return lb; } void ListBoxX::Create(Window &parent_, int ctrlID_, Point location_, int lineHeight_, bool unicodeMode_) { parent = &parent_; ctrlID = ctrlID_; location = location_; lineHeight = lineHeight_; unicodeMode = unicodeMode_; HWND hwndParent = reinterpret_cast<HWND>(parent->GetID()); HINSTANCE hinstanceParent = GetWindowInstance(hwndParent); // Window created as popup so not clipped within parent client area wid = ::CreateWindowEx( WS_EX_WINDOWEDGE, ListBoxX_ClassName, TEXT(""), WS_POPUP | WS_THICKFRAME, 100,100, 150,80, hwndParent, NULL, hinstanceParent, this); ::MapWindowPoints(hwndParent, NULL, reinterpret_cast<POINT*>(&location), 1); } void ListBoxX::SetFont(Font &font) { LOGFONT lf; if (0 != ::GetObject(font.GetID(), sizeof(lf), &lf)) { if (fontCopy) { ::DeleteObject(fontCopy); fontCopy = 0; } fontCopy = ::CreateFontIndirect(&lf); ::SendMessage(lb, WM_SETFONT, reinterpret_cast<WPARAM>(fontCopy), 0); } } void ListBoxX::SetAverageCharWidth(int width) { aveCharWidth = width; } void ListBoxX::SetVisibleRows(int rows) { desiredVisibleRows = rows; } int ListBoxX::GetVisibleRows() const { return desiredVisibleRows; } HWND ListBoxX::GetHWND() const { return reinterpret_cast<HWND>(GetID()); } PRectangle ListBoxX::GetDesiredRect() { PRectangle rcDesired = GetPosition(); int rows = Length(); if ((rows == 0) || (rows > desiredVisibleRows)) rows = desiredVisibleRows; rcDesired.bottom = rcDesired.top + ItemHeight() * rows; int width = MinClientWidth(); HDC hdc = ::GetDC(lb); HFONT oldFont = SelectFont(hdc, fontCopy); SIZE textSize = {0, 0}; int len = widestItem ? strlen(widestItem) : 0; if (unicodeMode) { const TextWide tbuf(widestItem, len, unicodeMode); ::GetTextExtentPoint32W(hdc, tbuf.buffer, tbuf.tlen, &textSize); } else { ::GetTextExtentPoint32A(hdc, widestItem, len, &textSize); } TEXTMETRIC tm; ::GetTextMetrics(hdc, &tm); maxCharWidth = tm.tmMaxCharWidth; SelectFont(hdc, oldFont); ::ReleaseDC(lb, hdc); int widthDesired = Platform::Maximum(textSize.cx, (len + 1) * tm.tmAveCharWidth); if (width < widthDesired) width = widthDesired; rcDesired.right = rcDesired.left + TextOffset() + width + (TextInset.x * 2); if (Length() > rows) rcDesired.right += ::GetSystemMetrics(SM_CXVSCROLL); AdjustWindowRect(&rcDesired); return rcDesired; } int ListBoxX::TextOffset() const { int pixWidth = const_cast<XPMSet*>(&xset)->GetWidth(); return pixWidth == 0 ? ItemInset.x : ItemInset.x + pixWidth + (ImageInset.x * 2); } int ListBoxX::CaretFromEdge() { PRectangle rc; AdjustWindowRect(&rc); return TextOffset() + TextInset.x + (0 - rc.left) - 1; } void ListBoxX::Clear() { ::SendMessage(lb, LB_RESETCONTENT, 0, 0); maxItemCharacters = 0; widestItem = NULL; lti.Clear(); } void ListBoxX::Append(char *s, int type) { int index = ::SendMessage(lb, LB_ADDSTRING, 0, reinterpret_cast<LPARAM>(s)); if (index < 0) return; ListItemData *newItem = lti.Append(s, type); unsigned int len = static_cast<unsigned int>(strlen(s)); if (maxItemCharacters < len) { maxItemCharacters = len; widestItem = newItem->text; } } int ListBoxX::Length() { return lti.Count(); } void ListBoxX::Select(int n) { // We are going to scroll to centre on the new selection and then select it, so disable // redraw to avoid flicker caused by a painting new selection twice in unselected and then // selected states SetRedraw(false); CentreItem(n); ::SendMessage(lb, LB_SETCURSEL, n, 0); SetRedraw(true); } int ListBoxX::GetSelection() { return ::SendMessage(lb, LB_GETCURSEL, 0, 0); } // This is not actually called at present int ListBoxX::Find(const char *) { return LB_ERR; } void ListBoxX::GetValue(int n, char *value, int len) { ListItemData item = lti.Get(n); strncpy(value, item.text, len); value[len-1] = '\0'; } void ListBoxX::RegisterImage(int type, const char *xpm_data) { xset.Add(type, xpm_data); } void ListBoxX::ClearRegisteredImages() { xset.Clear(); } void ListBoxX::Draw(DRAWITEMSTRUCT *pDrawItem) { if ((pDrawItem->itemAction == ODA_SELECT) || (pDrawItem->itemAction == ODA_DRAWENTIRE)) { RECT rcBox = pDrawItem->rcItem; rcBox.left += TextOffset(); if (pDrawItem->itemState & ODS_SELECTED) { RECT rcImage = pDrawItem->rcItem; rcImage.right = rcBox.left; // The image is not highlighted ::FillRect(pDrawItem->hDC, &rcImage, reinterpret_cast<HBRUSH>(COLOR_WINDOW+1)); ::FillRect(pDrawItem->hDC, &rcBox, reinterpret_cast<HBRUSH>(COLOR_HIGHLIGHT+1)); ::SetBkColor(pDrawItem->hDC, ::GetSysColor(COLOR_HIGHLIGHT)); ::SetTextColor(pDrawItem->hDC, ::GetSysColor(COLOR_HIGHLIGHTTEXT)); } else { ::FillRect(pDrawItem->hDC, &pDrawItem->rcItem, reinterpret_cast<HBRUSH>(COLOR_WINDOW+1)); ::SetBkColor(pDrawItem->hDC, ::GetSysColor(COLOR_WINDOW)); ::SetTextColor(pDrawItem->hDC, ::GetSysColor(COLOR_WINDOWTEXT)); } ListItemData item = lti.Get(pDrawItem->itemID); int pixId = item.pixId; const char *text = item.text; int len = strlen(text); RECT rcText = rcBox; ::InsetRect(&rcText, TextInset.x, TextInset.y); if (unicodeMode) { const TextWide tbuf(text, len, unicodeMode); ::DrawTextW(pDrawItem->hDC, tbuf.buffer, tbuf.tlen, &rcText, DT_NOPREFIX|DT_END_ELLIPSIS|DT_SINGLELINE|DT_NOCLIP); } else { ::DrawTextA(pDrawItem->hDC, text, len, &rcText, DT_NOPREFIX|DT_END_ELLIPSIS|DT_SINGLELINE|DT_NOCLIP); } if (pDrawItem->itemState & ODS_SELECTED) { ::DrawFocusRect(pDrawItem->hDC, &rcBox); } // Draw the image, if any XPM *pxpm = xset.Get(pixId); if (pxpm) { Surface *surfaceItem = Surface::Allocate(); if (surfaceItem) { surfaceItem->Init(pDrawItem->hDC, pDrawItem->hwndItem); //surfaceItem->SetUnicodeMode(unicodeMode); //surfaceItem->SetDBCSMode(codePage); int left = pDrawItem->rcItem.left + ItemInset.x + ImageInset.x; PRectangle rcImage(left, pDrawItem->rcItem.top, left + xset.GetWidth(), pDrawItem->rcItem.bottom); pxpm->Draw(surfaceItem, rcImage); delete surfaceItem; ::SetTextAlign(pDrawItem->hDC, TA_TOP); } } } } void ListBoxX::AppendListItem(const char *startword, const char *numword) { ListItemData *item = lti.AllocItem(); item->text = startword; if (numword) { int pixId = 0; char ch; while ((ch = *++numword) != '\0') { pixId = 10 * pixId + (ch - '0'); } item->pixId = pixId; } else { item->pixId = -1; } unsigned int len = static_cast<unsigned int>(strlen(item->text)); if (maxItemCharacters < len) { maxItemCharacters = len; widestItem = item->text; } } void ListBoxX::SetList(const char *list, char separator, char typesep) { // Turn off redraw while populating the list - this has a significant effect, even if // the listbox is not visible. SetRedraw(false); Clear(); int size = strlen(list) + 1; char *words = new char[size]; lti.SetWords(words); memcpy(words, list, size); char *startword = words; char *numword = NULL; int i = 0; for (; words[i]; i++) { if (words[i] == separator) { words[i] = '\0'; if (numword) *numword = '\0'; AppendListItem(startword, numword); startword = words + i + 1; numword = NULL; } else if (words[i] == typesep) { numword = words + i; } } if (startword) { if (numword) *numword = '\0'; AppendListItem(startword, numword); } // Finally populate the listbox itself with the correct number of items int count = lti.Count(); ::SendMessage(lb, LB_INITSTORAGE, count, 0); for (int j=0; j<count; j++) { ::SendMessage(lb, LB_ADDSTRING, 0, j+1); } SetRedraw(true); } void ListBoxX::AdjustWindowRect(PRectangle *rc) const { ::AdjustWindowRectEx(reinterpret_cast<RECT*>(rc), WS_THICKFRAME, false, WS_EX_WINDOWEDGE); } int ListBoxX::ItemHeight() const { int itemHeight = lineHeight + (TextInset.y * 2); int pixHeight = const_cast<XPMSet*>(&xset)->GetHeight() + (ImageInset.y * 2); if (itemHeight < pixHeight) { itemHeight = pixHeight; } return itemHeight; } int ListBoxX::MinClientWidth() const { return 12 * (aveCharWidth+aveCharWidth/3); } POINT ListBoxX::MinTrackSize() const { PRectangle rc(0, 0, MinClientWidth(), ItemHeight()); AdjustWindowRect(&rc); POINT ret = {rc.Width(), rc.Height()}; return ret; } POINT ListBoxX::MaxTrackSize() const { PRectangle rc(0, 0, maxCharWidth * maxItemCharacters + TextInset.x * 2 + TextOffset() + ::GetSystemMetrics(SM_CXVSCROLL), ItemHeight() * lti.Count()); AdjustWindowRect(&rc); POINT ret = {rc.Width(), rc.Height()}; return ret; } void ListBoxX::SetRedraw(bool on) { ::SendMessage(lb, WM_SETREDRAW, static_cast<BOOL>(on), 0); if (on) ::InvalidateRect(lb, NULL, TRUE); } void ListBoxX::ResizeToCursor() { PRectangle rc = GetPosition(); Point pt; ::GetCursorPos(reinterpret_cast<POINT*>(&pt)); pt.x += dragOffset.x; pt.y += dragOffset.y; switch (resizeHit) { case HTLEFT: rc.left = pt.x; break; case HTRIGHT: rc.right = pt.x; break; case HTTOP: rc.top = pt.y; break; case HTTOPLEFT: rc.top = pt.y; rc.left = pt.x; break; case HTTOPRIGHT: rc.top = pt.y; rc.right = pt.x; break; case HTBOTTOM: rc.bottom = pt.y; break; case HTBOTTOMLEFT: rc.bottom = pt.y; rc.left = pt.x; break; case HTBOTTOMRIGHT: rc.bottom = pt.y; rc.right = pt.x; break; } POINT ptMin = MinTrackSize(); POINT ptMax = MaxTrackSize(); // We don't allow the left edge to move at present, but just in case rc.left = Platform::Maximum(Platform::Minimum(rc.left, rcPreSize.right - ptMin.x), rcPreSize.right - ptMax.x); rc.top = Platform::Maximum(Platform::Minimum(rc.top, rcPreSize.bottom - ptMin.y), rcPreSize.bottom - ptMax.y); rc.right = Platform::Maximum(Platform::Minimum(rc.right, rcPreSize.left + ptMax.x), rcPreSize.left + ptMin.x); rc.bottom = Platform::Maximum(Platform::Minimum(rc.bottom, rcPreSize.top + ptMax.y), rcPreSize.top + ptMin.y); SetPosition(rc); } void ListBoxX::StartResize(WPARAM hitCode) { rcPreSize = GetPosition(); POINT cursorPos; ::GetCursorPos(&cursorPos); switch (hitCode) { case HTRIGHT: case HTBOTTOM: case HTBOTTOMRIGHT: dragOffset.x = rcPreSize.right - cursorPos.x; dragOffset.y = rcPreSize.bottom - cursorPos.y; break; case HTTOPRIGHT: dragOffset.x = rcPreSize.right - cursorPos.x; dragOffset.y = rcPreSize.top - cursorPos.y; break; // Note that the current hit test code prevents the left edge cases ever firing // as we don't want the left edge to be moveable case HTLEFT: case HTTOP: case HTTOPLEFT: dragOffset.x = rcPreSize.left - cursorPos.x; dragOffset.y = rcPreSize.top - cursorPos.y; break; case HTBOTTOMLEFT: dragOffset.x = rcPreSize.left - cursorPos.x; dragOffset.y = rcPreSize.bottom - cursorPos.y; break; default: return; } ::SetCapture(GetHWND()); resizeHit = hitCode; } int ListBoxX::NcHitTest(WPARAM wParam, LPARAM lParam) const { int hit = ::DefWindowProc(GetHWND(), WM_NCHITTEST, wParam, lParam); // There is an apparent bug in the DefWindowProc hit test code whereby it will // return HTTOPXXX if the window in question is shorter than the default // window caption height + frame, even if one is hovering over the bottom edge of // the frame, so workaround that here if (hit >= HTTOP && hit <= HTTOPRIGHT) { int minHeight = GetSystemMetrics(SM_CYMINTRACK); PRectangle rc = const_cast<ListBoxX*>(this)->GetPosition(); int yPos = GET_Y_LPARAM(lParam); if ((rc.Height() < minHeight) && (yPos > ((rc.top + rc.bottom)/2))) { hit += HTBOTTOM - HTTOP; } } // Nerver permit resizing that moves the left edge. Allow movement of top or bottom edge // depending on whether the list is above or below the caret switch (hit) { case HTLEFT: case HTTOPLEFT: case HTBOTTOMLEFT: hit = HTERROR; break; case HTTOP: case HTTOPRIGHT: { PRectangle rc = const_cast<ListBoxX*>(this)->GetPosition(); // Valid only if caret below list if (location.y < rc.top) hit = HTERROR; } break; case HTBOTTOM: case HTBOTTOMRIGHT: { PRectangle rc = const_cast<ListBoxX*>(this)->GetPosition(); // Valid only if caret above list if (rc.bottom < location.y) hit = HTERROR; } break; } return hit; } void ListBoxX::OnDoubleClick() { if (doubleClickAction != NULL) { doubleClickAction(doubleClickActionData); } } Point ListBoxX::GetClientExtent() const { PRectangle rc = const_cast<ListBoxX*>(this)->GetClientPosition(); return Point(rc.Width(), rc.Height()); } void ListBoxX::CentreItem(int n) { // If below mid point, scroll up to centre, but with more items below if uneven if (n >= 0) { Point extent = GetClientExtent(); int visible = extent.y/ItemHeight(); if (visible < Length()) { int top = ::SendMessage(lb, LB_GETTOPINDEX, 0, 0); int half = (visible - 1) / 2; if (n > (top + half)) ::SendMessage(lb, LB_SETTOPINDEX, n - half , 0); } } } // Performs a double-buffered paint operation to avoid flicker void ListBoxX::Paint(HDC hDC) { Point extent = GetClientExtent(); HBITMAP hBitmap = ::CreateCompatibleBitmap(hDC, extent.x, extent.y); HDC bitmapDC = ::CreateCompatibleDC(hDC); HBITMAP hBitmapOld = SelectBitmap(bitmapDC, hBitmap); // The list background is mainly erased during painting, but can be a small // unpainted area when at the end of a non-integrally sized list with a // vertical scroll bar RECT rc = { 0, 0, extent.x, extent.y }; ::FillRect(bitmapDC, &rc, reinterpret_cast<HBRUSH>(COLOR_WINDOW+1)); // Paint the entire client area and vertical scrollbar ::SendMessage(lb, WM_PRINT, reinterpret_cast<WPARAM>(bitmapDC), PRF_CLIENT|PRF_NONCLIENT); ::BitBlt(hDC, 0, 0, extent.x, extent.y, bitmapDC, 0, 0, SRCCOPY); // Select a stock brush to prevent warnings from BoundsChecker ::SelectObject(bitmapDC, GetStockFont(WHITE_BRUSH)); SelectBitmap(bitmapDC, hBitmapOld); ::DeleteDC(bitmapDC); ::DeleteObject(hBitmap); } LRESULT PASCAL ListBoxX::ControlWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { try { switch (uMsg) { case WM_ERASEBKGND: return TRUE; case WM_PAINT: { PAINTSTRUCT ps; HDC hDC = ::BeginPaint(hWnd, &ps); ListBoxX *lbx = reinterpret_cast<ListBoxX *>(PointerFromWindow(::GetParent(hWnd))); if (lbx) lbx->Paint(hDC); ::EndPaint(hWnd, &ps); } return 0; case WM_MOUSEACTIVATE: // This prevents the view activating when the scrollbar is clicked return MA_NOACTIVATE; case WM_LBUTTONDOWN: { // We must take control of selection to prevent the ListBox activating // the popup LRESULT lResult = ::SendMessage(hWnd, LB_ITEMFROMPOINT, 0, lParam); int item = LOWORD(lResult); if (HIWORD(lResult) == 0 && item >= 0) { ::SendMessage(hWnd, LB_SETCURSEL, item, 0); } } return 0; case WM_LBUTTONUP: return 0; case WM_LBUTTONDBLCLK: { ListBoxX *lbx = reinterpret_cast<ListBoxX *>(PointerFromWindow(::GetParent(hWnd))); if (lbx) { lbx->OnDoubleClick(); } } return 0; } WNDPROC prevWndProc = reinterpret_cast<WNDPROC>(GetWindowLongPtr(hWnd, GWLP_USERDATA)); if (prevWndProc) { return ::CallWindowProc(prevWndProc, hWnd, uMsg, wParam, lParam); } else { return ::DefWindowProc(hWnd, uMsg, wParam, lParam); } } catch (...) { } return ::DefWindowProc(hWnd, uMsg, wParam, lParam); } LRESULT ListBoxX::WndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam) { switch (iMessage) { case WM_CREATE: { HINSTANCE hinstanceParent = GetWindowInstance(reinterpret_cast<HWND>(parent->GetID())); // Note that LBS_NOINTEGRALHEIGHT is specified to fix cosmetic issue when resizing the list // but has useful side effect of speeding up list population significantly lb = ::CreateWindowEx( 0, TEXT("listbox"), TEXT(""), WS_CHILD | WS_VSCROLL | WS_VISIBLE | LBS_OWNERDRAWFIXED | LBS_NODATA | LBS_NOINTEGRALHEIGHT, 0, 0, 150,80, hWnd, reinterpret_cast<HMENU>(ctrlID), hinstanceParent, 0); WNDPROC prevWndProc = reinterpret_cast<WNDPROC>(::SetWindowLongPtr(lb, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(ControlWndProc))); ::SetWindowLongPtr(lb, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(prevWndProc)); } break; case WM_SIZE: if (lb) { SetRedraw(false); ::SetWindowPos(lb, 0, 0,0, LOWORD(lParam), HIWORD(lParam), SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOMOVE); // Ensure the selection remains visible CentreItem(GetSelection()); SetRedraw(true); } break; case WM_PAINT: { PAINTSTRUCT ps; ::BeginPaint(hWnd, &ps); ::EndPaint(hWnd, &ps); } break; case WM_COMMAND: // This is not actually needed now - the registered double click action is used // directly to action a choice from the list. ::SendMessage(reinterpret_cast<HWND>(parent->GetID()), iMessage, wParam, lParam); break; case WM_MEASUREITEM: { MEASUREITEMSTRUCT *pMeasureItem = reinterpret_cast<MEASUREITEMSTRUCT *>(lParam); pMeasureItem->itemHeight = static_cast<unsigned int>(ItemHeight()); } break; case WM_DRAWITEM: Draw(reinterpret_cast<DRAWITEMSTRUCT *>(lParam)); break; case WM_DESTROY: lb = 0; ::SetWindowLong(hWnd, 0, 0); return ::DefWindowProc(hWnd, iMessage, wParam, lParam); case WM_ERASEBKGND: // To reduce flicker we can elide background erasure since this window is // completely covered by its child. return TRUE; case WM_GETMINMAXINFO: { MINMAXINFO *minMax = reinterpret_cast<MINMAXINFO*>(lParam); minMax->ptMaxTrackSize = MaxTrackSize(); minMax->ptMinTrackSize = MinTrackSize(); } break; case WM_MOUSEACTIVATE: return MA_NOACTIVATE; case WM_NCHITTEST: return NcHitTest(wParam, lParam); case WM_NCLBUTTONDOWN: // We have to implement our own window resizing because the DefWindowProc // implementation insists on activating the resized window StartResize(wParam); return 0; case WM_MOUSEMOVE: { if (resizeHit == 0) { return ::DefWindowProc(hWnd, iMessage, wParam, lParam); } else { ResizeToCursor(); } } break; case WM_LBUTTONUP: case WM_CANCELMODE: if (resizeHit != 0) { resizeHit = 0; ::ReleaseCapture(); } return ::DefWindowProc(hWnd, iMessage, wParam, lParam); default: return ::DefWindowProc(hWnd, iMessage, wParam, lParam); } return 0; } LRESULT PASCAL ListBoxX::StaticWndProc( HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam) { if (iMessage == WM_CREATE) { CREATESTRUCT *pCreate = reinterpret_cast<CREATESTRUCT *>(lParam); SetWindowPointer(hWnd, pCreate->lpCreateParams); } // Find C++ object associated with window. ListBoxX *lbx = reinterpret_cast<ListBoxX *>(PointerFromWindow(hWnd)); if (lbx) { return lbx->WndProc(hWnd, iMessage, wParam, lParam); } else { return ::DefWindowProc(hWnd, iMessage, wParam, lParam); } } static bool ListBoxX_Register() { WNDCLASSEX wndclassc; wndclassc.cbSize = sizeof(wndclassc); // We need CS_HREDRAW and CS_VREDRAW because of the ellipsis that might be drawn for // truncated items in the list and the appearance/disappearance of the vertical scroll bar. // The list repaint is double-buffered to avoid the flicker this would otherwise cause. wndclassc.style = CS_GLOBALCLASS | CS_HREDRAW | CS_VREDRAW; wndclassc.cbClsExtra = 0; wndclassc.cbWndExtra = sizeof(ListBoxX *); wndclassc.hInstance = hinstPlatformRes; wndclassc.hIcon = NULL; wndclassc.hbrBackground = NULL; wndclassc.lpszMenuName = NULL; wndclassc.lpfnWndProc = ListBoxX::StaticWndProc; wndclassc.hCursor = ::LoadCursor(NULL, IDC_ARROW); wndclassc.lpszClassName = ListBoxX_ClassName; wndclassc.hIconSm = 0; return ::RegisterClassEx(&wndclassc) != 0; } bool ListBoxX_Unregister() { return ::UnregisterClass(ListBoxX_ClassName, hinstPlatformRes) != 0; } Menu::Menu() : mid(0) { } void Menu::CreatePopUp() { Destroy(); mid = ::CreatePopupMenu(); } void Menu::Destroy() { if (mid) ::DestroyMenu(reinterpret_cast<HMENU>(mid)); mid = 0; } void Menu::Show(Point pt, Window &w) { ::TrackPopupMenu(reinterpret_cast<HMENU>(mid), 0, pt.x - 4, pt.y, 0, reinterpret_cast<HWND>(w.GetID()), NULL); Destroy(); } static bool initialisedET = false; static bool usePerformanceCounter = false; static LARGE_INTEGER frequency; ElapsedTime::ElapsedTime() { if (!initialisedET) { usePerformanceCounter = ::QueryPerformanceFrequency(&frequency) != 0; initialisedET = true; } if (usePerformanceCounter) { LARGE_INTEGER timeVal; ::QueryPerformanceCounter(&timeVal); bigBit = timeVal.HighPart; littleBit = timeVal.LowPart; } else { bigBit = clock(); } } double ElapsedTime::Duration(bool reset) { double result; long endBigBit; long endLittleBit; if (usePerformanceCounter) { LARGE_INTEGER lEnd; ::QueryPerformanceCounter(&lEnd); endBigBit = lEnd.HighPart; endLittleBit = lEnd.LowPart; LARGE_INTEGER lBegin; lBegin.HighPart = bigBit; lBegin.LowPart = littleBit; double elapsed = lEnd.QuadPart - lBegin.QuadPart; result = elapsed / static_cast<double>(frequency.QuadPart); } else { endBigBit = clock(); endLittleBit = 0; double elapsed = endBigBit - bigBit; result = elapsed / CLOCKS_PER_SEC; } if (reset) { bigBit = endBigBit; littleBit = endLittleBit; } return result; } class DynamicLibraryImpl : public DynamicLibrary { protected: HMODULE h; public: DynamicLibraryImpl(const char *modulePath) { h = ::LoadLibraryA(modulePath); } virtual ~DynamicLibraryImpl() { if (h != NULL) ::FreeLibrary(h); } // Use GetProcAddress to get a pointer to the relevant function. virtual Function FindFunction(const char *name) { if (h != NULL) { // C++ standard doesn't like casts betwen function pointers and void pointers so use a union union { FARPROC fp; Function f; } fnConv; fnConv.fp = ::GetProcAddress(h, name); return fnConv.f; } else return NULL; } virtual bool IsValid() { return h != NULL; } }; DynamicLibrary *DynamicLibrary::Load(const char *modulePath) { return static_cast<DynamicLibrary *>(new DynamicLibraryImpl(modulePath)); } ColourDesired Platform::Chrome() { return ::GetSysColor(COLOR_3DFACE); } ColourDesired Platform::ChromeHighlight() { return ::GetSysColor(COLOR_3DHIGHLIGHT); } const char *Platform::DefaultFont() { return "Verdana"; } int Platform::DefaultFontSize() { return 8; } unsigned int Platform::DoubleClickTime() { return ::GetDoubleClickTime(); } bool Platform::MouseButtonBounce() { return false; } void Platform::DebugDisplay(const char *s) { ::OutputDebugStringA(s); } bool Platform::IsKeyDown(int key) { return (::GetKeyState(key) & 0x80000000) != 0; } long Platform::SendScintilla(WindowID w, unsigned int msg, unsigned long wParam, long lParam) { return ::SendMessage(reinterpret_cast<HWND>(w), msg, wParam, lParam); } long Platform::SendScintillaPointer(WindowID w, unsigned int msg, unsigned long wParam, void *lParam) { return ::SendMessage(reinterpret_cast<HWND>(w), msg, wParam, reinterpret_cast<LPARAM>(lParam)); } bool Platform::IsDBCSLeadByte(int codePage, char ch) { return ::IsDBCSLeadByteEx(codePage, ch) != 0; } int Platform::DBCSCharLength(int codePage, const char *s) { return (::IsDBCSLeadByteEx(codePage, s[0]) != 0) ? 2 : 1; } int Platform::DBCSCharMaxLength() { return 2; } // These are utility functions not really tied to a platform int Platform::Minimum(int a, int b) { if (a < b) return a; else return b; } int Platform::Maximum(int a, int b) { if (a > b) return a; else return b; } //#define TRACE #ifdef TRACE void Platform::DebugPrintf(const char *format, ...) { char buffer[2000]; va_list pArguments; va_start(pArguments, format); vsprintf(buffer,format,pArguments); va_end(pArguments); Platform::DebugDisplay(buffer); } #else void Platform::DebugPrintf(const char *, ...) { } #endif static bool assertionPopUps = true; bool Platform::ShowAssertionPopUps(bool assertionPopUps_) { bool ret = assertionPopUps; assertionPopUps = assertionPopUps_; return ret; } void Platform::Assert(const char *c, const char *file, int line) { char buffer[2000]; sprintf(buffer, "Assertion [%s] failed at %s %d", c, file, line); if (assertionPopUps) { int idButton = ::MessageBoxA(0, buffer, "Assertion failure", MB_ABORTRETRYIGNORE|MB_ICONHAND|MB_SETFOREGROUND|MB_TASKMODAL); if (idButton == IDRETRY) { ::DebugBreak(); } else if (idButton == IDIGNORE) { // all OK } else { abort(); } } else { strcat(buffer, "\r\n"); Platform::DebugDisplay(buffer); ::DebugBreak(); abort(); } } int Platform::Clamp(int val, int minVal, int maxVal) { if (val > maxVal) val = maxVal; if (val < minVal) val = minVal; return val; } void Platform_Initialise(void *hInstance) { OSVERSIONINFO osv = {sizeof(OSVERSIONINFO),0,0,0,0,TEXT("")}; ::GetVersionEx(&osv); onNT = osv.dwPlatformId == VER_PLATFORM_WIN32_NT; ::InitializeCriticalSection(&crPlatformLock); hinstPlatformRes = reinterpret_cast<HINSTANCE>(hInstance); // This may be called from DllMain, in which case the call to LoadLibrary // is bad because it can upset the DLL load order. if (!hDLLImage) { hDLLImage = ::LoadLibrary(TEXT("Msimg32")); } if (hDLLImage) { AlphaBlendFn = (AlphaBlendSig)::GetProcAddress(hDLLImage, "AlphaBlend"); } ListBoxX_Register(); } void Platform_Finalise() { ListBoxX_Unregister(); ::DeleteCriticalSection(&crPlatformLock); }
[ "donho@9e717b3d-e3cd-45c4-bdc4-af0eb0386351" ]
[ [ [ 1, 2311 ] ] ]
d996c6c569d0df0e47922b12675363113c619f1c
4891542ea31c89c0ab2377428e92cc72bd1d078f
/Arcanoid/Arcanoid/PowerUpSpr.cpp
124980d03ff49770b45e4c5d6befc5bb83c247b4
[]
no_license
koutsop/arcanoid
aa32c46c407955a06c6d4efe34748e50c472eea8
5bfef14317e35751fa386d841f0f5fa2b8757fb4
refs/heads/master
2021-01-18T14:11:00.321215
2008-07-17T21:50:36
2008-07-17T21:50:36
33,115,792
0
0
null
null
null
null
UTF-8
C++
false
false
1,636
cpp
#include "PowerUpSpr.h" #include "PowerUp.h" #include <iostream> #include "Terrain.h" #define SPEED_POWER 1 PowerUpSpr::PowerUpSpr(Point point, AnimationFilm* film): Sprite(point, film){ this->SetVisibility(false); return; } void PowerUpSpr::Collide(Sprite *s){ if( dynamic_cast<Board*>(s) && IsVisible()){ SetVisibility(false); switch(kind){ case MAX: PowerUp::Max(); break; //OK case MIN: PowerUp::Min(); break; //OK case STIC: break; //NO case LIFE_UP: PowerUp::LifeUp(); break; //OK case CLONE_BALL: break; //NO case SPEED_UP: PowerUp::SpeedUp(); break; //OK case SPEED_DOWN: PowerUp::SpeedDown(); break; //OK case DESTRUCTION: PowerUp::Destruction(); break; //OK case EXPLOSION: PowerUp::Explosion(); break; //OK case BUCKLER: break; //NO case BAD: PowerUp::Bad(); break; //OK case MONEY: PowerUp::Money(); break; //OK case BOMB: PowerUp::Bomb(); break; // case BANANA: PowerUp::Banana(); break; //OK case FIRE: break; //NO case MONEY_X2: PowerUp::DoubleMoney(); break; //OK case NONE: break; //NO default: assert(0); }//end of chitc } return; } void PowerUpSpr::Move(const int x, const int y){ int tmpY = GetPosition().GetY(); //Den exei ginei collide me ton katw wall if( (tmpY + GetHeight()) < (Terrain::height+Terrain::coordinates.GetY()) ){ SetPosition(GetPosition().GetX(), tmpY + SPEED_POWER); } else{ //Kanei collide me ton katw SetVisibility(false); } return; } PowerUpSpr::~PowerUpSpr(){ }
[ "apixkernel@5c4dd20e-9542-0410-abe3-ad2d610f3ba4", "koutsop@5c4dd20e-9542-0410-abe3-ad2d610f3ba4" ]
[ [ [ 1, 2 ], [ 5, 5 ], [ 12, 12 ], [ 14, 19 ], [ 46, 46 ], [ 57, 59 ], [ 61, 62 ] ], [ [ 3, 4 ], [ 6, 11 ], [ 13, 13 ], [ 20, 45 ], [ 47, 56 ], [ 60, 60 ] ] ]
4108a6748937ee620a08c40007eec58df18b9ee8
a6a5c29ab75e58093e813afc951f08222001c38d
/TCC/include/core/ScriptObject.h
2b18bfe6d9cbf06cb2ffe0e4350dac023e2c5858
[]
no_license
voidribeiro/jogoshadow
b066bc75cc24c0f50b6243f91d91e286c0d997c7
946a4648ac420cb8988267f69c42688a0bc5ba6f
refs/heads/master
2016-09-05T23:42:09.869743
2010-02-25T12:17:06
2010-02-25T12:17:06
32,122,243
0
0
null
null
null
null
UTF-8
C++
false
false
980
h
#ifndef _SCRIPTOBJECT_H_ #define _SCRIPTOBJECT_H_ extern "C"{ #include "lua.h" #include "lauxlib.h" #include "lualib.h" }; #include <string> #include <iostream> #include "Script.h" //Include classes for bind #include "Game.h" #include "GameObject.h" #include "ComponentScript.h" #include "ComponentImage.h" #include "ComponentTimer.h" #include "ComponentSkybox.h" #include "ComponentModel.h" #include "ComponentGUI.h" #include "ComponentDialog.h" #include "ComponentSelector.h" #include "ComponentInteract.h" #include "ComponentSkeleton.h" using namespace std; class ScriptObject{ protected: Script luaScript; std::string scriptToExecute; public: explicit ScriptObject(const char* _scriptToExecute); virtual ~ScriptObject(); void Execute(const char* functionToExecute); void AddGlobalVar(const char* name, const char* value); void AddGlobalUserVar(const char* name, const void* value); }; #endif
[ "rafarlira@17fd7b7e-20b4-11de-a108-cd2f117ce590", "suisen.no.ryuu@17fd7b7e-20b4-11de-a108-cd2f117ce590" ]
[ [ [ 1, 20 ], [ 25, 26 ], [ 28, 43 ] ], [ [ 21, 24 ], [ 27, 27 ] ] ]
409dde393494267d847397e715c368fdafe237bf
001a97b7d4dba30c022f7fe118161f69fa8bed24
/Launchy_VC7/src/Options.cpp
0e910e0e4fa23a2a47debdc6fdb16383cd175629
[]
no_license
svn2github/Launchy
8d8e56727a9a1df600a42f349cbca3d51840c943
601356dbb4e9cdda87605cfff049b315a70b438f
refs/heads/master
2023-09-03T11:37:28.828055
2010-11-10T01:14:44
2010-11-10T01:14:44
98,788,809
1
0
null
null
null
null
UTF-8
C++
false
false
8,779
cpp
/* Launchy: Application Launcher Copyright (C) 2005 Josh Karlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "StdAfx.h" #include "Options.h" #include "LaunchyDlg.h" #include "LaunchySmarts.h" #include ".\options.h" Options::Options(void) : ini(new CIniFile()) , vkey(0) , mod_key(0) , usbmode(false) , Indexing(false) { firstRun = false; hMutex = CreateMutex( NULL, // default security attributes FALSE, // initially not owned NULL); // unnamed mutex CDiskObject disk; if (disk.FileExists(_T("launchy.ini"))) { ini->SetPath(_T("launchy.ini")); usbmode = true; } else { CString dir; LaunchySmarts::GetShellDir(CSIDL_APPDATA, dir); dir += _T("\\Launchy\\"); disk.CreateDirectory(dir); set_dataPath(dir); dir += _T("\\launchy.ini"); ini->SetPath(dir); } if (!ini->ReadFile()) { firstRun = true; } ParseIni(); LoadSkins(); UpgradeCleanup(); } void Options::changeUsbMode(bool toUSB) { if (toUSB) { set_dataPath(_T("")); ini->SetPath(_T("launchy.ini")); usbmode = true; } else { CDiskObject disk; CString dir; LaunchySmarts::GetShellDir(CSIDL_APPDATA, dir); dir += _T("\\Launchy\\"); disk.CreateDirectory(dir); set_dataPath(dir); dir += _T("launchy.ini"); ini->SetPath(dir); usbmode = false; // Need to delete the old files else they will // be used when next Launchy starts! getLock(); disk.RemoveFile(_T("launchy.ini")); disk.RemoveFile(_T("launchy.db")); relLock(); } } Options::~Options(void) { Store(); } vector<CString> DeSerializeStringArray(CString input) { vector<CString> output; CString tmp; int cur = 0; while(true) { int c = input.Find(_T(";"), cur); if (c > 0 && c < input.GetLength()) { tmp = input.Mid(cur,c-cur); output.push_back(tmp); } else { break; } cur = c+1; } return output; } CString SerializeStringArray(vector<CString> input) { CString output = _T(""); for(uint i = 0; i < input.size(); i++) { output.Append(input[i]); output.Append(_T(";")); } return output; } vector<DirOptions> DeSerializeDirArray(CString input) { vector<DirOptions> output; CString tmp; int cur = 0; while(true) { DirOptions d; int c = input.Find(_T(";"), cur); if (c > 0 && c < input.GetLength()) { tmp = input.Mid(cur,c-cur); d.dir = tmp; cur = c+1; int end = input.Find(_T("|"),cur); if (end != -1) { c = input.Find(_T(","),cur); while(cur < end && c < end && c != -1) { CString type = input.Mid(cur, c-cur); d.types.push_back(type); cur = c+1; c = input.Find(_T(","),cur); } cur = end + 1; } output.push_back(d); } else { break; } } return output; } CString SerializeDirArray(vector<DirOptions> input) { CString output = _T(""); for(uint i = 0; i < input.size(); i++) { output.Append(input[i].dir); output.Append(_T(";")); for(uint j = 0; j < input[i].types.size(); j++) { output.Append(input[i].types[j]); output.Append(_T(",")); } output.Append(_T("|")); } return output; } bool Options::LoadPlugin(CString PluginName) { return ini->GetValueB(_T("Plugins"), PluginName, true); } void Options::ParseIni(void) { CString DefaultDirs; CString myMenu, allMenus; LaunchySmarts::GetShellDir(CSIDL_COMMON_STARTMENU, allMenus); LaunchySmarts::GetShellDir(CSIDL_STARTMENU, myMenu); DefaultDirs.Format(_T("%s;.lnk,|%s;.lnk,|Utilities\\;.lnk,|"), myMenu, allMenus); ver = ini->GetValueI(_T("Launchy Information"), _T("Version"), 0); posX = ini->GetValueI(_T("Position"), _T("pos_x")); posY = ini->GetValueI(_T("Position"), _T("pos_y")); listLength = ini->GetValueI(_T("Advanced"), _T("List Length"), 10); stickyWindow = ini->GetValueB(_T("Advanced"), _T("Sticky Window"), false); chkupdate = ini->GetValueB(_T("Advanced"), _T("Check For Updates"), true); aot = ini->GetValueB(_T("Advanced"), _T("Always on Top"), false); indexTime = ini->GetValueI(_T("Advanced"), _T("Index Time"), 20); mod_key = ini->GetValueI(_T("Hotkey"), _T("mod_key"), MOD_ALT); vkey = ini->GetValueI(_T("Hotkey"), _T("vkey"), VK_SPACE); skinName = ini->GetValue(_T("Skin"), _T("name"), _T("Default")); set_Directories(DeSerializeDirArray(ini->GetValue(_T("General"), _T("Directories"), DefaultDirs))); set_Types(DeSerializeStringArray(ini->GetValue(_T("General"), _T("Types"), _T(".lnk;")))); CTime t = CTime::GetCurrentTime(); installTime = CTime( ini->GetValueTime(_T("Launchy Information"), _T("InstallTime"), t.GetTime())); } void Options::Store(void) { CWinApp* pApp = AfxGetApp(); if (pApp == NULL) return; RECT location; pApp->GetMainWnd()->GetWindowRect(&location); ini->SetValueI(_T("Launchy Information"), _T("Version"), LAUNCHY_VERSION); ini->SetValueI(_T("Position"), _T("pos_x"), location.left); ini->SetValueI(_T("Position"), _T("pos_y"), location.top); ini->SetValueI(_T("Advanced"), _T("List Length"), listLength); ini->SetValueB(_T("Advanced"), _T("Sticky Window"), stickyWindow); ini->SetValueB(_T("Advanced"), _T("Check For Updates"), chkupdate); ini->SetValueB(_T("Advanced"), _T("Always on Top"), aot); ini->SetValueI(_T("Advanced"), _T("Index Time"), indexTime); ini->SetValueI(_T("Hotkey"), _T("mod_key"), mod_key); ini->SetValueI(_T("Hotkey"), _T("vkey"), vkey); ini->SetValue(_T("Skin"), _T("name"), skinName); ini->SetValue(_T("General"), _T("Directories"), SerializeDirArray(get_Directories())); ini->SetValue(_T("General"), _T("Types"), SerializeStringArray(get_Types())); ini->SetValueTime(_T("Launchy Information"), _T("InstallTime"), installTime.GetTime()); shared_ptr<Plugin> plugins = ((CLaunchyDlg*)AfxGetMainWnd())->plugins; if (plugins != NULL) { for(int i = 0; i < plugins->allPlugins.size(); i++) { ini->SetValueB(_T("Plugins"), plugins->allPlugins[i].name, plugins->allPlugins[i].loaded); } } ini->WriteFile(); } void Options::LoadSkins(void) { wchar_t buffer[_MAX_PATH]; /* Get the current working directory: */ _wgetcwd( buffer, _MAX_PATH ); CString dir = buffer; dir += "\\Skins\\"; CDiskObject disk; CStringArray skinDirs; disk.EnumAllDirectories(dir, skinDirs); INT_PTR count = skinDirs.GetCount(); for(int i = 0; i < count; i++) { shared_ptr<Skin> x(new Skin(skinDirs[i])); if (x->name == _T("")) continue; skins.push_back(x); if (x->name == skinName) { skin = x; } } } void Options::UpgradeCleanup(void) { if (firstRun) { /* AfxMessageBox(_T("Welcome to Launchy!\n \ Launchy is currently running in the background and can be brought forward by pressing Alt+Space\n \ Enjoy!")); */ } // Ver == 0 for all versions below 0.91 (ver wasn't added until 0.91) // Delete the Users/ config files if (ver < 98) { // Remove the old configuration directories if they exist CDiskObject disk; disk.RemoveDirectory(_T("Users")); } if (ver < 102) { CString file; LaunchySmarts::GetShellDir(CSIDL_APPDATA, file); file += _T("\\Launchy\\"); file += L"launchy.db"; CDiskObject disk; disk.RemoveFile(file); } if (ver < LAUNCHY_VERSION) { installTime = CTime::GetCurrentTime(); } } void Options::SetSkin(CString name) { // Select this skin for(uint i = 0; i < skins.size(); i++) { if (skins[i]->name == name) { skin = skins[i]; skinName = name; break; } } } void Options::Associate(CString entry, CString destination) { ini->SetValue(_T("Associations"), entry, destination); } CString Options::GetAssociation(CString query) { CString res = ini->GetValue(_T("Associations"), query, _T("")); if (res != _T("")) return res; return _T(""); return res; } void Options::getLock(void) { WaitForSingleObject(hMutex, INFINITE); } void Options::relLock(void) { ReleaseMutex(hMutex); }
[ "karlinjf@a198a55a-610f-0410-8134-935da841aa8c" ]
[ [ [ 1, 350 ] ] ]
bff1fa0103763bf284e214d9583a380e320b0568
e028e7765c46ba9399dbaa563e278f1d2c718e5e
/hmm/include/hmm.h
4425ba2b42ac6cdd49b104ba0c69a6c2f3ebda41
[]
no_license
cider-load-test/wiigesture
fd794b16f6edf9bcebe8761fe236dd6cca2c6921
7ba49185d3b7b049e643cc7f3c1755937611dede
refs/heads/master
2021-12-02T05:56:30.646752
2008-10-19T12:22:52
2008-10-19T12:22:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,318
h
#ifndef HMM_H_INCLUDED #define HMM_H_INCLUDED #include <vector> #include <iostream> #include <fstream> class HMM { private: // numero di stati int numStati; // numero di simboli osservabili int numOss; // true: HMM ergodico, false: HMM left-to-right bool isErgodic; // vettore probabilità stati iniziali double* pi; // matrice transizione: prob da stato i a stato j A[i][j] double** A; // matrice emissione: prob emettere simbolo k trovandosi in stato i B[i][k] double** B; // inizializza come HMM left-to-right void init_left_to_right(int span); // inizializza come HMM ergodico void init_ergodic(); /** * Procedura forward. * * @param O la sequenza osservata * @return Array[Stato][Tempo] */ double** forwardProc(std::vector<int> O); /** * Riporta la probabilità della sequenza osservata. * * @param alpha Matrice delle variabili forward (calcolabile con forwardProc) * @return Probabilità della sequenza osservata O dato il modello lambda: P(O|lambda) */ double getProbability(double** alpha, int size); public: /** * Inizializza l'HMM. * * @param stati Numero di stati * @param osservazionu Numero di simboli osservabili * @param isErgodic Indica se il modello sarà ergodico (true) o left-to-right (false) * @param span Indica, nel modello left-to-right, quanti stati sono connessi a sx e dx con lo stato corrente (default=2) */ HMM(int stati, int osservazioni, bool isErgodic, int span = 2); /** * Addestra l'HMM a partire da un dataset di gesture * * @param trainingset Vettore delle gesture */ void train(std::vector< std::vector<int> > trainingset); /** * Training con sequenze multiple * * @param trainingset Vettore delle gesture */ void trainMS(std::vector< std::vector<int> > trainingset); /** * Procedura backward. * * @param O La sequenza osservata. * @return Array[Stato][Tempo] */ double** backwardProc(std::vector<int> O); double getP(std::vector<int> O); /** * Stampa a video il contenuto delle matrici A e B * */ void print(); void print_to_file(); void save(char* filename); void load(char* filename); double** getA(); double** getB(); double* getPi(); int getNumStati(); int getNumOss(); }; #endif // HMM_H_INCLUDED
[ [ [ 1, 3 ], [ 5, 116 ] ], [ [ 4, 4 ] ] ]
f59d531493eb5cfe9fb8182d4db352c708cd5134
fe202e665e666decce19b2c4c2840d03903f357f
/common/VideoSpringCommon.h
ba551948615d67a51661b24be17703c9aa64fc25
[]
no_license
woodcom/videospring
e038ee9aa67d4a38566a2d9740773c07e6882c95
04b08649da189fe6f093b944e5f70eace4fee416
refs/heads/master
2021-01-01T06:45:15.377090
2010-11-10T04:10:35
2010-11-10T04:10:35
33,705,206
0
0
null
null
null
null
UTF-8
C++
false
false
1,370
h
#ifndef H_VIDSPRINGCOMMON #define H_VIDSPRINGCOMMON 1 #define TCP_CHUNKSIZE 1024 #if defined(WIN32) || defined(_WINDLL) #include "../VideoSpring/VideoSpring/includes.h" #else #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> typedef uint32_t DWORD; typedef unsigned char BYTE; typedef int SOCKET; #ifndef NULL #define NULL 0 #endif #define SOCKET_ERROR -1 #define INVALID_SOCKET -1 #define NOERROR 0 #define WSAEWOULDBLOCK ENOTBLK #define closesocket(socket) close(socket) #endif enum { C_SET_AUDIO_SENDER, C_SET_VIDEO_SENDER, C_SET_AUDIO_RECEIVER, C_SET_VIDEO_RECEIVER, C_SET_MEDIA_TYPE, C_SET_FORMAT, C_BROADCAST_AUDIO, C_BROADCAST_AUDIO_KEYFRAME, C_BROADCAST_VIDEO, C_BROADCAST_VIDEO_KEYFRAME, C_RECEIVE, C_NEW_PRESENTER, C_NEW_CLIENT, C_DROP_PRESENTER }; struct MessageHeader { uint16_t command; uint32_t length; }; class Message { public: MessageHeader header; BYTE *data; Message() { header.command = 0; header.length = 0; data = NULL; } }; int sendMessage(SOCKET s, Message *m); int receiveMessage(SOCKET s, Message &m); int deleteMessage(Message &m); #endif
[ "[email protected]@97fa9fb9-d99c-c0a3-0dfb-269dd1aed276", "[email protected]@97fa9fb9-d99c-c0a3-0dfb-269dd1aed276" ]
[ [ [ 1, 8 ], [ 10, 39 ], [ 45, 45 ], [ 50, 80 ] ], [ [ 9, 9 ], [ 40, 44 ], [ 46, 49 ] ] ]
4c40db3e6370b81fb4d789c5038baa7721c36768
da49fe5fb9fc91dba1f0236411de3021e1e25348
/UnitGroupAI.cpp
69661819e8e33227d943989433aa2fec1852caf9
[]
no_license
imbaczek/baczek-kpai
7f84d83ba395c2e5b5d85c10c14072049b4830ab
4291ec37f49fc8cb4a643133ed5f3024264e1e27
refs/heads/master
2020-03-28T19:13:42.841144
2009-10-29T21:39:02
2009-10-29T21:39:02
151,447
1
0
null
null
null
null
UTF-8
C++
false
false
14,847
cpp
#include <boost/shared_ptr.hpp> #include <boost/foreach.hpp> #include <boost/timer.hpp> #include "Sim/MoveTypes/MoveInfo.h" #include "Log.h" #include "BaczekKPAI.h" #include "Unit.h" #include "UnitGroupAI.h" #include "Goal.h" #include "UnitAI.h" #include "RNG.h" using boost::shared_ptr; GoalProcessor::goal_process_t UnitGroupAI::ProcessGoal(Goal* goal) { if (!goal || goal->is_finished()) { return PROCESS_POP_CONTINUE; } switch(goal->type) { case BUILD_CONSTRUCTOR: if (goal->is_executing()) return PROCESS_CONTINUE; ProcessBuildConstructor(goal); return PROCESS_CONTINUE; case BUILD_EXPANSION: if (goal->is_executing()) return PROCESS_CONTINUE; ProcessBuildExpansion(goal); return PROCESS_CONTINUE; case MOVE: case RETREAT: if (goal->params.empty()) return PROCESS_POP_CONTINUE; ProcessRetreatMove(goal); return PROCESS_BREAK; case ATTACK: if (goal->params.empty()) return PROCESS_POP_CONTINUE; ProcessAttack(goal); return PROCESS_BREAK; default: return PROCESS_POP_CONTINUE; } return PROCESS_CONTINUE; } void UnitGroupAI::Update() { boost::timer t; int frameNum = ai->cb->GetCurrentFrame(); if (frameNum % 30 == 0) { CheckUnit2Goal(); std::sort(goals.begin(), goals.end(), goal_priority_less()); DumpGoalStack("UnitGroupAI"); ProcessGoalStack(frameNum); } // update units BOOST_FOREACH(UnitAISet::value_type& v, units) { v.second->Update(); } ailog->info() << __FUNCTION__ << " took " << t.elapsed() << std::endl; } /////////////////////////////////////////////////////////////////////////// // goal processing void UnitGroupAI::ProcessBuildConstructor(Goal* goal) { assert(goal); assert(goal->type == BUILD_CONSTRUCTOR); BOOST_FOREACH(UnitAISet::value_type& v, units) { UnitAIPtr uai = v.second; Unit* unit = uai->owner; assert(unit); if (unit->is_producing) continue; Goal *g = Goal::GetGoal(Goal::CreateGoal(goal->priority, BUILD_CONSTRUCTOR)); assert(g); g->parent = goal->id; // behaviour when parent goal changes goal->OnAbort(AbortGoal(*g)); goal->OnComplete(CompleteGoal(*g)); // behaviour when subgoal changes g->OnComplete(CompleteGoal(*goal)); ailog->info() << "unit " << unit->id << " assigned to producing a constructor" << std::endl; uai->AddGoal(g); goal->start(); // unit found, exit loop break; } } void UnitGroupAI::ProcessBuildExpansion(Goal* goal) { assert(goal); assert(goal->type == BUILD_EXPANSION); BOOST_FOREACH(UnitAISet::value_type& v, units) { UnitAIPtr uai = v.second; Unit* unit = uai->owner; assert(unit); if (unit->is_producing) continue; if (!unit->is_constructor) continue; if (usedUnits.find(unit->id) != usedUnits.end()) continue; // TODO FIXME used goals aren't freed when units assigned to them die if (usedGoals.find(goal->id) != usedGoals.end()) continue; Goal *g = Goal::GetGoal(Goal::CreateGoal(1, BUILD_EXPANSION)); assert(g); assert(goal->params.size() >= 1); g->parent = goal->id; g->params.push_back(goal->params[0]); // behaviour when parent goal changes goal->OnAbort(AbortGoal(*g)); // abort subgoal goal->OnComplete(CompleteGoal(*g)); // complete subgoal // behaviour when subgoal changes // mark parent as complete g->OnComplete(CompleteGoal(*goal)); // do not suspend - risk matrix may have changed g->OnAbort(AbortGoal(*goal)); // remove marks g->OnComplete(RemoveUsedUnit(*this, unit->id)); g->OnComplete(RemoveUsedGoal(*this, goal->id)); g->OnAbort(RemoveUsedUnit(*this, unit->id)); g->OnAbort(RemoveUsedGoal(*this, goal->id)); ailog->info() << "unit " << unit->id << " assigned to building an expansion (goal id " << goal->id << " " << goal->params[0] << ")" << std::endl; uai->AddGoal(g); goal->start(); usedUnits.insert(std::make_pair(unit->id, g->priority)); usedGoals.insert(goal->id); unit2goal[unit->id] = goal->id; goal2unit[goal->id] = unit->id; // unit found, exit loop break; } } void UnitGroupAI::ProcessRetreatMove(Goal* goal) { assert(goal); assert(goal->type == MOVE || goal->type == RETREAT); // may throw rallyPoint = boost::get<float3>(goal->params[0]); int i = 0; BOOST_FOREACH(UnitAISet::value_type& v, units) { UnitAIPtr uai = v.second; Unit* unit = uai->owner; assert(unit); std::map<int, int>::iterator used = usedUnits.find(unit->id); if (used != usedUnits.end() && used->second >= goal->priority) continue; if (used != usedUnits.end() && used->second < goal->priority) ailog->info() << "overriding move goal due to lower priority" << std::endl; if (uai->HaveGoalType(RETREAT, goal->priority)) continue; usedUnits.insert(std::make_pair(unit->id, goal->priority)); ailog->info() << "gave " << unit->id << " RETREAT to " << rallyPoint << std::endl; Goal* g = CreateRetreatGoal(*uai, goal->timeoutFrame); g->parent = goal->id; // behaviour when subgoal changes // remove marks g->OnComplete(RemoveUsedUnit(*this, unit->id)); // order matters! g->OnAbort(RemoveUsedUnit(*this, unit->id)); g->OnComplete(IfUsedUnitsEmpty(*this, CompleteGoal(*goal))); g->OnStart(StartGoal(*goal)); // behaviour when parent goal changes goal->OnAbort(AbortGoal(*g)); // abort subgoal goal->OnComplete(CompleteGoal(*g)); // complete subgoal uai->AddGoal(g); } } void UnitGroupAI::ProcessAttack(Goal* goal) { assert(goal); assert(goal->type == ATTACK); int i = 0; BOOST_FOREACH(UnitAISet::value_type& v, units) { UnitAIPtr uai = v.second; Unit* unit = uai->owner; assert(unit); std::map<int, int>::iterator used = usedUnits.find(unit->id); if (used != usedUnits.end() && used->second >= goal->priority) continue; if (uai->HaveGoalType(ATTACK, goal->priority)) continue; usedUnits.insert(std::make_pair(unit->id, goal->priority)); assert(goal->params.size() >= 1); Goal* g = Goal::GetGoal(Goal::CreateGoal(goal->priority, ATTACK)); g->parent = goal->id; g->timeoutFrame = goal->timeoutFrame; g->params.push_back(goal->params[0]); // behaviour when subgoal changes // remove marks g->OnComplete(RemoveUsedUnit(*this, unit->id)); // order matters! g->OnAbort(RemoveUsedUnit(*this, unit->id)); g->OnComplete(IfUsedUnitsEmpty(*this, CompleteGoal(*goal))); g->OnStart(StartGoal(*goal)); // behaviour when parent goal changes goal->OnAbort(AbortGoal(*g)); // abort subgoal goal->OnComplete(CompleteGoal(*g)); // complete subgoal uai->AddGoal(g); } } //////////////////////////////////////////////////////////////////// // unit stuff struct OnKilledHandler : std::unary_function<UnitAI&, void> { UnitGroupAI& self; OnKilledHandler(UnitGroupAI& s):self(s) {} void operator()(UnitAI& uai) { self.RemoveUnitAI(uai); } }; void UnitGroupAI::AssignUnit(Unit* unit) { assert(unit); if (!unit->ai) { unit->ai.reset(new UnitAI(ai, unit)); } UnitAIPtr uai = unit->ai; assert(uai); units.insert(UnitAISet::value_type(unit->id, uai)); //uai->OnKilled(boost::bind(&UnitGroupAI::RemoveUnitAI, this)); // crashes msvc9 lol uai->OnKilled(OnKilledHandler(*this)); } void UnitGroupAI::RemoveUnit(Unit* unit) { assert(unit); units.erase(unit->id); usedUnits.erase(unit->id); } void UnitGroupAI::RemoveUnitAI(UnitAI& unitAi) { assert(unitAi.owner); ailog->info() << "removing unit " << unitAi.owner->id << " from group" << std::endl; RemoveUnit(unitAi.owner); } void UnitGroupAI::RetreatUnusedUnits() { boost::timer t; if (!rallyPoint.IsInBounds()) { ailog->info() << "cannot retreat unit group, rally point not set" << std::endl; return; } for (std::map<int, int>::iterator it = usedUnits.begin(); it != usedUnits.end(); ++it) { ailog->info() << it->first << " is used" << std::endl; } for (UnitAISet::iterator it = units.begin(); it != units.end(); ++it) { if (usedUnits.find(it->first) == usedUnits.end() // unit not used && it->second->owner // and exists && it->second->owner->last_idle_frame + 30 < ai->cb->GetCurrentFrame() // and is idle for a while && rallyPoint.SqDistance2D(ai->cb->GetUnitPos(it->first)) > 20*20*SQUARE_SIZE*SQUARE_SIZE // and not close to rally point && !it->second->HaveGoalType(RETREAT)) { // and doesn't have a retreat goal // retreat ailog->info() << "retreating unused " << it->first << std::endl; Goal* newgoal = CreateRetreatGoal(*it->second, 15*GAME_SPEED); it->second->AddGoal(newgoal); } } ailog->info() << __FUNCTION__ << " took " << t.elapsed() << std::endl; } Goal* UnitGroupAI::CreateRetreatGoal(UnitAI &uai, int timeoutFrame) { Unit* unit = uai.owner; Goal *g = Goal::GetGoal(Goal::CreateGoal(1, RETREAT)); assert(g); g->timeoutFrame = timeoutFrame; g->params.push_back(random_offset_pos(rallyPoint, SQUARE_SIZE*4, SQUARE_SIZE*4*sqrt((float)units.size()))); return g; } bool UnitGroupAI::CheckUnit2Goal() { #ifdef _DEBUG // check unit2goal for (std::map<int, int>::iterator it = unit2goal.begin(); it != unit2goal.end(); ++it) { Unit* unit = ai->GetUnit(it->first); assert(unit); assert(!unit->is_killed); assert(it->first == goal2unit[it->second]); Goal* unitgoal = Goal::GetGoal(unit->ai->currentGoalId); assert(unitgoal); assert(unitgoal->parent == it->second); } // check goal2unit for (std::map<int, int>::iterator it = goal2unit.begin(); it != goal2unit.end(); ++it) { Goal* goal = Goal::GetGoal(it->first); assert(goal); assert(it->first == unit2goal[it->second]); Unit* unit = ai->GetUnit(it->second); assert(unit); } #endif return true; } //////////////////////////////////////////////////////////////////// // utils /// if unitdef is NULL, "assembler" is used float UnitGroupAI::SqDistanceClosestUnit(const float3& pos, int* unit, const UnitDef* unitdef) { float min = 1e30; int found_uid = -1; if (!unitdef) { unitdef = ai->cb->GetUnitDef("assembler"); if (!unitdef) { ailog->error() << "default unitdef \"assembler\" not found in SqDistanceClosestUnit" << std::endl; return -1; } } BOOST_FOREACH(const UnitAISet::value_type& v, units) { int id = v.first; const UnitDef* ud = ai->cb->GetUnitDef(id); const float size = std::max(ud->xsize, ud->zsize)*SQUARE_SIZE; float3 upos = ai->cb->GetUnitPos(id); float3 startpos = random_offset_pos(upos, size*1.5, size*2); float tmp = ai->EstimateSqDistancePF(unitdef, startpos, pos); if (tmp < min && tmp >=0) { min = tmp; found_uid = id; } else if (tmp < 0) { ailog->error() << "can't reach " << pos << " from " << startpos << std::endl; } } if (unit) *unit = found_uid; if (found_uid == -1) min = -1; return min; } /// if unitdef is NULL, "assembler" is used float UnitGroupAI::DistanceClosestUnit(const float3& pos, int* unit, const UnitDef* unitdef) { float min = 1e30; int found_uid = -1; if (!unitdef) { unitdef = ai->cb->GetUnitDef("assembler"); if (!unitdef) { ailog->error() << "default unitdef \"assembler\" not found in SqDistanceClosestUnit" << std::endl; return -1; } } BOOST_FOREACH(const UnitAISet::value_type& v, units) { int id = v.first; const UnitDef* ud = ai->cb->GetUnitDef(id); const float size = std::max(ud->xsize, ud->zsize)*SQUARE_SIZE; float3 upos = ai->cb->GetUnitPos(id); float3 startpos = random_offset_pos(upos, size*1.5, size*2); float tmp = ai->cb->GetPathLength(startpos, pos, unitdef->movedata->pathType); if (tmp < min && tmp >=0) { min = tmp; found_uid = id; } else if (tmp < 0) { ailog->error() << "can't reach " << pos << " from " << startpos << std::endl; } } if (unit) *unit = found_uid; if (found_uid == -1) min = -1; return min; } float3 UnitGroupAI::GetGroupMidPos() { float3 pos(0, 0, 0); if (units.empty()) return pos; for (UnitAISet::iterator it = units.begin(); it != units.end(); ++it) { pos += ai->cb->GetUnitPos(it->first); } pos /= (float)units.size(); return pos; } int UnitGroupAI::GetGroupHealth() { int health = 0; for (UnitAISet::iterator it = units.begin(); it != units.end(); ++it) { health += ai->cb->GetUnitHealth(it->first); } return health; } void UnitGroupAI::TurnTowards(float3 point) { float3 midpos = GetGroupMidPos(); float3 diff = midpos - point; dir = diff; dir.y = 0; dir.ANormalize(); rightdir.x = -dir.z; rightdir.z = dir.x; // TODO move units to the new locations SetupFormation(point); } void UnitGroupAI::MoveTurnTowards(float3 dest, float3 point) { float3 diff = dest - point; dir = diff; dir.y = 0; dir.ANormalize(); rightdir.x = -dir.z; rightdir.z = dir.x; // TODO move units to the new locations SetupFormation(dest); } void UnitGroupAI::SetupFormation(float3 point) { // TODO move to data file const static float aspectRatio = 4.f; const static int spacing = 48; int friends[MAX_UNITS]; int friend_cnt; // perRow ** 2 / aspect ratio = total units perRow = std::ceil(std::sqrt(units.size()*aspectRatio)); ailog->info() << "SetupFormation: perRow = " << perRow << std::endl; // put units like this // front // 3 1 0 2 4 // 8 6 5 7 9 // if there are units on chosen spots, skip that spot and just move units to the destination int i = 0; for (UnitAISet::iterator it = units.begin(); it != units.end(); ++i, ++it) { if (it->second->currentGoalId >= 0) { continue; } int rowPos = i%perRow; int x; if (rowPos & 1) { // odd variant x = -(rowPos % perRow) / 2 - 1; } else { // even x = (rowPos % perRow) / 2; } int y = i/perRow; float3 dest = dir*y*-spacing + rightdir*x*spacing + point; dest.y = ai->GetGroundHeight(dest.x, dest.z); // don't issue a move order if there already is a unit on the destination friend_cnt = ai->cb->GetFriendlyUnits(friends, dest, spacing); if (friend_cnt > 0) { continue; } Goal* g = Goal::GetGoal(Goal::CreateGoal(10, MOVE)); assert(g); g->params.push_back(dest); it->second->AddGoal(g); } } void UnitGroupAI::AttackMoveToSpot(float3 dest) { Goal* g = Goal::GetGoal(Goal::CreateGoal(11, ATTACK)); assert(g); g->params.push_back(dest); g->timeoutFrame = ai->cb->GetCurrentFrame() + 60*GAME_SPEED; AddGoal(g); } void UnitGroupAI::MoveToSpot(float3 dest) { Goal* g = Goal::GetGoal(Goal::CreateGoal(10, MOVE)); assert(g); g->params.push_back(dest); g->timeoutFrame = ai->cb->GetCurrentFrame() + 30*GAME_SPEED; AddGoal(g); }
[ [ [ 1, 545 ] ] ]
bd7fa06d137b1d1af1f4ffd4f21f67da15e36d80
340f8c7e48059a93b16b8c5a2499f3a352f92fe3
/wloo/Message.cpp
cff33d3e3bbf3bdd70c89c6d0e90d80f9348e940
[ "BSD-2-Clause" ]
permissive
silphire/wloo
c93073c6487f0c09e14b5f54206e78e4cb89da1b
7a9b3e2f8cff6e39b8b3416a98e014daebf33800
refs/heads/master
2020-12-30T14:55:44.233574
2011-05-15T22:05:37
2011-05-15T22:05:37
1,686,466
0
1
null
null
null
null
UTF-8
C++
false
false
108
cpp
#include "StdAfx.h" #include "Message.h" Message::Message(void) { } Message::~Message(void) { }
[ [ [ 1, 10 ] ] ]
3e9e31223e36145c4cb13c1643dddf6ee989f1b3
10bac563fc7e174d8f7c79c8777e4eb8460bc49e
/sense/detail/ipc_camera_recv_impl.cpp
df947686327542b2a45f1ca5897cc728abd8298d
[]
no_license
chenbk85/alcordev
41154355a837ebd15db02ecaeaca6726e722892a
bdb9d0928c80315d24299000ca6d8c492808f1d5
refs/heads/master
2021-01-10T13:36:29.338077
2008-10-22T15:57:50
2008-10-22T15:57:50
44,953,286
0
1
null
null
null
null
UTF-8
C++
false
false
2,612
cpp
//boost.interprocess #include <boost/interprocess/shared_memory_object.hpp> #include <boost/interprocess/mapped_region.hpp> using namespace boost::interprocess; //-------------------------------------------------------------------------++ #include "alcor/core/image_info_t.h" #include "alcor/core/ipc_serializable_t.h" #include "alcor/core/ipc_serializable_image.hpp" #include "alcor/core/config_parser_t.h" //-------------------------------------------------------------------------++ class ipc_camera_recv_impl { public: /// ipc_camera_recv_impl()//:_ptr_info(0) { }; /// ~ipc_camera_recv_impl() { }; /// bool open(const std::string& in_name) { all::core::config_parser_t conf; conf.load(all::core::xml,in_name); if (conf.as_int("grabber.cameramode", 1)) { printf("Receiving From Camera ...\n"); } else { printf("Receiving A Video Source ...\n"); } std::string info_obj_tag = conf.as_string("grabber.info_mem_tag", "_ipc_capture_info_"); std::string mem_obj_tag = conf.as_string("grabber.image_mem_tag","_ipc_capture_buffer_"); try { all::core::ipc_serializable_t<all::core::image_info_t> image_info(all::core::open_read,info_obj_tag); image_info_obj = image_info.get_const_reference(); //height_ = image_info.get_const().height; //width_ = image_info.get_const().width; //channels_ = image_info.get_const().channels; //memory_size_ = image_info.get_const().memory_size; //////////////////////////////////////////////////// //all::core::ipc_serializable_t<all::core::byte_image_640_t> // ipc_image(all::core::open_read,"_ipc_dummy_image__"); //////////////////////////////////////////////////// ///Open DATA //Open already created shared memory object. _data_mem.reset( new shared_memory_object (open_only ,mem_obj_tag.c_str() //name ,read_only) ); //Map the whole shared memory in this process _data_region.reset( new mapped_region (*_data_mem.get() //What to map ,read_only ) //Map it as read-only ); } //try_block catch(interprocess_exception &ex){ std::cout << "Unexpected exception: " << ex.what() << std::endl; return false; }//catch block return true; }; /// all::core::image_info_t image_info_obj; /// std::auto_ptr<shared_memory_object> _data_mem; /// std::auto_ptr<mapped_region> _data_region; }; //-------------------------------------------------------------------------++
[ "andrea.carbone@1c7d64d3-9b28-0410-bae3-039769c3cb81" ]
[ [ [ 1, 92 ] ] ]
3da752c897a812af01a5434826d85fab3cd3b256
648a948acfb8e75e1efa968894f13b0889622433
/ttrackdll/ttrackdll.cpp
cb6e1ef7b65f7535e5e88aa01f84de1c2ce7cc5f
[]
no_license
mallowlabs/ttrack
43fe0a7d01055d567456db4f868ceca70a0f1156
957c5b32ad2b0783199018490df08317f22a0ae0
refs/heads/master
2021-01-15T11:43:42.447749
2008-11-20T16:25:41
2008-11-20T16:25:41
78,701
3
2
null
null
null
null
SHIFT_JIS
C++
false
false
140
cpp
// TTrackDLL.cpp : DLL アプリケーション用にエクスポートされる関数を定義します。 // #include "stdafx.h"
[ [ [ 1, 6 ] ] ]
099f9c2715521ea3f96aead4625028837cd28f8f
a2904986c09bd07e8c89359632e849534970c1be
/topcoder/ContestCoordinator.cpp
ca1ee037bf689774cffe9e5941731f0418af8cd8
[]
no_license
naturalself/topcoder_srms
20bf84ac1fd959e9fbbf8b82a93113c858bf6134
7b42d11ac2cc1fe5933c5bc5bc97ee61b6ec55e5
refs/heads/master
2021-01-22T04:36:40.592620
2010-11-29T17:30:40
2010-11-29T17:30:40
444,669
1
0
null
null
null
null
UTF-8
C++
false
false
6,821
cpp
// BEGIN CUT HERE // END CUT HERE #line 5 "ContestCoordinator.cpp" #include <cstdio> #include <cstdlib> #include <cmath> #include <climits> #include <cfloat> #include <map> #include <utility> #include <set> #include <iostream> #include <memory> #include <string> #include <vector> #include <algorithm> #include <numeric> #include <functional> #include <sstream> #include <complex> #include <stack> #include <queue> using namespace std; #define debug(p) cout << #p << "=" << p << endl; #define forv(i, v) for (int i = 0; i < (int)(v.size()); ++i) #define fors(i, s) for (int i = 0; i < (int)(s.length()); ++i) #define all(a) a.begin(), a.end() #define pb push_back class ContestCoordinator { public: double bestAverage(vector <int> sc) { int n =(int)sc.size(); double ret=0.0; sort(all(sc)); for(int i=0;i<n;i++){ vector<int> tar; for(int j=i;j<n-i;j++) tar.pb(sc[j]); double avg = (double)accumulate(all(tar),0)/(double)tar.size(); ret = max(ret,avg); } return ret; } }; // BEGIN CUT HERE namespace moj_harness { int run_test_case(int); void run_test(int casenum = -1, bool quiet = false) { if (casenum != -1) { if (run_test_case(casenum) == -1 && !quiet) { cerr << "Illegal input! Test case " << casenum << " does not exist." << endl; } return; } int correct = 0, total = 0; for (int i=0;; ++i) { int x = run_test_case(i); if (x == -1) { if (i >= 100) break; continue; } correct += x; ++total; } if (total == 0) { cerr << "No test cases run." << endl; } else if (correct < total) { cerr << "Some cases FAILED (passed " << correct << " of " << total << ")." << endl; } else { cerr << "All " << total << " tests passed!" << endl; } } static const double MAX_DOUBLE_ERROR = 1e-9; static bool topcoder_fequ(double expected, double result) { if (isnan(expected)) { return isnan(result); } else if (isinf(expected)) { if (expected > 0) { return result > 0 && isinf(result); } else { return result < 0 && isinf(result); } } else if (isnan(result) || isinf(result)) { return false; } else if (fabs(result - expected) < MAX_DOUBLE_ERROR) { return true; } else { double mmin = min(expected * (1.0 - MAX_DOUBLE_ERROR), expected * (1.0 + MAX_DOUBLE_ERROR)); double mmax = max(expected * (1.0 - MAX_DOUBLE_ERROR), expected * (1.0 + MAX_DOUBLE_ERROR)); return result > mmin && result < mmax; } } double moj_relative_error(double expected, double result) { if (isnan(expected) || isinf(expected) || isnan(result) || isinf(result) || expected == 0) return 0; return fabs(result-expected) / fabs(expected); } int verify_case(int casenum, const double &expected, const double &received, clock_t elapsed) { cerr << "Example " << casenum << "... "; string verdict; vector<string> info; char buf[100]; if (elapsed > CLOCKS_PER_SEC / 200) { sprintf(buf, "time %.2fs", elapsed * (1.0/CLOCKS_PER_SEC)); info.push_back(buf); } if (topcoder_fequ(expected, received)) { verdict = "PASSED"; double rerr = moj_relative_error(expected, received); if (rerr > 0) { sprintf(buf, "relative error %.3e", rerr); info.push_back(buf); } } else { verdict = "FAILED"; } cerr << verdict; if (!info.empty()) { cerr << " ("; for (int i=0; i<(int)info.size(); ++i) { if (i > 0) cerr << ", "; cerr << info[i]; } cerr << ")"; } cerr << endl; if (verdict == "FAILED") { cerr << " Expected: " << expected << endl; cerr << " Received: " << received << endl; } return verdict == "PASSED"; } int run_test_case(int casenum) { switch (casenum) { case 0: { int scores[] = {1}; double expected__ = 1.0; clock_t start__ = clock(); double received__ = ContestCoordinator().bestAverage(vector <int>(scores, scores + (sizeof scores / sizeof scores[0]))); return verify_case(casenum, expected__, received__, clock()-start__); } case 1: { int scores[] = {1,2,3,4}; double expected__ = 2.5; clock_t start__ = clock(); double received__ = ContestCoordinator().bestAverage(vector <int>(scores, scores + (sizeof scores / sizeof scores[0]))); return verify_case(casenum, expected__, received__, clock()-start__); } case 2: { int scores[] = {1,1,999,999,1000,1000}; double expected__ = 999.0; clock_t start__ = clock(); double received__ = ContestCoordinator().bestAverage(vector <int>(scores, scores + (sizeof scores / sizeof scores[0]))); return verify_case(casenum, expected__, received__, clock()-start__); } case 3: { int scores[] = {1,13,8,6,7,9}; double expected__ = 7.5; clock_t start__ = clock(); double received__ = ContestCoordinator().bestAverage(vector <int>(scores, scores + (sizeof scores / sizeof scores[0]))); return verify_case(casenum, expected__, received__, clock()-start__); } case 4: { int scores[] = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}; double expected__ = 1.0; clock_t start__ = clock(); double received__ = ContestCoordinator().bestAverage(vector <int>(scores, scores + (sizeof scores / sizeof scores[0]))); return verify_case(casenum, expected__, received__, clock()-start__); } // custom cases /* case 5: { int scores[] = ; double expected__ = ; clock_t start__ = clock(); double received__ = ContestCoordinator().bestAverage(vector <int>(scores, scores + (sizeof scores / sizeof scores[0]))); return verify_case(casenum, expected__, received__, clock()-start__); }*/ /* case 6: { int scores[] = ; double expected__ = ; clock_t start__ = clock(); double received__ = ContestCoordinator().bestAverage(vector <int>(scores, scores + (sizeof scores / sizeof scores[0]))); return verify_case(casenum, expected__, received__, clock()-start__); }*/ /* case 7: { int scores[] = ; double expected__ = ; clock_t start__ = clock(); double received__ = ContestCoordinator().bestAverage(vector <int>(scores, scores + (sizeof scores / sizeof scores[0]))); return verify_case(casenum, expected__, received__, clock()-start__); }*/ default: return -1; } } } int main(int argc, char *argv[]) { if (argc == 1) { moj_harness::run_test(); } else { for (int i=1; i<argc; ++i) moj_harness::run_test(atoi(argv[i])); } } // END CUT HERE
[ "shin@CF-7AUJ41TT52JO.(none)" ]
[ [ [ 1, 213 ] ] ]
176b39a6851667e98e2ea627a7448dbefc06713c
741b36f4ddf392c4459d777930bc55b966c2111a
/incubator/deeppurple/lwplugins/lwwrapper/XPanel/XInfo.cpp
a12a12c49e6019ace56aa9d90455d70c878d0d2f
[]
no_license
BackupTheBerlios/lwpp-svn
d2e905641f60a7c9ca296d29169c70762f5a9281
fd6f80cbba14209d4ca639f291b1a28a0ed5404d
refs/heads/master
2021-01-17T17:01:31.802187
2005-10-16T22:12:52
2005-10-16T22:12:52
40,805,554
0
0
null
null
null
null
UTF-8
C++
false
false
207
cpp
#include "StdAfx.h" #include "XInfo.h" XInfo::XInfo() { Type="sInfo"; DataType="string"; } void XInfo::Initialize(const char * name, XPanel * owner) { XControl::Initialize(name,owner); }
[ "deeppurple@dac1304f-7ce9-0310-a59f-f2d444f72a61" ]
[ [ [ 1, 13 ] ] ]
11b94232ef1c5a0b602d99c0d004818fefd295d9
23f0b5476178fd850df7064c60dff925cfa6289f
/nachoshotga/code/userprog/rwfile.cc
4a01bc374f2c015b25e53a28a10d79cb1df08995
[]
no_license
kuroyakumo95/nachoshotga
b305780c8806ad33955cc1673f244597429506d3
e37a810eb4e686c22f959d4ce00e12dd8aebead1
refs/heads/master
2021-01-19T08:52:59.910590
2009-05-29T02:58:08
2009-05-29T02:58:08
35,772,907
0
1
null
null
null
null
UTF-8
C++
false
false
1,435
cc
#include "rwfile.h" #include "scexception.h" CRWFile::CRWFile(OpenFile *f) { m_pFile = f; } CRWFile::~CRWFile() { if (m_pFile != NULL) delete m_pFile; } int CRWFile::fClose() { delete m_pFile; m_pFile = NULL; return 0; } int CRWFile::fWrite(int virtAddr, int size) { int irs = 0; int ivA = virtAddr; int isz = size; if (isz < 0){ printf("\n CRWFile:fWrite Error unexpected bytes to write %d",size); return -1; } else if (isz == 0) return 0; char *buf = User2System(ivA,isz); if (buf == NULL || buf == (char*)0) { printf("\n CRWFile:fWrite Error- user memory space empty"); if (buf != NULL) delete buf; return -1; } irs = m_pFile->Write(buf,strlen(buf)); if (irs <= 0) printf("\n fail to write"); delete buf; return irs; } int CRWFile::fRead(int virtAddr,int size) { int irs = 0; int ivA = virtAddr; int isz = size; char *buf = new char[isz +1]; ASSERT(buf != NULL); int ibytesread = m_pFile->Read(buf,isz); if (ibytesread < 0){ printf("\n Error- read fail."); delete buf; return -1; } else if (ibytesread == 0) { delete buf; return 0; } irs = System2User(ivA,ibytesread,buf); if(buf[ibytesread - 1] == EOF) { delete buf; return -2; } delete buf; return irs; }
[ "hotga2801@87b1fc82-3d1b-11de-90e1-f9f1724fc9cc" ]
[ [ [ 1, 87 ] ] ]
1d6a445d606b66989c13473230ccaa222d182e8a
60365cfb5278ec1dfcc07a5b3e07f3c9d680fa2a
/xlview/SettingAbout.cpp
90fce6474c9ddacb260dbbe9833b1d9e9ba59f12
[]
no_license
cyberscorpio/xlview
6c01e96dbf225cfbc2be1cc15a8b70c61976eb46
a4b5088ce049695de2ed7ed191162e6034326381
refs/heads/master
2021-01-01T16:34:47.787022
2011-04-28T13:34:25
2011-04-28T13:34:25
38,444,399
0
0
null
null
null
null
UTF-8
C++
false
false
4,431
cpp
#include <assert.h> #include <utility> #include "libxl/include/Language.h" #include "version.h" #include "resource.h" #include "SettingAbout.h" static const int TAB_PADDING_X = 4; static const int TAB_PADDING_Y = 8; static const int TAB_MARGIN_X = 8; static const int TAB_MARGIN_Y = 12; // static ID and the [link | static] ID // just like the key and value pair static std::pair<UINT, UINT> sLines[] = { std::make_pair(IDC_STATIC_COPYRIGHT, IDC_SYSLINK_COPYRIGHT), std::make_pair(IDC_STATIC_AUTHOR, IDC_STATIC_CYBERSCORPIO), std::make_pair(IDC_STATIC_TWITTER, IDC_SYSLINK_TWITTER), std::make_pair(IDC_STATIC_PROJECT_HOME, IDC_SYSLINK_PROJECT_HOME), std::make_pair(IDC_STATIC_LICENSE, IDC_SYSLINK_LICENSE), std::make_pair(IDC_STATIC_THANKS, IDC_SYSLINK_THANKS), }; CAboutDialog::CAboutDialog () { } CAboutDialog::~CAboutDialog () { } LRESULT CAboutDialog::OnInitDialog (UINT, WPARAM, LPARAM, BOOL &) { xl::CLanguage *pLanguage = xl::CLanguage::getInstance(); xl::tchar text[MAX_PATH]; for (size_t i = 0; i < COUNT_OF(sLines); ++ i) { HWND hWndKey = GetDlgItem(sLines[i].first); assert(hWndKey != NULL); ::GetWindowText(hWndKey, text, MAX_PATH); xl::tstring lang = pLanguage->getString(text); ::SetWindowText(hWndKey, lang); } HWND hWnd = GetDlgItem(IDC_SYSLINK_COPYRIGHT); m_brush4SysLink = (HBRUSH)::SetClassLongPtr(hWnd, GCL_HBRBACKGROUND, (LONG_PTR)::GetStockObject(NULL_BRUSH)); hWnd = GetDlgItem(IDC_STATIC_VERSION); assert(hWnd); _stprintf_s(text, MAX_PATH, _T("xlview 1.0.0.%s (r%s)"), xlview_revision, xlview_revision); ::SetWindowText(hWnd, text); return TRUE; } LRESULT CAboutDialog::OnDestroy (UINT, WPARAM, LPARAM, BOOL &bHandled) { HWND hWnd = GetDlgItem(IDC_SYSLINK_COPYRIGHT); assert(hWnd != NULL); ::SetClassLongPtr(hWnd, GCL_HBRBACKGROUND, (LONG_PTR)m_brush4SysLink); bHandled = false; return 0; } LRESULT CAboutDialog::OnNotify (UINT, WPARAM, LPARAM lParam, BOOL &bHandled) { LPNMHDR lpnmh = (LPNMHDR)lParam; assert(lpnmh != NULL); switch (lpnmh->code) { case NM_CLICK: case NM_RETURN: { PNMLINK pNMLink = (PNMLINK)lpnmh; LITEM item = pNMLink->item; ::ShellExecute(NULL, _T("open"), item.szUrl, NULL, NULL, SW_SHOW); break; } break; default: bHandled = false; break; } return 0; } LRESULT CAboutDialog::OnSize (UINT, WPARAM, LPARAM, BOOL &) { CRect rc; GetClientRect(&rc); rc.DeflateRect(TAB_PADDING_X, TAB_PADDING_Y); int x = rc.left + TAB_MARGIN_X; int y = rc.top + TAB_MARGIN_Y; int keyWidth = (rc.Width() - TAB_MARGIN_X * 3) / 3; int valueWidth = rc.Width() - TAB_MARGIN_X * 3 - keyWidth; for (size_t i = 0; i < COUNT_OF(sLines); ++ i) { HWND hWndKey = GetDlgItem(sLines[i].first); HWND hWndValue = GetDlgItem(sLines[i].second); assert(hWndKey && hWndValue); CRect rcKey, rcValue; ::GetWindowRect(hWndKey, &rcKey); ::GetWindowRect(hWndValue, &rcValue); // make syslink the same height as the static control rcValue.bottom = rcValue.top + rcKey.bottom - rcKey.top; // has no hurt, but if we don't make the same height above, the below code make sense int lineHeight = max(rcKey.Height(), rcValue.Height()); int offsetKeyY = (lineHeight - rcKey.Height()) / 2; int offsetValueY = (lineHeight - rcValue.Height()) / 2; ::MoveWindow(hWndKey, x, y + offsetKeyY, keyWidth, rcKey.Height(), TRUE); ::MoveWindow(hWndValue, x + keyWidth + TAB_MARGIN_X, y + offsetValueY, valueWidth, rcValue.Height(), TRUE); y += lineHeight + TAB_MARGIN_Y; } HWND hWndVersion = GetDlgItem(IDC_STATIC_VERSION); if (hWndVersion) { CRect rcVersion; ::GetWindowRect(hWndVersion, &rcVersion); y = rc.bottom - TAB_MARGIN_Y - rcVersion.Height(); rcVersion.MoveToXY(x, y); ::MoveWindow(hWndVersion, x, y, rc.Width() - TAB_MARGIN_X * 2, rcVersion.Height(), true); y += TAB_MARGIN_Y + rcVersion.Height(); } return 0; } LRESULT CAboutDialog::OnCommand (UINT, WPARAM, LPARAM, BOOL &bHandled) { bHandled = false; return 0; } LRESULT CAboutDialog::OnEraseBkGnd (UINT, WPARAM, LPARAM, BOOL &) { return TRUE; } LRESULT CAboutDialog::OnCtlColorStatic (UINT, WPARAM wParam, LPARAM, BOOL &) { HDC hdc = (HDC)wParam; ::SetBkMode(hdc, TRANSPARENT); return (LRESULT)::GetStockObject(NULL_BRUSH); }
[ [ [ 1, 144 ] ] ]
60883b29510f6e87b35f585a54d1390c66be2536
881321ed22c5c024aa515e0f152b7f9cc7d1decd
/Pathman/StageConfig.h
19c6b17e547ae65744e9a400a7e9a6704d047d62
[]
no_license
titarenko/Pathman
c37f756c08a1473fc0df561f303942cde97e1d90
1c998f57b02576574c48943734fcc0e22e9a63c3
refs/heads/master
2020-05-19T08:02:44.881983
2011-04-01T20:13:39
2011-04-01T20:13:39
3,443,429
0
0
null
null
null
null
UTF-8
C++
false
false
818
h
#pragma once #include "Config.h" #include "EStageType.h" #include "EGameEvent.h" class Game; class StageConfig : Config { public: StageConfig(Game* game, const irr::io::path& filename, const irr::core::stringw& nodeName); ~StageConfig(void); /*! When any of these events is happened stage should be started (activated). */ irr::core::array<E_GAME_EVENT> ActivationEvents; /*! Event that should be broadcasted when stage has been deactivated (finished). */ E_GAME_EVENT DefaultDeactivationEvent; irr::video::ITexture* BackgroundTexture; irr::u32 FadeTime; irr::io::path BackgroundSoundFilename; bool LoopBackgroundSound; private: irr::core::stringw _nodeName; /*! Implementation of Config. */ void OnNode(const irr::core::stringw& name); };
[ [ [ 1, 41 ] ] ]
3358281dc31c9c84667221b0b9cb825df9630b35
672d939ad74ccb32afe7ec11b6b99a89c64a6020
/Graph/FloatLevel/FloatLevel.h
42386ee10dfd324c466d040ffe2c7be205030e13
[]
no_license
cloudlander/legacy
a073013c69e399744de09d649aaac012e17da325
89acf51531165a29b35e36f360220eeca3b0c1f6
refs/heads/master
2022-04-22T14:55:37.354762
2009-04-11T13:51:56
2009-04-11T13:51:56
256,939,313
1
0
null
null
null
null
UTF-8
C++
false
false
1,411
h
// FloatLevel.h : main header file for the FLOATLEVEL application // #if !defined(AFX_FLOATLEVEL_H__3B28E263_04AE_4A29_81C4_347229B81C4D__INCLUDED_) #define AFX_FLOATLEVEL_H__3B28E263_04AE_4A29_81C4_347229B81C4D__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #ifndef __AFXWIN_H__ #error include 'stdafx.h' before including this file for PCH #endif #include "resource.h" // main symbols ///////////////////////////////////////////////////////////////////////////// // CFloatLevelApp: // See FloatLevel.cpp for the implementation of this class // class CFloatLevelApp : public CWinApp { public: CFloatLevelApp(); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CFloatLevelApp) public: virtual BOOL InitInstance(); //}}AFX_VIRTUAL // Implementation public: //{{AFX_MSG(CFloatLevelApp) afx_msg void OnAppAbout(); // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_FLOATLEVEL_H__3B28E263_04AE_4A29_81C4_347229B81C4D__INCLUDED_)
[ "xmzhang@5428276e-be0b-f542-9301-ee418ed919ad" ]
[ [ [ 1, 51 ] ] ]
9be04468bd96eee0b21ab74479731f513fcf83a4
353bd39ba7ae46ed521936753176ed17ea8546b5
/src/layer2_support/python/test/axpy_test.cpp
00aaa214d865d5ff6330a5d3799cf467bd1d5684
[]
no_license
d0n3val/axe-engine
1a13e8eee0da667ac40ac4d92b6a084ab8a910e8
320b08df3a1a5254b776c81775b28fa7004861dc
refs/heads/master
2021-01-01T19:46:39.641648
2007-12-10T18:26:22
2007-12-10T18:26:22
32,251,179
1
0
null
null
null
null
UTF-8
C++
false
false
2,420
cpp
/** * @file * Axe 'python' test code * @see axe_python.h */ #include "axpy_test.h" #define AXPY_NO_AUTOLINK #include "axe_python.h" /// Version of this test code #define AXE_PYTHON_TEST_VERSION 1 // Use proper library -------- #ifdef _DEBUG #pragma comment( lib, "../../../output_debug/lib/axe_python.lib" ) #else #pragma comment( lib, "../../../output_release/lib/axe_python.lib" ) #endif /** * Checks for the current 'error' state of the library */ void error( int num, const char* file, long line ) { printf( "\n\n\n*** ERROR in %s(%u): %s\n", file, line, axpy_get_error_message(num) ); getchar(); } /** * Checks if this code and the lib have the same version */ int check_versions() { printf( "\nGetting lib version ... " ); int lib_version = axpy_get( AXPY_VERSION ); if( lib_version != AXE_PYTHON_TEST_VERSION ) { printf( "This test program and the library versions differ! Lib:%d Test:%d\n", lib_version, AXE_PYTHON_TEST_VERSION ); getchar(); return( 0 ); } printf( "Library Version: %d - This testing program: %d\n\n", lib_version, AXE_PYTHON_TEST_VERSION ); return( 1 ); } /** * Simple code to test all functionality of the library */ int main() { printf( "Axe 'python' library test STARTED\n" ); // Check versions ------------------------------------ if( check_versions() == 0 ) { return( 0 ); } axpy_init(); // Start --------------------------------------------- getchar(); // Test ---------------------------------------------- printf( "\nExecuting print 'hello world'...\n" ); axpy_exec( "print 'hello world'" ); // Test ---------------------------------------------- printf( "\nLoading script_test.py and executing foo() function...\n" ); if( axpy_load_file( "script_test", "foo" ) == AXE_FALSE ) { printf( "\nFAIL\n" ); axpy_finalize(); return( 0 ); } // Test ---------------------------------------------- printf( "\nExecuting function 'foo()' included in script_test.py, should print 'Im foo from test.py'\n" ); axpy_exec( "import script_test\nfoo()" ); // Finish -------------------------------------------- axpy_finalize(); printf( "\nAxe 'python' library test FINISHED\n" ); getchar(); return( 1 ); } /* $Id: axpl_test.cpp,v 1.1 2004/07/27 22:42:49 doneval Exp $ */
[ "d0n3val@2cff7946-3f3c-0410-b79f-f9b517ddbf54" ]
[ [ [ 1, 97 ] ] ]
b3dff017e4b5dc3897eec451f3c41dcf8a8c44e6
4be39d7d266a00f543cf89bcf5af111344783205
/test_boost_futures/n2561_future.hpp
a48b0b54ac9346433ca7cdc16c38f722ba8bd8a0
[]
no_license
nkzxw/lastigen-haustiere
6316bb56b9c065a52d7c7edb26131633423b162a
bdf6219725176ae811c1063dd2b79c2d51b4bb6a
refs/heads/master
2021-01-10T05:42:05.591510
2011-02-03T14:59:11
2011-02-03T14:59:11
47,530,529
1
0
null
null
null
null
UTF-8
C++
false
false
38,375
hpp
// (C) Copyright 2008 Anthony Williams // // 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 N2561_FUTURE_HPP #define N2561_FUTURE_HPP #include <stdexcept> #include <boost/thread/detail/move.hpp> #include <boost/thread/thread_time.hpp> #include <boost/exception_ptr.hpp> #include <boost/shared_ptr.hpp> #include <boost/scoped_ptr.hpp> #include <boost/type_traits/is_fundamental.hpp> #include <boost/type_traits/is_convertible.hpp> #include <boost/mpl/if.hpp> #include <boost/config.hpp> #include <algorithm> #include <boost/function.hpp> #include <boost/bind.hpp> #include <boost/ref.hpp> #include <boost/scoped_array.hpp> #include <boost/utility/enable_if.hpp> #include <list> #include <boost/next_prior.hpp> namespace jss { class future_uninitialized: public std::logic_error { public: future_uninitialized(): std::logic_error("Future Uninitialized") {} }; class broken_promise: public std::logic_error { public: broken_promise(): std::logic_error("Broken promise") {} }; class future_already_retrieved: public std::logic_error { public: future_already_retrieved(): std::logic_error("Future already retrieved") {} }; class promise_already_satisfied: public std::logic_error { public: promise_already_satisfied(): std::logic_error("Promise already satisfied") {} }; class task_already_started: public std::logic_error { public: task_already_started(): std::logic_error("Task already started") {} }; class task_moved: public std::logic_error { public: task_moved(): std::logic_error("Task moved") {} }; namespace future_state { enum state { uninitialized, waiting, ready, moved }; } namespace detail { struct future_object_base { boost::exception_ptr exception; bool done; boost::mutex mutex; boost::condition_variable waiters; typedef std::list<boost::condition_variable_any*> waiter_list; waiter_list external_waiters; boost::function<void()> callback; future_object_base(): done(false) {} virtual ~future_object_base() {} waiter_list::iterator register_external_waiter(boost::condition_variable_any& cv) { boost::unique_lock<boost::mutex> lock(mutex); do_callback(lock); return external_waiters.insert(external_waiters.end(),&cv); } void remove_external_waiter(waiter_list::iterator it) { boost::lock_guard<boost::mutex> lock(mutex); external_waiters.erase(it); } void mark_finished_internal() { done=true; waiters.notify_all(); for(waiter_list::const_iterator it=external_waiters.begin(), end=external_waiters.end();it!=end;++it) { (*it)->notify_all(); } } struct relocker { boost::unique_lock<boost::mutex>& lock; relocker(boost::unique_lock<boost::mutex>& lock_): lock(lock_) { lock.unlock(); } ~relocker() { lock.lock(); } }; void do_callback(boost::unique_lock<boost::mutex>& lock) { if(callback && !done) { boost::function<void()> local_callback=callback; relocker relock(lock); local_callback(); } } void wait(bool rethrow=true) { boost::unique_lock<boost::mutex> lock(mutex); do_callback(lock); while(!done) { waiters.wait(lock); } if(rethrow && exception) { boost::rethrow_exception(exception); } } bool timed_wait_until(boost::system_time const& target_time) { boost::unique_lock<boost::mutex> lock(mutex); do_callback(lock); while(!done) { bool const success=waiters.timed_wait(lock,target_time); if(!success && !done) { return false; } } return true; } void mark_exceptional_finish_internal(boost::exception_ptr const& e) { exception=e; mark_finished_internal(); } void mark_exceptional_finish() { boost::lock_guard<boost::mutex> lock(mutex); mark_exceptional_finish_internal(boost::current_exception()); } bool has_value() { boost::lock_guard<boost::mutex> lock(mutex); return done && !exception; } bool has_exception() { boost::lock_guard<boost::mutex> lock(mutex); return done && exception; } template<typename F,typename U> void set_wait_callback(F f,U* u) { callback=boost::bind(f,boost::ref(*u)); } private: future_object_base(future_object_base const&); future_object_base& operator=(future_object_base const&); }; template<typename T> struct future_traits { typedef boost::scoped_ptr<T> storage_type; #ifdef BOOST_HAS_RVALUE_REFS typedef T const& source_reference_type; struct dummy; typedef typename boost::mpl::if_<boost::is_fundamental<T>,dummy&,T&&>::type rvalue_source_type; typedef typename boost::mpl::if_<boost::is_fundamental<T>,T,T&&>::type move_dest_type; #else typedef T& source_reference_type; typedef typename boost::mpl::if_<boost::is_convertible<T&,boost::detail::thread_move_t<T> >,boost::detail::thread_move_t<T>,T const&>::type rvalue_source_type; typedef typename boost::mpl::if_<boost::is_convertible<T&,boost::detail::thread_move_t<T> >,boost::detail::thread_move_t<T>,T>::type move_dest_type; #endif static void init(storage_type& storage,source_reference_type t) { storage.reset(new T(t)); } static void init(storage_type& storage,rvalue_source_type t) { storage.reset(new T(static_cast<rvalue_source_type>(t))); } static void cleanup(storage_type& storage) { storage.reset(); } }; template<typename T> struct future_traits<T&> { typedef T* storage_type; typedef T& source_reference_type; struct rvalue_source_type {}; typedef T& move_dest_type; static void init(storage_type& storage,T& t) { storage=&t; } static void cleanup(storage_type& storage) { storage=0; } }; template<> struct future_traits<void> { typedef bool storage_type; typedef void move_dest_type; static void init(storage_type& storage) { storage=true; } static void cleanup(storage_type& storage) { storage=false; } }; template<typename T> struct future_object: detail::future_object_base { typedef typename future_traits<T>::storage_type storage_type; typedef typename future_traits<T>::source_reference_type source_reference_type; typedef typename future_traits<T>::rvalue_source_type rvalue_source_type; typedef typename future_traits<T>::move_dest_type move_dest_type; storage_type result; future_object(): result(0) {} void mark_finished_with_result_internal(source_reference_type result_) { future_traits<T>::init(result,result_); mark_finished_internal(); } void mark_finished_with_result_internal(rvalue_source_type result_) { future_traits<T>::init(result,static_cast<rvalue_source_type>(result_)); mark_finished_internal(); } void mark_finished_with_result(source_reference_type result_) { boost::lock_guard<boost::mutex> lock(mutex); mark_finished_with_result_internal(result_); } void mark_finished_with_result(rvalue_source_type result_) { boost::lock_guard<boost::mutex> lock(mutex); mark_finished_with_result_internal(result_); } move_dest_type get() { wait(); return *result; } future_state::state get_state() { boost::lock_guard<boost::mutex> guard(mutex); if(!done) { return future_state::waiting; } else { return future_state::ready; } } private: future_object(future_object const&); future_object& operator=(future_object const&); }; template<> struct future_object<void>: detail::future_object_base { future_object() {} void mark_finished_with_result_internal() { mark_finished_internal(); } void mark_finished_with_result() { boost::lock_guard<boost::mutex> lock(mutex); mark_finished_with_result_internal(); } void get() { wait(); } future_state::state get_state() { boost::lock_guard<boost::mutex> guard(mutex); if(!done) { return future_state::waiting; } else { return future_state::ready; } } private: future_object(future_object const&); future_object& operator=(future_object const&); }; class future_waiter { struct registered_waiter { boost::shared_ptr<detail::future_object_base> future; detail::future_object_base::waiter_list::iterator wait_iterator; unsigned index; registered_waiter(boost::shared_ptr<detail::future_object_base> const& future_, detail::future_object_base::waiter_list::iterator wait_iterator_, unsigned index_): future(future_),wait_iterator(wait_iterator_),index(index_) {} }; struct all_futures_lock { unsigned count; boost::scoped_array<boost::unique_lock<boost::mutex> > locks; all_futures_lock(std::vector<registered_waiter>& futures): count(futures.size()),locks(new boost::unique_lock<boost::mutex>[count]) { for(unsigned i=0;i<count;++i) { locks[i]=boost::unique_lock<boost::mutex>(futures[i].future->mutex); } } void lock() { boost::lock(locks.get(),locks.get()+count); } void unlock() { for(unsigned i=0;i<count;++i) { locks[i].unlock(); } } }; boost::condition_variable_any cv; std::vector<registered_waiter> futures; unsigned future_count; public: future_waiter(): future_count(0) {} template<typename F> void add(F& f) { if(f.future) { futures.push_back(registered_waiter(f.future,f.future->register_external_waiter(cv),future_count)); } ++future_count; } unsigned wait() { all_futures_lock lk(futures); for(;;) { for(unsigned i=0;i<futures.size();++i) { if(futures[i].future->done) { return futures[i].index; } } cv.wait(lk); } } ~future_waiter() { for(unsigned i=0;i<futures.size();++i) { futures[i].future->remove_external_waiter(futures[i].wait_iterator); } } }; } template <typename R> class unique_future; template <typename R> class shared_future; template<typename T> struct is_future_type { BOOST_STATIC_CONSTANT(bool, value=false); }; template<typename T> struct is_future_type<unique_future<T> > { BOOST_STATIC_CONSTANT(bool, value=true); }; template<typename T> struct is_future_type<shared_future<T> > { BOOST_STATIC_CONSTANT(bool, value=true); }; template<typename Iterator> typename boost::disable_if<is_future_type<Iterator>,void>::type wait_for_all(Iterator begin,Iterator end) { for(Iterator current=begin;current!=end;++current) { current->wait(); } } template<typename F1,typename F2> typename boost::enable_if<is_future_type<F1>,void>::type wait_for_all(F1& f1,F2& f2) { f1.wait(); f2.wait(); } template<typename F1,typename F2,typename F3> void wait_for_all(F1& f1,F2& f2,F3& f3) { f1.wait(); f2.wait(); f3.wait(); } template<typename F1,typename F2,typename F3,typename F4> void wait_for_all(F1& f1,F2& f2,F3& f3,F4& f4) { f1.wait(); f2.wait(); f3.wait(); f4.wait(); } template<typename F1,typename F2,typename F3,typename F4,typename F5> void wait_for_all(F1& f1,F2& f2,F3& f3,F4& f4,F5& f5) { f1.wait(); f2.wait(); f3.wait(); f4.wait(); f5.wait(); } template<typename Iterator> typename boost::disable_if<is_future_type<Iterator>,Iterator>::type wait_for_any(Iterator begin,Iterator end) { detail::future_waiter waiter; for(Iterator current=begin;current!=end;++current) { waiter.add(*current); } return boost::next(begin,waiter.wait()); } template<typename F1,typename F2> typename boost::enable_if<is_future_type<F1>,unsigned>::type wait_for_any(F1& f1,F2& f2) { detail::future_waiter waiter; waiter.add(f1); waiter.add(f2); return waiter.wait(); } template<typename F1,typename F2,typename F3> unsigned wait_for_any(F1& f1,F2& f2,F3& f3) { detail::future_waiter waiter; waiter.add(f1); waiter.add(f2); waiter.add(f3); return waiter.wait(); } template<typename F1,typename F2,typename F3,typename F4> unsigned wait_for_any(F1& f1,F2& f2,F3& f3,F4& f4) { detail::future_waiter waiter; waiter.add(f1); waiter.add(f2); waiter.add(f3); waiter.add(f4); return waiter.wait(); } template<typename F1,typename F2,typename F3,typename F4,typename F5> unsigned wait_for_any(F1& f1,F2& f2,F3& f3,F4& f4,F5& f5) { detail::future_waiter waiter; waiter.add(f1); waiter.add(f2); waiter.add(f3); waiter.add(f4); waiter.add(f5); return waiter.wait(); } template <typename R> class promise; template <typename R> class packaged_task; template <typename R> class unique_future { unique_future(unique_future & rhs);// = delete; unique_future& operator=(unique_future& rhs);// = delete; typedef boost::shared_ptr<detail::future_object<R> > future_ptr; future_ptr future; friend class shared_future<R>; friend class promise<R>; friend class packaged_task<R>; friend class detail::future_waiter; typedef typename detail::future_traits<R>::move_dest_type move_dest_type; unique_future(future_ptr future_): future(future_) {} public: typedef future_state::state state; unique_future() {} ~unique_future() {} #ifdef BOOST_HAS_RVALUE_REFS unique_future(unique_future && other) { future.swap(other.future); } unique_future& operator=(unique_future && other) { future=other.future; other.future.reset(); return *this; } #else unique_future(boost::detail::thread_move_t<unique_future> other): future(other->future) { other->future.reset(); } unique_future& operator=(boost::detail::thread_move_t<unique_future> other) { future=other->future; other->future.reset(); return *this; } operator boost::detail::thread_move_t<unique_future>() { return boost::detail::thread_move_t<unique_future>(*this); } #endif void swap(unique_future& other) { future.swap(other.future); } // retrieving the value move_dest_type get() { if(!future) { throw future_uninitialized(); } return future->get(); } // functions to check state, and wait for ready state get_state() const { if(!future) { return future_state::uninitialized; } return future->get_state(); } bool is_ready() const { return get_state()==future_state::ready; } bool has_exception() const { return future && future->has_exception(); } bool has_value() const { return future && future->has_value(); } void wait() const { if(!future) { throw future_uninitialized(); } future->wait(false); } template<typename Duration> bool timed_wait(Duration const& rel_time) const { return timed_wait_until(boost::get_system_time()+rel_time); } bool timed_wait_until(boost::system_time const& abs_time) const { if(!future) { throw future_uninitialized(); } return future->timed_wait_until(abs_time); } }; template <typename R> class shared_future { typedef boost::shared_ptr<detail::future_object<R> > future_ptr; future_ptr future; // shared_future(const unique_future<R>& other); // shared_future& operator=(const unique_future<R>& other); friend class detail::future_waiter; friend class promise<R>; friend class packaged_task<R>; shared_future(future_ptr future_): future(future_) {} public: shared_future(shared_future const& other): future(other.future) {} typedef future_state::state state; shared_future() {} ~shared_future() {} shared_future& operator=(shared_future const& other) { future=other.future; return *this; } #ifdef BOOST_HAS_RVALUE_REFS shared_future(shared_future && other) { future.swap(other.future); } shared_future(unique_future<R> && other) { future.swap(other.future); } shared_future& operator=(shared_future && other) { future.swap(other.future); other.future.reset(); return *this; } shared_future& operator=(unique_future<R> && other) { future.swap(other.future); other.future.reset(); return *this; } #else shared_future(boost::detail::thread_move_t<shared_future> other): future(other->future) { other->future.reset(); } // shared_future(const unique_future<R> &) = delete; shared_future(boost::detail::thread_move_t<unique_future<R> > other): future(other->future) { other->future.reset(); } shared_future& operator=(boost::detail::thread_move_t<shared_future> other) { future.swap(other->future); other->future.reset(); return *this; } shared_future& operator=(boost::detail::thread_move_t<unique_future<R> > other) { future.swap(other->future); other->future.reset(); return *this; } operator boost::detail::thread_move_t<shared_future>() { return boost::detail::thread_move_t<shared_future>(*this); } #endif void swap(shared_future& other) { future.swap(other.future); } // retrieving the value R get() { if(!future) { throw future_uninitialized(); } return future->get(); } // functions to check state, and wait for ready state get_state() const { if(!future) { return future_state::uninitialized; } return future->get_state(); } bool is_ready() const { return get_state()==future_state::ready; } bool has_exception() const { return future && future->has_exception(); } bool has_value() const { return future && future->has_value(); } void wait() const { if(!future) { throw future_uninitialized(); } future->wait(false); } template<typename Duration> bool timed_wait(Duration const& rel_time) const { return timed_wait_until(boost::get_system_time()+rel_time); } bool timed_wait_until(boost::system_time const& abs_time) const { if(!future) { throw future_uninitialized(); } return future->timed_wait_until(abs_time); } }; template <typename R> class promise { typedef boost::shared_ptr<detail::future_object<R> > future_ptr; future_ptr future; bool future_obtained; promise(promise & rhs);// = delete; promise & operator=(promise & rhs);// = delete; void lazy_init() { if(!future) { future_obtained=false; future.reset(new detail::future_object<R>); } } public: // template <class Allocator> explicit promise(Allocator a); promise(): future(),future_obtained(false) {} ~promise() { if(future) { boost::lock_guard<boost::mutex> lock(future->mutex); if(!future->done) { future->mark_exceptional_finish_internal(boost::copy_exception(broken_promise())); } } } // Assignment #ifdef BOOST_HAS_RVALUE_REFS promise(promise && rhs): future_obtained(rhs.future_obtained) { future.swap(rhs.future); } promise & operator=(promise&& rhs) { future.swap(rhs.future); future_obtained=rhs.future_obtained; rhs.future.reset(); return *this; } #else promise(boost::detail::thread_move_t<promise> rhs): future(rhs->future),future_obtained(rhs->future_obtained) { rhs->future.reset(); } promise & operator=(boost::detail::thread_move_t<promise> rhs) { future=rhs->future; future_obtained=rhs->future_obtained; rhs->future.reset(); return *this; } operator boost::detail::thread_move_t<promise>() { return boost::detail::thread_move_t<promise>(*this); } #endif void swap(promise& other) { future.swap(other.future); std::swap(future_obtained,other.future_obtained); } // Result retrieval unique_future<R> get_future() { lazy_init(); if(future_obtained) { throw future_already_retrieved(); } future_obtained=true; return unique_future<R>(future); } void set_value(typename detail::future_traits<R>::source_reference_type r) { lazy_init(); boost::lock_guard<boost::mutex> lock(future->mutex); if(future->done) { throw promise_already_satisfied(); } future->mark_finished_with_result_internal(r); } // void set_value(R && r); void set_value(typename detail::future_traits<R>::rvalue_source_type r) { lazy_init(); boost::lock_guard<boost::mutex> lock(future->mutex); if(future->done) { throw promise_already_satisfied(); } future->mark_finished_with_result_internal(static_cast<typename detail::future_traits<R>::rvalue_source_type>(r)); } void set_exception(boost::exception_ptr p) { lazy_init(); boost::lock_guard<boost::mutex> lock(future->mutex); if(future->done) { throw promise_already_satisfied(); } future->mark_exceptional_finish_internal(p); } template<typename F> void set_wait_callback(F f) { lazy_init(); future->set_wait_callback(f,this); } }; template <> class promise<void> { typedef boost::shared_ptr<detail::future_object<void> > future_ptr; future_ptr future; bool future_obtained; promise(promise & rhs);// = delete; promise & operator=(promise & rhs);// = delete; void lazy_init() { if(!future) { future_obtained=false; future.reset(new detail::future_object<void>); } } public: // template <class Allocator> explicit promise(Allocator a); promise(): future(),future_obtained(false) {} ~promise() { if(future) { boost::lock_guard<boost::mutex> lock(future->mutex); if(!future->done) { future->mark_exceptional_finish_internal(boost::copy_exception(broken_promise())); } } } // Assignment #ifdef BOOST_HAS_RVALUE_REFS promise(promise && rhs): future_obtained(rhs.future_obtained) { future.swap(rhs.future); } promise & operator=(promise&& rhs) { future.swap(rhs.future); future_obtained=rhs.future_obtained; rhs.future.reset(); return *this; } #else promise(boost::detail::thread_move_t<promise> rhs): future(rhs->future),future_obtained(rhs->future_obtained) { rhs->future.reset(); } promise & operator=(boost::detail::thread_move_t<promise> rhs) { future=rhs->future; future_obtained=rhs->future_obtained; rhs->future.reset(); return *this; } operator boost::detail::thread_move_t<promise>() { return boost::detail::thread_move_t<promise>(*this); } #endif void swap(promise& other) { future.swap(other.future); std::swap(future_obtained,other.future_obtained); } // Result retrieval unique_future<void> get_future() { lazy_init(); if(future_obtained) { throw future_already_retrieved(); } future_obtained=true; return unique_future<void>(future); } void set_value() { lazy_init(); boost::lock_guard<boost::mutex> lock(future->mutex); if(future->done) { throw promise_already_satisfied(); } future->mark_finished_with_result_internal(); } void set_exception(boost::exception_ptr p) { lazy_init(); boost::lock_guard<boost::mutex> lock(future->mutex); if(future->done) { throw promise_already_satisfied(); } future->mark_exceptional_finish_internal(p); } template<typename F> void set_wait_callback(F f) { lazy_init(); future->set_wait_callback(f,this); } }; namespace detail { template<typename R> struct task_base: detail::future_object<R> { bool started; task_base(): started(false) {} void run() { { boost::lock_guard<boost::mutex> lk(this->mutex); if(started) { throw task_already_started(); } started=true; } do_run(); } void owner_destroyed() { boost::lock_guard<boost::mutex> lk(this->mutex); if(!started) { started=true; this->mark_exceptional_finish_internal(boost::copy_exception(jss::broken_promise())); } } virtual void do_run()=0; }; template<typename R,typename F> struct task_object: task_base<R> { F f; task_object(F const& f_): f(f_) {} task_object(boost::detail::thread_move_t<F> f_): f(f_) {} void do_run() { try { this->mark_finished_with_result(f()); } catch(...) { this->mark_exceptional_finish(); } } }; template<typename F> struct task_object<void,F>: task_base<void> { F f; task_object(F const& f_): f(f_) {} task_object(boost::detail::thread_move_t<F> f_): f(f_) {} void do_run() { try { f(); this->mark_finished_with_result(); } catch(...) { this->mark_exceptional_finish(); } } }; } template<typename R> class packaged_task { boost::shared_ptr<detail::task_base<R> > task; bool future_obtained; packaged_task(packaged_task&);// = delete; packaged_task& operator=(packaged_task&);// = delete; public: packaged_task(): future_obtained(false) {} // construction and destruction template <class F> explicit packaged_task(F const& f): task(new detail::task_object<R,F>(f)),future_obtained(false) {} explicit packaged_task(R(*f)()): task(new detail::task_object<R,R(*)()>(f)),future_obtained(false) {} template <class F> explicit packaged_task(boost::detail::thread_move_t<F> f): task(new detail::task_object<R,F>(f)),future_obtained(false) {} // template <class F, class Allocator> // explicit packaged_task(F const& f, Allocator a); // template <class F, class Allocator> // explicit packaged_task(F&& f, Allocator a); ~packaged_task() { if(task) { task->owner_destroyed(); } } // assignment #ifdef BOOST_HAS_RVALUE_REFS packaged_task(packaged_task&& other): future_obtained(other.future_obtained) { task.swap(other.task); other.future_obtained=false; } packaged_task& operator=(packaged_task&& other) { packaged_task temp(static_cast<packaged_task&&>(other)); swap(temp); return *this; } #else packaged_task(boost::detail::thread_move_t<packaged_task> other): future_obtained(other->future_obtained) { task.swap(other->task); other->future_obtained=false; } packaged_task& operator=(boost::detail::thread_move_t<packaged_task> other) { packaged_task temp(other); swap(temp); return *this; } operator boost::detail::thread_move_t<packaged_task>() { return boost::detail::thread_move_t<packaged_task>(*this); } #endif void swap(packaged_task& other) { task.swap(other.task); std::swap(future_obtained,other.future_obtained); } // result retrieval unique_future<R> get_future() { if(!task) { throw task_moved(); } else if(!future_obtained) { future_obtained=true; return unique_future<R>(task); } else { throw future_already_retrieved(); } } // execution void operator()() { if(!task) { throw task_moved(); } task->run(); } template<typename F> void set_wait_callback(F f) { task->set_wait_callback(f,this); } }; } #endif
[ "fpelliccioni@c29dda52-a065-11de-a33f-1de61d9b9616" ]
[ [ [ 1, 1363 ] ] ]