blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
sequencelengths
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
sequencelengths
1
16
author_lines
sequencelengths
1
16
905b9c790b853704f8b4d6cb21ecc242bca2f8ed
b08e948c33317a0a67487e497a9afbaf17b0fc4c
/Display/GeometryHelper.h
8f8bcab4e6c373ed1791daf12e2bc0409b103f08
[]
no_license
15831944/bastionlandscape
e1acc932f6b5a452a3bd94471748b0436a96de5d
c8008384cf4e790400f9979b5818a5a3806bd1af
refs/heads/master
2023-03-16T03:28:55.813938
2010-05-21T15:00:07
2010-05-21T15:00:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,059
h
#ifndef __GEOMETRYHELPER_H__ #define __GEOMETRYHELPER_H__ #include "../Core/Core.h" #include "../Core/Octree.h" #include "../Display/Display.h" namespace ElixirEngine { //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- struct GeometryHelperVertex { static VertexElement s_VertexElement[4]; Vector3 m_f3Position; Vector3 m_f3Normal; Vector2 m_f2UV; }; struct GeometryHelperVertexColor { static VertexElement s_VertexElement[5]; Vector3 m_f3Position; Vector3 m_f3Normal; Vector2 m_f2UV; Vector4 m_f4Color; }; //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- class DisplayGeometrySphere : public DisplayObject, public OctreeObject { public: struct CreateInfo { Vector4 m_f4Color; Vector3 m_f3Pos; Vector3 m_f3Rot; Vector3 m_f3Radius; UInt m_uHorizSlices; // for one hemisphere UInt m_uVertSlices; bool m_bTopHemisphere; bool m_bBottomHemisphere; bool m_bViewFromInside; }; typedef CreateInfo* CreateInfoPtr; typedef CreateInfo& CreateInfoRef; public: DisplayGeometrySphere(OctreeRef _rOctree); virtual ~DisplayGeometrySphere(); virtual bool Create(const boost::any& _rConfig); virtual void Update(); virtual void Release(); virtual void RenderBegin(); virtual void Render(); virtual bool RayIntersect(const Vector3& _f3RayBegin, const Vector3& _f3RayEnd, Vector3& _f3Intersect); protected: bool CreateBuffers(CreateInfoRef _rInfo); bool FillVertexBuffer(CreateInfoRef _rInfo); bool FillIndexBuffer(CreateInfoRef _rInfo); bool CreateBoundingMesh(CreateInfoRef _rInfo); protected: Vector4 m_f4Color; WordPtr m_pIndex16; UIntPtr m_pIndex32; GeometryHelperVertexPtr m_pVertex; Key m_uVertexBuffer; Key m_uIndexBuffer; UInt m_uVertexCount; UInt m_uIndexCount; UInt m_uFanToStripSize; }; //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- class DisplayGeometryLineManager : public DisplayObject { public: struct CreateInfo { Vector3 m_f3Pos; Vector3 m_f3Rot; }; typedef CreateInfo* CreateInfoPtr; typedef CreateInfo& CreateInfoRef; struct LineStripInfo { GeometryHelperVertexColorVec m_vVertexBuffer; UIntVec m_vIndexBuffer; }; typedef LineStripInfo* LineStripInfoPtr; typedef LineStripInfo& LineStripInfoRef; typedef vector<LineStripInfo> LineStripInfoVec; typedef vector<LineStripInfoPtr> LineStripInfoPtrVec; public: DisplayGeometryLineManager(); virtual ~DisplayGeometryLineManager(); virtual bool Create(const boost::any& _rConfig); virtual void Update(); virtual void Release(); virtual void RenderBegin(); virtual void Render(); virtual void RenderEnd(); LineStripInfoRef NewLineStrip(); void NewTriangle(const Vector3& _f3Point0, const Vector3& _f3Point1, const Vector3& _f3Point2, const Vector4& _f4Color); void NewAABB(const Vector3& _f3TopRightFar, const Vector3& _f3BottomLeftNear, const Vector4& _f4Color); void NewBoundingMesh(DisplayObject::BoundingMeshRef _rBoundingMesh, const Vector4& _f4Color); protected: LineStripInfoPtrVec m_vLineStrips; Key m_uVertDecl; UInt m_uCurrentLineStripIndex; }; } #endif // __GEOMETRYHELPER_H__
[ "voodoohaust@97c0069c-804f-11de-81da-11cc53ed4329" ]
[ [ [ 1, 134 ] ] ]
904586240650b047bd09fed45b5b23bf782b1f18
2b80036db6f86012afcc7bc55431355fc3234058
/src/core/ThreadHelper.h
f4b7d7d80118fb73a4599cc9abc4a32d02a15865
[ "BSD-3-Clause" ]
permissive
leezhongshan/musikcube
d1e09cf263854bb16acbde707cb6c18b09a0189f
e7ca6a5515a5f5e8e499bbdd158e5cb406fda948
refs/heads/master
2021-01-15T11:45:29.512171
2011-02-25T14:09:21
2011-02-25T14:09:21
null
0
0
null
null
null
null
ISO-8859-9
C++
false
false
2,496
h
////////////////////////////////////////////////////////////////////////////// // // License Agreement: // // The following are Copyright © 2008, Daniel Önnerby // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the author nor the names of other contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////////// #pragma once #include <core/config.h> #include <boost/thread/mutex.hpp> #include <boost/thread/condition.hpp> namespace musik{ namespace core{ class ThreadHelper{ public: ThreadHelper(void); virtual ~ThreadHelper(void); virtual void Exit(); boost::mutex exitMutex; protected: bool Exited(); void NotificationWait(); void NotificationTimedWait(const boost::xtime &oTime); void Notify(); bool bExit; // boost::mutex oNotificationMutex; boost::condition notify; }; } }
[ "onnerby@6a861d04-ae47-0410-a6da-2d49beace72e", "urioxis@6a861d04-ae47-0410-a6da-2d49beace72e" ]
[ [ [ 1, 45 ], [ 47, 67 ] ], [ [ 46, 46 ] ] ]
6950c48fa0eef9df0322ef2aa964c46c1a2cb9cb
b7c505dcef43c0675fd89d428e45f3c2850b124f
/Src/Modules/BehaviorControl/BH2009BehaviorControl/Symbols/BH2009TeamSymbols.h
883511deed071f880e204a54e6178a05a65f7c50
[ "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,062
h
/** * \file BH2009TeamSymbols.h * Implementation of symbols for TeamMateData. * \author Colin Graf */ #ifndef __BH2009TeamSymbols_h_ #define __BH2009TeamSymbols_h_ #include "../../Symbols.h" #include "Representations/Infrastructure/RobotInfo.h" #include "Representations/Infrastructure/FrameInfo.h" #include "Representations/Infrastructure/TeamMateData.h" #include "Representations/Modeling/BallModel.h" #include "Representations/Configuration/FieldDimensions.h" /** * \class BH2009TeamSymbols * The Xabsl symbols that are defined in "team_symbols.xabsl" * \author Colin Graf */ class BH2009TeamSymbols : public Symbols { public: /** * Constructor. * \param robotInfo A reference to the RobotInfo. * \param robotPose A reference to the RobotPose. * \param ballModel A reference to the BallModel. * \param teamMateData A refernece to the TeamMateData. * \param fieldDimensions A reference to the FieldDimensions. * \param frameInfo a reference to the FrameInfo. * \param behaviorData A reference to the BehaviorData. */ BH2009TeamSymbols( const RobotInfo& robotInfo, const RobotPose& robotPose, const BallModel& ballModel, const TeamMateData& teamMateData, const FieldDimensions& fieldDimensions, const FrameInfo& frameInfo, const BehaviorData& behaviorData) : robotInfo(robotInfo), ballModel(ballModel), robotPose(robotPose), teamMateData(teamMateData), fieldDimensions(fieldDimensions), frameInfo(frameInfo), behaviorData(behaviorData) { theInstance = this; } PROCESS_WIDE_STORAGE_STATIC BH2009TeamSymbols* theInstance; const static int networkTimeout = 2000; /** registers the symbols at an engine */ void registerSymbols(xabsl::Engine& engine); /** updates the symbols */ void update() {}; static Vector2<double> staticComputeBallPositionAllPlayers() { return theInstance->computeBallPositionAllPlayers();} private: double getBallDistance(); double distanceTo(); double getBallAngle(); double getBallX(); double getBallY(); double getBallPositionFieldX(); double getBallPositionFieldY(); double getLocatorPoseX(); double getLocatorPoseY(); double getLocatorPoseAngle(); double getConnectedPlayers(); int getFirstTeamMate(); int getSecondTeamMate(); bool getLostConnection(); int getRole(); int getAction(); bool isTeamAttacking(); double getBallDistanceAllPlayers(); double getBallDistanceTeamMateAllPlayers(); double getBallPositionAllPlayersX(); double getBallPositionAllPlayersY(); Vector2<double> computeBallPositionAllPlayers(); // data sources const RobotInfo& robotInfo; const BallModel& ballModel; const RobotPose& robotPose; const TeamMateData& teamMateData; const FieldDimensions& fieldDimensions; const FrameInfo& frameInfo; const BehaviorData& behaviorData; // symbol parameter int player; double xPosition; double yPosition; // static symbol provider functions for the xabsl engine static double staticGetBallDistance() { return theInstance->getBallDistance(); }; static double staticDistanceTo() { return theInstance->distanceTo(); }; static double staticGetBallAngle() { return theInstance->getBallAngle(); }; static double staticGetBallX() { return theInstance->getBallX(); }; static double staticGetBallY() { return theInstance->getBallY(); }; static double staticGetBallPositionFieldX() { return theInstance->getBallPositionFieldX(); }; static double staticGetBallPositionFieldY() { return theInstance->getBallPositionFieldY(); }; static double staticGetLocatorPoseX() { return theInstance->getLocatorPoseX(); }; static double staticGetLocatorPoseY() { return theInstance->getLocatorPoseY(); }; static double staticGetLocatorPoseAngle() { return theInstance->getLocatorPoseAngle(); }; static double staticGetConnectedPlayers() { return theInstance->getConnectedPlayers(); } static int staticGetFirstTeamMate() { return theInstance->getFirstTeamMate(); } static int staticGetSecondTeamMate() { return theInstance->getSecondTeamMate(); } static bool staticGetLostConnection() { return theInstance->getLostConnection(); } static int staticGetRole() { return theInstance->getRole(); } static int staticGetAction() { return theInstance->getAction(); } static bool staticIsTeamAttacking() { return theInstance->isTeamAttacking(); } static double staticGetBallDistanceAllPlayers() { return theInstance->getBallDistanceAllPlayers(); } static double staticGetBallPositionAllPlayersX() { return theInstance->getBallPositionAllPlayersX(); } static double staticGetBallPositionAllPlayersY() { return theInstance->getBallPositionAllPlayersY(); } static double staticGetBallDistanceTeamMateAllPlayers() { return theInstance->getBallDistanceTeamMateAllPlayers(); } friend class BH2009SoccerSymbols; friend class BH2009RoleSymbols; }; #endif // __BH2009TeamSymbols_h_
[ "alon@rogue.(none)" ]
[ [ [ 1, 135 ] ] ]
04b0bae71027a2a7651b5063a0a87d58271ec04f
f177993b13e97f9fecfc0e751602153824dfef7e
/ImPro/ImProFilters/TouchLibFilter/Touchlib/include/HighpassFilter.h
428c9fac04cfda2a8492f7c4e1fd7b6e03bcbf31
[]
no_license
svn2github/imtophooksln
7bd7412947d6368ce394810f479ebab1557ef356
bacd7f29002135806d0f5047ae47cbad4c03f90e
refs/heads/master
2020-05-20T04:00:56.564124
2010-09-24T09:10:51
2010-09-24T09:10:51
11,787,598
1
0
null
null
null
null
UTF-8
C++
false
false
724
h
#ifndef __TOUCHSCREEN_FILTER_HIGHPASS__ #define __TOUCHSCREEN_FILTER_HIGHPASS__ #include <TouchlibFilter.h> class HighpassFilter : public Filter { public: HighpassFilter(char*); virtual ~HighpassFilter(); void kernel(); void kernelWithROI(); virtual void getParameters(ParameterMap& pMap); virtual void setParameter(const char *name, const char *value); virtual void showOutput(bool value, int windowx, int windowy); private: int filterLevel; int filterLevel_slider; int scale; int scale_slider; IplConvKernel* element; IplConvKernel* element2; IplImage* outra; IplImage* outra2; bool noErodeDialate; }; #endif // __TOUCHSCREEN_FILTER_HIGHPASS__
[ "ndhumuscle@fa729b96-8d43-11de-b54f-137c5e29c83a" ]
[ [ [ 1, 39 ] ] ]
28bdbc58f524fb06da7062ee044b7f6f55dc391f
e09dfcc817c731587fd756f7611aacb19b17018a
/FilterLog/inc/DocManagerEx.h
f4ae764b2b7fe80a0af5ab7fca777511c7ab4b8f
[]
no_license
jweitzen/analogqct
cb77f50f2682ee46325cafd738fcf1299d2710aa
535bcf32fd615815d640b06c860cfec9acb7f983
refs/heads/master
2021-01-10T09:31:14.808743
2009-06-12T16:46:03
2009-06-12T16:46:03
50,674,838
0
0
null
null
null
null
UTF-8
C++
false
false
469
h
// CDocManagerEx class declaration // class CDocManagerEx : public CDocManager { DECLARE_DYNAMIC(CDocManagerEx) // Construction public: CDocManagerEx(); // Attributes public: // Operations public: // Overrides // helper for standard commdlg dialogs virtual BOOL DoPromptFileName(CString& fileName, UINT nIDSTitle, DWORD lFlags, BOOL bOpenFileDialog, CDocTemplate* pTemplate); // Implementation public: virtual ~CDocManagerEx(); };
[ "giulio.inbox@6d061dfa-575b-11de-9a1b-6103e4980ab8" ]
[ [ [ 1, 26 ] ] ]
dc8e3385690ce156a53bf38aed1162b6979cafe5
0922bf0d76bdd99c086a66c701640f8538cee7a9
/ext/rqr/QR_Encode.cpp
2e85637135bd6486020327e666257f8c59415eb6
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
contentfree/rqr
ded0479ccc4ca71a0f7f969f4e910025e1e81489
2b33afa3690e7f8f36f36a0e20a54c80d3fa5172
refs/heads/master
2021-01-15T17:02:38.144856
2011-02-17T00:42:55
2011-02-17T00:42:55
1,376,332
2
2
null
null
null
null
UTF-8
C++
false
false
64,437
cpp
//// QR_Encode.cpp : CQR_Encode クラス インプリメンテーション ファイル //// Date 2006/05/17 Ver. 1.12 [Class Ver.1.21] Psytec Inc. // //#include "stdafx.h" #include "QR_Encode.h" //#ifdef _DEBUG //#define new DEBUG_NEW //#undef THIS_FILE //static char THIS_FILE[] = __FILE__; //#endif ///////////////////////////////////////////////////////////////////////////// // QRコードバージョン(型番)情報 static QR_VERSIONINFO QR_VersonInfo[] = {{0}, // (ダミー:Ver.0) { 1, // Ver.1 26, 19, 16, 13, 9, 0, 0, 0, 0, 0, 0, 0, 1, 26, 19, 1, 26, 16, 1, 26, 13, 1, 26, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, { 2, // Ver.2 44, 34, 28, 22, 16, 1, 18, 0, 0, 0, 0, 0, 1, 44, 34, 1, 44, 28, 1, 44, 22, 1, 44, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, { 3, // Ver.3 70, 55, 44, 34, 26, 1, 22, 0, 0, 0, 0, 0, 1, 70, 55, 1, 70, 44, 2, 35, 17, 2, 35, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, { 4, // Ver.4 100, 80, 64, 48, 36, 1, 26, 0, 0, 0, 0, 0, 1, 100, 80, 2, 50, 32, 2, 50, 24, 4, 25, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, { 5, // Ver.5 134, 108, 86, 62, 46, 1, 30, 0, 0, 0, 0, 0, 1, 134, 108, 2, 67, 43, 2, 33, 15, 2, 33, 11, 0, 0, 0, 0, 0, 0, 2, 34, 16, 2, 34, 12}, { 6, // Ver.6 172, 136, 108, 76, 60, 1, 34, 0, 0, 0, 0, 0, 2, 86, 68, 4, 43, 27, 4, 43, 19, 4, 43, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, { 7, // Ver.7 196, 156, 124, 88, 66, 2, 22, 38, 0, 0, 0, 0, 2, 98, 78, 4, 49, 31, 2, 32, 14, 4, 39, 13, 0, 0, 0, 0, 0, 0, 4, 33, 15, 1, 40, 14}, { 8, // Ver.8 242, 194, 154, 110, 86, 2, 24, 42, 0, 0, 0, 0, 2, 121, 97, 2, 60, 38, 4, 40, 18, 4, 40, 14, 0, 0, 0, 2, 61, 39, 2, 41, 19, 2, 41, 15}, { 9, // Ver.9 292, 232, 182, 132, 100, 2, 26, 46, 0, 0, 0, 0, 2, 146, 116, 3, 58, 36, 4, 36, 16, 4, 36, 12, 0, 0, 0, 2, 59, 37, 4, 37, 17, 4, 37, 13}, {10, // Ver.10 346, 274, 216, 154, 122, 2, 28, 50, 0, 0, 0, 0, 2, 86, 68, 4, 69, 43, 6, 43, 19, 6, 43, 15, 2, 87, 69, 1, 70, 44, 2, 44, 20, 2, 44, 16}, {11, // Ver.11 404, 324, 254, 180, 140, 2, 30, 54, 0, 0, 0, 0, 4, 101, 81, 1, 80, 50, 4, 50, 22, 3, 36, 12, 0, 0, 0, 4, 81, 51, 4, 51, 23, 8, 37, 13}, {12, // Ver.12 466, 370, 290, 206, 158, 2, 32, 58, 0, 0, 0, 0, 2, 116, 92, 6, 58, 36, 4, 46, 20, 7, 42, 14, 2, 117, 93, 2, 59, 37, 6, 47, 21, 4, 43, 15}, {13, // Ver.13 532, 428, 334, 244, 180, 2, 34, 62, 0, 0, 0, 0, 4, 133, 107, 8, 59, 37, 8, 44, 20, 12, 33, 11, 0, 0, 0, 1, 60, 38, 4, 45, 21, 4, 34, 12}, {14, // Ver.14 581, 461, 365, 261, 197, 3, 26, 46, 66, 0, 0, 0, 3, 145, 115, 4, 64, 40, 11, 36, 16, 11, 36, 12, 1, 146, 116, 5, 65, 41, 5, 37, 17, 5, 37, 13}, {15, // Ver.15 655, 523, 415, 295, 223, 3, 26, 48, 70, 0, 0, 0, 5, 109, 87, 5, 65, 41, 5, 54, 24, 11, 36, 12, 1, 110, 88, 5, 66, 42, 7, 55, 25, 7, 37, 13}, {16, // Ver.16 733, 589, 453, 325, 253, 3, 26, 50, 74, 0, 0, 0, 5, 122, 98, 7, 73, 45, 15, 43, 19, 3, 45, 15, 1, 123, 99, 3, 74, 46, 2, 44, 20, 13, 46, 16}, {17, // Ver.17 815, 647, 507, 367, 283, 3, 30, 54, 78, 0, 0, 0, 1, 135, 107, 10, 74, 46, 1, 50, 22, 2, 42, 14, 5, 136, 108, 1, 75, 47, 15, 51, 23, 17, 43, 15}, {18, // Ver.18 901, 721, 563, 397, 313, 3, 30, 56, 82, 0, 0, 0, 5, 150, 120, 9, 69, 43, 17, 50, 22, 2, 42, 14, 1, 151, 121, 4, 70, 44, 1, 51, 23, 19, 43, 15}, {19, // Ver.19 991, 795, 627, 445, 341, 3, 30, 58, 86, 0, 0, 0, 3, 141, 113, 3, 70, 44, 17, 47, 21, 9, 39, 13, 4, 142, 114, 11, 71, 45, 4, 48, 22, 16, 40, 14}, {20, // Ver.20 1085, 861, 669, 485, 385, 3, 34, 62, 90, 0, 0, 0, 3, 135, 107, 3, 67, 41, 15, 54, 24, 15, 43, 15, 5, 136, 108, 13, 68, 42, 5, 55, 25, 10, 44, 16}, {21, // Ver.21 1156, 932, 714, 512, 406, 4, 28, 50, 72, 94, 0, 0, 4, 144, 116, 17, 68, 42, 17, 50, 22, 19, 46, 16, 4, 145, 117, 0, 0, 0, 6, 51, 23, 6, 47, 17}, {22, // Ver.22 1258, 1006, 782, 568, 442, 4, 26, 50, 74, 98, 0, 0, 2, 139, 111, 17, 74, 46, 7, 54, 24, 34, 37, 13, 7, 140, 112, 0, 0, 0, 16, 55, 25, 0, 0, 0}, {23, // Ver.23 1364, 1094, 860, 614, 464, 4, 30, 54, 78, 102, 0, 0, 4, 151, 121, 4, 75, 47, 11, 54, 24, 16, 45, 15, 5, 152, 122, 14, 76, 48, 14, 55, 25, 14, 46, 16}, {24, // Ver.24 1474, 1174, 914, 664, 514, 4, 28, 54, 80, 106, 0, 0, 6, 147, 117, 6, 73, 45, 11, 54, 24, 30, 46, 16, 4, 148, 118, 14, 74, 46, 16, 55, 25, 2, 47, 17}, {25, // Ver.25 1588, 1276, 1000, 718, 538, 4, 32, 58, 84, 110, 0, 0, 8, 132, 106, 8, 75, 47, 7, 54, 24, 22, 45, 15, 4, 133, 107, 13, 76, 48, 22, 55, 25, 13, 46, 16}, {26, // Ver.26 1706, 1370, 1062, 754, 596, 4, 30, 58, 86, 114, 0, 0, 10, 142, 114, 19, 74, 46, 28, 50, 22, 33, 46, 16, 2, 143, 115, 4, 75, 47, 6, 51, 23, 4, 47, 17}, {27, // Ver.27 1828, 1468, 1128, 808, 628, 4, 34, 62, 90, 118, 0, 0, 8, 152, 122, 22, 73, 45, 8, 53, 23, 12, 45, 15, 4, 153, 123, 3, 74, 46, 26, 54, 24, 28, 46, 16}, {28, // Ver.28 1921, 1531, 1193, 871, 661, 5, 26, 50, 74, 98, 122, 0, 3, 147, 117, 3, 73, 45, 4, 54, 24, 11, 45, 15, 10, 148, 118, 23, 74, 46, 31, 55, 25, 31, 46, 16}, {29, // Ver.29 2051, 1631, 1267, 911, 701, 5, 30, 54, 78, 102, 126, 0, 7, 146, 116, 21, 73, 45, 1, 53, 23, 19, 45, 15, 7, 147, 117, 7, 74, 46, 37, 54, 24, 26, 46, 16}, {30, // Ver.30 2185, 1735, 1373, 985, 745, 5, 26, 52, 78, 104, 130, 0, 5, 145, 115, 19, 75, 47, 15, 54, 24, 23, 45, 15, 10, 146, 116, 10, 76, 48, 25, 55, 25, 25, 46, 16}, {31, // Ver.31 2323, 1843, 1455, 1033, 793, 5, 30, 56, 82, 108, 134, 0, 13, 145, 115, 2, 74, 46, 42, 54, 24, 23, 45, 15, 3, 146, 116, 29, 75, 47, 1, 55, 25, 28, 46, 16}, {32, // Ver.32 2465, 1955, 1541, 1115, 845, 5, 34, 60, 86, 112, 138, 0, 17, 145, 115, 10, 74, 46, 10, 54, 24, 19, 45, 15, 0, 0, 0, 23, 75, 47, 35, 55, 25, 35, 46, 16}, {33, // Ver.33 2611, 2071, 1631, 1171, 901, 5, 30, 58, 86, 114, 142, 0, 17, 145, 115, 14, 74, 46, 29, 54, 24, 11, 45, 15, 1, 146, 116, 21, 75, 47, 19, 55, 25, 46, 46, 16}, {34, // Ver.34 2761, 2191, 1725, 1231, 961, 5, 34, 62, 90, 118, 146, 0, 13, 145, 115, 14, 74, 46, 44, 54, 24, 59, 46, 16, 6, 146, 116, 23, 75, 47, 7, 55, 25, 1, 47, 17}, {35, // Ver.35 2876, 2306, 1812, 1286, 986, 6, 30, 54, 78, 102, 126, 150, 12, 151, 121, 12, 75, 47, 39, 54, 24, 22, 45, 15, 7, 152, 122, 26, 76, 48, 14, 55, 25, 41, 46, 16}, {36, // Ver.36 3034, 2434, 1914, 1354, 1054, 6, 24, 50, 76, 102, 128, 154, 6, 151, 121, 6, 75, 47, 46, 54, 24, 2, 45, 15, 14, 152, 122, 34, 76, 48, 10, 55, 25, 64, 46, 16}, {37, // Ver.37 3196, 2566, 1992, 1426, 1096, 6, 28, 54, 80, 106, 132, 158, 17, 152, 122, 29, 74, 46, 49, 54, 24, 24, 45, 15, 4, 153, 123, 14, 75, 47, 10, 55, 25, 46, 46, 16}, {38, // Ver.38 3362, 2702, 2102, 1502, 1142, 6, 32, 58, 84, 110, 136, 162, 4, 152, 122, 13, 74, 46, 48, 54, 24, 42, 45, 15, 18, 153, 123, 32, 75, 47, 14, 55, 25, 32, 46, 16}, {39, // Ver.39 3532, 2812, 2216, 1582, 1222, 6, 26, 54, 82, 110, 138, 166, 20, 147, 117, 40, 75, 47, 43, 54, 24, 10, 45, 15, 4, 148, 118, 7, 76, 48, 22, 55, 25, 67, 46, 16}, {40, // Ver.40 3706, 2956, 2334, 1666, 1276, 6, 30, 58, 86, 114, 142, 170, 19, 148, 118, 18, 75, 47, 34, 54, 24, 20, 45, 15, 6, 149, 119, 31, 76, 48, 34, 55, 25, 61, 46, 16} }; ///////////////////////////////////////////////////////////////////////////// // GF(2^8)α指数→整数変換テーブル static BYTE byExpToInt[] = { 1, 2, 4, 8, 16, 32, 64, 128, 29, 58, 116, 232, 205, 135, 19, 38, 76, 152, 45, 90, 180, 117, 234, 201, 143, 3, 6, 12, 24, 48, 96, 192, 157, 39, 78, 156, 37, 74, 148, 53, 106, 212, 181, 119, 238, 193, 159, 35, 70, 140, 5, 10, 20, 40, 80, 160, 93, 186, 105, 210, 185, 111, 222, 161, 95, 190, 97, 194, 153, 47, 94, 188, 101, 202, 137, 15, 30, 60, 120, 240, 253, 231, 211, 187, 107, 214, 177, 127, 254, 225, 223, 163, 91, 182, 113, 226, 217, 175, 67, 134, 17, 34, 68, 136, 13, 26, 52, 104, 208, 189, 103, 206, 129, 31, 62, 124, 248, 237, 199, 147, 59, 118, 236, 197, 151, 51, 102, 204, 133, 23, 46, 92, 184, 109, 218, 169, 79, 158, 33, 66, 132, 21, 42, 84, 168, 77, 154, 41, 82, 164, 85, 170, 73, 146, 57, 114, 228, 213, 183, 115, 230, 209, 191, 99, 198, 145, 63, 126, 252, 229, 215, 179, 123, 246, 241, 255, 227, 219, 171, 75, 150, 49, 98, 196, 149, 55, 110, 220, 165, 87, 174, 65, 130, 25, 50, 100, 200, 141, 7, 14, 28, 56, 112, 224, 221, 167, 83, 166, 81, 162, 89, 178, 121, 242, 249, 239, 195, 155, 43, 86, 172, 69, 138, 9, 18, 36, 72, 144, 61, 122, 244, 245, 247, 243, 251, 235, 203, 139, 11, 22, 44, 88, 176, 125, 250, 233, 207, 131, 27, 54, 108, 216, 173, 71, 142, 1}; ///////////////////////////////////////////////////////////////////////////// // GF(2^8)α整数→指数変換テーブル static BYTE byIntToExp[] = { 0, 0, 1, 25, 2, 50, 26, 198, 3, 223, 51, 238, 27, 104, 199, 75, 4, 100, 224, 14, 52, 141, 239, 129, 28, 193, 105, 248, 200, 8, 76, 113, 5, 138, 101, 47, 225, 36, 15, 33, 53, 147, 142, 218, 240, 18, 130, 69, 29, 181, 194, 125, 106, 39, 249, 185, 201, 154, 9, 120, 77, 228, 114, 166, 6, 191, 139, 98, 102, 221, 48, 253, 226, 152, 37, 179, 16, 145, 34, 136, 54, 208, 148, 206, 143, 150, 219, 189, 241, 210, 19, 92, 131, 56, 70, 64, 30, 66, 182, 163, 195, 72, 126, 110, 107, 58, 40, 84, 250, 133, 186, 61, 202, 94, 155, 159, 10, 21, 121, 43, 78, 212, 229, 172, 115, 243, 167, 87, 7, 112, 192, 247, 140, 128, 99, 13, 103, 74, 222, 237, 49, 197, 254, 24, 227, 165, 153, 119, 38, 184, 180, 124, 17, 68, 146, 217, 35, 32, 137, 46, 55, 63, 209, 91, 149, 188, 207, 205, 144, 135, 151, 178, 220, 252, 190, 97, 242, 86, 211, 171, 20, 42, 93, 158, 132, 60, 57, 83, 71, 109, 65, 162, 31, 45, 67, 216, 183, 123, 164, 118, 196, 23, 73, 236, 127, 12, 111, 246, 108, 161, 59, 82, 41, 157, 85, 170, 251, 96, 134, 177, 187, 204, 62, 90, 203, 89, 95, 176, 156, 169, 160, 81, 11, 245, 22, 235, 122, 117, 44, 215, 79, 174, 213, 233, 230, 231, 173, 232, 116, 214, 244, 234, 168, 80, 88, 175}; ///////////////////////////////////////////////////////////////////////////// // 誤り訂正生成多項式α係数 static BYTE byRSExp7[] = {87, 229, 146, 149, 238, 102, 21}; static BYTE byRSExp10[] = {251, 67, 46, 61, 118, 70, 64, 94, 32, 45}; static BYTE byRSExp13[] = { 74, 152, 176, 100, 86, 100, 106, 104, 130, 218, 206, 140, 78}; static BYTE byRSExp15[] = { 8, 183, 61, 91, 202, 37, 51, 58, 58, 237, 140, 124, 5, 99, 105}; static BYTE byRSExp16[] = {120, 104, 107, 109, 102, 161, 76, 3, 91, 191, 147, 169, 182, 194, 225, 120}; static BYTE byRSExp17[] = { 43, 139, 206, 78, 43, 239, 123, 206, 214, 147, 24, 99, 150, 39, 243, 163, 136}; static BYTE byRSExp18[] = {215, 234, 158, 94, 184, 97, 118, 170, 79, 187, 152, 148, 252, 179, 5, 98, 96, 153}; static BYTE byRSExp20[] = { 17, 60, 79, 50, 61, 163, 26, 187, 202, 180, 221, 225, 83, 239, 156, 164, 212, 212, 188, 190}; static BYTE byRSExp22[] = {210, 171, 247, 242, 93, 230, 14, 109, 221, 53, 200, 74, 8, 172, 98, 80, 219, 134, 160, 105, 165, 231}; static BYTE byRSExp24[] = {229, 121, 135, 48, 211, 117, 251, 126, 159, 180, 169, 152, 192, 226, 228, 218, 111, 0, 117, 232, 87, 96, 227, 21}; static BYTE byRSExp26[] = {173, 125, 158, 2, 103, 182, 118, 17, 145, 201, 111, 28, 165, 53, 161, 21, 245, 142, 13, 102, 48, 227, 153, 145, 218, 70}; static BYTE byRSExp28[] = {168, 223, 200, 104, 224, 234, 108, 180, 110, 190, 195, 147, 205, 27, 232, 201, 21, 43, 245, 87, 42, 195, 212, 119, 242, 37, 9, 123}; static BYTE byRSExp30[] = { 41, 173, 145, 152, 216, 31, 179, 182, 50, 48, 110, 86, 239, 96, 222, 125, 42, 173, 226, 193, 224, 130, 156, 37, 251, 216, 238, 40, 192, 180}; static BYTE byRSExp32[] = { 10, 6, 106, 190, 249, 167, 4, 67, 209, 138, 138, 32, 242, 123, 89, 27, 120, 185, 80, 156, 38, 69, 171, 60, 28, 222, 80, 52, 254, 185, 220, 241}; static BYTE byRSExp34[] = {111, 77, 146, 94, 26, 21, 108, 19, 105, 94, 113, 193, 86, 140, 163, 125, 58, 158, 229, 239, 218, 103, 56, 70, 114, 61, 183, 129, 167, 13, 98, 62, 129, 51}; static BYTE byRSExp36[] = {200, 183, 98, 16, 172, 31, 246, 234, 60, 152, 115, 0, 167, 152, 113, 248, 238, 107, 18, 63, 218, 37, 87, 210, 105, 177, 120, 74, 121, 196, 117, 251, 113, 233, 30, 120}; static BYTE byRSExp38[] = {159, 34, 38, 228, 230, 59, 243, 95, 49, 218, 176, 164, 20, 65, 45, 111, 39, 81, 49, 118, 113, 222, 193, 250, 242, 168, 217, 41, 164, 247, 177, 30, 238, 18, 120, 153, 60, 193}; static BYTE byRSExp40[] = { 59, 116, 79, 161, 252, 98, 128, 205, 128, 161, 247, 57, 163, 56, 235, 106, 53, 26, 187, 174, 226, 104, 170, 7, 175, 35, 181, 114, 88, 41, 47, 163, 125, 134, 72, 20, 232, 53, 35, 15}; static BYTE byRSExp42[] = {250, 103, 221, 230, 25, 18, 137, 231, 0, 3, 58, 242, 221, 191, 110, 84, 230, 8, 188, 106, 96, 147, 15, 131, 139, 34, 101, 223, 39, 101, 213, 199, 237, 254, 201, 123, 171, 162, 194, 117, 50, 96}; static BYTE byRSExp44[] = {190, 7, 61, 121, 71, 246, 69, 55, 168, 188, 89, 243, 191, 25, 72, 123, 9, 145, 14, 247, 1, 238, 44, 78, 143, 62, 224, 126, 118, 114, 68, 163, 52, 194, 217, 147, 204, 169, 37, 130, 113, 102, 73, 181}; static BYTE byRSExp46[] = {112, 94, 88, 112, 253, 224, 202, 115, 187, 99, 89, 5, 54, 113, 129, 44, 58, 16, 135, 216, 169, 211, 36, 1, 4, 96, 60, 241, 73, 104, 234, 8, 249, 245, 119, 174, 52, 25, 157, 224, 43, 202, 223, 19, 82, 15}; static BYTE byRSExp48[] = {228, 25, 196, 130, 211, 146, 60, 24, 251, 90, 39, 102, 240, 61, 178, 63, 46, 123, 115, 18, 221, 111, 135, 160, 182, 205, 107, 206, 95, 150, 120, 184, 91, 21, 247, 156, 140, 238, 191, 11, 94, 227, 84, 50, 163, 39, 34, 108}; static BYTE byRSExp50[] = {232, 125, 157, 161, 164, 9, 118, 46, 209, 99, 203, 193, 35, 3, 209, 111, 195, 242, 203, 225, 46, 13, 32, 160, 126, 209, 130, 160, 242, 215, 242, 75, 77, 42, 189, 32, 113, 65, 124, 69, 228, 114, 235, 175, 124, 170, 215, 232, 133, 205}; static BYTE byRSExp52[] = {116, 50, 86, 186, 50, 220, 251, 89, 192, 46, 86, 127, 124, 19, 184, 233, 151, 215, 22, 14, 59, 145, 37, 242, 203, 134, 254, 89, 190, 94, 59, 65, 124, 113, 100, 233, 235, 121, 22, 76, 86, 97, 39, 242, 200, 220, 101, 33, 239, 254, 116, 51}; static BYTE byRSExp54[] = {183, 26, 201, 87, 210, 221, 113, 21, 46, 65, 45, 50, 238, 184, 249, 225, 102, 58, 209, 218, 109, 165, 26, 95, 184, 192, 52, 245, 35, 254, 238, 175, 172, 79, 123, 25, 122, 43, 120, 108, 215, 80, 128, 201, 235, 8, 153, 59, 101, 31, 198, 76, 31, 156}; static BYTE byRSExp56[] = {106, 120, 107, 157, 164, 216, 112, 116, 2, 91, 248, 163, 36, 201, 202, 229, 6, 144, 254, 155, 135, 208, 170, 209, 12, 139, 127, 142, 182, 249, 177, 174, 190, 28, 10, 85, 239, 184, 101, 124, 152, 206, 96, 23, 163, 61, 27, 196, 247, 151, 154, 202, 207, 20, 61, 10}; static BYTE byRSExp58[] = { 82, 116, 26, 247, 66, 27, 62, 107, 252, 182, 200, 185, 235, 55, 251, 242, 210, 144, 154, 237, 176, 141, 192, 248, 152, 249, 206, 85, 253, 142, 65, 165, 125, 23, 24, 30, 122, 240, 214, 6, 129, 218, 29, 145, 127, 134, 206, 245, 117, 29, 41, 63, 159, 142, 233, 125, 148, 123}; static BYTE byRSExp60[] = {107, 140, 26, 12, 9, 141, 243, 197, 226, 197, 219, 45, 211, 101, 219, 120, 28, 181, 127, 6, 100, 247, 2, 205, 198, 57, 115, 219, 101, 109, 160, 82, 37, 38, 238, 49, 160, 209, 121, 86, 11, 124, 30, 181, 84, 25, 194, 87, 65, 102, 190, 220, 70, 27, 209, 16, 89, 7, 33, 240}; static BYTE byRSExp62[] = { 65, 202, 113, 98, 71, 223, 248, 118, 214, 94, 0, 122, 37, 23, 2, 228, 58, 121, 7, 105, 135, 78, 243, 118, 70, 76, 223, 89, 72, 50, 70, 111, 194, 17, 212, 126, 181, 35, 221, 117, 235, 11, 229, 149, 147, 123, 213, 40, 115, 6, 200, 100, 26, 246, 182, 218, 127, 215, 36, 186, 110, 106}; static BYTE byRSExp64[] = { 45, 51, 175, 9, 7, 158, 159, 49, 68, 119, 92, 123, 177, 204, 187, 254, 200, 78, 141, 149, 119, 26, 127, 53, 160, 93, 199, 212, 29, 24, 145, 156, 208, 150, 218, 209, 4, 216, 91, 47, 184, 146, 47, 140, 195, 195, 125, 242, 238, 63, 99, 108, 140, 230, 242, 31, 204, 11, 178, 243, 217, 156, 213, 231}; static BYTE byRSExp66[] = { 5, 118, 222, 180, 136, 136, 162, 51, 46, 117, 13, 215, 81, 17, 139, 247, 197, 171, 95, 173, 65, 137, 178, 68, 111, 95, 101, 41, 72, 214, 169, 197, 95, 7, 44, 154, 77, 111, 236, 40, 121, 143, 63, 87, 80, 253, 240, 126, 217, 77, 34, 232, 106, 50, 168, 82, 76, 146, 67, 106, 171, 25, 132, 93, 45, 105}; static BYTE byRSExp68[] = {247, 159, 223, 33, 224, 93, 77, 70, 90, 160, 32, 254, 43, 150, 84, 101, 190, 205, 133, 52, 60, 202, 165, 220, 203, 151, 93, 84, 15, 84, 253, 173, 160, 89, 227, 52, 199, 97, 95, 231, 52, 177, 41, 125, 137, 241, 166, 225, 118, 2, 54, 32, 82, 215, 175, 198, 43, 238, 235, 27, 101, 184, 127, 3, 5, 8, 163, 238}; static LPBYTE byRSExp[] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, byRSExp7, NULL, NULL, byRSExp10, NULL, NULL, byRSExp13, NULL, byRSExp15, byRSExp16, byRSExp17, byRSExp18, NULL, byRSExp20, NULL, byRSExp22, NULL, byRSExp24, NULL, byRSExp26, NULL, byRSExp28, NULL, byRSExp30, NULL, byRSExp32, NULL, byRSExp34, NULL, byRSExp36, NULL, byRSExp38, NULL, byRSExp40, NULL, byRSExp42, NULL, byRSExp44, NULL, byRSExp46, NULL, byRSExp48, NULL, byRSExp50, NULL, byRSExp52, NULL, byRSExp54, NULL, byRSExp56, NULL, byRSExp58, NULL, byRSExp60, NULL, byRSExp62, NULL, byRSExp64, NULL, byRSExp66, NULL, byRSExp68}; // 文字数インジケータビット長(バージョングループ別, {S, M, L}) static int nIndicatorLenNumeral[] = {10, 12, 14}; static int nIndicatorLenAlphabet[] = { 9, 11, 13}; static int nIndicatorLen8Bit[] = { 8, 16, 16}; static int nIndicatorLenKanji[] = { 8, 10, 12}; ///////////////////////////////////////////////////////////////////////////// // QR_Encode クラスの構築/消滅 CQR_Encode::CQR_Encode() { } CQR_Encode::~CQR_Encode() { } ///////////////////////////////////////////////////////////////////////////// // CQR_Encode::EncodeData // 用 途:データエンコード // 引 数:誤り訂正レベル、型番(0=自動)、型番自動拡張フラグ、マスキング番号(-1=自動)、エンコードデータ、エンコードデータ長 // 戻り値:エンコード成功時=TRUE、データなし、または容量オーバー時=FALSE BOOL CQR_Encode::EncodeData(int nLevel, int nVersion, BOOL bAutoExtent, int nMaskingNo, LPCSTR lpsSource, int ncSource) { int i, j; m_nLevel = nLevel; m_nMaskingNo = nMaskingNo; // データ長が指定されていない場合は lstrlen によって取得 int ncLength = ncSource > 0 ? ncSource : lstrlen(lpsSource); if (ncLength == 0) return FALSE; // データなし // バージョン(型番)チェック int nEncodeVersion = GetEncodeVersion(nVersion, lpsSource, ncLength); if (nEncodeVersion == 0) return FALSE; // 容量オーバー if (nVersion == 0) { // 型番自動 m_nVersion = nEncodeVersion; } else { if (nEncodeVersion <= nVersion) { m_nVersion = nVersion; } else { if (bAutoExtent) m_nVersion = nEncodeVersion; // バージョン(型番)自動拡張 else return FALSE; // 容量オーバー } } // ターミネータコード"0000"付加 int ncDataCodeWord = QR_VersonInfo[m_nVersion].ncDataCodeWord[nLevel]; int ncTerminater = min(4, (ncDataCodeWord * 8) - m_ncDataCodeWordBit); if (ncTerminater > 0) m_ncDataCodeWordBit = SetBitStream(m_ncDataCodeWordBit, 0, ncTerminater); // パディングコード"11101100, 00010001"付加 BYTE byPaddingCode = 0xec; for (i = (m_ncDataCodeWordBit + 7) / 8; i < ncDataCodeWord; ++i) { m_byDataCodeWord[i] = byPaddingCode; byPaddingCode = (BYTE)(byPaddingCode == 0xec ? 0x11 : 0xec); } // 総コードワード算出エリアクリア m_ncAllCodeWord = QR_VersonInfo[m_nVersion].ncAllCodeWord; ZeroMemory(m_byAllCodeWord, m_ncAllCodeWord); int nDataCwIndex = 0; // データコードワード処理位置 // データブロック分割数 int ncBlock1 = QR_VersonInfo[m_nVersion].RS_BlockInfo1[nLevel].ncRSBlock; int ncBlock2 = QR_VersonInfo[m_nVersion].RS_BlockInfo2[nLevel].ncRSBlock; int ncBlockSum = ncBlock1 + ncBlock2; int nBlockNo = 0; // 処理中ブロック番号 // ブロック別データコードワード数 int ncDataCw1 = QR_VersonInfo[m_nVersion].RS_BlockInfo1[nLevel].ncDataCodeWord; int ncDataCw2 = QR_VersonInfo[m_nVersion].RS_BlockInfo2[nLevel].ncDataCodeWord; // データコードワードインターリーブ配置 for (i = 0; i < ncBlock1; ++i) { for (j = 0; j < ncDataCw1; ++j) { m_byAllCodeWord[(ncBlockSum * j) + nBlockNo] = m_byDataCodeWord[nDataCwIndex++]; } ++nBlockNo; } for (i = 0; i < ncBlock2; ++i) { for (j = 0; j < ncDataCw2; ++j) { if (j < ncDataCw1) { m_byAllCodeWord[(ncBlockSum * j) + nBlockNo] = m_byDataCodeWord[nDataCwIndex++]; } else { // 2種目ブロック端数分配置 m_byAllCodeWord[(ncBlockSum * ncDataCw1) + i] = m_byDataCodeWord[nDataCwIndex++]; } } ++nBlockNo; } // ブロック別RSコードワード数(※現状では同数) int ncRSCw1 = QR_VersonInfo[m_nVersion].RS_BlockInfo1[nLevel].ncAllCodeWord - ncDataCw1; int ncRSCw2 = QR_VersonInfo[m_nVersion].RS_BlockInfo2[nLevel].ncAllCodeWord - ncDataCw2; ///////////////////////////////////////////////////////////////////////// // RSコードワード算出 nDataCwIndex = 0; nBlockNo = 0; for (i = 0; i < ncBlock1; ++i) { ZeroMemory(m_byRSWork, sizeof(m_byRSWork)); memmove(m_byRSWork, m_byDataCodeWord + nDataCwIndex, ncDataCw1); GetRSCodeWord(m_byRSWork, ncDataCw1, ncRSCw1); // RSコードワード配置 for (j = 0; j < ncRSCw1; ++j) { m_byAllCodeWord[ncDataCodeWord + (ncBlockSum * j) + nBlockNo] = m_byRSWork[j]; } nDataCwIndex += ncDataCw1; ++nBlockNo; } for (i = 0; i < ncBlock2; ++i) { ZeroMemory(m_byRSWork, sizeof(m_byRSWork)); memmove(m_byRSWork, m_byDataCodeWord + nDataCwIndex, ncDataCw2); GetRSCodeWord(m_byRSWork, ncDataCw2, ncRSCw2); // RSコードワード配置 for (j = 0; j < ncRSCw2; ++j) { m_byAllCodeWord[ncDataCodeWord + (ncBlockSum * j) + nBlockNo] = m_byRSWork[j]; } nDataCwIndex += ncDataCw2; ++nBlockNo; } m_nSymbleSize = m_nVersion * 4 + 17; // モジュール配置 FormatModule(); return TRUE; } ///////////////////////////////////////////////////////////////////////////// // CQR_Encode::GetEncodeVersion // 用 途:エンコード時バージョン(型番)取得 // 引 数:調査開始バージョン、エンコードデータ、エンコードデータ長 // 戻り値:バージョン番号(容量オーバー時=0) int CQR_Encode::GetEncodeVersion(int nVersion, LPCSTR lpsSource, int ncLength) { int nVerGroup = nVersion >= 27 ? QR_VRESION_L : (nVersion >= 10 ? QR_VRESION_M : QR_VRESION_S); int i, j; for (i = nVerGroup; i <= QR_VRESION_L; ++i) { if (EncodeSourceData(lpsSource, ncLength, i)) { if (i == QR_VRESION_S) { for (j = 1; j <= 9; ++j) { if ((m_ncDataCodeWordBit + 7) / 8 <= QR_VersonInfo[j].ncDataCodeWord[m_nLevel]) return j; } } else if (i == QR_VRESION_M) { for (j = 10; j <= 26; ++j) { if ((m_ncDataCodeWordBit + 7) / 8 <= QR_VersonInfo[j].ncDataCodeWord[m_nLevel]) return j; } } else if (i == QR_VRESION_L) { for (j = 27; j <= 40; ++j) { if ((m_ncDataCodeWordBit + 7) / 8 <= QR_VersonInfo[j].ncDataCodeWord[m_nLevel]) return j; } } } } return 0; } ///////////////////////////////////////////////////////////////////////////// // CQR_Encode::EncodeSourceData // 用 途:入力データエンコード // 引 数:入力データ、入力データ長、バージョン(型番)グループ // 戻り値:エンコード成功時=TRUE BOOL CQR_Encode::EncodeSourceData(LPCSTR lpsSource, int ncLength, int nVerGroup) { ZeroMemory(m_nBlockLength, sizeof(m_nBlockLength)); int i, j; // どのモードが何文字(バイト)継続しているかを調査 for (m_ncDataBlock = i = 0; i < ncLength; ++i) { BYTE byMode; if (i < ncLength - 1 && IsKanjiData(lpsSource[i], lpsSource[i + 1])) byMode = QR_MODE_KANJI; else if (IsNumeralData(lpsSource[i])) byMode = QR_MODE_NUMERAL; else if (IsAlphabetData(lpsSource[i])) byMode = QR_MODE_ALPHABET; else byMode = QR_MODE_8BIT; if (i == 0) m_byBlockMode[0] = byMode; if (m_byBlockMode[m_ncDataBlock] != byMode) m_byBlockMode[++m_ncDataBlock] = byMode; ++m_nBlockLength[m_ncDataBlock]; if (byMode == QR_MODE_KANJI) { // 漢字は文字数ではなく 数で記録 ++m_nBlockLength[m_ncDataBlock]; ++i; } } ++m_ncDataBlock; ///////////////////////////////////////////////////////////////////////// // 隣接する英数字モードブロックと数字モードブロックの並びをを条件により結合 int ncSrcBits, ncDstBits; // 元のビット長と単一の英数字モードブロック化した場合のビット長 int nBlock = 0; while (nBlock < m_ncDataBlock - 1) { int ncJoinFront, ncJoinBehind; // 前後8ビットバイトモードブロックと結合した場合のビット長 int nJoinPosition = 0; // 8ビットバイトモードブロックとの結合:-1=前と結合、0=結合しない、1=後ろと結合 // 「数字−英数字」または「英数字−数字」の並び if ((m_byBlockMode[nBlock] == QR_MODE_NUMERAL && m_byBlockMode[nBlock + 1] == QR_MODE_ALPHABET) || (m_byBlockMode[nBlock] == QR_MODE_ALPHABET && m_byBlockMode[nBlock + 1] == QR_MODE_NUMERAL)) { // 元のビット長と単一の英数字モードブロック化した場合のビット長を比較 ncSrcBits = GetBitLength(m_byBlockMode[nBlock], m_nBlockLength[nBlock], nVerGroup) + GetBitLength(m_byBlockMode[nBlock + 1], m_nBlockLength[nBlock + 1], nVerGroup); ncDstBits = GetBitLength(QR_MODE_ALPHABET, m_nBlockLength[nBlock] + m_nBlockLength[nBlock + 1], nVerGroup); if (ncSrcBits > ncDstBits) { // 前後に8ビットバイトモードブロックがある場合、それらとの結合が有利かどうかをチェック if (nBlock >= 1 && m_byBlockMode[nBlock - 1] == QR_MODE_8BIT) { // 前に8ビットバイトモードブロックあり ncJoinFront = GetBitLength(QR_MODE_8BIT, m_nBlockLength[nBlock - 1] + m_nBlockLength[nBlock], nVerGroup) + GetBitLength(m_byBlockMode[nBlock + 1], m_nBlockLength[nBlock + 1], nVerGroup); if (ncJoinFront > ncDstBits + GetBitLength(QR_MODE_8BIT, m_nBlockLength[nBlock - 1], nVerGroup)) ncJoinFront = 0; // 8ビットバイトモードブロックとは結合しない } else ncJoinFront = 0; if (nBlock < m_ncDataBlock - 2 && m_byBlockMode[nBlock + 2] == QR_MODE_8BIT) { // 後ろに8ビットバイトモードブロックあり ncJoinBehind = GetBitLength(m_byBlockMode[nBlock], m_nBlockLength[nBlock], nVerGroup) + GetBitLength(QR_MODE_8BIT, m_nBlockLength[nBlock + 1] + m_nBlockLength[nBlock + 2], nVerGroup); if (ncJoinBehind > ncDstBits + GetBitLength(QR_MODE_8BIT, m_nBlockLength[nBlock + 2], nVerGroup)) ncJoinBehind = 0; // 8ビットバイトモードブロックとは結合しない } else ncJoinBehind = 0; if (ncJoinFront != 0 && ncJoinBehind != 0) { // 前後両方に8ビットバイトモードブロックがある場合はデータ長が短くなる方を優先 nJoinPosition = (ncJoinFront < ncJoinBehind) ? -1 : 1; } else { nJoinPosition = (ncJoinFront != 0) ? -1 : ((ncJoinBehind != 0) ? 1 : 0); } if (nJoinPosition != 0) { // 8ビットバイトモードブロックとの結合 if (nJoinPosition == -1) { m_nBlockLength[nBlock - 1] += m_nBlockLength[nBlock]; // 後続をシフト for (i = nBlock; i < m_ncDataBlock - 1; ++i) { m_byBlockMode[i] = m_byBlockMode[i + 1]; m_nBlockLength[i] = m_nBlockLength[i + 1]; } } else { m_byBlockMode[nBlock + 1] = QR_MODE_8BIT; m_nBlockLength[nBlock + 1] += m_nBlockLength[nBlock + 2]; // 後続をシフト for (i = nBlock + 2; i < m_ncDataBlock - 1; ++i) { m_byBlockMode[i] = m_byBlockMode[i + 1]; m_nBlockLength[i] = m_nBlockLength[i + 1]; } } --m_ncDataBlock; } else { // 英数字と数字の並びを単一の英数字モードブロックに統合 if (nBlock < m_ncDataBlock - 2 && m_byBlockMode[nBlock + 2] == QR_MODE_ALPHABET) { // 結合しようとするブロックの後ろに続く英数字モードブロックを結合 m_nBlockLength[nBlock + 1] += m_nBlockLength[nBlock + 2]; // 後続をシフト for (i = nBlock + 2; i < m_ncDataBlock - 1; ++i) { m_byBlockMode[i] = m_byBlockMode[i + 1]; m_nBlockLength[i] = m_nBlockLength[i + 1]; } --m_ncDataBlock; } m_byBlockMode[nBlock] = QR_MODE_ALPHABET; m_nBlockLength[nBlock] += m_nBlockLength[nBlock + 1]; // 後続をシフト for (i = nBlock + 1; i < m_ncDataBlock - 1; ++i) { m_byBlockMode[i] = m_byBlockMode[i + 1]; m_nBlockLength[i] = m_nBlockLength[i + 1]; } --m_ncDataBlock; if (nBlock >= 1 && m_byBlockMode[nBlock - 1] == QR_MODE_ALPHABET) { // 結合したブロックの前の英数字モードブロックを結合 m_nBlockLength[nBlock - 1] += m_nBlockLength[nBlock]; // 後続をシフト for (i = nBlock; i < m_ncDataBlock - 1; ++i) { m_byBlockMode[i] = m_byBlockMode[i + 1]; m_nBlockLength[i] = m_nBlockLength[i + 1]; } --m_ncDataBlock; } } continue; // 現在位置のブロックを再調査 } } ++nBlock; // 次ブロックを調査 } ///////////////////////////////////////////////////////////////////////// // 連続する短いモードブロックを8ビットバイトモードブロック化 nBlock = 0; while (nBlock < m_ncDataBlock - 1) { ncSrcBits = GetBitLength(m_byBlockMode[nBlock], m_nBlockLength[nBlock], nVerGroup) + GetBitLength(m_byBlockMode[nBlock + 1], m_nBlockLength[nBlock + 1], nVerGroup); ncDstBits = GetBitLength(QR_MODE_8BIT, m_nBlockLength[nBlock] + m_nBlockLength[nBlock + 1], nVerGroup); // 前に8ビットバイトモードブロックがある場合、重複するインジケータ分を減算 if (nBlock >= 1 && m_byBlockMode[nBlock - 1] == QR_MODE_8BIT) ncDstBits -= (4 + nIndicatorLen8Bit[nVerGroup]); // 後ろに8ビットバイトモードブロックがある場合、重複するインジケータ分を減算 if (nBlock < m_ncDataBlock - 2 && m_byBlockMode[nBlock + 2] == QR_MODE_8BIT) ncDstBits -= (4 + nIndicatorLen8Bit[nVerGroup]); if (ncSrcBits > ncDstBits) { if (nBlock >= 1 && m_byBlockMode[nBlock - 1] == QR_MODE_8BIT) { // 結合するブロックの前にある8ビットバイトモードブロックを結合 m_nBlockLength[nBlock - 1] += m_nBlockLength[nBlock]; // 後続をシフト for (i = nBlock; i < m_ncDataBlock - 1; ++i) { m_byBlockMode[i] = m_byBlockMode[i + 1]; m_nBlockLength[i] = m_nBlockLength[i + 1]; } --m_ncDataBlock; --nBlock; } if (nBlock < m_ncDataBlock - 2 && m_byBlockMode[nBlock + 2] == QR_MODE_8BIT) { // 結合するブロックの後ろにある8ビットバイトモードブロックを結合 m_nBlockLength[nBlock + 1] += m_nBlockLength[nBlock + 2]; // 後続をシフト for (i = nBlock + 2; i < m_ncDataBlock - 1; ++i) { m_byBlockMode[i] = m_byBlockMode[i + 1]; m_nBlockLength[i] = m_nBlockLength[i + 1]; } --m_ncDataBlock; } m_byBlockMode[nBlock] = QR_MODE_8BIT; m_nBlockLength[nBlock] += m_nBlockLength[nBlock + 1]; // 後続をシフト for (i = nBlock + 1; i < m_ncDataBlock - 1; ++i) { m_byBlockMode[i] = m_byBlockMode[i + 1]; m_nBlockLength[i] = m_nBlockLength[i + 1]; } --m_ncDataBlock; // 結合したブロックの前から再調査 if (nBlock >= 1) --nBlock; continue; } ++nBlock; // 次ブロックを調査 } ///////////////////////////////////////////////////////////////////////// // ビット配列化 int ncComplete = 0; // 処理済データカウンタ WORD wBinCode; m_ncDataCodeWordBit = 0; // ビット単位処理カウンタ ZeroMemory(m_byDataCodeWord, MAX_DATACODEWORD); for (i = 0; i < m_ncDataBlock && m_ncDataCodeWordBit != -1; ++i) { if (m_byBlockMode[i] == QR_MODE_NUMERAL) { ///////////////////////////////////////////////////////////////// // 数字モード // インジケータ(0001b) m_ncDataCodeWordBit = SetBitStream(m_ncDataCodeWordBit, 1, 4); // 文字数セット m_ncDataCodeWordBit = SetBitStream(m_ncDataCodeWordBit, (WORD)m_nBlockLength[i], nIndicatorLenNumeral[nVerGroup]); // ビット列保存 for (j = 0; j < m_nBlockLength[i]; j += 3) { if (j < m_nBlockLength[i] - 2) { wBinCode = (WORD)(((lpsSource[ncComplete + j] - '0') * 100) + ((lpsSource[ncComplete + j + 1] - '0') * 10) + (lpsSource[ncComplete + j + 2] - '0')); m_ncDataCodeWordBit = SetBitStream(m_ncDataCodeWordBit, wBinCode, 10); } else if (j == m_nBlockLength[i] - 2) { // 端数2バイト wBinCode = (WORD)(((lpsSource[ncComplete + j] - '0') * 10) + (lpsSource[ncComplete + j + 1] - '0')); m_ncDataCodeWordBit = SetBitStream(m_ncDataCodeWordBit, wBinCode, 7); } else if (j == m_nBlockLength[i] - 1) { // 端数1バイト wBinCode = (WORD)(lpsSource[ncComplete + j] - '0'); m_ncDataCodeWordBit = SetBitStream(m_ncDataCodeWordBit, wBinCode, 4); } } ncComplete += m_nBlockLength[i]; } else if (m_byBlockMode[i] == QR_MODE_ALPHABET) { ///////////////////////////////////////////////////////////////// // 英数字モード // モードインジケータ(0010b) m_ncDataCodeWordBit = SetBitStream(m_ncDataCodeWordBit, 2, 4); // 文字数セット m_ncDataCodeWordBit = SetBitStream(m_ncDataCodeWordBit, (WORD)m_nBlockLength[i], nIndicatorLenAlphabet[nVerGroup]); // ビット列保存 for (j = 0; j < m_nBlockLength[i]; j += 2) { if (j < m_nBlockLength[i] - 1) { wBinCode = (WORD)((AlphabetToBinaly(lpsSource[ncComplete + j]) * 45) + AlphabetToBinaly(lpsSource[ncComplete + j + 1])); m_ncDataCodeWordBit = SetBitStream(m_ncDataCodeWordBit, wBinCode, 11); } else { // 端数1バイト wBinCode = (WORD)AlphabetToBinaly(lpsSource[ncComplete + j]); m_ncDataCodeWordBit = SetBitStream(m_ncDataCodeWordBit, wBinCode, 6); } } ncComplete += m_nBlockLength[i]; } else if (m_byBlockMode[i] == QR_MODE_8BIT) { ///////////////////////////////////////////////////////////////// // 8ビットバイトモード // モードインジケータ(0100b) m_ncDataCodeWordBit = SetBitStream(m_ncDataCodeWordBit, 4, 4); // 文字数セット m_ncDataCodeWordBit = SetBitStream(m_ncDataCodeWordBit, (WORD)m_nBlockLength[i], nIndicatorLen8Bit[nVerGroup]); // ビット列保存 for (j = 0; j < m_nBlockLength[i]; ++j) { m_ncDataCodeWordBit = SetBitStream(m_ncDataCodeWordBit, (WORD)lpsSource[ncComplete + j], 8); } ncComplete += m_nBlockLength[i]; } else // m_byBlockMode[i] == QR_MODE_KANJI { ///////////////////////////////////////////////////////////////// // 漢字モード // モードインジケータ(1000b) m_ncDataCodeWordBit = SetBitStream(m_ncDataCodeWordBit, 8, 4); // 文字数セット m_ncDataCodeWordBit = SetBitStream(m_ncDataCodeWordBit, (WORD)(m_nBlockLength[i] / 2), nIndicatorLenKanji[nVerGroup]); // 漢字モードでビット列保存 for (j = 0; j < m_nBlockLength[i] / 2; ++j) { WORD wBinCode = KanjiToBinaly((WORD)(((BYTE)lpsSource[ncComplete + (j * 2)] << 8) + (BYTE)lpsSource[ncComplete + (j * 2) + 1])); m_ncDataCodeWordBit = SetBitStream(m_ncDataCodeWordBit, wBinCode, 13); } ncComplete += m_nBlockLength[i]; } } return (m_ncDataCodeWordBit != -1); } ///////////////////////////////////////////////////////////////////////////// // CQR_Encode::GetBitLength // 用 途:ビット長取得 // 引 数:データモード種別、データ長、バージョン(型番)グループ // 戻り値:データビット長 // 備 考:漢字モードでのデータ長引数は文字数ではなくバイト数 int CQR_Encode::GetBitLength(BYTE nMode, int ncData, int nVerGroup) { int ncBits = 0; switch (nMode) { case QR_MODE_NUMERAL: ncBits = 4 + nIndicatorLenNumeral[nVerGroup] + (10 * (ncData / 3)); switch (ncData % 3) { case 1: ncBits += 4; break; case 2: ncBits += 7; break; default: // case 0: break; } break; case QR_MODE_ALPHABET: ncBits = 4 + nIndicatorLenAlphabet[nVerGroup] + (11 * (ncData / 2)) + (6 * (ncData % 2)); break; case QR_MODE_8BIT: ncBits = 4 + nIndicatorLen8Bit[nVerGroup] + (8 * ncData); break; default: // case QR_MODE_KANJI: ncBits = 4 + nIndicatorLenKanji[nVerGroup] + (13 * (ncData / 2)); break; } return ncBits; } ///////////////////////////////////////////////////////////////////////////// // CQR_Encode::SetBitStream // 用 途:ビットセット // 引 数:挿入位置、ビット配列データ、データビット長(最大16) // 戻り値:次回挿入位置(バッファオーバー時=-1) // 備 考:m_byDataCodeWord に結果をセット(要ゼロ初期化) int CQR_Encode::SetBitStream(int nIndex, WORD wData, int ncData) { int i; if (nIndex == -1 || nIndex + ncData > MAX_DATACODEWORD * 8) return -1; for (i = 0; i < ncData; ++i) { if (wData & (1 << (ncData - i - 1))) { m_byDataCodeWord[(nIndex + i) / 8] |= 1 << (7 - ((nIndex + i) % 8)); } } return nIndex + ncData; } ///////////////////////////////////////////////////////////////////////////// // CQR_Encode::IsNumeralData // 用 途:数字モード該当チェック // 引 数:調査文字 // 戻り値:該当時=TRUE BOOL CQR_Encode::IsNumeralData(unsigned char c) { if (c >= '0' && c <= '9') return TRUE; return FALSE; } ///////////////////////////////////////////////////////////////////////////// // CQR_Encode::IsAlphabetData // 用 途:英数字モード該当チェック // 引 数:調査文字 // 戻り値:該当時=TRUE BOOL CQR_Encode::IsAlphabetData(unsigned char c) { if (c >= '0' && c <= '9') return TRUE; if (c >= 'A' && c <= 'Z') return TRUE; if (c == ' ' || c == '$' || c == '%' || c == '*' || c == '+' || c == '-' || c == '.' || c == '/' || c == ':') return TRUE; return FALSE; } ///////////////////////////////////////////////////////////////////////////// // CQR_Encode::IsKanjiData // 用 途:漢字モード該当チェック // 引 数:調査文字(16ビット文字) // 戻り値:該当時=TRUE // 備 考:EBBFh 以降の S-JIS は対象外 BOOL CQR_Encode::IsKanjiData(unsigned char c1, unsigned char c2) { if (((c1 >= 0x81 && c1 <= 0x9f) || (c1 >= 0xe0 && c1 <= 0xeb)) && (c2 >= 0x40)) { if ((c1 == 0x9f && c2 > 0xfc) || (c1 == 0xeb && c2 > 0xbf)) return FALSE; return TRUE; } return FALSE; } ///////////////////////////////////////////////////////////////////////////// // CQR_Encode::AlphabetToBinaly // 用 途:英数字モード文字のバイナリ化 // 引 数:対象文字 // 戻り値:バイナリ値 BYTE CQR_Encode::AlphabetToBinaly(unsigned char c) { if (c >= '0' && c <= '9') return (unsigned char)(c - '0'); if (c >= 'A' && c <= 'Z') return (unsigned char)(c - 'A' + 10); if (c == ' ') return 36; if (c == '$') return 37; if (c == '%') return 38; if (c == '*') return 39; if (c == '+') return 40; if (c == '-') return 41; if (c == '.') return 42; if (c == '/') return 43; return 44; // c == ':' } ///////////////////////////////////////////////////////////////////////////// // CQR_Encode::KanjiToBinaly // 用 途:漢字モード文字のバイナリ化 // 引 数:対象文字 // 戻り値:バイナリ値 WORD CQR_Encode::KanjiToBinaly(WORD wc) { if (wc >= 0x8140 && wc <= 0x9ffc) wc -= 0x8140; else // (wc >= 0xe040 && wc <= 0xebbf) wc -= 0xc140; return (WORD)(((wc >> 8) * 0xc0) + (wc & 0x00ff)); } ///////////////////////////////////////////////////////////////////////////// // CQR_Encode::GetRSCodeWord // 用 途:RS誤り訂正コードワード取得 // 引 数:データコードワードアドレス、データコードワード長、RSコードワード長 // 備 考:総コードワード分のエリアを確保してから呼び出し void CQR_Encode::GetRSCodeWord(LPBYTE lpbyRSWork, int ncDataCodeWord, int ncRSCodeWord) { int i, j; for (i = 0; i < ncDataCodeWord ; ++i) { if (lpbyRSWork[0] != 0) { BYTE nExpFirst = byIntToExp[lpbyRSWork[0]]; // 初項係数より乗数算出 for (j = 0; j < ncRSCodeWord; ++j) { // 各項乗数に初項乗数を加算(% 255 → α^255 = 1) BYTE nExpElement = (BYTE)(((int)(byRSExp[ncRSCodeWord][j] + nExpFirst)) % 255); // 排他論理和による剰余算出 lpbyRSWork[j] = (BYTE)(lpbyRSWork[j + 1] ^ byExpToInt[nExpElement]); } // 残り桁をシフト for (j = ncRSCodeWord; j < ncDataCodeWord + ncRSCodeWord - 1; ++j) lpbyRSWork[j] = lpbyRSWork[j + 1]; } else { // 残り桁をシフト for (j = 0; j < ncDataCodeWord + ncRSCodeWord - 1; ++j) lpbyRSWork[j] = lpbyRSWork[j + 1]; } } } ///////////////////////////////////////////////////////////////////////////// // CQR_Encode::FormatModule // 用 途:モジュールへのデータ配置 // 戻り値:一辺のモジュール数 void CQR_Encode::FormatModule() { int i, j; ZeroMemory(m_byModuleData, sizeof(m_byModuleData)); // 機能モジュール配置 SetFunctionModule(); // データパターン配置 SetCodeWordPattern(); if (m_nMaskingNo == -1) { // 最適マスキングパターン選択 m_nMaskingNo = 0; SetMaskingPattern(m_nMaskingNo); // マスキング SetFormatInfoPattern(m_nMaskingNo); // フォーマット情報パターン配置 int nMinPenalty = CountPenalty(); for (i = 1; i <= 7; ++i) { SetMaskingPattern(i); // マスキング SetFormatInfoPattern(i); // フォーマット情報パターン配置 int nPenalty = CountPenalty(); if (nPenalty < nMinPenalty) { nMinPenalty = nPenalty; m_nMaskingNo = i; } } } SetMaskingPattern(m_nMaskingNo); // マスキング SetFormatInfoPattern(m_nMaskingNo); // フォーマット情報パターン配置 // モジュールパターンをブール値に変換 for (i = 0; i < m_nSymbleSize; ++i) { for (j = 0; j < m_nSymbleSize; ++j) { m_byModuleData[i][j] = (BYTE)((m_byModuleData[i][j] & 0x11) != 0); } } } ///////////////////////////////////////////////////////////////////////////// // CQR_Encode::SetFunctionModule // 用 途:機能モジュール配置 // 備 考:フォーマット情報は機能モジュール登録のみ(実データは空白) void CQR_Encode::SetFunctionModule() { int i, j; // 位置検出パターン SetFinderPattern(0, 0); SetFinderPattern(m_nSymbleSize - 7, 0); SetFinderPattern(0, m_nSymbleSize - 7); // 位置検出パターンセパレータ for (i = 0; i < 8; ++i) { m_byModuleData[i][7] = m_byModuleData[7][i] = '\x20'; m_byModuleData[m_nSymbleSize - 8][i] = m_byModuleData[m_nSymbleSize - 8 + i][7] = '\x20'; m_byModuleData[i][m_nSymbleSize - 8] = m_byModuleData[7][m_nSymbleSize - 8 + i] = '\x20'; } // フォーマット情報記述位置を機能モジュール部として登録 for (i = 0; i < 9; ++i) { m_byModuleData[i][8] = m_byModuleData[8][i] = '\x20'; } for (i = 0; i < 8; ++i) { m_byModuleData[m_nSymbleSize - 8 + i][8] = m_byModuleData[8][m_nSymbleSize - 8 + i] = '\x20'; } // バージョン情報パターン SetVersionPattern(); // 位置合わせパターン for (i = 0; i < QR_VersonInfo[m_nVersion].ncAlignPoint; ++i) { SetAlignmentPattern(QR_VersonInfo[m_nVersion].nAlignPoint[i], 6); SetAlignmentPattern(6, QR_VersonInfo[m_nVersion].nAlignPoint[i]); for (j = 0; j < QR_VersonInfo[m_nVersion].ncAlignPoint; ++j) { SetAlignmentPattern(QR_VersonInfo[m_nVersion].nAlignPoint[i], QR_VersonInfo[m_nVersion].nAlignPoint[j]); } } // タイミングパターン for (i = 8; i <= m_nSymbleSize - 9; ++i) { m_byModuleData[i][6] = (i % 2) == 0 ? '\x30' : '\x20'; m_byModuleData[6][i] = (i % 2) == 0 ? '\x30' : '\x20'; } } ///////////////////////////////////////////////////////////////////////////// // CQR_Encode::SetFinderPattern // 用 途:位置検出パターン配置 // 引 数:配置左上座標 void CQR_Encode::SetFinderPattern(int x, int y) { static BYTE byPattern[] = {0x7f, // 1111111b 0x41, // 1000001b 0x5d, // 1011101b 0x5d, // 1011101b 0x5d, // 1011101b 0x41, // 1000001b 0x7f}; // 1111111b int i, j; for (i = 0; i < 7; ++i) { for (j = 0; j < 7; ++j) { m_byModuleData[x + j][y + i] = (byPattern[i] & (1 << (6 - j))) ? '\x30' : '\x20'; } } } ///////////////////////////////////////////////////////////////////////////// // CQR_Encode::SetAlignmentPattern // 用 途:位置合わせパターン配置 // 引 数:配置中央座標 void CQR_Encode::SetAlignmentPattern(int x, int y) { static BYTE byPattern[] = {0x1f, // 11111b 0x11, // 10001b 0x15, // 10101b 0x11, // 10001b 0x1f}; // 11111b int i, j; if (m_byModuleData[x][y] & 0x20) return; // 機能モジュールと重複するため除外 x -= 2; y -= 2; // 左上隅座標に変換 for (i = 0; i < 5; ++i) { for (j = 0; j < 5; ++j) { m_byModuleData[x + j][y + i] = (byPattern[i] & (1 << (4 - j))) ? '\x30' : '\x20'; } } } ///////////////////////////////////////////////////////////////////////////// // CQR_Encode::SetVersionPattern // 用 途:バージョン(型番)情報パターン配置 // 備 考:拡張BCH(18,6)符号を誤り訂正として使用 void CQR_Encode::SetVersionPattern() { int i, j; if (m_nVersion <= 6) return; int nVerData = m_nVersion << 12; // 剰余ビット算出 for (i = 0; i < 6; ++i) { if (nVerData & (1 << (17 - i))) { nVerData ^= (0x1f25 << (5 - i)); } } nVerData += m_nVersion << 12; for (i = 0; i < 6; ++i) { for (j = 0; j < 3; ++j) { m_byModuleData[m_nSymbleSize - 11 + j][i] = m_byModuleData[i][m_nSymbleSize - 11 + j] = (nVerData & (1 << (i * 3 + j))) ? '\x30' : '\x20'; } } } ///////////////////////////////////////////////////////////////////////////// // CQR_Encode::SetCodeWordPattern // 用 途:データパターン配置 void CQR_Encode::SetCodeWordPattern() { int x = m_nSymbleSize; int y = m_nSymbleSize - 1; int nCoef_x = 1; // x軸配置向き int nCoef_y = 1; // y軸配置向き int i, j; for (i = 0; i < m_ncAllCodeWord; ++i) { for (j = 0; j < 8; ++j) { do { x += nCoef_x; nCoef_x *= -1; if (nCoef_x < 0) { y += nCoef_y; if (y < 0 || y == m_nSymbleSize) { y = (y < 0) ? 0 : m_nSymbleSize - 1; nCoef_y *= -1; x -= 2; if (x == 6) // タイミングパターン --x; } } } while (m_byModuleData[x][y] & 0x20); // 機能モジュールを除外 m_byModuleData[x][y] = (m_byAllCodeWord[i] & (1 << (7 - j))) ? '\x02' : '\x00'; } } } ///////////////////////////////////////////////////////////////////////////// // CQR_Encode::SetMaskingPattern // 用 途:マスキングパターン配置 // 引 数:マスキングパターン番号 void CQR_Encode::SetMaskingPattern(int nPatternNo) { int i, j; for (i = 0; i < m_nSymbleSize; ++i) { for (j = 0; j < m_nSymbleSize; ++j) { if (! (m_byModuleData[j][i] & 0x20)) // 機能モジュールを除外 { BOOL bMask; switch (nPatternNo) { case 0: bMask = ((i + j) % 2 == 0); break; case 1: bMask = (i % 2 == 0); break; case 2: bMask = (j % 3 == 0); break; case 3: bMask = ((i + j) % 3 == 0); break; case 4: bMask = (((i / 2) + (j / 3)) % 2 == 0); break; case 5: bMask = (((i * j) % 2) + ((i * j) % 3) == 0); break; case 6: bMask = ((((i * j) % 2) + ((i * j) % 3)) % 2 == 0); break; default: // case 7: bMask = ((((i * j) % 3) + ((i + j) % 2)) % 2 == 0); break; } m_byModuleData[j][i] = (BYTE)((m_byModuleData[j][i] & 0xfe) | (((m_byModuleData[j][i] & 0x02) > 1) ^ bMask)); } } } } ///////////////////////////////////////////////////////////////////////////// // CQR_Encode::SetFormatInfoPattern // 用 途:フォーマット情報配置 // 引 数:マスキングパターン番号 void CQR_Encode::SetFormatInfoPattern(int nPatternNo) { int nFormatInfo; int i; switch (m_nLevel) { case QR_LEVEL_M: nFormatInfo = 0x00; // 00nnnb break; case QR_LEVEL_L: nFormatInfo = 0x08; // 01nnnb break; case QR_LEVEL_Q: nFormatInfo = 0x18; // 11nnnb break; default: // case QR_LEVEL_H: nFormatInfo = 0x10; // 10nnnb break; } nFormatInfo += nPatternNo; int nFormatData = nFormatInfo << 10; // 剰余ビット算出 for (i = 0; i < 5; ++i) { if (nFormatData & (1 << (14 - i))) { nFormatData ^= (0x0537 << (4 - i)); // 10100110111b } } nFormatData += nFormatInfo << 10; // マスキング nFormatData ^= 0x5412; // 101010000010010b // 左上位置検出パターン周り配置 for (i = 0; i <= 5; ++i) m_byModuleData[8][i] = (nFormatData & (1 << i)) ? '\x30' : '\x20'; m_byModuleData[8][7] = (nFormatData & (1 << 6)) ? '\x30' : '\x20'; m_byModuleData[8][8] = (nFormatData & (1 << 7)) ? '\x30' : '\x20'; m_byModuleData[7][8] = (nFormatData & (1 << 8)) ? '\x30' : '\x20'; for (i = 9; i <= 14; ++i) m_byModuleData[14 - i][8] = (nFormatData & (1 << i)) ? '\x30' : '\x20'; // 右上位置検出パターン下配置 for (i = 0; i <= 7; ++i) m_byModuleData[m_nSymbleSize - 1 - i][8] = (nFormatData & (1 << i)) ? '\x30' : '\x20'; // 左下位置検出パターン右配置 m_byModuleData[8][m_nSymbleSize - 8] = '\x30'; // 固定暗モジュール for (i = 8; i <= 14; ++i) m_byModuleData[8][m_nSymbleSize - 15 + i] = (nFormatData & (1 << i)) ? '\x30' : '\x20'; } ///////////////////////////////////////////////////////////////////////////// // CQR_Encode::CountPenalty // 用 途:マスク後ペナルティスコア算出 int CQR_Encode::CountPenalty() { int nPenalty = 0; int i, j, k; // 同色の列の隣接モジュール for (i = 0; i < m_nSymbleSize; ++i) { for (j = 0; j < m_nSymbleSize - 4; ++j) { int nCount = 1; for (k = j + 1; k < m_nSymbleSize; k++) { if (((m_byModuleData[i][j] & 0x11) == 0) == ((m_byModuleData[i][k] & 0x11) == 0)) ++nCount; else break; } if (nCount >= 5) { nPenalty += 3 + (nCount - 5); } j = k - 1; } } // 同色の行の隣接モジュール for (i = 0; i < m_nSymbleSize; ++i) { for (j = 0; j < m_nSymbleSize - 4; ++j) { int nCount = 1; for (k = j + 1; k < m_nSymbleSize; k++) { if (((m_byModuleData[j][i] & 0x11) == 0) == ((m_byModuleData[k][i] & 0x11) == 0)) ++nCount; else break; } if (nCount >= 5) { nPenalty += 3 + (nCount - 5); } j = k - 1; } } // 同色のモジュールブロック(2×2) for (i = 0; i < m_nSymbleSize - 1; ++i) { for (j = 0; j < m_nSymbleSize - 1; ++j) { if ((((m_byModuleData[i][j] & 0x11) == 0) == ((m_byModuleData[i + 1][j] & 0x11) == 0)) && (((m_byModuleData[i][j] & 0x11) == 0) == ((m_byModuleData[i] [j + 1] & 0x11) == 0)) && (((m_byModuleData[i][j] & 0x11) == 0) == ((m_byModuleData[i + 1][j + 1] & 0x11) == 0))) { nPenalty += 3; } } } // 同一列における 1:1:3:1:1 比率(暗:明:暗:明:暗)のパターン for (i = 0; i < m_nSymbleSize; ++i) { for (j = 0; j < m_nSymbleSize - 6; ++j) { if (((j == 0) || (! (m_byModuleData[i][j - 1] & 0x11))) && // 明 または シンボル外 ( m_byModuleData[i][j] & 0x11) && // 暗 - 1 (! (m_byModuleData[i][j + 1] & 0x11)) && // 明 - 1 ( m_byModuleData[i][j + 2] & 0x11) && // 暗 ┐ ( m_byModuleData[i][j + 3] & 0x11) && // 暗 │3 ( m_byModuleData[i][j + 4] & 0x11) && // 暗 ┘ (! (m_byModuleData[i][j + 5] & 0x11)) && // 明 - 1 ( m_byModuleData[i][j + 6] & 0x11) && // 暗 - 1 ((j == m_nSymbleSize - 7) || (! (m_byModuleData[i][j + 7] & 0x11)))) // 明 または シンボル外 { // 前または後に4以上の明パターン if (((j < 2 || ! (m_byModuleData[i][j - 2] & 0x11)) && (j < 3 || ! (m_byModuleData[i][j - 3] & 0x11)) && (j < 4 || ! (m_byModuleData[i][j - 4] & 0x11))) || ((j >= m_nSymbleSize - 8 || ! (m_byModuleData[i][j + 8] & 0x11)) && (j >= m_nSymbleSize - 9 || ! (m_byModuleData[i][j + 9] & 0x11)) && (j >= m_nSymbleSize - 10 || ! (m_byModuleData[i][j + 10] & 0x11)))) { nPenalty += 40; } } } } // 同一行における 1:1:3:1:1 比率(暗:明:暗:明:暗)のパターン for (i = 0; i < m_nSymbleSize; ++i) { for (j = 0; j < m_nSymbleSize - 6; ++j) { if (((j == 0) || (! (m_byModuleData[j - 1][i] & 0x11))) && // 明 または シンボル外 ( m_byModuleData[j] [i] & 0x11) && // 暗 - 1 (! (m_byModuleData[j + 1][i] & 0x11)) && // 明 - 1 ( m_byModuleData[j + 2][i] & 0x11) && // 暗 ┐ ( m_byModuleData[j + 3][i] & 0x11) && // 暗 │3 ( m_byModuleData[j + 4][i] & 0x11) && // 暗 ┘ (! (m_byModuleData[j + 5][i] & 0x11)) && // 明 - 1 ( m_byModuleData[j + 6][i] & 0x11) && // 暗 - 1 ((j == m_nSymbleSize - 7) || (! (m_byModuleData[j + 7][i] & 0x11)))) // 明 または シンボル外 { // 前または後に4以上の明パターン if (((j < 2 || ! (m_byModuleData[j - 2][i] & 0x11)) && (j < 3 || ! (m_byModuleData[j - 3][i] & 0x11)) && (j < 4 || ! (m_byModuleData[j - 4][i] & 0x11))) || ((j >= m_nSymbleSize - 8 || ! (m_byModuleData[j + 8][i] & 0x11)) && (j >= m_nSymbleSize - 9 || ! (m_byModuleData[j + 9][i] & 0x11)) && (j >= m_nSymbleSize - 10 || ! (m_byModuleData[j + 10][i] & 0x11)))) { nPenalty += 40; } } } } // 全体に対する暗モジュールの占める割合 int nCount = 0; for (i = 0; i < m_nSymbleSize; ++i) { for (j = 0; j < m_nSymbleSize; ++j) { if (! (m_byModuleData[i][j] & 0x11)) { ++nCount; } } } nPenalty += (abs(50 - ((nCount * 100) / (m_nSymbleSize * m_nSymbleSize))) / 5) * 10; return nPenalty; }
[ [ [ 1, 1949 ] ] ]
3806728373a4725aafaccd185b473f24da670e83
ef23e388061a637f82b815d32f7af8cb60c5bb1f
/src/mame/includes/tecmo.h
0880dd3c1f72f529fd40b2c2f9af411905f3f1a4
[]
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
844
h
class tecmo_state : public driver_device { public: tecmo_state(running_machine &machine, const driver_device_config_base &config) : driver_device(machine, config) { } int m_adpcm_pos; int m_adpcm_end; int m_adpcm_data; int m_video_type; UINT8 *m_txvideoram; UINT8 *m_fgvideoram; UINT8 *m_bgvideoram; tilemap_t *m_tx_tilemap; tilemap_t *m_fg_tilemap; tilemap_t *m_bg_tilemap; UINT8 m_fgscroll[3]; UINT8 m_bgscroll[3]; UINT8 *m_spriteram; size_t m_spriteram_size; }; /*----------- defined in video/tecmo.c -----------*/ WRITE8_HANDLER( tecmo_txvideoram_w ); WRITE8_HANDLER( tecmo_fgvideoram_w ); WRITE8_HANDLER( tecmo_bgvideoram_w ); WRITE8_HANDLER( tecmo_fgscroll_w ); WRITE8_HANDLER( tecmo_bgscroll_w ); WRITE8_HANDLER( tecmo_flipscreen_w ); VIDEO_START( tecmo ); SCREEN_UPDATE( tecmo );
[ "Mike@localhost" ]
[ [ [ 1, 34 ] ] ]
ad4f2ff946f352875e1666463b41f901ed3efc94
e792f8b7b8d7846cf754d7a7d9eb0e8765374f53
/hopfield/hop.cpp
d98bec5a439487e2cd571874e407ccb3c7303e18
[]
no_license
edvelezg/unb-nn
2163be652081e78b84ad0e99bb77b99cdf1f9abc
4d3146999735468ae0a82896ea48dc1c8db545ac
refs/heads/master
2020-05-17T07:02:45.563458
2011-07-13T01:49:42
2011-07-13T01:49:42
33,052,902
0
0
null
null
null
null
UTF-8
C++
false
false
2,436
cpp
#include "hop.h" neuron::neuron(int *j) { int i; for (i=0;i<4;i++) { weightv[i]= *(j+i); } } int neuron::act(int m, int *x) { int i; int a=0; for (i=0;i<m;i++) { a += x[i]*weightv[i]; } return a; } int network::threshld(int k) { if (k>=0) return(1); else return(0); } network::network(int a[4],int b[4],int c[4],int d[4]) { nrn[0] = neuron(a) ; nrn[1] = neuron(b) ; nrn[2] = neuron(c) ; nrn[3] = neuron(d) ; } void network::activation(int *patrn) { int i,j; for (i=0;i<4;i++) { for (j=0;j<4;j++) { cout<<"\n nrn["<<i<<"].weightv["<<j<<"] is " <<nrn[i].weightv[j]; } nrn[i].activation = nrn[i].act(4,patrn); cout<<"\nactivation is "<<nrn[i].activation; output[i]=threshld(nrn[i].activation); cout<<"\noutput value is "<<output[i]<<"\n"; } } int main () { int patrn1[]= {1,0,1,0},i; int wt1[]= {0,-3,3,-3}; int wt2[]= {-3,0,-3,3}; int wt3[]= {3,-3,0,-3}; int wt4[]= {-3,3,-3,0}; cout<<"\nTHIS PROGRAM IS FOR A HOPFIELD NETWORK WITH A SINGLE LAYER OF"; cout<<"\n4 FULLY INTERCONNECTED NEURONS. THE NETWORK SHOULD RECALL THE"; cout<<"\nPATTERNS 1010 AND 0101 CORRECTLY.\n"; //create the network by calling its constructor. // the constructor calls neuron constructor as many times as the number of // neurons in the network. network h1(wt1,wt2,wt3,wt4); //present a pattern to the network and get the activations of the neurons h1.activation(patrn1); //check if the pattern given is correctly recalled and give message for (i=0;i<4;i++) { if (h1.output[i] == patrn1[i]) cout<<"\n pattern= "<<patrn1[i]<< " output = "<<h1.output[i]<<" component matches"; else cout<<"\n pattern= "<<patrn1[i]<< " output = "<<h1.output[i]<< " discrepancy occurred"; } cout<<"\n\n"; int patrn2[]= {0,1,0,1}; h1.activation(patrn2); for (i=0;i<4;i++) { if (h1.output[i] == patrn2[i]) cout<<"\n pattern= "<<patrn2[i]<< " output = "<<h1.output[i]<<" component matches"; else cout<<"\n pattern= "<<patrn2[i]<< " output = "<<h1.output[i]<< " discrepancy occurred"; } return 0; }
[ "EdVelez.G@9a33703e-7ef9-c3aa-938f-e7d449b18700" ]
[ [ [ 1, 88 ] ] ]
ba5a271b3774ba5b0473406ccc1a33e031f9b891
bd37f7b494990542d0d9d772368239a2d44e3b2d
/server/src/Operacion.cpp
ce787af59e1d046fa302642a4685ebd4f847e2a7
[]
no_license
nicosuarez/pacmantaller
b559a61355517383d704f313b8c7648c8674cb4c
0e0491538ba1f99b4420340238b09ce9a43a3ee5
refs/heads/master
2020-12-11T02:11:48.900544
2007-12-19T21:49:27
2007-12-19T21:49:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
322
cpp
/////////////////////////////////////////////////////////// // Operacion.cpp // Implementation of the Class Operacion // Created on: 21-Nov-2007 23:40:20 /////////////////////////////////////////////////////////// #include "Operacion.h" Operacion::Operacion(){ } Operacion::~Operacion(){ }
[ "scamjayi@5682bcf5-5c3f-0410-a8fd-ab24993f6fe8" ]
[ [ [ 1, 17 ] ] ]
6795af197f66d7828cfd9fe52d734e5d6fb69193
4d01363b089917facfef766868fb2b1a853605c7
/src/Graphics/Camera.cpp
06ca23ccc3557fdbf2d7f85e94848bf37d4ff86c
[]
no_license
FardMan69420/aimbot-57
2bc7075e2f24dc35b224fcfb5623083edcd0c52b
3f2b86a1f86e5a6da0605461e7ad81be2a91c49c
refs/heads/master
2022-03-20T07:18:53.690175
2009-07-21T22:45:12
2009-07-21T22:45:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
476
cpp
#include "Camera.h" #include "Glut/GlutDisplay.h" Camera::Camera() { up = Vector3(0, 1, 0); } void Camera::setDisplay(GlutDisplay* display) { this->display = display; } void Camera::updateView() { gluLookAt(eye.x, eye.y, eye.z, eye.x - look.x, eye.y - look.y, eye.z - look.z, up.x, up.y, up.z); } void Camera::setLook(Vector3 direction) { look = direction; } void Camera::setEye(const Position3& position) { eye = position; }
[ "daven.hughes@92c3b6dc-493d-11de-82d9-516ade3e46db" ]
[ [ [ 1, 29 ] ] ]
930f46422af746402fae966d767c3dedc032ed04
dadf8e6f3c1adef539a5ad409ce09726886182a7
/airplay/h/TinyOpenEngine.h
6f941715357290d072d681ecf93063d28a81f5a4
[]
no_license
sarthakpandit/toe
63f59ea09f2c1454c1270d55b3b4534feedc7ae3
196aa1e71e9f22f2ecfded1c3da141e7a75b5c2b
refs/heads/master
2021-01-10T04:04:45.575806
2011-06-09T12:56:05
2011-06-09T12:56:05
53,861,788
0
0
null
null
null
null
UTF-8
C++
false
false
916
h
#pragma once #include <string> #include <toeIntrusiveList.h> class CIwTextParserITX; namespace TinyOpenEngine { class CtoeWorld; class ItoeScriptingSubsystem; class CtoeScriptableClassDeclaration; class CYieldHandler: public TtoeIntrusiveListItem<CYieldHandler> { public: virtual void OnYield() = 0; }; void toeInit(); void toeTerminate(); void toeRunWorld(CtoeWorld*); void toeOpenWorld(const char*resource,const char*world); void toeOpenGroupWorld(const char*resource); void toeCloseWorld(); void toeTrace(const char*, ...); bool toeIsTraceEnabled(); void toeRegisterClass(CtoeScriptableClassDeclaration*); TtoeIntrusiveList<CYieldHandler>* toeGetYieldHandlers(); void toeDeviceYield(int32 ms); void toeRegisterScriptableClasses(ItoeScriptingSubsystem*); void toeSerialiseString(std::string & s); void toeReadString(CIwTextParserITX* pParser, std::string * s); }
[ [ [ 1, 30 ] ] ]
1d25e91be6bfbe03278a0a9743b27b75ee853f85
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/_Interface/WndChatFilter.cpp
30e46aa826c80f66af582184f1f919992b049f44
[]
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
8,882
cpp
#include "stdafx.h" #include "defineText.h" #include "AppDefine.h" #include "WndChatFilter.h" #include "WndManager.h" #include "DPClient.h" extern CDPClient g_DPlay; /**************************************************** WndId : APP_CHAT_FILTER - 채팅 필터 CtrlId : WIDC_CHECK1 - 일반 채팅 CtrlId : WIDC_CHECK2 - 귓속말 CtrlId : WIDC_CHECK3 - 외치기 CtrlId : WIDC_CHECK4 - 파티 CtrlId : WIDC_CHECK5 - 길드 CtrlId : WIDC_CHECK6 - 도움말, 화면 CtrlId : WIDC_CHECK7 - 도움말, 챗 CtrlId : WIDC_RADIO1 - 게임, 화면 CtrlId : WIDC_RADIO2 - 게임, 챗 CtrlId : WIDC_RADIO3 - 알림, 화면 CtrlId : WIDC_RADIO4 - 알림, 챗 CtrlId : WIDC_STATIC1 - 채팅 채널 CtrlId : WIDC_STATIC2 - 매시지 필터 ****************************************************/ CWndChatFilter::CWndChatFilter() { } CWndChatFilter::~CWndChatFilter() { } void CWndChatFilter::OnDraw( C2DRender* p2DRender ) { } void CWndChatFilter::OnInitialUpdate() { CWndNeuz::OnInitialUpdate(); // 여기에 코딩하세요 SetButtonStatus(); #if __VER >= 8 //__Y_CHAT_SYSTEM_8 CRect rect = GetClientRect(); SetWndRect( CRect(0, 0, rect.right, rect.bottom - 130)); CWndGroupBox* pWndGroup = (CWndGroupBox*)GetDlgItem( WIDC_GROUPBOX2 ); if( pWndGroup ) pWndGroup->SetVisible(FALSE); #endif //__Y_CHAT_SYSTEM_8 // 윈도를 중앙으로 옮기는 부분. CRect rectRoot = m_pWndRoot->GetLayoutRect(); CRect rectWindow = GetWindowRect(); CPoint point( rectRoot.right - rectWindow.Width(), 110 ); Move( point ); MoveParentCenter(); } void CWndChatFilter::SetButtonStatus() { CWndButton* pWndCheck1 = (CWndButton*)GetDlgItem( WIDC_CHECK1 ); CWndButton* pWndCheck2 = (CWndButton*)GetDlgItem( WIDC_CHECK2 ); CWndButton* pWndCheck3 = (CWndButton*)GetDlgItem( WIDC_CHECK3 ); CWndButton* pWndCheck4 = (CWndButton*)GetDlgItem( WIDC_CHECK4 ); CWndButton* pWndCheck5 = (CWndButton*)GetDlgItem( WIDC_CHECK5 ); #if __VER >= 8 //__Y_CHAT_SYSTEM_8 #else //#if __VER >= 8 CWndButton* pWndCheck6 = (CWndButton*)GetDlgItem( WIDC_CHECK6 ); CWndButton* pWndCheck7 = (CWndButton*)GetDlgItem( WIDC_CHECK7 ); CWndButton* pWndRadio1 = (CWndButton*)GetDlgItem( WIDC_RADIO1 ); CWndButton* pWndRadio2 = (CWndButton*)GetDlgItem( WIDC_RADIO2 ); CWndButton* pWndRadio3 = (CWndButton*)GetDlgItem( WIDC_RADIO3 ); CWndButton* pWndRadio4 = (CWndButton*)GetDlgItem( WIDC_RADIO4 ); #endif //__Y_CHAT_SYSTEM_8 int nChannel = 0; switch( CWndChat::m_nChatChannel ) { case CHATSTY_GENERAL: nChannel = 0; break; case CHATSTY_WHISPER: nChannel = 1; break; case CHATSTY_SHOUT : nChannel = 2; break; case CHATSTY_PARTY : nChannel = 3; break; case CHATSTY_GUILD : nChannel = 4; break; } DWORD dwChatFilter = g_Option.m_dwChatFilter[ nChannel ]; if( dwChatFilter & CHATSTY_GENERAL ) pWndCheck1->SetCheck( TRUE ); if( dwChatFilter & CHATSTY_WHISPER ) pWndCheck2->SetCheck( TRUE ); if( dwChatFilter & CHATSTY_SHOUT ) pWndCheck3->SetCheck( TRUE ); if( dwChatFilter & CHATSTY_PARTY ) pWndCheck4->SetCheck( TRUE ); if( dwChatFilter & CHATSTY_GUILD ) pWndCheck5->SetCheck( TRUE ); #if __VER >= 8 //__Y_CHAT_SYSTEM_8 #else //#if __VER >= 8 DWORD dwChatFilterEtc = g_Option.m_dwChatFilterEtc; if( dwChatFilterEtc & CHATSTY_HELP_CLIENT ) pWndCheck6->SetCheck( TRUE ); if( dwChatFilterEtc & CHATSTY_HELP_CHAT ) pWndCheck7->SetCheck( TRUE ); if( dwChatFilterEtc & CHATSTY_GAME_CLIENT ) pWndRadio1->SetCheck( TRUE ); if( dwChatFilterEtc & CHATSTY_GAME_CHAT ) pWndRadio2->SetCheck( TRUE ); if( dwChatFilterEtc & CHATSTY_SYSTEM_CLIENT ) pWndRadio3->SetCheck( TRUE ); if( dwChatFilterEtc & CHATSTY_SYSTEM_CHAT ) pWndRadio4->SetCheck( TRUE ); #endif//__Y_CHAT_SYSTEM_8 if( CWndChat::m_nChatChannel == CHATSTY_GENERAL ) pWndCheck1->EnableWindow( FALSE ); if( CWndChat::m_nChatChannel == CHATSTY_WHISPER ) pWndCheck2->EnableWindow( FALSE ); if( CWndChat::m_nChatChannel == CHATSTY_SHOUT ) pWndCheck3->EnableWindow( FALSE ); if( CWndChat::m_nChatChannel == CHATSTY_PARTY ) pWndCheck4->EnableWindow( FALSE ); if( CWndChat::m_nChatChannel == CHATSTY_GUILD ) pWndCheck5->EnableWindow( FALSE ); } // 처음 이 함수를 부르면 윈도가 열린다. BOOL CWndChatFilter::Initialize( CWndBase* pWndParent, DWORD /*dwWndId*/ ) { // Daisy에서 설정한 리소스로 윈도를 연다. return CWndNeuz::InitDialog( g_Neuz.GetSafeHwnd(), APP_CHAT_FILTER, WBS_MODAL, CPoint( 0, 0 ), pWndParent ); } /* 직접 윈도를 열때 사용 BOOL CWndChatFilter::Initialize( CWndBase* pWndParent, DWORD dwWndId ) { CRect rectWindow = m_pWndRoot->GetWindowRect(); CRect rect( 50 ,50, 300, 300 ); SetTitle( _T( "title" ) ); return CWndNeuz::Create( WBS_THICKFRAME | WBS_MOVE | WBS_SOUND | WBS_CAPTION, rect, pWndParent, dwWndId ); } */ BOOL CWndChatFilter::OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase ) { return CWndNeuz::OnCommand( nID, dwMessage, pWndBase ); } void CWndChatFilter::OnSize( UINT nType, int cx, int cy ) \ { CWndNeuz::OnSize( nType, cx, cy ); } void CWndChatFilter::OnLButtonUp( UINT nFlags, CPoint point ) { } void CWndChatFilter::OnLButtonDown( UINT nFlags, CPoint point ) { } BOOL CWndChatFilter::OnChildNotify( UINT message, UINT nID, LRESULT* pLResult ) { CWndButton* pWndCheck1 = (CWndButton*)GetDlgItem( WIDC_CHECK1 ); CWndButton* pWndCheck2 = (CWndButton*)GetDlgItem( WIDC_CHECK2 ); CWndButton* pWndCheck3 = (CWndButton*)GetDlgItem( WIDC_CHECK3 ); CWndButton* pWndCheck4 = (CWndButton*)GetDlgItem( WIDC_CHECK4 ); CWndButton* pWndCheck5 = (CWndButton*)GetDlgItem( WIDC_CHECK5 ); #if __VER >= 8 //__Y_CHAT_SYSTEM_8 #else //#if __VER >= 8 // CWndButton* pWndCheck6 = (CWndButton*)GetDlgItem( WIDC_CHECK6 ); CWndButton* pWndCheck7 = (CWndButton*)GetDlgItem( WIDC_CHECK7 ); CWndButton* pWndRadio1 = (CWndButton*)GetDlgItem( WIDC_RADIO1 ); CWndButton* pWndRadio2 = (CWndButton*)GetDlgItem( WIDC_RADIO2 ); CWndButton* pWndRadio3 = (CWndButton*)GetDlgItem( WIDC_RADIO3 ); CWndButton* pWndRadio4 = (CWndButton*)GetDlgItem( WIDC_RADIO4 ); #endif //__Y_CHAT_SYSTEM_8 CWndChat* pWndChat = (CWndChat*)g_WndMng.GetWndBase( APP_COMMUNICATION_CHAT ); int nChannel = 0; switch( pWndChat->m_nChatChannel ) { case CHATSTY_GENERAL: nChannel = 0; break; case CHATSTY_WHISPER: nChannel = 1; break; case CHATSTY_SHOUT : nChannel = 2; break; case CHATSTY_PARTY : nChannel = 3; break; case CHATSTY_GUILD : nChannel = 4; break; } switch( nID ) { case WIDC_CHECK1 : if( pWndCheck1->GetCheck() ) g_Option.m_dwChatFilter[nChannel] |= CHATSTY_GENERAL; else g_Option.m_dwChatFilter[nChannel] &= ~CHATSTY_GENERAL; SetButtonStatus(); break; case WIDC_CHECK2 : if( pWndCheck2->GetCheck() ) g_Option.m_dwChatFilter[nChannel] |= CHATSTY_WHISPER; else g_Option.m_dwChatFilter[nChannel] &= ~CHATSTY_WHISPER; SetButtonStatus(); break; case WIDC_CHECK3 : if( pWndCheck3->GetCheck() ) g_Option.m_dwChatFilter[nChannel] |= CHATSTY_SHOUT; else g_Option.m_dwChatFilter[nChannel] &= ~CHATSTY_SHOUT; SetButtonStatus(); break; case WIDC_CHECK4 : if( pWndCheck4->GetCheck() ) g_Option.m_dwChatFilter[nChannel] |= CHATSTY_PARTY; else g_Option.m_dwChatFilter[nChannel] &= ~CHATSTY_PARTY; SetButtonStatus(); break; case WIDC_CHECK5 : if( pWndCheck5->GetCheck() ) g_Option.m_dwChatFilter[nChannel] |= CHATSTY_GUILD; else g_Option.m_dwChatFilter[nChannel] &= ~CHATSTY_GUILD; SetButtonStatus(); break; #if __VER >= 8 //__Y_CHAT_SYSTEM_8 #else //#if __VER >= 8 // case WIDC_CHECK6 : if( pWndCheck6->GetCheck() ) g_Option.m_dwChatFilterEtc |= CHATSTY_HELP_CLIENT; else g_Option.m_dwChatFilterEtc &= ~CHATSTY_HELP_CLIENT; SetButtonStatus(); break; case WIDC_CHECK7 : if( pWndCheck7->GetCheck() ) g_Option.m_dwChatFilterEtc |= CHATSTY_HELP_CHAT; else g_Option.m_dwChatFilterEtc &= ~CHATSTY_HELP_CHAT; SetButtonStatus(); break; case WIDC_RADIO1 : g_Option.m_dwChatFilterEtc |= CHATSTY_GAME_CLIENT; g_Option.m_dwChatFilterEtc &= ~CHATSTY_GAME_CHAT; break; case WIDC_RADIO2 : g_Option.m_dwChatFilterEtc |= CHATSTY_GAME_CHAT; g_Option.m_dwChatFilterEtc &= ~CHATSTY_GAME_CLIENT; break; case WIDC_RADIO3 : g_Option.m_dwChatFilterEtc |= CHATSTY_SYSTEM_CLIENT; g_Option.m_dwChatFilterEtc &= ~CHATSTY_SYSTEM_CHAT; break; case WIDC_RADIO4 : g_Option.m_dwChatFilterEtc |= CHATSTY_SYSTEM_CHAT; g_Option.m_dwChatFilterEtc &= ~CHATSTY_SYSTEM_CLIENT; break; #endif //__Y_CHAT_SYSTEM_8 } pWndChat->SetChannel(); return CWndNeuz::OnChildNotify( message, nID, pLResult ); }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 251 ] ] ]
06efe8f2794554e3e8c7936d442ec1c13864d5d7
7d7efaf156c201ee742b51b0d7b6122abd3236d2
/math_util.h
f8d5afbb1eff61c75ecc57fafe271672a7aba1d7
[]
no_license
jrobble/kalman-filter
efbc711e10f70670e6228203c07e6b2153b9ff93
ef698b665f68af0b73cdb040db3eb5222b8d8b83
refs/heads/master
2021-01-19T17:13:31.442565
2009-05-14T09:59:08
2009-05-14T09:59:08
32,262,597
0
1
null
null
null
null
UTF-8
C++
false
false
4,431
h
#ifndef MATH_UTIL_H #define MATH_UTIL_H // limits library not fully implemented in Open Watcom, so use Visual C++ 2008 compiler #include <limits> #include <iostream> // Visual C++ 2008 compiler has no pow(int,int) implementation int pow(int a, int p) { return (int)(pow((double)a,p)); } // element-by-element matrix square root void sqrt(double* a, int size, double* ret) { for(int i = 0; i < size; i++) { ret[i] = sqrt(a[i]); } } // matrix maximum void max(double* a, int size, double* ret) { double max = -std::numeric_limits<double>::infinity(); double maxindex = -1; for(int i = 0; i < size; i++) { if(a[i] > max) { max = a[i]; maxindex = i; } } ret[0] = max; ret[1] = maxindex; } // matrix minimum void min(double* a, int size, double* ret) { // double min = mxGetInf(); // corrupts obj data double min = std::numeric_limits<double>::infinity(); double minindex = -1; for(int i = 0; i < size; i++) { if(a[i] < min) { min = a[i]; minindex = i; } } ret[0] = min; ret[1] = minindex; } // element-by-element absolute matrix values void abs(double* a, int size, double* ret) { for(int i = 0; i < size; i++) { ret[i] = abs(a[i]); } } // element-by-element matrix multiplication void mult(double a1, double* a2, int size, double* ret) { for(int i = 0; i < size; i++) { ret[i] = a1 * a2[i]; } } // element-by-element matrix multiplication void mult(double* a1, double* a2, int size, double* ret) { for(int i = 0; i < size; i++) { ret[i] = a1[i] * a2[i]; } } // element-by-element matrix substraction void subtract(double a1, double* a2, int size, double* ret) { for(int i = 0; i < size; i++) { ret[i] = a1 - a2[i]; } } // element-by-element matrix substraction void subtract(double* a1, double* a2, int size, double* ret) { for(int i = 0; i < size; i++) { ret[i] = a1[i] - a2[i]; } } // calc Euclidean distance double distance(double x1, double x2, double y1, double y2) { return sqrt( pow(x2-x1,2) + pow(y2-y1,2) ); } // calc maximum double max(double first, double second) { if(first >= second) { return first; } else { return second; } } // calc minimum double min(double first, double second) { if(first <= second) { return first; } else { return second; } } // calc product double prod(double array[], int size) { double prod = 0; if(size > 0) { prod = 1; for(int i = 0; i < size; i++) { prod *= array[i]; } } // DEBUG /* mexPrintf("prod size: %d\n",size); // DEBUG for(int i = 0; i < size; i++) { mexPrintf("array[%d]: %f\n",i,array[i]); // DEBUG } mexPrintf("prod: %f\n",prod); // DEBUG */ return prod; } // calculate mean squared error double calc_fitnessMSE(double absErr) { double fitnessMSE = 100000 * (1 / (1 + pow(absErr,2))); return fitnessMSE; } // round number int round(double num) { return (int) floor(num+.5); } // calculate sum double sum(double* array, int size) { double sum = 0; for(int i = 0; i < size; i++) { sum += array[i]; } return sum; } // calculate mean // note that there is no way to get the size of a dynamic array, so pass it in double mean(double* array, int size) { return sum(array,size) / size; } // calculate median double median(double* array, int size) { // quickSort(array, size); // actually, already sorted /* mexPrintf("pre-sorted:\n"); // DEBUG for(int i = 0; i < size; i++) { mexPrintf("%f, ", array[i]); // DEBUG } mexPrintf("\n"); // DEBUG mexPrintf("post-sorted:\n"); // DEBUG for(int i = 0; i < size; i++) { mexPrintf("%f, ", array[i]); // DEBUG } mexPrintf("\n"); // DEBUG */ double median = -1; if (size % 2 == 1) { // odd median = array[(int)size/2]; } else { // even median = (array[(int)size/2] + array[((int)(size/2))-1]) / 2; } return median; } #endif /* MATH_UTIL_H */
[ "fejjro@802d17c2-23ed-11de-bf1e-7b5f7763e386" ]
[ [ [ 1, 181 ] ] ]
2d3f8fd666eeb804f58c86f5eb5e0b8283bf96ed
ef23e388061a637f82b815d32f7af8cb60c5bb1f
/src/mame/includes/segag80v.h
0692c128bb4fa06da1998872091c895a76223a0a
[]
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,056
h
/************************************************************************* Sega vector hardware *************************************************************************/ #include "machine/segag80.h" class segag80v_state : public driver_device { public: segag80v_state(running_machine &machine, const driver_device_config_base &config) : driver_device(machine, config) { } UINT8 *m_mainram; UINT8 m_has_usb; UINT8 m_mult_data[2]; UINT16 m_mult_result; UINT8 m_spinner_select; UINT8 m_spinner_sign; UINT8 m_spinner_count; segag80_decrypt_func m_decrypt; UINT8 *m_vectorram; size_t m_vectorram_size; int m_min_x; int m_min_y; }; /*----------- defined in audio/segag80v.c -----------*/ WRITE8_HANDLER( elim1_sh_w ); WRITE8_HANDLER( elim2_sh_w ); WRITE8_HANDLER( spacfury1_sh_w ); WRITE8_HANDLER( spacfury2_sh_w ); WRITE8_HANDLER( zektor1_sh_w ); WRITE8_HANDLER( zektor2_sh_w ); /*----------- defined in video/segag80v.c -----------*/ VIDEO_START( segag80v ); SCREEN_UPDATE( segag80v );
[ "Mike@localhost" ]
[ [ [ 1, 43 ] ] ]
b4b42c5b4dc8f11883a24f847eb92a5c3dfc3ce5
59ce53af7ad5a1f9b12a69aadbfc7abc4c4bfc02
/publish/skinctrlex/CoolMenu/CoolContextMenu.h
46e43a01889c46cbe61b39a7eed3b9df853e57f2
[]
no_license
fingomajom/skinengine
444a89955046a6f2c7be49012ff501dc465f019e
6bb26a46a7edac88b613ea9a124abeb8a1694868
refs/heads/master
2021-01-10T11:30:51.541442
2008-07-30T07:13:11
2008-07-30T07:13:11
47,892,418
0
0
null
null
null
null
UTF-8
C++
false
false
16,022
h
// CoolContextMenu.h - implementation of the CCoolContextMenu class // ///////////////////////////////////////////////////////////////////////////// #pragma once #include "stdafx.h" #include "Draw.h" #define MAX_MENU_ITEM_TEXT_LENGTH 100 #define IMGPADDING 6 #define TEXTPADDING 8 // From <winuser.h> #define OBM_CHECK 32760 template <class T> class CCoolContextMenu { private: SIZE m_szBitmap; SIZE m_szButton; CFont m_fontMenu; // used internally, only to measure text int m_cxExtraSpacing; bool m_bFlatMenus; COLORREF m_clrMask; CSimpleStack<HMENU> m_stackMenuHandle; protected: struct MenuItemData // menu item data { LPTSTR lpstrText; UINT fType; UINT fState; int iImage; }; public: CImageList m_ImageList; protected: void MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct) { MenuItemData* pmd = (MenuItemData*)lpMeasureItemStruct->itemData; if (pmd->fType & MFT_SEPARATOR) // separator - use half system height and zero width { lpMeasureItemStruct->itemHeight = ::GetSystemMetrics(SM_CYMENU) / 2; lpMeasureItemStruct->itemWidth = 0; } else { // Compute size of text - use DrawText with DT_CALCRECT CWindowDC dc(NULL); CFont fontBold; HFONT hOldFont = NULL; if (pmd->fState & MFS_DEFAULT) { // Need bold version of font LOGFONT lf = { 0 }; m_fontMenu.GetLogFont(lf); lf.lfWeight += 200; fontBold.CreateFontIndirect(&lf); ATLASSERT(fontBold.m_hFont != NULL); hOldFont = dc.SelectFont(fontBold); fontBold.DeleteObject(); } else hOldFont = dc.SelectFont(m_fontMenu); RECT rcText = { 0, 0, 0, 0 }; dc.DrawText(pmd->lpstrText, -1, &rcText, DT_SINGLELINE | DT_LEFT | DT_VCENTER | DT_CALCRECT); int cx = rcText.right - rcText.left; dc.SelectFont(hOldFont); LOGFONT lf = { 0 }; m_fontMenu.GetLogFont(lf); int cy = lf.lfHeight; if (cy < 0) cy = -cy; const int cyMargin = 10; cy += cyMargin; lpMeasureItemStruct->itemHeight = cy; // Width is width of text plus some cx += 4; // L/R margin for readability cx += 1; // space between button and menu text cx += 2 * m_szButton.cx; // button width cx += m_cxExtraSpacing; // extra between item text and accelerator keys // Windows adds 1 to returned value cx -= ::GetSystemMetrics(SM_CXMENUCHECK) - 1; lpMeasureItemStruct->itemWidth = cx; // we are done } } void DrawItem (LPDRAWITEMSTRUCT lpDrawItemStruct) { MenuItemData* pmd = (MenuItemData*)lpDrawItemStruct->itemData; CDCHandle dc = lpDrawItemStruct->hDC; RECT& rcItem = lpDrawItemStruct->rcItem; LPCRECT pRect = &rcItem; BOOL bDisabled = lpDrawItemStruct->itemState & ODS_GRAYED; BOOL bSelected = lpDrawItemStruct->itemState & ODS_SELECTED; BOOL bChecked = lpDrawItemStruct->itemState & ODS_CHECKED; COLORREF crBackImg = CLR_NONE; CDCHandle* pDC = &dc; if (bSelected && !bDisabled) { COLORREF crHighLight = ::GetSysColor(COLOR_HIGHLIGHT); CPenDC pen(*pDC, crHighLight); CBrushDC brush(*pDC, crBackImg = bDisabled ? HLS_TRANSFORM(::GetSysColor (COLOR_3DFACE), +73, 0) : HLS_TRANSFORM (crHighLight, +70, -57)); pDC->Rectangle (pRect); } else { // Draw the menu item background CRect rc(pRect); rc.right = m_szBitmap.cx + IMGPADDING; pDC->FillSolidRect(rc, crBackImg = HLS_TRANSFORM(::GetSysColor(COLOR_3DFACE), +20, 0)); rc.left = rc.right; rc.right = pRect->right; pDC->FillSolidRect(rc, HLS_TRANSFORM(::GetSysColor(COLOR_3DFACE), +75, 0)); } // Menu item is a separator if (pmd->fType & MFT_SEPARATOR) { rcItem.top += (rcItem.bottom - rcItem.top) / 2; // vertical center dc.DrawEdge(&rcItem, EDGE_ETCHED, BF_TOP); // draw separator line } else { // Draw the text CRect rc (pRect); CString sCaption = pmd->lpstrText; int nTab = sCaption.Find('\t'); if (nTab >= 0) { sCaption = sCaption.Left (nTab); } pDC->SetTextColor(bDisabled ? HLS_TRANSFORM(::GetSysColor(COLOR_3DFACE), -18, 0) : ::GetSysColor(COLOR_MENUTEXT)); pDC->SetBkMode(TRANSPARENT); CBoldDC bold(*pDC, (lpDrawItemStruct->itemState & ODS_DEFAULT) != 0); rc.left = m_szBitmap.cx + IMGPADDING + TEXTPADDING; pDC->DrawText(sCaption, sCaption.GetLength(), rc, DT_SINGLELINE|DT_VCENTER|DT_LEFT); if (nTab >= 0) { rc.right -= TEXTPADDING + 4; pDC->DrawText(pmd->lpstrText + nTab + 1, _tcslen(pmd->lpstrText + nTab + 1), rc, DT_SINGLELINE|DT_VCENTER|DT_RIGHT); } // Draw background and border around the check mark if (bChecked) { COLORREF crHighLight = ::GetSysColor(COLOR_HIGHLIGHT); CPenDC pen(*pDC, crHighLight); CBrushDC brush(*pDC, crBackImg = bDisabled ? HLS_TRANSFORM(::GetSysColor (COLOR_3DFACE), +73, 0) : (bSelected ? HLS_TRANSFORM(crHighLight, +50, -50) : HLS_TRANSFORM(crHighLight, +70, -57))); pDC->Rectangle(CRect(pRect->left + 1, pRect->top + 1, pRect->left + m_szButton.cx - 2, pRect->bottom - 1)); } if (m_ImageList != NULL && pmd->iImage >= 0) { bool bOver = !bDisabled && bSelected; if (bDisabled || (bSelected && !bChecked)) { HICON hIcon = ImageList_ExtractIcon(NULL, m_ImageList, pmd->iImage); CBrush brush; brush.CreateSolidBrush(bOver ? HLS_TRANSFORM(::GetSysColor(COLOR_HIGHLIGHT), +50, -66) : HLS_TRANSFORM(::GetSysColor(COLOR_3DFACE), -27, 0)); pDC->DrawState(CPoint(pRect->left + (bOver ? 4 : 3), rc.top + (bOver ? 5 : 4)), CSize(m_szBitmap.cx, m_szBitmap.cx), hIcon, DSS_MONO, brush); DestroyIcon(hIcon); } if (!bDisabled) { ::ImageList_Draw(m_ImageList, pmd->iImage, pDC->m_hDC, pRect->left + ((bSelected && !bChecked) ? 2 : 3), rc.top + ((bSelected && !bChecked) ? 3 : 4), ILD_TRANSPARENT); } } else if (bChecked) { // Draw the check mark rc.left = pRect->left + 5; rc.right = rc.left + m_szBitmap.cx + IMGPADDING; pDC->SetBkColor(crBackImg); HBITMAP hBmp = LoadBitmap(NULL, MAKEINTRESOURCE(OBM_CHECK)); BOOL bRet = pDC->DrawState(CPoint(rc.left,rc.top + 3), CSize(rc.Size()), hBmp, DSS_NORMAL, (HBRUSH)NULL); DeleteObject(hBmp); } } } LRESULT InitMenuPopupHandler(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { // System menu, do nothing if ((BOOL)HIWORD(lParam)) { bHandled = FALSE; return 1; } CMenuHandle menuPopup = (HMENU)wParam; ATLASSERT(menuPopup.m_hMenu != NULL); TCHAR szString[MAX_MENU_ITEM_TEXT_LENGTH]; BOOL bRet = FALSE; for (int i = 0; i < menuPopup.GetMenuItemCount(); i++) { CMenuItemInfo mii; mii.cch = MAX_MENU_ITEM_TEXT_LENGTH; mii.fMask = MIIM_CHECKMARKS | MIIM_DATA | MIIM_ID | MIIM_STATE | MIIM_SUBMENU | MIIM_TYPE; mii.dwTypeData = szString; bRet = menuPopup.GetMenuItemInfo(i, TRUE, &mii); ATLASSERT(bRet); if (!(mii.fType & MFT_OWNERDRAW)) // not already an ownerdraw item { MenuItemData * pMI = new MenuItemData; ATLASSERT(pMI != NULL); if (pMI) { // Make this menu item an owner-drawn mii.fType |= MFT_OWNERDRAW; pMI->fType = mii.fType; pMI->fState = mii.fState; // Associate an image with a menu item static_cast<T*>(this)->AssociateImage(mii, pMI); pMI->lpstrText = new TCHAR[lstrlen(szString) + 1]; ATLASSERT(pMI->lpstrText != NULL); if (pMI->lpstrText != NULL) lstrcpy(pMI->lpstrText, szString); mii.dwItemData = (ULONG_PTR)pMI; bRet = menuPopup.SetMenuItemInfo(i, TRUE, &mii); ATLASSERT(bRet); } } } // Add it to the list m_stackMenuHandle.Push(menuPopup.m_hMenu); return 0; } LRESULT MenuSelectHandler(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { // Check if a menu is closing, do a cleanup if (HIWORD(wParam) == 0xFFFF && lParam == NULL) // Menu closing { // Restore the menu items to the previous state for all menus that were converted HMENU hMenu = NULL; while ((hMenu = m_stackMenuHandle.Pop()) != NULL) { CMenuHandle menuPopup = hMenu; ATLASSERT(menuPopup.m_hMenu != NULL); // Restore state and delete menu item data BOOL bRet = FALSE; for (int i = 0; i < menuPopup.GetMenuItemCount(); i++) { CMenuItemInfo mii; mii.fMask = MIIM_DATA | MIIM_TYPE; bRet = menuPopup.GetMenuItemInfo(i, TRUE, &mii); ATLASSERT(bRet); MenuItemData * pMI = (MenuItemData*)mii.dwItemData; if (pMI != NULL) { mii.fMask = MIIM_DATA | MIIM_TYPE | MIIM_STATE; mii.fType = pMI->fType; mii.dwTypeData = pMI->lpstrText; mii.cch = lstrlen(pMI->lpstrText); mii.dwItemData = NULL; bRet = menuPopup.SetMenuItemInfo(i, TRUE, &mii); ATLASSERT(bRet); delete [] pMI->lpstrText; delete pMI; } } } } bHandled = FALSE; return 1; } LRESULT MeasureItemHandler(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { LPMEASUREITEMSTRUCT lpMeasureItemStruct = (LPMEASUREITEMSTRUCT)lParam; MenuItemData * pmd = (MenuItemData*)lpMeasureItemStruct->itemData; if (lpMeasureItemStruct->CtlType == ODT_MENU && pmd != NULL) MeasureItem(lpMeasureItemStruct); else bHandled = FALSE; return (LRESULT)TRUE; } LRESULT DrawItemHandler(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { LPDRAWITEMSTRUCT lpDrawItemStruct = (LPDRAWITEMSTRUCT)lParam; MenuItemData * pMI = (MenuItemData*)lpDrawItemStruct->itemData; if (lpDrawItemStruct->CtlType == ODT_MENU && pMI != NULL) // only owner-drawn menu item DrawItem(lpDrawItemStruct); else bHandled = FALSE; return TRUE; } public: CCoolContextMenu() { m_cxExtraSpacing = 0; m_clrMask = RGB(192, 192, 192); m_szBitmap.cx = 16; m_szBitmap.cy = 15; m_szButton.cx = m_szBitmap.cx + 6; m_szButton.cy = m_szBitmap.cy + 6; } ~CCoolContextMenu() { m_ImageList.Destroy(); m_fontMenu.DeleteObject(); } // Note: do not forget to put CHAIN_MSG_MAP in your message map. BEGIN_MSG_MAP(CCoolContextMenu) MESSAGE_HANDLER(WM_INITMENUPOPUP, OnInitMenuPopup) MESSAGE_HANDLER(WM_MENUSELECT, OnMenuSelect) MESSAGE_HANDLER(WM_DRAWITEM, OnDrawItem) MESSAGE_HANDLER(WM_MEASUREITEM, OnMeasureItem) END_MSG_MAP() // Mostly copied from atlctrlw.h void GetSystemSettings() { // Set up the font NONCLIENTMETRICS info = { 0 }; info.cbSize = sizeof(info); BOOL bRet = ::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(info), &info, 0); ATLASSERT(bRet); if (bRet) { LOGFONT logfont = { 0 }; if (m_fontMenu.m_hFont != NULL) m_fontMenu.GetLogFont(logfont); if (logfont.lfHeight != info.lfMenuFont.lfHeight || logfont.lfWidth != info.lfMenuFont.lfWidth || logfont.lfEscapement != info.lfMenuFont.lfEscapement || logfont.lfOrientation != info.lfMenuFont.lfOrientation || logfont.lfWeight != info.lfMenuFont.lfWeight || logfont.lfItalic != info.lfMenuFont.lfItalic || logfont.lfUnderline != info.lfMenuFont.lfUnderline || logfont.lfStrikeOut != info.lfMenuFont.lfStrikeOut || logfont.lfCharSet != info.lfMenuFont.lfCharSet || logfont.lfOutPrecision != info.lfMenuFont.lfOutPrecision || logfont.lfClipPrecision != info.lfMenuFont.lfClipPrecision || logfont.lfQuality != info.lfMenuFont.lfQuality || logfont.lfPitchAndFamily != info.lfMenuFont.lfPitchAndFamily || lstrcmp(logfont.lfFaceName, info.lfMenuFont.lfFaceName) != 0) { HFONT hFontMenu = ::CreateFontIndirect(&info.lfMenuFont); ATLASSERT(hFontMenu != NULL); if (hFontMenu != NULL) { if (m_fontMenu.m_hFont != NULL) m_fontMenu.DeleteObject(); m_fontMenu.Attach(hFontMenu); static_cast<T*>(this)->SetFont(m_fontMenu); } } } // Check if we need extra spacing for menu item text CWindowDC dc(static_cast<T*>(this)->m_hWnd); HFONT hFontOld = dc.SelectFont(m_fontMenu); RECT rcText = { 0, 0, 0, 0 }; dc.DrawText(_T("\t"), -1, &rcText, DT_SINGLELINE | DT_LEFT | DT_VCENTER | DT_CALCRECT); if ((rcText.right - rcText.left) < 4) { ::SetRectEmpty(&rcText); dc.DrawText(_T("x"), -1, &rcText, DT_SINGLELINE | DT_LEFT | DT_VCENTER | DT_CALCRECT); m_cxExtraSpacing = rcText.right - rcText.left; } else m_cxExtraSpacing = 0; dc.SelectFont(hFontOld); // Get Windows version OSVERSIONINFO ovi = { sizeof(OSVERSIONINFO) }; ::GetVersionEx(&ovi); // Query flat menu mode (Windows XP or later) if ((ovi.dwMajorVersion == 5 && ovi.dwMinorVersion >= 1) || (ovi.dwMajorVersion > 5)) { #ifndef SPI_GETFLATMENU const UINT SPI_GETFLATMENU = 0x1022; #endif // !SPI_GETFLATMENU BOOL bRetVal = FALSE; bRet = ::SystemParametersInfo(SPI_GETFLATMENU, 0, &bRetVal, 0); m_bFlatMenus = (bRet && bRetVal); } } LRESULT OnInitMenuPopup(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { return InitMenuPopupHandler(uMsg, wParam, lParam, bHandled); } LRESULT OnMenuSelect(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { return MenuSelectHandler(uMsg, wParam, lParam, bHandled); } LRESULT OnMeasureItem(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { return MeasureItemHandler(uMsg, wParam, lParam, bHandled); } LRESULT OnDrawItem(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { return DrawItemHandler(uMsg, wParam, lParam, bHandled); } void AssociateImage(CMenuItemInfo& mii, MenuItemData * pMI) { // Default implementation, does not do anything } };
[ [ [ 1, 463 ] ] ]
cc1545bf29c4f88cb1f0ca9c04a1396201437e6f
e03ee4538dce040fe16fc7bb48d495735ac324f4
/SpecialEffects/Ejemplo/main.cpp
1689f8b20888b30223d6caabb3c4f5c26d7cce32
[]
no_license
vdelgadov/itcvideogame
dca6bcb084c5dde25ecf29ab1555dbe8b0a9a441
5eac60e901b29bff4d844f34cd52f97f4d1407b5
refs/heads/master
2020-05-16T23:43:48.956373
2009-12-01T02:09:08
2009-12-01T02:09:08
42,265,496
0
0
null
null
null
null
UTF-8
C++
false
false
10,661
cpp
//Every windows application needs to include this #include "windows.h" //Every Direct3D application this #include "d3d9.h" #include "d3dx9.h" bool g_bContinue = true; LPD3DXEFFECT g_lpEffect = NULL; LPDIRECT3DVERTEXBUFFER9 g_lpVertexBuffer = NULL; //The combined transformation will end up in this matrix: D3DXMATRIX g_ShaderMatrix; //Camera Position LPD3DXMESH meshTeapot; // define the mesh pointer D3DXVECTOR4 g_v3Position4; D3DXVECTOR3 g_v3Position = D3DXVECTOR3(0.0f,0.0f,-5.0f); D3DXVECTOR4 g_vLightDirection = D3DXVECTOR4(0.0f,0.0f,1.0f,1.0f); //D3DXVECTOR4 g_vDIC = D3DXVECTOR4(0.4f,0.4f,0.4f,1.0f); //D3DXVECTOR4 g_vSpecIC = D3DXVECTOR4(1.0f,1.0f,1.0f,1.0f); //Camera LookAt point D3DXVECTOR3 g_v3LookAt = D3DXVECTOR3(0.0f,0.0f,0.0f); //TEXTURE LPDIRECT3DTEXTURE9 g_lpTexture = NULL; LPDIRECT3DTEXTURE9 g_lpTexture2 = NULL; //Definition of the first Vertex Format //including position and diffuse color #define D3DFVF_COLOREDVERTEX (D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_DIFFUSE | D3DFVF_TEX1 | D3DFVF_TEXCOORDSIZE3(3)) struct COLORED_VERTEX { float x, y, z; //Position float i,j,k; //normal vector DWORD color; //Color float tu,tv; float ti,tj,tk; //tangent }; //Besides the main function, there must be a message processing function LRESULT WINAPI MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { float fSpeed = 0.2f; switch( msg ) { case WM_DESTROY: PostQuitMessage( 0 ); g_bContinue = false; return 0; //handle keypress case WM_CHAR: switch(wParam) { case 'i': g_v3Position4.z += fSpeed; g_v3Position.z += fSpeed; break; case 'k': g_v3Position.z -= fSpeed; g_v3Position4.z-= fSpeed; break; } break; case WM_KEYDOWN: switch(wParam) { //change lookAt with arrow keys case VK_UP: g_v3LookAt.y += fSpeed; break; case VK_DOWN: g_v3LookAt.y -= fSpeed; break; case VK_LEFT: g_v3LookAt.x += fSpeed; break; case VK_RIGHT: g_v3LookAt.x -= fSpeed; break; case 0X069: g_v3Position4.z += fSpeed; g_v3Position.z += fSpeed; break; case 'j': g_v3Position.z -= fSpeed; g_v3Position4.z-= fSpeed; break; } break; } return DefWindowProc( hWnd, msg, wParam, lParam ); } //The entry point of a windows application is the WinMain function INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR, INT ) { //Create a window class. WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, MsgProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, "Direct3D Window", NULL }; //Register the window class. RegisterClassEx( &wc ); //Create the application's window. HWND hWnd = CreateWindow( "Direct3D Window", "DirectX Wiki - D3D9 Tutorial 3", WS_OVERLAPPEDWINDOW, 100, 100, 400, 400, GetDesktopWindow(), NULL, wc.hInstance, NULL ); ShowWindow(hWnd,SW_SHOW); //Create the Direct3D Object LPDIRECT3D9 pD3D = NULL; if( NULL == (pD3D = Direct3DCreate9(D3D_SDK_VERSION))) return E_FAIL; //Setup the device presentation parameters D3DPRESENT_PARAMETERS d3dpp; ZeroMemory( &d3dpp, sizeof(d3dpp) ); d3dpp.Windowed = TRUE; d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dpp.BackBufferFormat = D3DFMT_UNKNOWN; //The final step is to use the IDirect3D9::CreateDevice method to create the Direct3D device, as illustrated in the //following code example. LPDIRECT3DDEVICE9 pd3dDevice = NULL; if( FAILED( pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &d3dpp, &pd3dDevice ) ) ) { MessageBox(hWnd, "No HAL HARDWARE_VERTEXPROCESSING! Sample will exit!", NULL, 0); pD3D->Release(); pD3D = NULL; return E_FAIL; } //setting the buffersize to 4 vertices * structure size UINT uiBufferSize = 4*sizeof(COLORED_VERTEX); //Creating Texture //creating the Vertexbuffer if( FAILED( pd3dDevice->CreateVertexBuffer( uiBufferSize, D3DUSAGE_WRITEONLY, D3DFVF_COLOREDVERTEX, D3DPOOL_DEFAULT, &g_lpVertexBuffer, NULL ) ) ) return E_FAIL; COLORED_VERTEX* pVertices; //lock for writing. if( FAILED( g_lpVertexBuffer->Lock( 0, uiBufferSize, (void**)&pVertices, 0 ) ) ) return E_FAIL; //Write now. //A simple Quadrangle pVertices[0].x = -1.0f; //left pVertices[0].y = -1.0f; //bottom pVertices[0].z = 0.0f; pVertices[0].color = 0xff0000ff; //red pVertices[0].i=0.0f; pVertices[0].j=0.0f; pVertices[0].k=1.0f; pVertices[0].tu=0.0f; pVertices[0].tv=1.0f; pVertices[0].ti=0.5f; pVertices[0].tj=0.5f; pVertices[0].tk=0.0f; pVertices[1].x = -1.0f; //left pVertices[1].y = 1.0f; //top pVertices[1].z = 0.0f; pVertices[1].color = 0xff0000ff; //blue pVertices[1].i=0.0f; pVertices[1].j=0.0f; pVertices[1].k=1.0f; pVertices[1].tu=0.0f; pVertices[1].tv=0.0f; pVertices[1].ti=0.5f; pVertices[1].tj=-0.5f; pVertices[1].tk=0.0f; pVertices[2].x = 1.0f; //right pVertices[2].y = -1.0f; //bottom pVertices[2].z = 0.0f; pVertices[2].color = 0xff0000ff; //green pVertices[2].i=0.0f; pVertices[2].j=0.0f; pVertices[2].k=1.0f; pVertices[2].tu=1.0f; pVertices[2].tv=1.0f; pVertices[2].ti=-0.5f; pVertices[2].tj=0.5f; pVertices[2].tk=0.0f; pVertices[3].x = 1.0f; //right pVertices[3].y = 1.0f; //top pVertices[3].z = 0.0f; pVertices[3].color = 0xff0000ff; //white pVertices[3].i=0.0f; pVertices[3].j=0.0f; pVertices[3].k=1.0f; pVertices[3].tu=1.0f; pVertices[3].tv=0.0f; pVertices[3].ti=-0.5f; pVertices[3].tj=-0.5f; pVertices[3].tk=0; //unlock buffer. g_lpVertexBuffer->Unlock(); //setting the vertex formats pd3dDevice->SetFVF( D3DFVF_COLOREDVERTEX ); //handover the buffer to the device pd3dDevice->SetStreamSource( 0, g_lpVertexBuffer, 0, sizeof(COLORED_VERTEX) ); if(FAILED(D3DXCreateEffectFromFile( pd3dDevice, "Effect.fx", NULL, NULL, D3DXSHADER_ENABLE_BACKWARDS_COMPATIBILITY, NULL, &g_lpEffect, NULL ))) return E_FAIL; D3DXCreateSphere(pd3dDevice,1.0f,40,40, &meshTeapot, NULL); LPD3DXMESH fvfMesh; //you need to clone the fvf before you do anything else /* meshTeapot->CloneMeshFVF(D3DXMESH_VB_MANAGED , D3DFVF_COLOREDVERTEX, pd3dDevice, &fvfMesh); D3DXComputeTangentFrameEx( fvfMesh, D3DDECLUSAGE_TEXCOORD, 0, D3DDECLUSAGE_TANGENT, 0, D3DX_DEFAULT, 0, D3DDECLUSAGE_NORMAL, 0, D3DXTANGENT_CALCULATE_NORMALS, NULL, -1, 0, -1, &newMesh, NULL ); fvfMesh->Release(); */ meshTeapot->CloneMeshFVF(D3DXMESH_VB_MANAGED , D3DFVF_COLOREDVERTEX, pd3dDevice, &fvfMesh); D3DXComputeTangentFrameEx( fvfMesh, D3DX_DEFAULT, 0, D3DX_DEFAULT, 0, D3DX_DEFAULT, 0, D3DDECLUSAGE_NORMAL, 0, D3DXTANGENT_GENERATE_IN_PLACE | D3DXTANGENT_CALCULATE_NORMALS, NULL, -1.01f, -0.01f, -1.01f, NULL, NULL); if( FAILED( D3DXCreateTextureFromFile( pd3dDevice, "brickwork-texture.jpg", &g_lpTexture ) ) ) return E_FAIL; if( FAILED( D3DXCreateTextureFromFile( pd3dDevice, "bricks.jpg", &g_lpTexture2 ) ) ) return E_FAIL; //the matrices: //the first transforms from world to view/camera space, //the second from camera to screen space, //the third transforms from object to world space D3DXMATRIX ViewMatrix, PerspectiveMatrix, WorldMatrix; //we intialize them with identity D3DXMatrixIdentity(&g_ShaderMatrix); D3DXMatrixIdentity(&WorldMatrix); D3DXMatrixIdentity(&ViewMatrix); D3DXMatrixIdentity(&PerspectiveMatrix); //calculating a perspective projection matrix //parameters besides the output matrix are: //the fovY, the aspect ration, the near and far z values(for clipping) D3DXMatrixPerspectiveFovLH(&PerspectiveMatrix, D3DX_PI/4.0f, 1.0f, 0.01f, 100.0f); //Pass the Texture to the .fx file g_lpEffect->SetTexture("ColorMap", g_lpTexture); g_lpEffect->SetTexture("BumpMap", g_lpTexture2); MSG msg; while( g_bContinue ) { //Do a little position animation here for the objects world matrix D3DXMatrixTranslation(&WorldMatrix,sinf(GetTickCount()/1000.0f),0,0); //Calculate a view matrix with position and look at vector D3DXMatrixLookAtLH(&ViewMatrix, &g_v3Position, &g_v3LookAt, &D3DXVECTOR3(0.0f,1.0f,0.0f)); //Concatenating the matrices by multiplication. g_ShaderMatrix = ViewMatrix * PerspectiveMatrix * WorldMatrix; g_v3Position4.x=g_v3LookAt.x-g_v3Position.x; g_v3Position4.y=g_v3LookAt.y-g_v3Position.y; g_v3Position4.z=g_v3LookAt.z-g_v3Position.z; //handover the matrix to the effect. g_lpEffect->SetMatrix( "matWorldViewProj", &g_ShaderMatrix); g_lpEffect->SetMatrix( "matWorld", &WorldMatrix ); g_lpEffect->SetVector("vecLightDir",&g_vLightDirection); g_lpEffect->SetVector("vecEye",&g_v3Position4);//posicion del ojo //g_lpEffect->SetVector("vDIC",&g_vDIC);//color del diffuse lighting //g_lpEffect->SetVector("VSpecIC",&g_vSpecIC); //Clear render region with blue pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0 ); //before rendering something, you have to call this pd3dDevice->BeginScene(); //rendering of scene objects happens here UINT uiPasses = 0; g_lpEffect->Begin(&uiPasses, 0);//0 = flags DWORD for (UINT uiPass = 0; uiPass < uiPasses; uiPass++) { g_lpEffect->BeginPass(uiPass); //meshTeapot->DrawSubset(0); //fvfMesh->DrawSubset(0); pd3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0, 2 ); g_lpEffect->EndPass(); } g_lpEffect->End(); //after the scene call pd3dDevice->EndScene(); //update Screen pd3dDevice->Present(NULL, NULL, NULL, NULL); // A window has to handle its messages. TranslateMessage( &msg ); DispatchMessage( &msg ); PeekMessage(&msg, 0, 0, 0, PM_REMOVE); } //Do not forget to clean up here meshTeapot->Release(); g_lpTexture->Release(); g_lpTexture2->Release(); g_lpTexture=NULL; g_lpEffect->Release(); g_lpEffect = NULL; g_lpVertexBuffer->Release(); g_lpVertexBuffer = NULL; pd3dDevice->Release(); pd3dDevice = NULL; pD3D->Release(); pD3D = NULL; return 0; }
[ "jr.glezt@972b8bf6-92a2-11de-b72a-e7346c8bff7a" ]
[ [ [ 1, 350 ] ] ]
43a5c3a0dac78f7a1c2066390defbcfe9a24834d
e2e49023f5a82922cb9b134e93ae926ed69675a1
/tools/aoslcpp/source/aosl/axis_positive_z.cpp
e4d04cbe222c446e432617f85acf38831781bd4a
[]
no_license
invy/mjklaim-freewindows
c93c867e93f0e2fe1d33f207306c0b9538ac61d6
30de8e3dfcde4e81a57e9059dfaf54c98cc1135b
refs/heads/master
2021-01-10T10:21:51.579762
2011-12-12T18:56:43
2011-12-12T18:56:43
54,794,395
1
0
null
null
null
null
UTF-8
C++
false
false
4,336
cpp
// Copyright (C) 2005-2010 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema // to C++ data binding compiler, in the Proprietary License mode. // You should have received a proprietary license from Code Synthesis // Tools CC prior to generating this code. See the license text for // conditions. // // Begin prologue. // #define AOSLCPP_SOURCE // // End prologue. #include <xsd/cxx/pre.hxx> #include "aosl/axis_positive_z.hpp" #include <xsd/cxx/xml/dom/wildcard-source.hxx> #include <xsd/cxx/xml/dom/parsing-source.hxx> #include <xsd/cxx/tree/type-factory-map.hxx> #include <xsd/cxx/tree/comparison-map.hxx> namespace _xsd { static const ::xsd::cxx::tree::type_factory_plate< 0, char > type_factory_plate_init; static const ::xsd::cxx::tree::comparison_plate< 0, char > comparison_plate_init; } namespace aosl { // Axis_positive_z // Axis_positive_z:: Axis_positive_z (const ::xercesc::DOMElement& e, ::xml_schema::Flags f, ::xml_schema::Container* c) : ::xml_schema::String (e, f, c) { _xsd_Axis_positive_z_convert (); } Axis_positive_z:: Axis_positive_z (const ::xercesc::DOMAttr& a, ::xml_schema::Flags f, ::xml_schema::Container* c) : ::xml_schema::String (a, f, c) { _xsd_Axis_positive_z_convert (); } Axis_positive_z:: Axis_positive_z (const ::std::string& s, const ::xercesc::DOMElement* e, ::xml_schema::Flags f, ::xml_schema::Container* c) : ::xml_schema::String (s, e, f, c) { _xsd_Axis_positive_z_convert (); } Axis_positive_z* Axis_positive_z:: _clone (::xml_schema::Flags f, ::xml_schema::Container* c) const { return new class Axis_positive_z (*this, f, c); } Axis_positive_z::Value Axis_positive_z:: _xsd_Axis_positive_z_convert () const { ::xsd::cxx::tree::enum_comparator< char > c (_xsd_Axis_positive_z_literals_); const Value* i (::std::lower_bound ( _xsd_Axis_positive_z_indexes_, _xsd_Axis_positive_z_indexes_ + 2, *this, c)); if (i == _xsd_Axis_positive_z_indexes_ + 2 || _xsd_Axis_positive_z_literals_[*i] != *this) { throw ::xsd::cxx::tree::unexpected_enumerator < char > (*this); } return *i; } const char* const Axis_positive_z:: _xsd_Axis_positive_z_literals_[2] = { "forward", "backward" }; const Axis_positive_z::Value Axis_positive_z:: _xsd_Axis_positive_z_indexes_[2] = { ::aosl::Axis_positive_z::backward, ::aosl::Axis_positive_z::forward }; } #include <ostream> #include <xsd/cxx/tree/std-ostream-map.hxx> namespace _xsd { static const ::xsd::cxx::tree::std_ostream_plate< 0, char > std_ostream_plate_init; } namespace aosl { ::std::ostream& operator<< (::std::ostream& o, Axis_positive_z::Value i) { return o << Axis_positive_z::_xsd_Axis_positive_z_literals_[i]; } ::std::ostream& operator<< (::std::ostream& o, const Axis_positive_z& i) { return o << static_cast< const ::xml_schema::String& > (i); } } #include <istream> #include <xsd/cxx/xml/sax/std-input-source.hxx> #include <xsd/cxx/tree/error-handler.hxx> namespace aosl { } #include <ostream> #include <xsd/cxx/tree/error-handler.hxx> #include <xsd/cxx/xml/dom/serialization-source.hxx> #include <xsd/cxx/tree/type-serializer-map.hxx> namespace _xsd { static const ::xsd::cxx::tree::type_serializer_plate< 0, char > type_serializer_plate_init; } namespace aosl { void operator<< (::xercesc::DOMElement& e, const Axis_positive_z& i) { e << static_cast< const ::xml_schema::String& > (i); } void operator<< (::xercesc::DOMAttr& a, const Axis_positive_z& i) { a << static_cast< const ::xml_schema::String& > (i); } void operator<< (::xml_schema::ListStream& l, const Axis_positive_z& i) { l << static_cast< const ::xml_schema::String& > (i); } } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue.
[ "klaim@localhost" ]
[ [ [ 1, 189 ] ] ]
7c841df50f55f2e345e6d16ec774f6f6e2a5ffb0
d4ba9775ead602c9f41e7859b956c0ac1efa2cfb
/src/framework-ActiveX/Js2nCtrl.cpp
d466ea14ebc534b001f299e81a2e52bd6e7ac5f2
[]
no_license
xgc820313/js2n
2460938a47e00a225e5c9a810285950b2d808756
77cec2ea39d465f98added96b61eab1ee30fd53a
refs/heads/master
2016-09-06T07:05:03.475054
2007-09-04T21:08:49
2007-09-04T21:08:49
38,345,093
0
0
null
null
null
null
UTF-8
C++
false
false
7,050
cpp
// Js2nCtrl.cpp : Implementation of the CJs2nCtrl ActiveX Control class. #include "stdafx.h" #include "Js2n.h" #include "Js2nCtrl.h" #include "Js2nPropPage.h" #include "helpers.h" #include "registry.h" #include "queue.h" #include <comcat.h> #include <objsafe.h> #ifdef _DEBUG #define new DEBUG_NEW #endif IMPLEMENT_DYNCREATE(CJs2nCtrl, COleControl) #define WM_NLOGICEVENT WM_USER+101 // Message map BEGIN_MESSAGE_MAP(CJs2nCtrl, COleControl) ON_MESSAGE(WM_NLOGICEVENT,OnNativeLogicEvent) ON_OLEVERB(AFX_IDS_VERB_PROPERTIES, OnProperties) END_MESSAGE_MAP() // Dispatch map BEGIN_DISPATCH_MAP(CJs2nCtrl, COleControl) DISP_FUNCTION(CJs2nCtrl, "sendCmd", Send, VT_BSTR, VTS_BSTR) DISP_FUNCTION_ID(CJs2nCtrl, "AboutBox", DISPID_ABOUTBOX, AboutBox, VT_EMPTY, VTS_NONE) END_DISPATCH_MAP() // Event map BEGIN_EVENT_MAP(CJs2nCtrl, COleControl) EVENT_CUSTOM("Js2nEvent", FireOnEvent, VTS_BSTR) END_EVENT_MAP() // Property pages // TODO: Add more property pages as needed. Remember to increase the count! BEGIN_PROPPAGEIDS(CJs2nCtrl, 1) PROPPAGEID(CJs2nPropPage::guid) END_PROPPAGEIDS(CJs2nCtrl) // Initialize class factory and guid // {C802F39D-BF85-427a-A334-77E501DB62E9} IMPLEMENT_OLECREATE_EX(CJs2nCtrl, "Js2n.Js2nCtrl.1", 0xc802f39d, 0xbf85, 0x427a, 0xa3, 0x34, 0x77, 0xe5, 0x1, 0xdb, 0x62, 0xe9); // Type library ID and version IMPLEMENT_OLETYPELIB(CJs2nCtrl, _tlid, _wVerMajor, _wVerMinor) // Interface IDs // {DB94C377-4B82-4cac-B5C6-B927ABCE6E52} const IID BASED_CODE IID_DJs2n = { 0xdb94c377, 0x4b82, 0x4cac, { 0xb5, 0xc6, 0xb9, 0x27, 0xab, 0xce, 0x6e, 0x52 } }; // {6FCA21FB-78E6-4825-8319-5C8285AE08CA} const IID BASED_CODE IID_DJs2nEvents = { 0x6fca21fb, 0x78e6, 0x4825, { 0x83, 0x19, 0x5c, 0x82, 0x85, 0xae, 0x8, 0xca } }; // Control type information static const DWORD BASED_CODE _dwJs2nOleMisc = OLEMISC_ACTIVATEWHENVISIBLE | OLEMISC_SETCLIENTSITEFIRST | OLEMISC_INSIDEOUT | OLEMISC_CANTLINKINSIDE | OLEMISC_RECOMPOSEONRESIZE; IMPLEMENT_OLECTLTYPE(CJs2nCtrl, IDS_Js2n, _dwJs2nOleMisc) PString FindPluginsPath( void ) { CRegString regStr( "CLSID\\{C802F39D-BF85-427A-A334-77E501DB62E9}\\InprocServer32\\", "", FALSE, HKEY_CLASSES_ROOT ); string strRead = regStr.read(); PString strPluginPath = strRead; PINDEX nPos = strPluginPath.FindLast( "\\" ); strPluginPath = strPluginPath.Mid( 0, nPos + 1 ) + "js2n\\"; return strPluginPath; } // CJs2nCtrl::CJs2nCtrlFactory::UpdateRegistry - // Adds or removes system registry entries for CJs2nCtrl BOOL CJs2nCtrl::CJs2nCtrlFactory::UpdateRegistry(BOOL bRegister) { if (bRegister) { BOOL retval = AfxOleRegisterControlClass( AfxGetInstanceHandle(), m_clsid, m_lpszProgID, IDS_Js2n, IDB_Js2n, afxRegApartmentThreading, _dwJs2nOleMisc, _tlid, _wVerMajor, _wVerMinor); // mark as safe for scripting--failure OK HRESULT hr = CreateComponentCategory(CATID_SafeForScripting, L"Controls that are safely scriptable"); if (SUCCEEDED(hr)) // only register if category exists RegisterCLSIDInCategory(m_clsid, CATID_SafeForScripting); // don't care if this call fails // mark as safe for data initialization hr = CreateComponentCategory(CATID_SafeForInitializing, L"Controls safely initializable from persistent data"); if (SUCCEEDED(hr)) // only register if category exists RegisterCLSIDInCategory(m_clsid, CATID_SafeForInitializing); // don't care if this call fails return retval; } else // since unregistering the class automatically eliminates // the category registration and since we don't want to // remove the categories, we don't need to do anything special return AfxOleUnregisterClass(m_clsid, m_lpszProgID); } CJs2nCtrl* g_pCJs2nCtrl = NULL; // CJs2nCtrl::CJs2nCtrl - Constructor CJs2nCtrl::CJs2nCtrl() { InitializeIIDs(&IID_DJs2n, &IID_DJs2nEvents); // TODO: Initialize your control's instance data here. g_pCJs2nCtrl = this; } // CJs2nCtrl::~CJs2nCtrl - Destructor CJs2nCtrl::~CJs2nCtrl() { // TODO: Cleanup your control's instance data here. } LRESULT CJs2nCtrl::OnNativeLogicEvent(WPARAM wParam, LPARAM lParam) { if ( !m_stringQueue.IsEmpty() ) { PString strEvent = m_stringQueue.RemoveHead(); FireOnEvent( strEvent ); } return 0; } // CJs2nCtrl::OnDraw - Drawing function void CJs2nCtrl::OnDraw( CDC* pdc, const CRect& rcBounds, const CRect& rcInvalid) { if (!pdc) return; // TODO: Replace the following code with your own drawing code. pdc->FillRect(rcBounds, CBrush::FromHandle((HBRUSH)GetStockObject(WHITE_BRUSH))); pdc->Ellipse(rcBounds); } // CJs2nCtrl::DoPropExchange - Persistence support void CJs2nCtrl::DoPropExchange(CPropExchange* pPX) { ExchangeVersion(pPX, MAKELONG(_wVerMinor, _wVerMajor)); COleControl::DoPropExchange(pPX); // TODO: Call PX_ functions for each persistent custom property. } // CJs2nCtrl::OnResetState - Reset control to default state void CJs2nCtrl::OnResetState() { COleControl::OnResetState(); // Resets defaults found in DoPropExchange // TODO: Reset any other control state here. } // CJs2nCtrl::AboutBox - Display an "About" box to the user void CJs2nCtrl::AboutBox() { //CDialog dlgAbout(IDD_ABOUTBOX_Js2n); //dlgAbout.DoModal(); } void CJs2nCtrl::OnSetClientSite() { // TODO: Add your specialized code here and/or call the base class LPOLECLIENTSITE pClientSite = GetClientSite(); if (pClientSite != NULL) { // Obtain URL from container moniker. IMoniker* ppmk; LPOLESTR pszDisplayName; if (SUCCEEDED(pClientSite->GetMoniker( OLEGETMONIKER_TEMPFORUSER, OLEWHICHMK_CONTAINER, &ppmk))) { if (SUCCEEDED(ppmk->GetDisplayName(NULL, NULL, &pszDisplayName))) { PString strURL( (WORD *)pszDisplayName ); PString strPluginsPath = FindPluginsPath(); m_NativeLogic.Init( strURL, strPluginsPath ); CoTaskMemFree((LPVOID)pszDisplayName); } } } COleControl::OnSetClientSite(); } // CJs2nCtrl message handlers BSTR CJs2nCtrl::Send(LPCTSTR szCommand) { string strCmd = szCommand; string strResult = m_NativeLogic.InvokeFunction( strCmd ); CString strRet = strResult.c_str(); return strRet.AllocSysString(); } //___________________________________________________________________________ bool SendEventToJS( const PString& strEvent ) { if ( g_pCJs2nCtrl == NULL ) { return false; } g_pCJs2nCtrl->m_stringQueue.AddTail( strEvent ); // replace this with queue; SendMessage( g_pCJs2nCtrl->m_hWnd, WM_NLOGICEVENT, 0, 0 ); //LPDISPATCH pDisp = g_pCjs2nCtrl->GetIDispatch( FALSE ); /* LPDISPATCH pDisp; g_pCjs2nCtrl->get_accParent( &pDisp ); CWebPage page; page.SetDocument( pDisp ); string strEvent1 = strEvent; page.CallJScript( "callback", strEvent1.c_str() ); */ return true; }
[ "amnon.david@a65ff7ae-d338-0410-b7a2-59eabbc4e8c3" ]
[ [ [ 1, 284 ] ] ]
1be10847b2091a139332b264fb88b6aedea05151
65dee2b7ed8a91f952831525d78bfced5abd713f
/winmob/XfMobile_WM6/Gamepe/json/json_tokener.cpp
65d92f392839c84c60fe06175b19a8dd8030020a
[]
no_license
felixnicitin1968/XFMobile
0249f90f111f0920a423228691bcbef0ecb0ce23
4a442d0127366afa9f80bdcdaaa4569569604dac
refs/heads/master
2016-09-06T05:02:18.589338
2011-07-05T17:25:39
2011-07-05T17:25:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,673
cpp
/* * $Id: json_tokener.c,v 1.20 2006/07/25 03:24:50 mclark Exp $ * * Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd. * Michael Clark <[email protected]> * * This library is free software; you can redistribute it and/or modify * it under the terms of the MIT license. See COPYING for details. * * * Copyright (c) 2008-2009 Yahoo! Inc. All rights reserved. * The copyrights to the contents of this file are licensed under the MIT License * (http://www.opensource.org/licenses/mit-license.php) */ #include "stdafx.h" #include "config.h" #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <ctype.h> #include <string.h> #include "bits.h" #include "debug.h" #include "printbuf.h" #include "arraylist.h" #include "json_object.h" #include "json_tokener.h" static char *strdup(const char*s) { char *result = (char*)malloc(strlen(s) + 1); if (result == (char*)0) return (char*)0; strcpy(result, s); return result; } #if !HAVE_STRNCASECMP && defined(_MSC_VER) /* MSC has the version as _strnicmp */ # define strncasecmp _strnicmp #elif !HAVE_STRNCASECMP # error You do not have strncasecmp on your system. #endif /* HAVE_STRNCASECMP */ static const char* json_null_str = "null"; static const char* json_true_str = "true"; static const char* json_false_str = "false"; const char* json_tokener_errors[] = { "success", "continue", "nesting to deep", "unexpected end of data", "unexpected character", "null expected", "boolean expected", "number expected", "array value separator ',' expected", "quoted object property name expected", "object property name separator ':' expected", "object value separator ',' expected", "invalid string sequence", "expected comment", }; struct json_tokener* json_tokener_new(void) { struct json_tokener *tok; tok = (struct json_tokener*)calloc(1, sizeof(struct json_tokener)); if (!tok) return NULL; tok->pb = printbuf_new(); json_tokener_reset(tok); return tok; } void json_tokener_free(struct json_tokener *tok) { json_tokener_reset(tok); if(tok) printbuf_free(tok->pb); free(tok); } static void json_tokener_reset_level(struct json_tokener *tok, int depth) { tok->stack[depth].state = json_tokener_state_eatws; tok->stack[depth].saved_state = json_tokener_state_start; json_object_put(tok->stack[depth].current); tok->stack[depth].current = NULL; free(tok->stack[depth].obj_field_name); tok->stack[depth].obj_field_name = NULL; } void json_tokener_reset(struct json_tokener *tok) { int i; if (!tok) return; for(i = tok->depth; i >= 0; i--) json_tokener_reset_level(tok, i); tok->depth = 0; tok->err = json_tokener_success; } struct json_object* json_tokener_parse(const char *str) { struct json_tokener* tok; struct json_object* obj; tok = json_tokener_new(); obj = json_tokener_parse_ex(tok, str, -1); if(tok->err != json_tokener_success) obj = (struct json_object*)error_ptr(-tok->err); json_tokener_free(tok); return obj; } #if !HAVE_STRNDUP /* CAW: compliant version of strndup() */ char* strndup(const char* str, size_t n) { if(str) { size_t len = strlen(str); size_t nn = json_min(len,n); char* s = (char*)malloc(sizeof(char) * (nn + 1)); if(s) { memcpy(s, str, nn); s[nn] = '\0'; } return s; } return NULL; } #endif #define state tok->stack[tok->depth].state #define saved_state tok->stack[tok->depth].saved_state #define current tok->stack[tok->depth].current #define obj_field_name tok->stack[tok->depth].obj_field_name /* Optimization: * json_tokener_parse_ex() consumed a lot of CPU in its main loop, * iterating character-by character. A large performance boost is * achieved by using tighter loops to locally handle units such as * comments and strings. Loops that handle an entire token within * their scope also gather entire strings and pass them to * printbuf_memappend() in a single call, rather than calling * printbuf_memappend() one char at a time. * * POP_CHAR() and ADVANCE_CHAR() macros are used for code that is * common to both the main loop and the tighter loops. */ /* POP_CHAR(dest, tok) macro: * Not really a pop()...peeks at the current char and stores it in dest. * Returns 1 on success, sets tok->err and returns 0 if no more chars. * Implicit inputs: str, len vars */ #define POP_CHAR(dest, tok) \ (((tok)->char_offset == len) ? \ (((tok)->depth == 0 && state == json_tokener_state_eatws && saved_state == json_tokener_state_finish) ? \ (((tok)->err = json_tokener_success), 0) \ : \ (((tok)->err = json_tokener_continue), 0) \ ) : \ (((dest) = *str), 1) \ ) /* ADVANCE_CHAR() macro: * Incrementes str & tok->char_offset. * For convenience of existing conditionals, returns the old value of c (0 on eof) * Implicit inputs: c var */ #define ADVANCE_CHAR(str, tok) \ ( ++(str), ((tok)->char_offset)++, c) /* End optimization macro defs */ struct json_object* json_tokener_parse_ex(struct json_tokener *tok, const char *str, int len) { struct json_object *obj = NULL; char c = '\1'; tok->char_offset = 0; tok->err = json_tokener_success; while (POP_CHAR(c, tok)) { redo_char: switch(state) { case json_tokener_state_eatws: /* Advance until we change state */ while (isspace(c)) { if ((!ADVANCE_CHAR(str, tok)) || (!POP_CHAR(c, tok))) goto out; } if(c == '/') { printbuf_reset(tok->pb); printbuf_memappend_fast(tok->pb, &c, 1); state = json_tokener_state_comment_start; } else { state = saved_state; goto redo_char; } break; case json_tokener_state_start: switch(c) { case '{': state = json_tokener_state_eatws; saved_state = json_tokener_state_object_field_start; current = json_object_new_object(); break; case '[': state = json_tokener_state_eatws; saved_state = json_tokener_state_array; current = json_object_new_array(); break; case 'N': case 'n': state = json_tokener_state_null; printbuf_reset(tok->pb); tok->st_pos = 0; goto redo_char; case '"': case '\'': state = json_tokener_state_string; printbuf_reset(tok->pb); tok->quote_char = c; break; case 'T': case 't': case 'F': case 'f': state = json_tokener_state_boolean; printbuf_reset(tok->pb); tok->st_pos = 0; goto redo_char; #if defined(__GNUC__) case '0' ... '9': #else case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': #endif case '-': state = json_tokener_state_number; printbuf_reset(tok->pb); tok->is_double = 0; goto redo_char; default: tok->err = json_tokener_error_parse_unexpected; goto out; } break; case json_tokener_state_finish: if(tok->depth == 0) goto out; obj = json_object_get(current); json_tokener_reset_level(tok, tok->depth); tok->depth--; goto redo_char; case json_tokener_state_null: printbuf_memappend_fast(tok->pb, &c, 1); if(strncasecmp(json_null_str, tok->pb->buf, json_min(tok->st_pos+1, strlen(json_null_str))) == 0) { if(tok->st_pos == strlen(json_null_str)) { current = NULL; saved_state = json_tokener_state_finish; state = json_tokener_state_eatws; goto redo_char; } } else { tok->err = json_tokener_error_parse_null; goto out; } tok->st_pos++; break; case json_tokener_state_comment_start: if(c == '*') { state = json_tokener_state_comment; } else if(c == '/') { state = json_tokener_state_comment_eol; } else { tok->err = json_tokener_error_parse_comment; goto out; } printbuf_memappend_fast(tok->pb, &c, 1); break; case json_tokener_state_comment: { /* Advance until we change state */ const char *case_start = str; while(c != '*') { if (!ADVANCE_CHAR(str, tok) || !POP_CHAR(c, tok)) { printbuf_memappend_fast(tok->pb, case_start, str-case_start); goto out; } } printbuf_memappend_fast(tok->pb, case_start, 1+str-case_start); state = json_tokener_state_comment_end; } break; case json_tokener_state_comment_eol: { /* Advance until we change state */ const char *case_start = str; while(c != '\n') { if (!ADVANCE_CHAR(str, tok) || !POP_CHAR(c, tok)) { printbuf_memappend_fast(tok->pb, case_start, str-case_start); goto out; } } printbuf_memappend_fast(tok->pb, case_start, str-case_start); MC_DEBUG("json_tokener_comment: %s\n", tok->pb->buf); state = json_tokener_state_eatws; } break; case json_tokener_state_comment_end: printbuf_memappend_fast(tok->pb, &c, 1); if(c == '/') { MC_DEBUG("json_tokener_comment: %s\n", tok->pb->buf); state = json_tokener_state_eatws; } else { state = json_tokener_state_comment; } break; case json_tokener_state_string: { /* Advance until we change state */ const char *case_start = str; while(1) { if(c == tok->quote_char) { printbuf_memappend_fast(tok->pb, case_start, str-case_start); current = json_object_new_string(tok->pb->buf); saved_state = json_tokener_state_finish; state = json_tokener_state_eatws; break; } else if(c == '\\') { printbuf_memappend_fast(tok->pb, case_start, str-case_start); saved_state = json_tokener_state_string; state = json_tokener_state_string_escape; break; } if (!ADVANCE_CHAR(str, tok) || !POP_CHAR(c, tok)) { printbuf_memappend_fast(tok->pb, case_start, str-case_start); goto out; } } } break; case json_tokener_state_string_escape: switch(c) { case '"': case '\\': case '/': printbuf_memappend_fast(tok->pb, &c, 1); state = saved_state; break; case 'b': case 'n': case 'r': case 't': if(c == 'b') printbuf_memappend_fast(tok->pb, "\b", 1); else if(c == 'n') printbuf_memappend_fast(tok->pb, "\n", 1); else if(c == 'r') printbuf_memappend_fast(tok->pb, "\r", 1); else if(c == 't') printbuf_memappend_fast(tok->pb, "\t", 1); state = saved_state; break; case 'u': tok->ucs_char = 0; tok->st_pos = 0; state = json_tokener_state_escape_unicode; break; default: tok->err = json_tokener_error_parse_string; goto out; } break; case json_tokener_state_escape_unicode: /* Note that the following code is inefficient for handling large * chunks of extended chars, calling printbuf_memappend() once * for each multi-byte character of input. * This is a good area for future optimization. */ { /* Advance until we change state */ while(1) { if(strchr(json_hex_chars, c)) { tok->ucs_char += ((unsigned int)hexdigit(c) << ((3-tok->st_pos++)*4)); if(tok->st_pos == 4) { unsigned char utf_out[3]; if (tok->ucs_char < 0x80) { utf_out[0] = tok->ucs_char; printbuf_memappend_fast(tok->pb, (char*)utf_out, 1); } else if (tok->ucs_char < 0x800) { utf_out[0] = 0xc0 | (tok->ucs_char >> 6); utf_out[1] = 0x80 | (tok->ucs_char & 0x3f); printbuf_memappend_fast(tok->pb, (char*)utf_out, 2); } else { utf_out[0] = 0xe0 | (tok->ucs_char >> 12); utf_out[1] = 0x80 | ((tok->ucs_char >> 6) & 0x3f); utf_out[2] = 0x80 | (tok->ucs_char & 0x3f); printbuf_memappend_fast(tok->pb, (char*)utf_out, 3); } state = saved_state; break; } } else { tok->err = json_tokener_error_parse_string; goto out; } if (!ADVANCE_CHAR(str, tok) || !POP_CHAR(c, tok)) goto out; } } break; case json_tokener_state_boolean: printbuf_memappend_fast(tok->pb, &c, 1); if(strncasecmp(json_true_str, tok->pb->buf, json_min(tok->st_pos+1, strlen(json_true_str))) == 0) { if(tok->st_pos == strlen(json_true_str)) { current = json_object_new_boolean(1); saved_state = json_tokener_state_finish; state = json_tokener_state_eatws; goto redo_char; } } else if(strncasecmp(json_false_str, tok->pb->buf, json_min(tok->st_pos+1, strlen(json_false_str))) == 0) { if(tok->st_pos == strlen(json_false_str)) { current = json_object_new_boolean(0); saved_state = json_tokener_state_finish; state = json_tokener_state_eatws; goto redo_char; } } else { tok->err = json_tokener_error_parse_boolean; goto out; } tok->st_pos++; break; case json_tokener_state_number: { /* Advance until we change state */ const char *case_start = str; int case_len=0; while(c && strchr(json_number_chars, c)) { ++case_len; if(c == '.' || c == 'e') tok->is_double = 1; if (!ADVANCE_CHAR(str, tok) || !POP_CHAR(c, tok)) { printbuf_memappend_fast(tok->pb, case_start, case_len); goto out; } } if (case_len>0) printbuf_memappend_fast(tok->pb, case_start, case_len); } { int numi; double numd; if(!tok->is_double && sscanf(tok->pb->buf, "%d", &numi) == 1) { current = json_object_new_int(numi); } else if(tok->is_double && sscanf(tok->pb->buf, "%lf", &numd) == 1) { current = json_object_new_double(numd); } else { tok->err = json_tokener_error_parse_number; goto out; } saved_state = json_tokener_state_finish; state = json_tokener_state_eatws; goto redo_char; } break; case json_tokener_state_array: if(c == ']') { saved_state = json_tokener_state_finish; state = json_tokener_state_eatws; } else { if(tok->depth >= JSON_TOKENER_MAX_DEPTH-1) { tok->err = json_tokener_error_depth; goto out; } state = json_tokener_state_array_add; tok->depth++; json_tokener_reset_level(tok, tok->depth); goto redo_char; } break; case json_tokener_state_array_add: json_object_array_add(current, obj); saved_state = json_tokener_state_array_sep; state = json_tokener_state_eatws; goto redo_char; case json_tokener_state_array_sep: if(c == ']') { saved_state = json_tokener_state_finish; state = json_tokener_state_eatws; } else if(c == ',') { saved_state = json_tokener_state_array; state = json_tokener_state_eatws; } else { tok->err = json_tokener_error_parse_array; goto out; } break; case json_tokener_state_object_field_start: if(c == '}') { saved_state = json_tokener_state_finish; state = json_tokener_state_eatws; } else if (c == '"' || c == '\'') { tok->quote_char = c; printbuf_reset(tok->pb); state = json_tokener_state_object_field; } else { tok->err = json_tokener_error_parse_object_key_name; goto out; } break; case json_tokener_state_object_field: { /* Advance until we change state */ const char *case_start = str; while(1) { if(c == tok->quote_char) { printbuf_memappend_fast(tok->pb, case_start, str-case_start); obj_field_name = strdup(tok->pb->buf); saved_state = json_tokener_state_object_field_end; state = json_tokener_state_eatws; break; } else if(c == '\\') { printbuf_memappend_fast(tok->pb, case_start, str-case_start); saved_state = json_tokener_state_object_field; state = json_tokener_state_string_escape; break; } if (!ADVANCE_CHAR(str, tok) || !POP_CHAR(c, tok)) { printbuf_memappend_fast(tok->pb, case_start, str-case_start); goto out; } } } break; case json_tokener_state_object_field_end: if(c == ':') { saved_state = json_tokener_state_object_value; state = json_tokener_state_eatws; } else { tok->err = json_tokener_error_parse_object_key_sep; goto out; } break; case json_tokener_state_object_value: if(tok->depth >= JSON_TOKENER_MAX_DEPTH-1) { tok->err = json_tokener_error_depth; goto out; } state = json_tokener_state_object_value_add; tok->depth++; json_tokener_reset_level(tok, tok->depth); goto redo_char; case json_tokener_state_object_value_add: json_object_object_add(current, obj_field_name, obj); free(obj_field_name); obj_field_name = NULL; saved_state = json_tokener_state_object_sep; state = json_tokener_state_eatws; goto redo_char; case json_tokener_state_object_sep: if(c == '}') { saved_state = json_tokener_state_finish; state = json_tokener_state_eatws; } else if(c == ',') { saved_state = json_tokener_state_object_field_start; state = json_tokener_state_eatws; } else { tok->err = json_tokener_error_parse_object_value_sep; goto out; } break; } if (!ADVANCE_CHAR(str, tok)) goto out; } /* while(POP_CHAR) */ out: if (!c) { /* We hit an eof char (0) */ if(state != json_tokener_state_finish && saved_state != json_tokener_state_finish) tok->err = json_tokener_error_parse_eof; } if(tok->err == json_tokener_success) return json_object_get(current); MC_DEBUG("json_tokener_parse_ex: error %s at offset %d\n", json_tokener_errors[tok->err], tok->char_offset); return NULL; }
[ [ [ 1, 638 ] ] ]
92e0719319b3871d590868ec0cda8829f036ec2b
5dc6c87a7e6459ef8e832774faa4b5ae4363da99
/vis_avs/r_clear.cpp
d3b82c495d02bd030dcabc9da052523918759ae4
[]
no_license
aidinabedi/avs4unity
407603d2fc44bc8b075b54cd0a808250582ee077
9b6327db1d092218e96d8907bd14d68b741dcc4d
refs/heads/master
2021-01-20T15:27:32.449282
2010-12-24T03:28:09
2010-12-24T03:28:09
90,773,183
5
2
null
null
null
null
UTF-8
C++
false
false
8,235
cpp
/* LICENSE ------- Copyright 2005 Nullsoft, 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: * 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 Nullsoft 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 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 "config.h" #include <windows.h> #include <stdlib.h> #include <vfw.h> #include <commctrl.h> #include "resource.h" #include "r_defs.h" #ifndef LASER #define MOD_NAME "Render / Clear screen" #define C_THISCLASS C_ClearClass class C_THISCLASS : public C_RBASE { protected: public: C_THISCLASS(); virtual ~C_THISCLASS(); virtual int render(char visdata[2][2][SAMPLES], int isBeat, int *framebuffer, int *fbout, int w, int h); virtual char *get_desc() { return MOD_NAME; } virtual HWND conf(HINSTANCE hInstance, HWND hwndParent); virtual void load_config(unsigned char *data, int len); virtual int save_config(unsigned char *data); int enabled; int onlyfirst; int color; int fcounter; int blend, blendavg; }; static C_THISCLASS *g_ConfigThis; // global configuration dialog pointer static HINSTANCE g_hDllInstance; // global DLL instance pointer (not needed in this example, but could be useful) C_THISCLASS::~C_THISCLASS() { } // configuration read/write C_THISCLASS::C_THISCLASS() // set up default configuration { color = 0; onlyfirst = 0; fcounter=0; blend = 0; blendavg = 0; enabled=1; } #define GET_INT() (data[pos]|(data[pos+1]<<8)|(data[pos+2]<<16)|(data[pos+3]<<24)) void C_THISCLASS::load_config(unsigned char *data, int len) // read configuration of max length "len" from data. { int pos=0; if (len-pos >= 4) { enabled=GET_INT(); pos+=4; } if (len-pos >= 4) { color=GET_INT(); pos+=4; } if (len-pos >= 4) { blend=GET_INT(); pos+=4; } if (len-pos >= 4) { blendavg=GET_INT(); pos+=4; } if (len-pos >= 4) { onlyfirst=GET_INT(); pos+=4; } } #define PUT_INT(y) data[pos]=(y)&255; data[pos+1]=(y>>8)&255; data[pos+2]=(y>>16)&255; data[pos+3]=(y>>24)&255 int C_THISCLASS::save_config(unsigned char *data) // write configuration to data, return length. config data should not exceed 64k. { int pos=0; PUT_INT(enabled); pos+=4; PUT_INT(color); pos+=4; PUT_INT(blend); pos+=4; PUT_INT(blendavg); pos+=4; PUT_INT(onlyfirst); pos+=4; return pos; } // render function // render should return 0 if it only used framebuffer, or 1 if the new output data is in fbout. this is // used when you want to do something that you'd otherwise need to make a copy of the framebuffer. // w and h are the width and height of the screen, in pixels. // isBeat is 1 if a beat has been detected. // visdata is in the format of [spectrum:0,wave:1][channel][band]. int C_THISCLASS::render(char visdata[2][2][SAMPLES], int isBeat, int *framebuffer, int *fbout, int w, int h) { int i=w*h; int *p=framebuffer; if (!enabled) return 0; if (onlyfirst && fcounter) return 0; if (isBeat&0x80000000) return 0; fcounter++; if (blend==2) while (i--) BLEND_LINE(p++,color); else if (blend) while (i--) *p++=BLEND(*p,color); else if (blendavg) while (i--) *p++=BLEND_AVG(*p,color); else while (i--) *p++=color; return 0; } // configuration dialog stuff static BOOL CALLBACK g_DlgProc(HWND hwndDlg, UINT uMsg, WPARAM wParam,LPARAM lParam) { switch (uMsg) { case WM_INITDIALOG: if (g_ConfigThis->enabled) CheckDlgButton(hwndDlg,IDC_CHECK1,BST_CHECKED); if (g_ConfigThis->onlyfirst) CheckDlgButton(hwndDlg,IDC_CLEARFIRSTFRAME,BST_CHECKED); if (g_ConfigThis->blend==1) CheckDlgButton(hwndDlg,IDC_ADDITIVE,BST_CHECKED); else if (g_ConfigThis->blend==2) CheckDlgButton(hwndDlg,IDC_DEFRENDBLEND,BST_CHECKED); else if (g_ConfigThis->blendavg) CheckDlgButton(hwndDlg,IDC_5050,BST_CHECKED); if (!g_ConfigThis->blend && !g_ConfigThis->blendavg) CheckDlgButton(hwndDlg,IDC_REPLACE,BST_CHECKED); return 1; case WM_DRAWITEM: { DRAWITEMSTRUCT *di=(DRAWITEMSTRUCT *)lParam; if (di->CtlID == IDC_DEFCOL) // paint nifty color button { int w=di->rcItem.right-di->rcItem.left; int _color=g_ConfigThis->color; _color = ((_color>>16)&0xff)|(_color&0xff00)|((_color<<16)&0xff0000); HPEN hPen,hOldPen; HBRUSH hBrush,hOldBrush; LOGBRUSH lb={BS_SOLID,_color,0}; hPen = (HPEN)CreatePen(PS_SOLID,0,_color); hBrush = CreateBrushIndirect(&lb); hOldPen=(HPEN)SelectObject(di->hDC,hPen); hOldBrush=(HBRUSH)SelectObject(di->hDC,hBrush); Rectangle(di->hDC,di->rcItem.left,di->rcItem.top,di->rcItem.right,di->rcItem.bottom); SelectObject(di->hDC,hOldPen); SelectObject(di->hDC,hOldBrush); DeleteObject(hBrush); DeleteObject(hPen); } } return 0; case WM_COMMAND: if ((LOWORD(wParam) == IDC_CHECK1) || (LOWORD(wParam) == IDC_ADDITIVE) || (LOWORD(wParam) == IDC_REPLACE) || (LOWORD(wParam) == IDC_5050) || (LOWORD(wParam) == IDC_DEFRENDBLEND)) { g_ConfigThis->enabled=IsDlgButtonChecked(hwndDlg,IDC_CHECK1)?1:0; g_ConfigThis->blend=IsDlgButtonChecked(hwndDlg,IDC_ADDITIVE)?1:0; if (!g_ConfigThis->blend) g_ConfigThis->blend=IsDlgButtonChecked(hwndDlg,IDC_DEFRENDBLEND)?2:0; g_ConfigThis->blendavg=IsDlgButtonChecked(hwndDlg,IDC_5050)?1:0; } if (LOWORD(wParam) == IDC_CLEARFIRSTFRAME) { g_ConfigThis->onlyfirst=IsDlgButtonChecked(hwndDlg,IDC_CLEARFIRSTFRAME)?1:0; if (g_ConfigThis->onlyfirst) g_ConfigThis->fcounter=0; } if (LOWORD(wParam) == IDC_DEFCOL) // handle clicks to nifty color button { int *a=&(g_ConfigThis->color); static COLORREF custcolors[16]; CHOOSECOLOR cs; cs.lStructSize = sizeof(cs); cs.hwndOwner = hwndDlg; cs.hInstance = 0; cs.rgbResult=((*a>>16)&0xff)|(*a&0xff00)|((*a<<16)&0xff0000); cs.lpCustColors = custcolors; cs.Flags = CC_RGBINIT|CC_FULLOPEN; if (ChooseColor(&cs)) { *a = ((cs.rgbResult>>16)&0xff)|(cs.rgbResult&0xff00)|((cs.rgbResult<<16)&0xff0000); g_ConfigThis->color = *a; } InvalidateRect(GetDlgItem(hwndDlg,IDC_DEFCOL),NULL,TRUE); } } return 0; } HWND C_THISCLASS::conf(HINSTANCE hInstance, HWND hwndParent) // return NULL if no config dialog possible { g_ConfigThis = this; return CreateDialog(hInstance,MAKEINTRESOURCE(IDD_CFG_CLEAR),hwndParent,g_DlgProc); } // export stuff C_RBASE *R_Clear(char *desc) // creates a new effect object if desc is NULL, otherwise fills in desc with description { if (desc) { strcpy(desc,MOD_NAME); return NULL; } return (C_RBASE *) new C_THISCLASS(); } #else C_RBASE *R_Clear(char *desc) { return NULL; } #endif
[ [ [ 1, 228 ] ] ]
c29c10e0a3bc529adeb4b0c1ec50d3d92a0ea94d
afe15882f32a1580fba6c4a400d9b400ace2ee70
/shaderprog.h
4901b146eedae4f180908cbcd1ae19a40b8bbe4b
[]
no_license
clarkds/Lugpu-ES
4e8769463afd31f5ef7d9ebf3f00a070bb16fda6
066bd1af6b19291e027711bd445213f603d0f8b5
refs/heads/master
2021-01-22T03:01:32.384608
2011-08-02T16:09:00
2011-08-02T16:09:00
2,107,139
0
0
null
null
null
null
UTF-8
C++
false
false
588
h
#ifndef _SHADERPROG_H #define _SHADERPROG_H #include <string.h> #ifdef WIN32 #include <windows.h> #elif defined(__APPLE__) #include <OpenGL/gl.h> #include <OpenGL/glext.h> #include <GLUT/glut.h> #else #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #endif class ShaderProg{ public: ShaderProg(){} ~ShaderProg(); void Load(char* vprog, char* fprog); void Bind(); void BindProg(); void Release(); void SetConstant(const char *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w); GLuint prog_id; char source[1024]; }; #endif
[ [ [ 1, 2 ], [ 7, 13 ], [ 15, 18 ], [ 20, 21 ], [ 23, 24 ], [ 31, 31 ], [ 34, 34 ] ], [ [ 3, 6 ], [ 14, 14 ], [ 19, 19 ], [ 22, 22 ], [ 25, 30 ], [ 32, 33 ], [ 35, 37 ] ] ]
657922ecc8070b2674eaaf18420bdbdd2c2c7c00
9566086d262936000a914c5dc31cb4e8aa8c461c
/EnigmaConfiguration/ServerConnectionInformation.hpp
502ee4691494ab6926e323210f81050928de995b
[]
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
1,274
hpp
#ifndef SERVERCONNECTIONINFORMATION_HPP_INCLUDED #define SERVERCONNECTIONINFORMATION_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 "string.hpp" #include "TypeDefs.hpp" namespace Enigma { struct DllExport ServerConnectionInformation { std::string Name; std::string Host; Enigma::s32 Port; }; }; #endif // SERVERCONNECTIONINFORMATION_HPP_INCLUDED
[ [ [ 1, 29 ] ] ]
f8b953711742e0891f25f56060de97c4399ae39f
fab77712e8dfd19aea9716b74314f998093093e2
/Utility/ShareResource.cpp
0159c442b8cc969b737b2524f68c3512f6008511
[]
no_license
alandigi/tsfriend
95f98b123ae52f1f515ab4a909de9af3724b138d
b8f246a51f01afde40a352248065a6a42f0bcbf8
refs/heads/master
2016-08-12T07:09:23.928793
2011-11-13T15:12:54
2011-11-13T15:12:54
45,849,814
0
2
null
null
null
null
UTF-8
C++
false
false
1,271
cpp
#include "StdAfx.h" #include "include.h" CShareResource::CShareResource(u8 IntSem ) { /* CSemaphore( LONG lInitialCount = 1, LONG lMaxCount = 1, LPCTSTR pstrName = NULL, LPSECURITY_ATTRIBUTES lpsaAttributes = NULL ); */ ptrSemaphore=new CSemaphore(IntSem,1); /* explicit CSingleLock( CSyncObject* pObject, BOOL bInitialLock = FALSE ); */ pSignalLock1 = new CSingleLock(ptrSemaphore); pSignalLock2 = new CSingleLock(ptrSemaphore); } CShareResource::~CShareResource() { delete pSignalLock1; delete pSignalLock2; delete ptrSemaphore; } /* Calls the Win32 function EnterCriticalSection, which waits until the thread can take ownership of the critical section object contained in the m_sec data member. Returns S_OK on success, E_OUTOFMEMORY or E_FAIL on failure. */ BOOL CShareResource::Lock1() { return pSignalLock1->Lock(); } BOOL CShareResource::UnLock1() { return pSignalLock1->Unlock(); } BOOL CShareResource::IsLocked1() { return pSignalLock1->IsLocked(); } BOOL CShareResource::Lock2() { return pSignalLock2->Lock(); } BOOL CShareResource::UnLock2() { return pSignalLock2->Unlock(); } BOOL CShareResource::IsLocked2() { return pSignalLock2->IsLocked(); }
[ [ [ 1, 68 ] ] ]
7a24ac6e9524a78291cf572a8d252135f3be735b
5d3c1be292f6153480f3a372befea4172c683180
/trunk/Event Heap/c++/Windows/include/eh2_SerializationException.h
ef9bf53c472f0cc5181129c2dd69e11b41a9560f
[ "Artistic-2.0" ]
permissive
BackupTheBerlios/istuff-svn
5f47aa73dd74ecf5c55f83765a5c50daa28fa508
d0bb9963b899259695553ccd2b01b35be5fb83db
refs/heads/master
2016-09-06T04:54:24.129060
2008-05-02T22:33:26
2008-05-02T22:33:26
40,820,013
0
0
null
null
null
null
UTF-8
C++
false
false
787
h
/* Copyright (c) 2003 The Board of Trustees of The Leland Stanford Junior * University. All Rights Reserved. * * See the file LICENSE.txt for information on redistributing this software. */ /* $Id: eh2_SerializationException.h,v 1.2 2003/06/02 08:02:05 tomoto Exp $ */ #ifndef _EH2_SERIALIZATIONEXCEPTION_H_ #define _EH2_SERIALIZATIONEXCEPTION_H_ #include <idk_ut_Types.h> #include <idk_ut_Exception.h> /** @file Definition of eh2_SerializationException. @internal belongs to eh2i_wb, */ /** Thrown to indicate errors during serialization or deserialization of the Event Heap wire bundle. */ class EH2_DECL eh2_SerializationException : public idk_ut_Exception { IDK_UT_EXCEPTION_DECL(eh2_SerializationException, idk_ut_Exception); }; #endif
[ "ballagas@2a53cb5c-8ff1-0310-8b75-b3ec22923d26" ]
[ [ [ 1, 28 ] ] ]
34244ae1f41759a3f783901fb2ccf6483a6d1fb2
854ee643a4e4d0b7a202fce237ee76b6930315ec
/arcemu_svn/src/arcemu-shared/Network/SocketOpsFreeBSD.cpp
bf1f609970b000fee10bb2a3fbc42cc0ce93aead
[]
no_license
miklasiak/projekt
df37fa82cf2d4a91c2073f41609bec8b2f23cf66
064402da950555bf88609e98b7256d4dc0af248a
refs/heads/master
2021-01-01T19:29:49.778109
2008-11-10T17:14:14
2008-11-10T17:14:14
34,016,391
2
0
null
null
null
null
UTF-8
C++
false
false
1,909
cpp
/* * Multiplatform Async Network Library * Copyright (c) 2007 Burlex * * SocketOpsLinux.cpp - Linux implementation of SocketOps. * */ #include "Network.h" #ifdef CONFIG_USE_KQUEUE namespace SocketOps { // Create file descriptor for socket i/o operations. SOCKET CreateTCPFileDescriptor() { // create a socket for use with overlapped i/o. return socket(AF_INET, SOCK_STREAM, 0); } // Disable blocking send/recv calls. bool Nonblocking(SOCKET fd) { uint32 arg = 1; return (::ioctl(fd, FIONBIO, &arg) == 0); } // Disable blocking send/recv calls. bool Blocking(SOCKET fd) { uint32 arg = 0; return (ioctl(fd, FIONBIO, &arg) == 0); } // Disable nagle buffering algorithm bool DisableBuffering(SOCKET fd) { uint32 arg = 1; return (setsockopt(fd, 0x6, 0x1, (const char*)&arg, sizeof(arg)) == 0); } // Enable nagle buffering algorithm bool EnableBuffering(SOCKET fd) { uint32 arg = 0; return (setsockopt(fd, 0x6, 0x1, (const char*)&arg, sizeof(arg)) == 0); } // Set internal buffer size to socket. bool SetSendBufferSize(SOCKET fd, uint32 size) { return (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const char*)&size, sizeof(size)) == 0); } // Set internal buffer size to socket. bool SetRecvBufferSize(SOCKET fd, uint32 size) { return (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (const char*)&size, sizeof(size)) == 0); } // Closes a socket fully. void CloseSocket(SOCKET fd) { shutdown(fd, SHUT_RDWR); close(fd); } // Sets reuseaddr void ReuseAddr(SOCKET fd) { uint32 option = 1; setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char*)&option, 4); } } #endif
[ "[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef" ]
[ [ [ 1, 77 ] ] ]
b998bb618b8fdc5202d1eade78f7576bd24c77ff
4797c7058b7157e3d942e82cf8ad94b58be488ae
/PlayerShip.cpp
f70fc2002f2cfb0b6a7261c671bdf0ac7d214a00
[]
no_license
koguz/DirectX-Space-Game
2d1d8179439870fd1427beb9624f1c5452546c39
be672051fd0009cbd5851c92bd344d3b23645474
refs/heads/master
2020-05-18T02:11:47.963185
2011-05-25T14:35:26
2011-05-25T14:35:26
1,799,267
0
0
null
null
null
null
UTF-8
C++
false
false
2,804
cpp
#include "PlayerShip.h" PlayerShip::PlayerShip():BaseObject() { speed = 0.0f; lastShot = 0; } bool PlayerShip::Init(IDirect3DDevice9 *d, IDirectSound8 *s) { ((MyMesh*)(this))->Init(d, "ship01.x"); Sound = s; Engine.Init(Sound, "PSEngine.wav"); Fire.Init(Sound, "PSFire.wav"); Fire.SetLoop(false); Scratch.Init(Sound, "Scratch.wav"); Scratch.SetLoop(false); HitSound.Init(Sound, "hitship.wav"); HitSound.SetLoop(false); /* Mission1.Init(Sound, "mission01.wav"); Mission1.SetLoop(false); Mission1.Play(); */ Engine.SetVolume(-800); Engine.Play(); maxSpeed = 6.0f; minSpeed = 0.6f; casSpeed = 2.0f; laserInterval = 500; health = 2000; return true; } void PlayerShip::Scratched() { Scratch.setPosition(position); Scratch.Play(); health -= 5; } void PlayerShip::Hit(int d) { health -= d; HitSound.Play(); } void PlayerShip::Update(float deltaTime) { if (health < 2000 && GetTickCount() - lastGen > 100 ) { health++; lastGen = GetTickCount(); } time = deltaTime; TranslateV(speed * look * deltaTime); Engine.setPosition(position); Fire.setPosition(position); HitSound.setPosition(position); // Mission1.setPosition(position); std::vector<Laser>::iterator temp; std::vector<Laser>::iterator toDel; bool d = false; for(temp = lasers.begin(); temp != lasers.end(); temp++) { (*temp).Update(time); // (*temp).Draw(); if (abs((*temp).getPosition().x) > 200 || abs((*temp).getPosition().y) > 200 || abs((*temp).getPosition().z) > 200 ) { toDel = temp; d = true; } if ((*temp).getHit()) { toDel = temp; d = true; } } if (d) lasers.erase(toDel); } void PlayerShip::SpeedUp() { SetSpeed(maxSpeed); } void PlayerShip::SpeedDown() { SetSpeed(minSpeed); } void PlayerShip::SpeedNormal() { SetSpeed(casSpeed); } void PlayerShip::SetSpeed(float s) { if (s == speed) return; if (s >= casSpeed && s < maxSpeed && speed != s) Engine.setFrequency(0); else if (s >= maxSpeed && speed != s) Engine.setFrequency(24000); else if (s >= minSpeed && s < casSpeed && speed != s) Engine.setFrequency(20000); speed = s; } void PlayerShip::FireLaser() { if (health < 0) return; if (GetTickCount() - lastShot > laserInterval) { Laser laser1(Device, Laser::RED); Laser laser2(Device, Laser::RED); laser1.SetRotation(rotationMatrix); laser1.TranslateV(position + (right * 0.6f)); laser1.SetOrientation(up, right, look); laser2.SetRotation(rotationMatrix); laser2.TranslateV(position - (right * 0.6f)); laser2.SetOrientation(up, right, look); lasers.push_back(laser1); lasers.push_back(laser2); Fire.Play(); lastShot = GetTickCount(); } else return; }
[ [ [ 1, 142 ] ] ]
72bfba3419682ca47bd8f4359f3abf9cb83d69f0
942b88e59417352fbbb1a37d266fdb3f0f839d27
/src/sprite.cxx
41db2af5987d4c7f0e6b5433399312820ab9b117
[ "BSD-2-Clause" ]
permissive
take-cheeze/ARGSS...
2c1595d924c24730cc714d017edb375cfdbae9ef
2f2830e8cc7e9c4a5f21f7649287cb6a4924573f
refs/heads/master
2016-09-05T15:27:26.319404
2010-12-13T09:07:24
2010-12-13T09:07:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,050
cxx
////////////////////////////////////////////////////////////////////////////////// /// 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 <cstring> #include <string> #include <GL/gl.h> #include <argss/ruby.hxx> #include <argss/sprite.hxx> #include "graphics.hxx" #include "player.hxx" #include "sprite.hxx" #include "system.hxx" #include "viewport.hxx" //////////////////////////////////////////////////////////// /// Constructor //////////////////////////////////////////////////////////// Sprite::Sprite(VALUE iid) : id(iid) , viewport_( rb_iv_get(id, "@viewport") ) , bitmap_(Qnil), srcRect_( rb_iv_get(id, "@src_rect") ) , visible(true) , x(0), y(0), z(0), ox(0), oy(0) , zoom_x(1.0), zoom_y(1.0) , angle(0), flipx(false), flipy(false) , bush_depth(0), bush_opacity(128), opacity(255) , blendType_(Blend::NORMAL) , color( rb_iv_get(id, "@color") ) , tone( rb_iv_get(id, "@tone") ) , flash_duration(0), sprite_() , flash_needs_refresh(false) { if ( ! NIL_P(viewport_) ) Viewport::get(viewport_).RegisterZObj(0, id); else Graphics::RegisterZObj(0, id); } //////////////////////////////////////////////////////////// /// Destructor //////////////////////////////////////////////////////////// Sprite::~Sprite() { if (flash_texture > 0) { glDeleteTextures(1, &flash_texture); flash_texture = 0; } } //////////////////////////////////////////////////////////// /// Class Is Sprite Disposed? //////////////////////////////////////////////////////////// bool Sprite::IsDisposed(VALUE id) { return Graphics::countDrawable(id) == 0; } //////////////////////////////////////////////////////////// /// Class New Sprite //////////////////////////////////////////////////////////// void Sprite::New(VALUE id) { Graphics::insertDrawable( id, std::auto_ptr<Drawable>(new Sprite(id)) ); } //////////////////////////////////////////////////////////// /// Class get Sprite //////////////////////////////////////////////////////////// Sprite& Sprite::get(VALUE id) { return dynamic_cast< Sprite& >( Graphics::getDrawable(id) ); } //////////////////////////////////////////////////////////// /// Class Dispose Sprite //////////////////////////////////////////////////////////// void Sprite::Dispose(VALUE id) { if ( ! NIL_P( Sprite::get(id).viewport_ ) ) Viewport::get(Sprite::get(id).viewport_).RemoveZObj(id); else Graphics::RemoveZObj(id); Graphics::eraseDrawable(id); } //////////////////////////////////////////////////////////// /// Refresh Bitmaps //////////////////////////////////////////////////////////// void Sprite::RefreshBitmaps() { if ( sprite_.get() ) sprite_->Changed(); } //////////////////////////////////////////////////////////// /// Draw //////////////////////////////////////////////////////////// void Sprite::draw(long z) { if( !getVisible() || NIL_P(bitmap_) ) return; Rect srcRectSprite(srcRect_); int width = srcRectSprite.width; int height = srcRectSprite.height; if(width <= 0 || height <= 0) if(x < -width || x > Player::getWidth() || y < -height || y > Player::getHeight()) return; if(zoom_x == 0 || zoom_y == 0 || opacity == 0) return; if(flash_duration > 0 && flash_color.red == -1) return; Refresh(); glEnable(GL_TEXTURE_2D); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); sprite_->BindBitmap(); glTranslatef((float)x, (float)y, 0.0f); if ( ! NIL_P(viewport_) ) { Rect rect = Viewport::get(viewport_).getViewportRect(); glEnable(GL_SCISSOR_TEST); glScissor(rect.x, Player::getHeight() - (rect.y + rect.height), rect.width, rect.height); glTranslatef((float)rect.x, (float)rect.y, 0.0f); } glRotatef((float)angle, 0.0f, 0.0f, 1.0f); glTranslatef((float)-ox * zoom_x, (float)-oy * zoom_y, 0.0f); glColor4f(1.0f, 1.0f, 1.0f, opacity / 255.0f); GLfloat corners[4][2] = {{0.0f, 0.0f}, {1.0f, 0.0f}, {1.0f, 1.0f}, {0.0f, 1.0f}}; if (srcRectSprite != sprite_->getRect()) { float rx = (float)srcRectSprite.x / (float)sprite_->getWidth(); float ry = (float)srcRectSprite.y / (float)sprite_->getHeight(); float rw = (float)srcRectSprite.width / (float)sprite_->getWidth(); float rh = (float)srcRectSprite.height / (float)sprite_->getHeight(); corners[0][0] = rx; corners[0][1] = ry; corners[1][0] = rx + rw; corners[1][1] = ry; corners[2][0] = rx + rw; corners[2][1] = ry + rh; corners[3][0] = rx; corners[3][1] = ry + rh; } if (flipx && flipy) { corners[0][0] = 1.0f - corners[0][0]; corners[0][1] = 1.0f - corners[0][1]; corners[1][0] = 1.0f - corners[1][0]; corners[1][1] = 1.0f - corners[1][1]; corners[2][0] = 1.0f - corners[2][0]; corners[2][1] = 1.0f - corners[2][1]; corners[3][0] = 1.0f - corners[3][0]; corners[3][1] = 1.0f - corners[3][1]; } else if (flipx) { corners[0][0] = 1.0f - corners[0][0]; corners[1][0] = 1.0f - corners[1][0]; corners[2][0] = 1.0f - corners[2][0]; corners[3][0] = 1.0f - corners[3][0]; } else if (flipy) { corners[0][1] = 1.0f - corners[0][1]; corners[1][1] = 1.0f - corners[1][1]; corners[2][1] = 1.0f - corners[2][1]; corners[3][1] = 1.0f - corners[3][1]; } glEnable(GL_BLEND); setBlendFunc(blendType_); GLfloat texCoords[4][2]; GLfloat vertexes[4][2]; glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); if (bush_depth == 0) { vertexes[0][0] = 0.f; vertexes[0][1] = 0.f; vertexes[1][0] = width * zoom_x; vertexes[1][1] = 0.f; vertexes[2][0] = width * zoom_x; vertexes[2][1] = height * zoom_y; vertexes[3][0] = 0.f; vertexes[3][1] = height * zoom_y; glVertexPointer(2, GL_FLOAT, 0, vertexes); glTexCoordPointer(2, GL_FLOAT, 0, corners); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); } else { int target; std::memcpy( vertexes, corners, sizeof(vertexes) ); vertexes[0][0] = 0.f; vertexes[0][1] = 0.f; vertexes[1][0] = width * zoom_x; vertexes[1][1] = 0.f; vertexes[2][0] = width * zoom_x; vertexes[2][1] = height * zoom_y; vertexes[3][0] = 0.f; vertexes[3][1] = height * zoom_y; target = flipy ? 0 : 2; texCoords[target + 0][1] -= bush_depth / (float)sprite_->getHeight(); vertexes[target + 0][1] += bush_depth * zoom_y; texCoords[target + 1][1] -= bush_depth / (float)sprite_->getHeight(); vertexes[target + 1][1] += bush_depth * zoom_y; glVertexPointer(2, GL_FLOAT, 0, vertexes); glTexCoordPointer(2, GL_FLOAT, 0, texCoords); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); glColor4f(1.0f, 1.0f, 1.0f, (bush_opacity / 255.0f) * (opacity / 255.0f)); std::memcpy( vertexes, corners, sizeof(vertexes) ); vertexes[0][0] = 0.f; vertexes[0][1] = 0.f; vertexes[1][0] = width * zoom_x; vertexes[1][1] = 0.f; vertexes[2][0] = width * zoom_x; vertexes[2][1] = height * zoom_y; vertexes[3][0] = 0.f; vertexes[3][1] = height * zoom_y; target = flipy ? 2 : 0; texCoords[target + 0][1] -= bush_depth / (float)sprite_->getHeight(); vertexes[target + 0][1] += bush_depth * zoom_y; texCoords[target + 1][1] -= bush_depth / (float)sprite_->getHeight(); vertexes[target + 1][1] += bush_depth * zoom_y; glVertexPointer(2, GL_FLOAT, 0, vertexes); glTexCoordPointer(2, GL_FLOAT, 0, texCoords); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); } if (flash_duration > 0) { glBindTexture(GL_TEXTURE_2D, flash_texture); GLfloat alpha = ((float)flash_color.alpha / 255.0f) * (1.0f - flash_frame / (float)flash_duration); glColor4f((float)flash_color.red / 255.0f, (GLfloat)flash_color.green / 255.0f, (float)flash_color.blue / 255.0f, alpha); vertexes[0][0] = 0.f; vertexes[0][1] = 0.f; vertexes[1][0] = width * zoom_x; vertexes[1][1] = 0.f; vertexes[2][0] = width * zoom_x; vertexes[2][1] = height * zoom_y; vertexes[3][0] = 0.f; vertexes[3][1] = height * zoom_y; glVertexPointer(2, GL_FLOAT, 0, vertexes); glTexCoordPointer(2, GL_FLOAT, 0, corners); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); } glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisable(GL_SCISSOR_TEST); /*if ( !getVisible() ) return; if ( NIL_P(bitmap_) ) return; srcRectSprite = Rect(srcRect_); int width = srcRectSprite.width; int height = srcRectSprite.height; if (width <= 0 || height <= 0) if (x < -width || x > Player::getWidth() || y < -height || y > Player::getHeight()) return; if (zoom_x == 0 || zoom_y == 0 || opacity == 0) return; if (flash_duration > 0 && flash_color.red == -1) return; Refresh(); glEnable(GL_TEXTURE_2D); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); sprite->BindBitmap(); glTranslatef((float)x, (float)y, 0.0f); if ( ! NIL_P(viewport_) ) { Rect rect = Viewport::get(viewport_)->getViewportRect(); glEnable(GL_SCISSOR_TEST); glScissor(rect.x, Player::getHeight() - (rect.y + rect.height), rect.width, rect.height); glTranslatef((float)rect.x, (float)rect.y, 0.0f); } glRotatef((float)angle, 0.0f, 0.0f, 1.0f); glTranslatef((float)-ox * zoom_x, (float)-oy * zoom_y, 0.0f); glColor4f(1.0f, 1.0f, 1.0f, opacity / 255.0f); float corners[4][2] = {0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f}; if (flipx && flipy) { corners[0][0] = 1.0f; corners[0][1] = 1.0f; corners[1][0] = 0.0f; corners[1][1] = 1.0f; corners[2][0] = 0.0f; corners[2][1] = 0.0f; corners[3][0] = 1.0f; corners[3][1] = 0.0f; } else if (flipx) { corners[0][0] = 1.0f; corners[0][1] = 0.0f; corners[1][0] = 0.0f; corners[1][1] = 0.0f; corners[2][0] = 0.0f; corners[2][1] = 1.0f; corners[3][0] = 1.0f; corners[3][1] = 1.0f; } else if (flipy) { corners[0][0] = 0.0f; corners[0][1] = 1.0f; corners[1][0] = 1.0f; corners[1][1] = 1.0f; corners[2][0] = 1.0f; corners[2][1] = 0.0f; corners[3][0] = 0.0f; corners[3][1] = 0.0f; } glEnable(GL_BLEND); setBlendFunc(blendType_); if (bush_depth == 0) { glBegin(GL_QUADS); glTexCoord2f(corners[0][0], corners[0][1]); glVertex2f(0.0f, 0.0f); glTexCoord2f(corners[1][0], corners[1][1]); glVertex2f(width * zoom_x, 0.0f); glTexCoord2f(corners[2][0], corners[2][1]); glVertex2f(width * zoom_x, height * zoom_y); glTexCoord2f(corners[3][0], corners[3][1]); glVertex2f(0.0f, height * zoom_y); glEnd(); } else { glBegin(GL_QUADS); glTexCoord2f(0.0f, 0.0f); glVertex2f(0.0f, 0.0f); glTexCoord2f(1.0f, 0.0f); glVertex2f(width * zoom_x, 0.0f); glTexCoord2f(1.0f, 1.0f - bush_depth / (float)height); glVertex2f(width * zoom_x, (height - bush_depth) * zoom_y); glTexCoord2f(0.0f, 1.0f - bush_depth / (float)height); glVertex2f(0.0f, (height - bush_depth) * zoom_y); glEnd(); glColor4f(1.0f, 1.0f, 1.0f, 0.5f * (opacity / 255.0f)); glBegin(GL_QUADS); glTexCoord2f(0.0f, (1.0f - bush_depth / (float)height)); glVertex2f(0.0f, (height - bush_depth) * zoom_y); glTexCoord2f(1.0f, (1.0f - bush_depth / (float)height)); glVertex2f(width * zoom_x, (height - bush_depth) * zoom_y); glTexCoord2f(1.0f, 1.0f); glVertex2f(width * zoom_x, height * zoom_y); glTexCoord2f(0.0f, 1.0f); glVertex2f(0.0f, height * zoom_y); glEnd(); } if (flash_duration > 0) { glBindTexture(GL_TEXTURE_2D, flash_texture); GLfloat alpha = ((float)flash_color.alpha / 255.0f) * (1.0f - flash_frame / (float)flash_duration); glColor4f((float)flash_color.red / 255.0f, (GLfloat)flash_color.green / 255.0f, (float)flash_color.blue / 255.0f, alpha); glBegin(GL_QUADS); glTexCoord2f(corners[0][0], corners[0][1]); glVertex2f(0.0f, 0.0f); glTexCoord2f(corners[1][0], corners[1][1]); glVertex2f(width * zoom_x, 0.0f); glTexCoord2f(corners[2][0], corners[2][1]); glVertex2f(width * zoom_x, height * zoom_y); glTexCoord2f(corners[3][0], corners[3][1]); glVertex2f(0.0f, height * zoom_y); glEnd(); } glDisable(GL_SCISSOR_TEST);*/ } void Sprite::draw(long z, Bitmap const& dst_bitmap) { /*if ( !getVisible() ) return; if (getWidth() <= 0 || getHeight() <= 0) return; if (x < -getWidth() || x > dst_bitmap->getWidth() || y < -getHeight() || y > dst_bitmap->getHeight()) return; if (!bitmap_) return; srcRectSprite = Rect(srcRect_); if (srcRectSprite != srcRect_last) { srcRect_last = srcRectSprite; needs_refresh = true; } if (needs_refresh) Refresh(); dst_bitmap->Blit(x - ox, y - oy, sprite, sprite->getRect(), 255);*/ } //////////////////////////////////////////////////////////// /// Refresh //////////////////////////////////////////////////////////// void Sprite::Refresh() { if (needs_refresh) { needs_refresh = false; sprite_.reset( new Bitmap( Bitmap::get(bitmap_), Bitmap::get(bitmap_).getRect() ) ); sprite_->ToneChange(Tone(tone)); } if (flash_needs_refresh) { flash_needs_refresh = false; RefreshFlash(); } sprite_->Refresh(); /*Tone tone_sprite(tone); if (srcRectSprite != srcRect_last) { srcRect_last = srcRectSprite; if (tone_sprite.red != 0 || tone_sprite.green != 0 || tone_sprite.blue != 0 || tone_sprite.gray != 0) { needs_refresh = true; } flash_needs_refresh = true; } if (needs_refresh) { needs_refresh = false; if (sprite) delete sprite; sprite = new Bitmap(Bitmap::get(bitmap_), srcRectSprite); sprite->ToneChange(tone_sprite); } if (flash_needs_refresh) { flash_needs_refresh = false; RefreshFlash(); } sprite->Refresh();*/ } //////////////////////////////////////////////////////////// /// get Width //////////////////////////////////////////////////////////// int Sprite::getWidth() { return NUM2INT(rb_iv_get(srcRect_, "@width")); } //////////////////////////////////////////////////////////// /// get Height //////////////////////////////////////////////////////////// int Sprite::getHeight() { return NUM2INT(rb_iv_get(srcRect_, "@height")); } //////////////////////////////////////////////////////////// /// Update //////////////////////////////////////////////////////////// void Sprite::Update() { if (flash_duration != 0) { flash_frame += 1; if (flash_duration == flash_frame) { flash_duration = 0; if (flash_texture > 0) { glDeleteTextures(1, &flash_texture); flash_texture = 0; } } } } //////////////////////////////////////////////////////////// /// Flash //////////////////////////////////////////////////////////// void Sprite::Flash(int duration) { flash_color = Color(-1, -1, -1, -1); flash_duration = duration; flash_frame = 0; } void Sprite::Flash(Color const& color, int duration) { flash_color = color; flash_duration = duration; flash_frame = 0; flash_needs_refresh = true; } void Sprite::RefreshFlash() { if (flash_texture > 0) glDeleteTextures(1, &flash_texture); glEnable(GL_TEXTURE_2D); glGenTextures(1, &flash_texture); glBindTexture(GL_TEXTURE_2D, flash_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glPixelTransferf(GL_RED_BIAS, 255.0f); glPixelTransferf(GL_GREEN_BIAS, 255.0f); glPixelTransferf(GL_BLUE_BIAS, 255.0f); glTexImage2D(GL_TEXTURE_2D, 0, 4, sprite_->getWidth(), sprite_->getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, sprite_->getPixels()); glPixelTransferf(GL_RED_BIAS, 0.0f); glPixelTransferf(GL_GREEN_BIAS, 0.0f); glPixelTransferf(GL_BLUE_BIAS, 0.0f); } //////////////////////////////////////////////////////////// /// Properties //////////////////////////////////////////////////////////// void Sprite::setViewport(VALUE nviewport) { if (viewport_ != nviewport) { if ( ! NIL_P(nviewport) ) { Graphics::RemoveZObj(id); Viewport::get(nviewport).RegisterZObj(0, id); } else { if ( ! NIL_P(viewport_) ) Viewport::get(viewport_).RemoveZObj(id); Graphics::RegisterZObj(0, id); } } viewport_ = nviewport; } void Sprite::setBitmap(VALUE nbitmap) { if (bitmap_ != nbitmap) { needs_refresh = true; flash_needs_refresh = true; } bitmap_ = nbitmap; } void Sprite::setZ(int nz) { if (z != nz) { if ( ! NIL_P(viewport_) ) Viewport::get(viewport_).UpdateZObj(id, nz); else Graphics::UpdateZObj(id, nz); } z = nz; } void Sprite::setTone(VALUE ntone) { if (tone != ntone) needs_refresh = true; tone = ntone; }
[ [ [ 1, 526 ] ] ]
056be218db5b6c3ccd91b7c8736eae2f248899d7
cd0987589d3815de1dea8529a7705caac479e7e9
/includes/webkitsupport/platform/BlackBerryPlatformSettings.h
6ad2723e6d9631d8ee0b89a01171f299c97b8890
[]
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
2,126
h
/* * Copyright (C) Research In Motion, Limited 2010. All rights reserved. */ #ifndef BlackBerryPlatformSettings_h #define BlackBerryPlatformSettings_h #include <string> namespace BlackBerry { namespace Platform { class Settings { private: Settings(); ~Settings() {}; public: static Settings* get(); bool isRSSFilteringEnabled() const { return m_rssFiltering; } void setRSSFilteringEnabled(bool enable) { m_rssFiltering = enable; } unsigned getSuggestedCacheCapacity(unsigned currentUsage) const; unsigned long secondaryThreadStackSize() const { return m_secondaryThreadStackSize; } void setSecondaryThreadStackSize(unsigned long size) { m_secondaryThreadStackSize = size; } unsigned maxPixelsPerDecodedImage() const { return m_maxPixelsPerDecodedImage; } bool shouldReportLowMemoryToUser() const { return m_shouldReportLowMemoryToUser; } void setShouldReportLowMemoryToUser(bool shouldReport) { m_shouldReportLowMemoryToUser = shouldReport; } unsigned numberOfBackingStoreTiles() const { return m_numberOfBackingStoreTiles; } unsigned maxNumberOfWorkers() const { return m_maxNumberOfWorkers; } void setMaxNumberOfWorkers(unsigned maxNumberOfWorkers) { m_maxNumberOfWorkers = maxNumberOfWorkers; } // Resource Path std::string resourceDirectory() const { return m_resourceDirectory; } void setResourceDirectory(const char* dir) { m_resourceDirectory = std::string(dir); } private: unsigned long m_secondaryThreadStackSize; unsigned m_maxPixelsPerDecodedImage; bool m_rssFiltering; bool m_shouldReportLowMemoryToUser; unsigned m_numberOfBackingStoreTiles; unsigned m_maxNumberOfWorkers; std::string m_resourceDirectory; }; } // namespace Platform } // namespace Olympia #endif // BlackBerryPlatformSettings_h
[ [ [ 1, 60 ] ] ]
9bceaa84bd6986053461cc40571b1a2a55c414bd
6581dacb25182f7f5d7afb39975dc622914defc7
/easyMule/easyMule/src/UILayer/Lists/SharedFilesCtrl.h
93f727528bc5eb22b262e9c92388c41ec80d934f
[]
no_license
dice2019/alexlabonline
caeccad28bf803afb9f30b9e3cc663bb2909cc4f
4c433839965ed0cff99dad82f0ba1757366be671
refs/heads/master
2021-01-16T19:37:24.002905
2011-09-21T15:20:16
2011-09-21T15:20:16
null
0
0
null
null
null
null
GB18030
C++
false
false
3,977
h
/* * $Id: SharedFilesCtrl.h 5158 2008-03-27 08:15:52Z huby $ * * this file is part of eMule * Copyright (C)2002-2006 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net ) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #pragma once #include "MuleListCtrl.h" #include "TitleMenu.h" #include "ListCtrlItemWalk.h" #include "JavaScriptEscape.h" //Added by thilon on 206.08.28, 在线杀毒 class CSharedFileList; class CKnownFile; class CDirectoryItem; class CSharedFilesCtrl : public CMuleListCtrl, public CListCtrlItemWalk { friend class CSharedDirsTreeCtrl; DECLARE_DYNAMIC(CSharedFilesCtrl) public: CSharedFilesCtrl(); virtual ~CSharedFilesCtrl(); void Init(); void CreateMenues(); void ReloadFileList(); void AddFile(const CKnownFile* file); void RemoveFile(const CKnownFile* file); void UpdateFile(const CKnownFile* file); void Localize(); void ShowFilesCount(); void ShowComments(CKnownFile* file); void SetAICHHashing(uint32 nVal) { nAICHHashing = nVal; } void SetDirectoryFilter(CDirectoryItem* pNewFilter, bool bRefresh = true); void SetDirectoryState(bool isShared); protected: CTitleMenu m_SharedFilesMenu; CTitleMenu m_CollectionsMenu; CMenu m_PrioMenu; CMenuXP* m_pSharedFilesMenuXP; bool sortstat[4]; CImageList m_ImageList; CDirectoryItem* m_pDirectoryFilter; volatile uint32 nAICHHashing; JavaScriptEscape m_JavaScriptEscape; bool m_bDirectoryShared; static int CALLBACK SortProc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort); void OpenFile(const CKnownFile* file); void ShowFileDialog(CTypedPtrList<CPtrList, CKnownFile*>& aFiles, UINT uPshInvokePage = 0); void SetAllIcons(); int FindFile(const CKnownFile* pFile); virtual BOOL OnCommand(WPARAM wParam, LPARAM lParam); virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct); DECLARE_MESSAGE_MAP() afx_msg void OnSysColorChange(); afx_msg void OnColumnClick( NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnContextMenu(CWnd* pWnd, CPoint point); afx_msg void OnNMDblclk(NMHDR *pNMHDR, LRESULT *pResult); afx_msg void OnGetDispInfo(NMHDR *pNMHDR, LRESULT *pResult); afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags); //VeryCD Start //共享文件列表中的评论,added by Chocobo on 2006.09.01 afx_msg void OnNMClick(NMHDR *pNMHDR, LRESULT *pResult); public: afx_msg void OnMouseMove(UINT nFlags, CPoint point); //VeryCD End afx_msg void OnLvnItemchanged(NMHDR *pNMHDR, LRESULT *pResult); afx_msg void OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct); afx_msg void OnMeasureItem(int nIDCtl, LPMEASUREITEMSTRUCT lpMeasureItemStruct); public: void RedrawCheckBox(int type, const CKnownFile* file); void RedrawCheckBox( const CString& filepath ); protected: bool CheckBoxHitTest(const POINT& point, int& item, int& subitem, bool* onCheckBox = NULL); BOOL GetSubItemRect(int nItem, int nSubItem, int nArea, CRect& rect); bool GetCheckboxRect(const int item, const int subitem, CRect& rect, bool checkOnly); void DrawCheckBox(CDC *pDC, CRect rc, CKnownFile* file); void Clear(); int FindItem(const CString& FilePath); public: CList<CKnownFile *, CKnownFile *> m_UnSharedFileList; };
[ "damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838" ]
[ [ [ 1, 108 ] ] ]
50e827afb872d67fb12b92ddb96c1425b2f5e6c1
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/Game/wheel/NewWheelDirector/include/WheelDirector.h
7de34a76433fb8b5c1c5b603f57db6d037f54e03
[]
no_license
dbabox/aomi
dbfb46c1c9417a8078ec9a516cc9c90fe3773b78
4cffc8e59368e82aed997fe0f4dcbd7df626d1d0
refs/heads/master
2021-01-13T14:05:10.813348
2011-06-07T09:36:41
2011-06-07T09:36:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,056
h
#ifndef __Orz_WheelDirector_h__ #define __Orz_WheelDirector_h__ #include "NewWheelDirectorStableHeaders.h" #include <orz/Toolkit_Base/FSMLogic.h> namespace Orz { class WheelGame; class WheelLogic; class WheelClock; class WheelMediator; class EntityLoader; class AutoEngineDecorator; class NewHardwareCode; typedef boost::shared_ptr<AutoEngineDecorator> AutoEngineDecoratorPtr; class WheelDirector: public Director { public: WheelDirector(const std::string & name/* , const std::string & xmlFile*/); virtual ~WheelDirector(void); void doExecute(Event * evt); void doEnable(void); void doDisable(void); void doFrame(unsigned int step); private: boost::scoped_ptr<WheelGame> _game; boost::scoped_ptr<EntityLoader> _loader; boost::scoped_ptr<NewHardwareCode> _code; // // boost::scoped_ptr<WheelMediator> _mediator; //boost::scoped_ptr<WheelClock> _clock; FSMLogicHandler<WheelGame, WheelLogic> _logic; ScenePtr _scene; AutoEngineDecoratorPtr _autoEngine; }; } #endif
[ [ [ 1, 42 ] ] ]
de9eb9dd125bc1464592f2ac90125446b7ae25c2
1c9f99b2b2e3835038aba7ec0abc3a228e24a558
/Projects/elastix/elastix_sources_v4/src/Core/ComponentBaseClasses/elxOptimizerBase.h
f5617047dcd070e9ab57a8abe062058b756ed5f5
[]
no_license
mijc/Diploma
95fa1b04801ba9afb6493b24b53383d0fbd00b33
bae131ed74f1b344b219c0ffe0fffcd90306aeb8
refs/heads/master
2021-01-18T13:57:42.223466
2011-02-15T14:19:49
2011-02-15T14:19:49
1,369,569
0
0
null
null
null
null
UTF-8
C++
false
false
4,880
h
/*====================================================================== This file is part of the elastix software. Copyright (c) University Medical Center Utrecht. All rights reserved. See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. ======================================================================*/ #ifndef __elxOptimizerBase_h #define __elxOptimizerBase_h /** Needed for the macros */ #include "elxMacro.h" #include "elxBaseComponentSE.h" #include "itkOptimizer.h" namespace elastix { using namespace itk; /** * \class OptimizerBase * \brief This class is the elastix base class for all Optimizers. * * This class contains all the common functionality for Optimizers. * * The parameters used in this class are: * \parameter NewSamplesEveryIteration: if this flag is set to "true" some * optimizers ask the metric to select a new set of spatial samples in * every iteration. This, if used in combination with the correct optimizer (such as the * StandardGradientDescent), and ImageSampler (Random, RandomCoordinate, or RandomSparseMask), * allows for a very low number of spatial samples (around 2000), even with large images * and transforms with a large number of parameters.\n * Choose one from {"true", "false"} for every resolution.\n * example: <tt>(NewSamplesEveryIteration "true" "true" "true")</tt> \n * Default is "false" for every resolution.\n * * \ingroup Optimizers * \ingroup ComponentBaseClasses */ template <class TElastix> class OptimizerBase : public BaseComponentSE<TElastix> { public: /** Standard ITK-stuff. */ typedef OptimizerBase Self; typedef BaseComponentSE<TElastix> Superclass; /** Run-time type information (and related methods). */ itkTypeMacro( OptimizerBase, BaseComponentSE ); /** Typedefs inherited from Elastix. */ typedef typename Superclass::ElastixType ElastixType; typedef typename Superclass::ElastixPointer ElastixPointer; typedef typename Superclass::ConfigurationType ConfigurationType; typedef typename Superclass::ConfigurationPointer ConfigurationPointer; typedef typename Superclass::RegistrationType RegistrationType; typedef typename Superclass::RegistrationPointer RegistrationPointer; /** ITKBaseType. */ typedef itk::Optimizer ITKBaseType; /** Typedef needed for the SetCurrentPositionPublic function. */ typedef typename ITKBaseType::ParametersType ParametersType; /** Cast to ITKBaseType. */ virtual ITKBaseType * GetAsITKBaseType(void) { return dynamic_cast<ITKBaseType *>(this); } /** Cast to ITKBaseType, to use in const functions. */ virtual const ITKBaseType * GetAsITKBaseType(void) const { return dynamic_cast<const ITKBaseType *>(this); } /** Add empty SetCurrentPositionPublic, so this function is known in every inherited class. */ virtual void SetCurrentPositionPublic( const ParametersType &param ); /** Execute stuff before each new pyramid resolution: * \li Find out if new samples are used every new iteration in this resolution. */ virtual void BeforeEachResolutionBase(); /** Method that sets the scales defined by a sinus * scale[i] = amplitude^( sin(i/nrofparam*2pi*frequency) ) */ virtual void SetSinusScales(double amplitude, double frequency, unsigned long numberOfParameters); protected: /** The constructor. */ OptimizerBase(); /** The destructor. */ virtual ~OptimizerBase() {} /** Force the metric to base its computation on a new subset of image samples. * Not every metric may have implemented this. */ virtual void SelectNewSamples(void); /** Check whether the user asked to select new samples every iteration. */ virtual const bool GetNewSamplesEveryIteration(void) const; private: /** The private constructor. */ OptimizerBase( const Self& ); // purposely not implemented /** The private copy constructor. */ void operator=( const Self& ); // purposely not implemented /** Member variable to store the user preference for using new * samples each iteration. */ bool m_NewSamplesEveryIteration; }; // end class OptimizerBase } // end namespace elastix #ifndef ITK_MANUAL_INSTANTIATION #include "elxOptimizerBase.hxx" #endif #endif // end #ifndef __elxOptimizerBase_h
[ [ [ 1, 140 ] ] ]
b577ddf562fa57c59e7f3c14a8d016246e221ed0
6247eceeb3d15fd80f27285de6808a11eb66a9e2
/lsprite.cpp
4879ebc3269dc4f98a0bf2995491e88249ebaea2
[]
no_license
sean-m/hgelua
7b48b30271f295f617b6242cb8996f802add0284
d4f94f0b5905cc4fa471bee7d9474ab2779c9a24
refs/heads/master
2021-01-10T04:58:00.146231
2010-04-12T16:27:14
2010-04-12T16:27:14
54,251,268
0
0
null
null
null
null
UTF-8
C++
false
false
7,635
cpp
#include "lhge.h" /*-------------------------------------------------------------*/ // Sprite /*-------------------------------------------------------------*/ #define HH2SPR(spr) ((hgeSprite*)(*spr)) hgeSprite* tosprite(lua_State *L, int index) { lua_pushvalue(L, 1); lua_pushstring(L, "__name"); lua_gettable(L, -2); const char* metaname = luaL_checkstring(L, -1); lua_pop(L, 2); if (strcmp(metaname, SPRITE) == 0) { return (hgeSprite*)*toudp(L, 1, SPRITE); } else if (strcmp(metaname, ANIMATION) == 0 ) { return (hgeSprite*)*toudp(L, 1, ANIMATION); } else return NULL; } int lhge_newsprite(lua_State *L) { HHANDLE * tex = toudp(L, 1, TEXTURE); hgeSprite * spr = new hgeSprite(*tex, luaL_checknumber(L, 2), luaL_checknumber(L, 3), luaL_checknumber(L, 4), luaL_checknumber(L, 5) ); HHANDLE * udp = newudp(L, SPRITE); *udp = (HHANDLE)spr; return 1; } static int sprite_gc(lua_State *L) { hgeSprite * spr = HH2SPR(toudp(L, 1, SPRITE)); delete spr; return 0; } static int sprite_tostring(lua_State *L) { HHANDLE * udp = toudp(L, 1, SPRITE); if (udp == NULL) lua_pushliteral(L, "Sprite (NULL)"); else lua_pushfstring(L, "Sprite (%p)", udp); return 1; } static int sprite_render(lua_State *L) { hgeSprite * spr = tosprite(L, 1); if (lua_isnoneornil(L, 4)) spr->Render( luaL_checknumber(L, 2), luaL_checknumber(L, 3) ); else spr->RenderEx( luaL_checknumber(L, 2), luaL_checknumber(L, 3), luaL_checknumber(L, 4), luaL_optnumber(L, 5, 1.0), luaL_optnumber(L, 6, 0.0) ); return 0; } static int sprite_renderstretch(lua_State *L) { hgeSprite * spr = tosprite(L, 1); spr->RenderStretch( luaL_checknumber(L, 2), luaL_checknumber(L, 3), luaL_checknumber(L, 4), luaL_checknumber(L, 5) ); return 0; } static int sprite_render4v(lua_State *L) { hgeSprite * spr = tosprite(L, 1); spr->Render4V( luaL_checknumber(L, 2), luaL_checknumber(L, 3), luaL_checknumber(L, 4), luaL_checknumber(L, 5), luaL_checknumber(L, 6), luaL_checknumber(L, 7), luaL_checknumber(L, 8), luaL_checknumber(L, 9) ); return 0; } static int sprite_settexture(lua_State *L) { hgeSprite * spr = tosprite(L, 1); HHANDLE * tex = toudp(L, 2, TEXTURE); spr->SetTexture(*tex); return 0; } static int sprite_settexturerect(lua_State *L) { hgeSprite * spr = tosprite(L, 1); bool adjSize = true; if (!lua_isnoneornil(L, 6)) adjSize = lua_toboolean(L, 6); spr->SetTextureRect( luaL_checknumber(L, 2), luaL_checknumber(L, 3), luaL_checknumber(L, 4), luaL_checknumber(L, 5), adjSize ); return 0; } static int sprite_setcolor(lua_State *L) { hgeSprite * spr = tosprite(L, 1); spr->SetColor( luaL_checkinteger(L, 2), luaL_optinteger(L, 3, -1) ); return 0; } static int sprite_setz(lua_State *L) { hgeSprite * spr = tosprite(L, 1); spr->SetZ( luaL_checkinteger(L, 2), luaL_optinteger(L, 3, -1) ); return 0; } static int sprite_setblendmode(lua_State *L) { hgeSprite * spr = tosprite(L, 1); spr->SetBlendMode( luaL_checkinteger(L, 2) ); return 0; } static int sprite_sethotspot(lua_State *L) { hgeSprite * spr = tosprite(L, 1); spr->SetHotSpot( luaL_checkinteger(L, 2), luaL_checkinteger(L, 3) ); return 0; } static int sprite_setflip(lua_State *L) { hgeSprite * spr = tosprite(L, 1); spr->SetFlip( lua_toboolean(L, 2), lua_toboolean(L, 3), lua_toboolean(L, 4) ); return 0; } static int sprite_gettexture(lua_State *L) { hgeSprite * spr = tosprite(L, 1); HHANDLE tex = spr->GetTexture(); HHANDLE * udp = newudp(L, TEXTURE); (*udp) = tex; return 1; } static int sprite_gettexturerect(lua_State *L) { hgeSprite * spr = tosprite(L, 1); float x, y, w, h; spr->GetTextureRect(&x, &y, &w, &h); lua_pushnumber(L, x); lua_pushnumber(L, y); lua_pushnumber(L, w); lua_pushnumber(L, h); return 4; } static int sprite_getcolor(lua_State *L) { hgeSprite * spr = tosprite(L, 1); lua_pushinteger(L, spr->GetColor(luaL_optinteger(L, 2, 0))); return 1; } static int sprite_getz(lua_State *L) { hgeSprite * spr = tosprite(L, 1); lua_pushnumber(L, spr->GetZ(luaL_optinteger(L, 2, 0))); return 1; } static int sprite_getblendmode(lua_State *L) { hgeSprite * spr = tosprite(L, 1); lua_pushinteger(L, spr->GetBlendMode()); return 1; } static int sprite_gethotspot(lua_State *L) { hgeSprite * spr = tosprite(L, 1); float x, y; spr->GetHotSpot(&x, &y); lua_pushnumber(L, x); lua_pushnumber(L, y); return 2; } static int sprite_getflip(lua_State *L) { hgeSprite * spr = tosprite(L, 1); bool bx, by; spr->GetFlip(&bx, &by); lua_pushboolean(L, bx); lua_pushboolean(L, by); return 2; } static int sprite_getwidth(lua_State *L) { hgeSprite * spr = tosprite(L, 1); lua_pushnumber(L, spr->GetWidth()); return 1; } static int sprite_getheight(lua_State *L) { hgeSprite * spr = tosprite(L, 1); lua_pushnumber(L, spr->GetHeight()); return 1; } static int sprite_getboundingbox(lua_State *L) { hgeSprite * spr = tosprite(L, 1); if (lua_gettop(L) == 4) // normal { hgeRect* rect = spr->GetBoundingBox( luaL_checknumber(L, 2), luaL_checknumber(L, 3), (hgeRect*)(*toudp(L, 4, RECT)) ); HHANDLE * udp = newudp(L, RECT); *udp = (HHANDLE)rect; } else { hgeRect* rect = spr->GetBoundingBoxEx( luaL_checknumber(L, 2), luaL_checknumber(L, 3), luaL_checknumber(L, 4), luaL_checknumber(L, 5), luaL_checknumber(L, 6), (hgeRect*)(*toudp(L, 7, RECT)) ); HHANDLE * udp = newudp(L, RECT); *udp = (HHANDLE)rect; } return 1; } static const luaL_Reg spritelib[] = { {"__gc", sprite_gc}, {"__tostring", sprite_tostring}, {"Render", sprite_render},// Renders sprite to the screen. {"RenderStretch", sprite_renderstretch},// Renders stretched sprite. {"Render4V", sprite_render4v},// Renders sprite into arbitrary quad on the screen. {"SetTexture", sprite_settexture},// Sets the texture to use for the sprite. {"SetTextureRect", sprite_settexturerect},// Sets the texture region to use for the sprite. {"SetColor", sprite_setcolor},// Sets tint and alpha for the specified vertex or entire sprite. {"SetZ", sprite_setz},// Sets Z-order for the specified vertex or entire sprite. {"SetBlendMode", sprite_setblendmode},// Sets the sprite blending mode. {"SetHotSpot", sprite_sethotspot},// Sets the sprite anchor point. {"SetFlip", sprite_setflip},// Flips the sprite horizontally and/or vertically. {"GetTexture", sprite_gettexture},// Returns the current sprite texture. {"GetTextureRect", sprite_gettexturerect},// Returns the current texture region used for the sprite. {"GetColor", sprite_getcolor},// Returns color of the specified sprite vertex. {"GetZ", sprite_getz},// Returns Z-order of the specified sprite vertex. {"GetBlendMode", sprite_getblendmode},// Returns the current sprite blending mode. {"GetHotSpot", sprite_gethotspot},// Returns the sprite anchor point. {"GetFlip", sprite_getflip},// Returns the current sprite flipping. {"GetWidth", sprite_getwidth},// Returns the sprite width. {"GetHeight", sprite_getheight},// Returns the sprite height. {"GetBoundingBox", sprite_getboundingbox},// Returns the sprite bounding box. {NULL, NULL} }; void luaopen_sprite(lua_State *L) { create_meta(L, SPRITE, spritelib); }
[ "fengyu05@e74d88d6-4bf9-11de-b850-9977aa68d080" ]
[ [ [ 1, 314 ] ] ]
04b93cc58e056ea3f5743b3ceca2fb2fd70adb3c
bd37f7b494990542d0d9d772368239a2d44e3b2d
/server/src/Fantasma.h
058c49f9c8e55715f19fcf940bd78e53b6eaba8f
[]
no_license
nicosuarez/pacmantaller
b559a61355517383d704f313b8c7648c8674cb4c
0e0491538ba1f99b4420340238b09ce9a43a3ee5
refs/heads/master
2020-12-11T02:11:48.900544
2007-12-19T21:49:27
2007-12-19T21:49:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,418
h
/////////////////////////////////////////////////////////// // Fantasma.h // Implementation of the Class Fantasma // Created on: 21-Nov-2007 23:40:19 /////////////////////////////////////////////////////////// #if !defined(EA_E4309321_8E59_4003_BC67_09BA7FB5090B__INCLUDED_) #define EA_E4309321_8E59_4003_BC67_09BA7FB5090B__INCLUDED_ #include "Personaje.h" #include "AgregarJugadorOp.h" /** * Clase que modela el personaje Fantasma */ class Fantasma : public Personaje { public: Fantasma(); Fantasma(Posicion& posicion); virtual ~Fantasma(); static const int FANTASMA_TYPE = 1; int GetRol()const; virtual int GetVelocidad(); bool IsVisible(); void SetVisible(bool visible); bool operator==( int tipo )const; double getRadio()const; int getPuntaje(){return puntaje;}; void irACasa(); /** * Velocidad inicial constante del fantasma */ static const int velocidadInicial=4; private: /** * Radio constante del fantasma */ static const double radio=0.25; /** * Determina si el fantasma esta en estado invisible que ocurre cuando un pacman * en estado powerUp como el fantasma. Cuando el mismo se encuentra invisible no * puede volver entrar en juego hasta que no haya pasado por la casa. */ bool visible; static const int puntaje=10; }; #endif // !defined(EA_E4309321_8E59_4003_BC67_09BA7FB5090B__INCLUDED_)
[ "scamjayi@5682bcf5-5c3f-0410-a8fd-ab24993f6fe8", "nicolas.suarez@5682bcf5-5c3f-0410-a8fd-ab24993f6fe8" ]
[ [ [ 1, 23 ], [ 25, 28 ], [ 30, 56 ] ], [ [ 24, 24 ], [ 29, 29 ] ] ]
408874099bf31480da35abbd6ec083bb1b9550a6
7b4e708809905ae003d0cb355bf53e4d16c9cbbc
/JuceLibraryCode/modules/juce_audio_utils/gui/juce_AudioThumbnailCache.cpp
8b6cfe58f8487dccc81768670704f42793212be9
[]
no_license
sonic59/JulesText
ce6507014e4cba7fb0b67597600d1cee48a973a5
986cbea68447ace080bf34ac2b94ac3ab46faca4
refs/heads/master
2016-09-06T06:10:01.815928
2011-11-18T01:19:26
2011-11-18T01:19:26
2,796,827
0
0
null
null
null
null
UTF-8
C++
false
false
4,897
cpp
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-11 by Raw Material Software Ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License (Version 2), as published by the Free Software Foundation. A copy of the license is included in the JUCE distribution, or can be found online at www.gnu.org/licenses. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ BEGIN_JUCE_NAMESPACE //============================================================================== class AudioThumbnailCache::ThumbnailCacheEntry { public: ThumbnailCacheEntry (const int64 hash_) : hash (hash_), lastUsed (Time::getMillisecondCounter()) { } ThumbnailCacheEntry (InputStream& in) : lastUsed (0) { hash = in.readInt64(); const int64 len = in.readInt64(); in.readIntoMemoryBlock (data, (ssize_t) len); } void write (OutputStream& out) { out.writeInt64 (hash); out.writeInt64 ((int64) data.getSize()); out << data; } int64 hash; uint32 lastUsed; MemoryBlock data; private: JUCE_LEAK_DETECTOR (ThumbnailCacheEntry); }; //============================================================================== AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_) : TimeSliceThread ("thumb cache"), maxNumThumbsToStore (maxNumThumbsToStore_) { jassert (maxNumThumbsToStore > 0); startThread (2); } AudioThumbnailCache::~AudioThumbnailCache() { } AudioThumbnailCache::ThumbnailCacheEntry* AudioThumbnailCache::findThumbFor (const int64 hash) const { for (int i = thumbs.size(); --i >= 0;) if (thumbs.getUnchecked(i)->hash == hash) return thumbs.getUnchecked(i); return nullptr; } int AudioThumbnailCache::findOldestThumb() const { int oldest = 0; uint32 oldestTime = Time::getMillisecondCounter() + 1; for (int i = thumbs.size(); --i >= 0;) { const ThumbnailCacheEntry* const te = thumbs.getUnchecked(i); if (te->lastUsed < oldestTime) { oldest = i; oldestTime = te->lastUsed; } } return oldest; } bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode) { const ScopedLock sl (lock); ThumbnailCacheEntry* te = findThumbFor (hashCode); if (te != nullptr) { te->lastUsed = Time::getMillisecondCounter(); MemoryInputStream in (te->data, false); thumb.loadFrom (in); return true; } return false; } void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb, const int64 hashCode) { const ScopedLock sl (lock); ThumbnailCacheEntry* te = findThumbFor (hashCode); if (te == nullptr) { te = new ThumbnailCacheEntry (hashCode); if (thumbs.size() < maxNumThumbsToStore) thumbs.add (te); else thumbs.set (findOldestThumb(), te); } MemoryOutputStream out (te->data, false); thumb.saveTo (out); } void AudioThumbnailCache::clear() { const ScopedLock sl (lock); thumbs.clear(); } static inline int getThumbnailCacheFileMagicHeader() noexcept { return (int) ByteOrder::littleEndianInt ("ThmC"); } bool AudioThumbnailCache::readFromStream (InputStream& source) { if (source.readInt() != getThumbnailCacheFileMagicHeader()) return false; const ScopedLock sl (lock); clear(); int numThumbnails = jmin (maxNumThumbsToStore, source.readInt()); while (--numThumbnails >= 0 && ! source.isExhausted()) thumbs.add (new ThumbnailCacheEntry (source)); return true; } void AudioThumbnailCache::writeToStream (OutputStream& out) { const ScopedLock sl (lock); out.writeInt (getThumbnailCacheFileMagicHeader()); out.writeInt (thumbs.size()); for (int i = 0; i < thumbs.size(); ++i) thumbs.getUnchecked(i)->write (out); } END_JUCE_NAMESPACE
[ [ [ 1, 176 ] ] ]
4011e7b170ba7df13e2522b0e4b1af6cb3e21f7d
580738f96494d426d6e5973c5b3493026caf8b6a
/Include/Vcl/mplayer.hpp
650fe73580cfe96dda6149ad04c97ef5ac323079
[]
no_license
bravesoftdz/cbuilder-vcl
6b460b4d535d17c309560352479b437d99383d4b
7b91ef1602681e094a6a7769ebb65ffd6f291c59
refs/heads/master
2021-01-10T14:21:03.726693
2010-01-11T11:23:45
2010-01-11T11:23:45
48,485,606
2
1
null
null
null
null
UTF-8
C++
false
false
12,476
hpp
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'MPlayer.pas' rev: 6.00 #ifndef MPlayerHPP #define MPlayerHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <Menus.hpp> // Pascal unit #include <SysUtils.hpp> // Pascal unit #include <Dialogs.hpp> // Pascal unit #include <MMSystem.hpp> // Pascal unit #include <Messages.hpp> // Pascal unit #include <Graphics.hpp> // Pascal unit #include <Forms.hpp> // Pascal unit #include <Controls.hpp> // Pascal unit #include <Classes.hpp> // Pascal unit #include <Windows.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Mplayer { //-- type declarations ------------------------------------------------------- #pragma option push -b- enum TMPBtnType { btPlay, btPause, btStop, btNext, btPrev, btStep, btBack, btRecord, btEject }; #pragma option pop typedef Set<TMPBtnType, btPlay, btEject> TButtonSet; #pragma option push -b- enum TMPGlyph { mgEnabled, mgDisabled, mgColored }; #pragma option pop #pragma pack(push, 4) struct TMPButton { bool Visible; bool Enabled; bool Colored; bool Auto; Graphics::TBitmap* Bitmaps[3]; } ; #pragma pack(pop) #pragma option push -b- enum TMPDeviceTypes { dtAutoSelect, dtAVIVideo, dtCDAudio, dtDAT, dtDigitalVideo, dtMMMovie, dtOther, dtOverlay, dtScanner, dtSequencer, dtVCR, dtVideodisc, dtWaveAudio }; #pragma option pop #pragma option push -b- enum TMPTimeFormats { tfMilliseconds, tfHMS, tfMSF, tfFrames, tfSMPTE24, tfSMPTE25, tfSMPTE30, tfSMPTE30Drop, tfBytes, tfSamples, tfTMSF }; #pragma option pop #pragma option push -b- enum TMPModes { mpNotReady, mpStopped, mpPlaying, mpRecording, mpSeeking, mpPaused, mpOpen }; #pragma option pop #pragma option push -b- enum TMPNotifyValues { nvSuccessful, nvSuperseded, nvAborted, nvFailure }; #pragma option pop #pragma option push -b- enum TMPDevCaps { mpCanStep, mpCanEject, mpCanPlay, mpCanRecord, mpUsesWindow }; #pragma option pop typedef Set<TMPDevCaps, mpCanStep, mpUsesWindow> TMPDevCapsSet; typedef void __fastcall (__closure *EMPNotify)(System::TObject* Sender, TMPBtnType Button, bool &DoDefault); typedef void __fastcall (__closure *EMPPostNotify)(System::TObject* Sender, TMPBtnType Button); class DELPHICLASS EMCIDeviceError; class PASCALIMPLEMENTATION EMCIDeviceError : public Sysutils::Exception { typedef Sysutils::Exception inherited; public: #pragma option push -w-inl /* Exception.Create */ inline __fastcall EMCIDeviceError(const AnsiString Msg) : Sysutils::Exception(Msg) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateFmt */ inline __fastcall EMCIDeviceError(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size) : Sysutils::Exception(Msg, Args, Args_Size) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateRes */ inline __fastcall EMCIDeviceError(int Ident)/* overload */ : Sysutils::Exception(Ident) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateResFmt */ inline __fastcall EMCIDeviceError(int Ident, const System::TVarRec * Args, const int Args_Size)/* overload */ : Sysutils::Exception(Ident, Args, Args_Size) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateHelp */ inline __fastcall EMCIDeviceError(const AnsiString Msg, int AHelpContext) : Sysutils::Exception(Msg, AHelpContext) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateFmtHelp */ inline __fastcall EMCIDeviceError(const AnsiString Msg, const System::TVarRec * Args, const int Args_Size, int AHelpContext) : Sysutils::Exception(Msg, Args, Args_Size, AHelpContext) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateResHelp */ inline __fastcall EMCIDeviceError(int Ident, int AHelpContext)/* overload */ : Sysutils::Exception(Ident, AHelpContext) { } #pragma option pop #pragma option push -w-inl /* Exception.CreateResFmtHelp */ inline __fastcall EMCIDeviceError(System::PResStringRec ResStringRec, const System::TVarRec * Args, const int Args_Size, int AHelpContext)/* overload */ : Sysutils::Exception(ResStringRec, Args, Args_Size, AHelpContext) { } #pragma option pop public: #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~EMCIDeviceError(void) { } #pragma option pop }; class DELPHICLASS TMediaPlayer; class PASCALIMPLEMENTATION TMediaPlayer : public Controls::TCustomControl { typedef Controls::TCustomControl inherited; private: TMPButton Buttons[9]; TButtonSet FVisibleButtons; TButtonSet FEnabledButtons; TButtonSet FColoredButtons; TButtonSet FAutoButtons; bool Pressed; bool Down; TMPBtnType CurrentButton; #pragma pack(push, 1) Types::TRect CurrentRect; #pragma pack(pop) int ButtonWidth; #pragma pack(push, 1) Types::TPoint MinBtnSize; #pragma pack(pop) EMPNotify FOnClick; EMPPostNotify FOnPostClick; Classes::TNotifyEvent FOnNotify; TMPBtnType FocusedButton; bool MCIOpened; TMPDevCapsSet FCapabilities; bool FCanPlay; bool FCanStep; bool FCanEject; bool FCanRecord; bool FHasVideo; int FFlags; bool FWait; bool FNotify; bool FUseWait; bool FUseNotify; bool FUseFrom; bool FUseTo; Word FDeviceID; TMPDeviceTypes FDeviceType; int FTo; int FFrom; int FFrames; int FError; TMPNotifyValues FNotifyValue; Controls::TWinControl* FDisplay; int FDWidth; int FDHeight; AnsiString FElementName; bool FAutoEnable; bool FAutoOpen; bool FAutoRewind; bool FShareable; void __fastcall LoadBitmaps(void); void __fastcall DestroyBitmaps(void); void __fastcall SetEnabledButtons(TButtonSet Value); void __fastcall SetColored(TButtonSet Value); HIDESBASE void __fastcall SetVisible(TButtonSet Value); void __fastcall SetAutoEnable(bool Value); void __fastcall DrawAutoButtons(void); HIDESBASE void __fastcall DoMouseDown(int XPos, int YPos); HIDESBASE MESSAGE void __fastcall WMLButtonDown(Messages::TWMMouse &Message); HIDESBASE MESSAGE void __fastcall WMLButtonDblClk(Messages::TWMMouse &Message); HIDESBASE MESSAGE void __fastcall WMMouseMove(Messages::TWMMouse &Message); HIDESBASE MESSAGE void __fastcall WMLButtonUp(Messages::TWMMouse &Message); HIDESBASE MESSAGE void __fastcall WMSetFocus(Messages::TWMSetFocus &Message); HIDESBASE MESSAGE void __fastcall WMKillFocus(Messages::TWMKillFocus &Message); MESSAGE void __fastcall WMGetDlgCode(Messages::TWMNoParams &Message); HIDESBASE MESSAGE void __fastcall WMSize(Messages::TWMSize &Message); int __fastcall VisibleButtonCount(void); void __fastcall Adjust(void); void __fastcall DoClick(TMPBtnType Button); void __fastcall DoPostClick(TMPBtnType Button); void __fastcall DrawButton(TMPBtnType Btn, int X); void __fastcall CheckIfOpen(void); void __fastcall SetPosition(int Value); void __fastcall SetDeviceType(TMPDeviceTypes Value); void __fastcall SetWait(bool Flag); void __fastcall SetNotify(bool Flag); void __fastcall SetFrom(int Value); void __fastcall SetTo(int Value); void __fastcall SetTimeFormat(TMPTimeFormats Value); void __fastcall SetDisplay(Controls::TWinControl* Value); void __fastcall SetOrigDisplay(void); void __fastcall SetDisplayRect(const Types::TRect &Value); Types::TRect __fastcall GetDisplayRect(); void __fastcall GetDeviceCaps(void); int __fastcall GetStart(void); int __fastcall GetLength(void); TMPModes __fastcall GetMode(void); int __fastcall GetTracks(void); int __fastcall GetPosition(void); AnsiString __fastcall GetErrorMessage(); TMPTimeFormats __fastcall GetTimeFormat(void); int __fastcall GetTrackLength(int TrackNum); int __fastcall GetTrackPosition(int TrackNum); protected: DYNAMIC void __fastcall KeyDown(Word &Key, Classes::TShiftState Shift); virtual void __fastcall Loaded(void); DYNAMIC void __fastcall AutoButtonSet(TMPBtnType Btn); virtual void __fastcall Notification(Classes::TComponent* AComponent, Classes::TOperation Operation); virtual void __fastcall Paint(void); MESSAGE void __fastcall MMNotify(Messages::TMessage &Message); HIDESBASEDYNAMIC void __fastcall Click(TMPBtnType Button, bool &DoDefault); DYNAMIC void __fastcall PostClick(TMPBtnType Button); DYNAMIC void __fastcall DoNotify(void); DYNAMIC void __fastcall Updated(void); public: __fastcall virtual TMediaPlayer(Classes::TComponent* AOwner); __fastcall virtual ~TMediaPlayer(void); void __fastcall Open(void); void __fastcall Close(void); void __fastcall Play(void); void __fastcall Stop(void); void __fastcall Pause(void); void __fastcall Step(void); void __fastcall Back(void); void __fastcall Previous(void); void __fastcall Next(void); void __fastcall StartRecording(void); void __fastcall Eject(void); void __fastcall Save(void); void __fastcall PauseOnly(void); void __fastcall Resume(void); void __fastcall Rewind(void); __property int TrackLength[int TrackNum] = {read=GetTrackLength}; __property int TrackPosition[int TrackNum] = {read=GetTrackPosition}; __property TMPDevCapsSet Capabilities = {read=FCapabilities, nodefault}; __property int Error = {read=FError, nodefault}; __property AnsiString ErrorMessage = {read=GetErrorMessage}; __property int Start = {read=GetStart, nodefault}; __property int Length = {read=GetLength, nodefault}; __property int Tracks = {read=GetTracks, nodefault}; __property int Frames = {read=FFrames, write=FFrames, nodefault}; __property TMPModes Mode = {read=GetMode, nodefault}; __property int Position = {read=GetPosition, write=SetPosition, nodefault}; __property bool Wait = {read=FWait, write=SetWait, nodefault}; __property bool Notify = {read=FNotify, write=SetNotify, nodefault}; __property TMPNotifyValues NotifyValue = {read=FNotifyValue, nodefault}; __property int StartPos = {read=FFrom, write=SetFrom, nodefault}; __property int EndPos = {read=FTo, write=SetTo, nodefault}; __property Word DeviceID = {read=FDeviceID, nodefault}; __property TMPTimeFormats TimeFormat = {read=GetTimeFormat, write=SetTimeFormat, nodefault}; __property Types::TRect DisplayRect = {read=GetDisplayRect, write=SetDisplayRect}; __published: __property TButtonSet ColoredButtons = {read=FColoredButtons, write=SetColored, default=511}; __property Enabled = {default=1}; __property TButtonSet EnabledButtons = {read=FEnabledButtons, write=SetEnabledButtons, default=511}; __property TButtonSet VisibleButtons = {read=FVisibleButtons, write=SetVisible, default=511}; __property Anchors = {default=3}; __property bool AutoEnable = {read=FAutoEnable, write=SetAutoEnable, default=1}; __property bool AutoOpen = {read=FAutoOpen, write=FAutoOpen, default=0}; __property bool AutoRewind = {read=FAutoRewind, write=FAutoRewind, default=1}; __property Constraints ; __property TMPDeviceTypes DeviceType = {read=FDeviceType, write=SetDeviceType, default=0}; __property Controls::TWinControl* Display = {read=FDisplay, write=SetDisplay}; __property AnsiString FileName = {read=FElementName, write=FElementName}; __property bool Shareable = {read=FShareable, write=FShareable, default=0}; __property Visible = {default=1}; __property ParentShowHint = {default=1}; __property ShowHint ; __property PopupMenu ; __property TabOrder = {default=-1}; __property TabStop = {default=1}; __property EMPNotify OnClick = {read=FOnClick, write=FOnClick}; __property OnContextPopup ; __property OnEnter ; __property OnExit ; __property EMPPostNotify OnPostClick = {read=FOnPostClick, write=FOnPostClick}; __property Classes::TNotifyEvent OnNotify = {read=FOnNotify, write=FOnNotify}; public: #pragma option push -w-inl /* TWinControl.CreateParented */ inline __fastcall TMediaPlayer(HWND ParentWindow) : Controls::TCustomControl(ParentWindow) { } #pragma option pop }; //-- var, const, procedure --------------------------------------------------- } /* namespace Mplayer */ using namespace Mplayer; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // MPlayer
[ "bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b" ]
[ [ [ 1, 310 ] ] ]
d01ad5e7a55f1b9536b6776f2bb60e2d31cae9c8
09a84291381a2ae9e366b848aff5ac94342e6d4b
/SubstSvc/Source/EntryPoint.cpp
50875364ab1496f1f3a95ab304ec852e1e88a5c9
[]
no_license
zephyrer/xsubst
0088343300d62d909a87e235da490728b9af5106
111829b6094d796aefb7c8e4ec7bd40bae4d6449
refs/heads/master
2020-05-20T03:22:44.200074
2011-06-18T05:50:34
2011-06-18T05:50:34
40,066,695
0
0
null
null
null
null
UTF-8
C++
false
false
4,943
cpp
// SubstSvc NT service. // Copyright (c) 2004-2011 by Elijah Zarezky, // All rights reserved. // 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. // EntryPoint.cpp - application entry point // initially generated by AfxScratch v1.0.2290 on 18.07.2004 at 11:12:43 // visit http://zarezky.spb.ru/projects/afx_scratch.html for more info ////////////////////////////////////////////////////////////////////////////////////////////// // PCH includes #include "stdafx.h" ////////////////////////////////////////////////////////////////////////////////////////////// // resource includes #include "Resource.h" ////////////////////////////////////////////////////////////////////////////////////////////// // other includes #include "SubstSvcApp.h" #include "ExecLogging.h" ////////////////////////////////////////////////////////////////////////////////////////////// // unwanted warnings #if defined(__INTEL_COMPILER) // remark #177: variable was declared but never referenced #pragma warning(disable: 177) // remark #981: operands are evaluated in unspecified order #pragma warning(disable: 981) #endif // __INTEL_COMPILER ////////////////////////////////////////////////////////////////////////////////////////////// // debugging support #if defined(_DEBUG) #undef THIS_FILE static char THIS_FILE[] = __FILE__; #define new DEBUG_NEW #endif // _DEBUG ////////////////////////////////////////////////////////////////////////////////////////////// // the one and only application object static CSubstSvcApp g_appSubstSvc; ////////////////////////////////////////////////////////////////////////////////////////////// // entry point int _tmain(int argc, TCHAR* argv[], TCHAR* /*envp*/[]) { // try to initialize MFC if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), SW_HIDE)) { return (-1); } #if defined(_DEBUG) // install a client-defined reporting function _CrtSetReportHook(LogFile_WriteDbgRpt); #endif // _DEBUG #if defined(_DEBUG) CMemoryState memStart, memStop, memDiff; // get the initial snapshot of memory memStart.Checkpoint(); #endif // _DEBUG // assign registry key g_appSubstSvc.SetRegistryKey(IDS_REGISTRY_KEY); // start logging CWinApp* pApp = AfxGetApp(); CString strLogName = pApp->GetProfileString(_T("Logging"), _T("TargetPath")); if (!strLogName.IsEmpty()) { LogFile_Create(strLogName); LogFile_WriteEntry(LL_MINIMAL, IDS_EXE_STARTED, argv[0]); } // parse command-line arguments if (argc > 1) { SC_HANDLE schManager = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (::lstrcmpi(argv[1], _T("/Register")) == 0) { // insert service into the SCM database SC_HANDLE schService = ::CreateService(schManager, g_szServiceName, g_szServiceName, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, argv[0], NULL, NULL, NULL, NULL, NULL); ::CloseServiceHandle(schService); LogFile_WriteEntry(LL_MINIMAL, IDS_SERVICE_REGISTERED, g_szServiceName); } else if (::lstrcmpi(argv[1], _T("/UnRegister")) == 0) { // remove service from the SCM database SC_HANDLE schService = ::OpenService(schManager, g_szServiceName, SERVICE_ALL_ACCESS); ::DeleteService(schService); ::CloseServiceHandle(schService); LogFile_WriteEntry(LL_MINIMAL, IDS_SERVICE_UNREGISTERED, g_szServiceName); } else { // unrecognized command-line argument LogFile_WriteEntry(LL_MINIMAL, IDS_CMDLINE_BAD_ARGUMENT, argv[1]); } ::CloseServiceHandle(schManager); } else { // just start the service static SERVICE_TABLE_ENTRY aste[] = { { g_szServiceName, ServiceMain }, { NULL, NULL } // end of table - required }; LogFile_WriteEntry(LL_MINIMAL, IDS_SCM_CONNECT); ::StartServiceCtrlDispatcher(aste); LogFile_WriteEntry(LL_MINIMAL, IDS_SCM_DISCONNECTED); } #if defined(_DEBUG) // get the final memory state... memStop.Checkpoint(); // ...and then check the leaks if (memDiff.Difference(memStart, memStop)) { _CrtMemDumpStatistics(&memDiff.m_memState); _CrtDumpMemoryLeaks(); } #endif // _DEBUG LogFile_WriteEntry(LL_MINIMAL, IDS_EXE_FINISHED, argv[0]); // terminate MFC #if defined(_DEBUG) AfxLockTempMaps(); AfxUnlockTempMaps(-1); #endif // _DEBUG AfxWinTerm(); // return to Windoze return (0); } // end of file
[ "Elijah Zarezky@9a190745-9f41-0410-876d-23307a9d09e3", "elijah@9a190745-9f41-0410-876d-23307a9d09e3" ]
[ [ [ 1, 4 ], [ 17, 67 ], [ 70, 96 ], [ 99, 99 ], [ 102, 108 ], [ 111, 124 ], [ 127, 138 ], [ 141, 158 ] ], [ [ 5, 16 ], [ 68, 69 ], [ 97, 98 ], [ 100, 101 ], [ 109, 110 ], [ 125, 126 ], [ 139, 140 ] ] ]
6fa8a2168b02185ba1e53da547148a5a35a37a15
42b578d005c2e8870a03fe02807e5607fec68f40
/src/string.cc
2e495991de0bbac5d985fd0636ea26af1d1064f3
[ "MIT" ]
permissive
hylom/xom
e2b02470cd984d0539ded408d13f9945af6e5f6f
a38841cfe50c3e076b07b86700dfd01644bf4d4a
refs/heads/master
2021-01-23T02:29:51.908501
2009-10-30T08:41:30
2009-10-30T08:41:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
28,504
cc
#include "ed.h" #include "sequence.h" #include "StrBuf.h" int update_column (int column, Char c) { if (c == '\n') column = 0; else if (c == '\t') column = ((column + app.default_tab_columns) / app.default_tab_columns * app.default_tab_columns); else column += char_width (c); return column; } int update_column (int column, const Char *s, int size) { for (const Char *se = s + size; s < se; s++) column = update_column (column, *s); return column; } int update_column (int column, Char c, int size) { if (size) { if (c == '\n') column = 0; else if (c == '\t') column = ((column + app.default_tab_columns) / app.default_tab_columns * app.default_tab_columns + (size - 1) * app.default_tab_columns); else column += char_width (c) * size; } return column; } size_t s2wl (const char *string) { size_t l = 0; const u_char *s = (const u_char *)string; while (*s) { if (SJISP (*s)) { if (!s[1]) { s++; break; } l++; s += 2; } else s++; } return s - (const u_char *)string - l; } Char * s2w (Char *b, size_t size, const char **string) { Char *be = b + size; const u_char *s = (const u_char *)*string; while (b < be && *s) { if (SJISP (*s)) { if (!s[1]) { *b++ = *s++; break; } *b++ = (*s << 8) | s[1]; s += 2; } else *b++ = *s++; } *string = (const char *)s; return b; } Char * s2w (Char *b, const char *string) { const u_char *s = (const u_char *)string; while (*s) { if (SJISP (*s)) { if (!s[1]) { *b = *s; break; } *b++ = (*s << 8) | s[1]; s += 2; } else *b++ = *s++; } return b; } Char * s2w (const char *string, size_t size) { Char *b = (Char *)xmalloc (sizeof (Char) * size); s2w (b, string); return b; } void a2w (Char *b, const char *string, size_t size) { const u_char *s = (const u_char *)string; const u_char *se = s + size; while (s < se) *b++ = *s++; } Char * a2w (Char *b, size_t size, const char **string) { Char *be = b + size; const u_char *s = (const u_char *)*string; while (b < be && *s) *b++ = *s++; *string = (const char *)s; return b; } Char * a2w (Char *b, const char *string) { for (const u_char *s = (const u_char *)string; *s;) *b++ = *s++; return b; } Char * a2w (const char *string, size_t size) { Char *b = (Char *)xmalloc (sizeof (Char) * size); a2w (b, string, size); return b; } size_t w2sl (const Char *s, size_t size) { size_t l = 0; for (const Char *se = s + size; s < se; s++) if (DBCP (*s)) l++; return size + l; } char * w2s (char *b, const Char *s, size_t size) { for (const Char *se = s + size; s < se; s++) { if (DBCP (*s)) *b++ = *s >> 8; *b++ = char (*s); } *b = 0; return b; } char * w2s (const Char *s, size_t size) { char *b = (char *)xmalloc (w2sl (s, size) + 1); w2s (b, s, size); return b; } char * w2s (char *b, char *be, const Char *s, size_t size) { be--; for (const Char *se = s + size; s < se && b < be; s++) { if (DBCP (*s)) { if (b == be - 1) break; *b++ = *s >> 8; } *b++ = char (*s); } *b = 0; return b; } char * w2s_quote (char *b, char *be, const Char *s, size_t size, int qc, int qe) { be--; for (const Char *se = s + size; s < se && b < be; s++) { if (DBCP (*s)) { if (b == be - 1) break; *b++ = *s >> 8; } else if (*s == qc) { if (b == be - 1) break; *b++ = qe; } *b++ = char (*s); } *b = 0; return b; } size_t s2wl (const char *string, const char *se, int zero_term) { size_t l = 0; const u_char *s = (const u_char *)string; while (s < (const u_char *)se && (!zero_term || *s)) { if (SJISP (*s)) { if (s + 1 >= (const u_char *)se || (zero_term && !s[1])) { s++; break; } l++; s += 2; } else s++; } return s - (const u_char *)string - l; } Char * s2w (Char *b, const char *string, const char *se, int zero_term) { const u_char *s = (const u_char *)string; while (s < (const u_char *)se && (!zero_term || *s)) { if (SJISP (*s)) { if (s + 1 >= (const u_char *)se || (zero_term && !s[1])) { *b = *s; break; } *b++ = (*s << 8) | s[1]; s += 2; } else *b++ = *s++; } return b; } void w2s_chunk (char *b, char *be, const Char *s, size_t size) { for (const Char *se = s + size; s < se && b < be; s++) { if (DBCP (*s)) { if (b == be - 1) break; *b++ = *s >> 8; } *b++ = char (*s); } if (b < be) *b = 0; } lisp make_string (const char *string) { lisp p = make_simple_string (); size_t size = s2wl (string); xstring_contents (p) = s2w (string, size); xstring_length (p) = size; return p; } lisp make_string (const char *string, size_t size) { lisp p = make_simple_string (); Char *b = (Char *)xmalloc (size * sizeof (Char)); xstring_contents (p) = b; xstring_length (p) = size; s2w (b, size, &string); return p; } lisp make_string_simple (const char *string, size_t size) { lisp p = make_simple_string (); xstring_contents (p) = a2w (string, size); xstring_length (p) = size; return p; } lisp make_string (const Char *string, size_t size) { lisp p = make_simple_string (); xstring_contents (p) = (Char *)xmemdup (string, size * sizeof (Char)); xstring_length (p) = size; return p; } lisp copy_string (lisp p) { assert (stringp (p)); return make_string (xstring_contents (p), xstring_length (p)); } lisp make_string (Char c, size_t size) { lisp p = make_simple_string (); Char *d = (Char *)xmalloc (size * sizeof (Char)); xstring_contents (p) = d; xstring_length (p) = size; bfill (d, int (size), c); return p; } lisp make_complex_string (Char c, int fillp, int size, int adjustable) { assert (fillp <= size); lisp p = make_complex_string (); Char *d = (Char *)xmalloc (size * sizeof (Char)); xstring_contents (p) = d; xstring_length (p) = fillp >= 0 ? fillp : size; xstring_dimension (p) = size; xarray_adjustable (p) = adjustable; xarray_has_fillp (p) = fillp >= 0; bfill (d, size, c); return p; } lisp make_string (size_t size) { lisp p = make_simple_string (); xstring_contents (p) = (Char *)xmalloc (size * sizeof (Char)); xstring_length (p) = size; return p; } lisp make_string_from_list (lisp list) { int l = 0; for (lisp x = list; consp (x); x = xcdr (x), l++) check_char (xcar (x)); lisp string = make_string (l); Char *s = xstring_contents (string); for (x = list; consp (x); x = xcdr (x)) *s++ = xchar_code (xcar (x)); return string; } lisp make_string_from_vector (lisp vector) { assert (general_vector_p (vector)); for (lisp *p = xvector_contents (vector), *pe = p + xvector_length (vector); p < pe; p++) check_char (*p); lisp string = make_string (xvector_length (vector)); Char *s = xstring_contents (string); for (p = xvector_contents (vector); p < pe; p++) *s++ = xchar_code (*p); return string; } int string_equalp (const Char *p1, int l1, const Char *p2, int l2) { if (l1 != l2) return 0; for (const Char *pe = p1 + l1; p1 < pe; p1++, p2++) if (char_upcase (*p1) != char_upcase (*p2)) return 0; return 1; } int string_equalp (lisp x, int xo, lisp y, int yo, int l) { if (xo + l > xstring_length (x) || yo + l > xstring_length (y)) return 0; return string_equalp (xstring_contents (x) + xo, l, xstring_contents (y) + yo, l); } lisp coerce_to_string (lisp x, int copy) { if (immediatep (x)) { if (charp (x)) { Char c = xchar_code (x); return make_string (&c, 1); } } else { switch (object_typeof (x)) { case Tsimple_string: case Tcomplex_string: return copy ? copy_string (x) : x; case Tsymbol: return copy ? Fcopy_string (xsymbol_name (x)) : xsymbol_name (x); case Tsimple_vector: case Tcomplex_vector: return make_string_from_vector (x); } } return FEtype_error (x, Qstring); } void string_start_end (lisp string, int &start, int &end, lisp lstart, lisp lend) { check_string (string); seq_start_end (xstring_length (string), start, end, lstart, lend); } lisp Fcopy_string (lisp string) { check_string (string); return copy_string (string); } lisp Fchar (lisp string, lisp index) { check_string (string); int i = fixnum_value (index); if (i < 0 || i >= xstring_length (string)) FErange_error (index); return make_char (xstring_contents (string) [i]); } lisp Fsi_set_char (lisp string, lisp index, lisp value) { check_string (string); check_char (value); int i = fixnum_value (index); if (i < 0 || i >= xstring_length (string)) FErange_error (index); xstring_contents (string) [i] = xchar_code (value); return value; } lisp Fschar (lisp string, lisp index) { check_simple_string (string); int i = fixnum_value (index); if (i < 0 || i >= xstring_length (string)) FErange_error (index); return make_char (xstring_contents (string) [i]); } lisp Fsi_set_schar (lisp string, lisp index, lisp value) { check_simple_string (string); check_char (value); int i = fixnum_value (index); if (i < 0 || i >= xstring_length (string)) FErange_error (index); xstring_contents (string) [i] = xchar_code (value); return value; } static const Char * string_compare1 (lisp string1, lisp string2, lisp keys, const Char *&p, const Char *&pe, const Char *&q, const Char *&qe) { string1 = coerce_to_string (string1, 0); int start1, end1; string_start_end (string1, start1, end1, find_keyword (Kstart1, keys, make_fixnum (0)), find_keyword (Kend1, keys, Qnil)); string2 = coerce_to_string (string2, 0); int start2, end2; string_start_end (string2, start2, end2, find_keyword (Kstart2, keys, make_fixnum (0)), find_keyword (Kend2, keys, Qnil)); p = xstring_contents (string1) + start1; pe = xstring_contents (string1) + end1; q = xstring_contents (string2) + start2; qe = xstring_contents (string2) + end2; return xstring_contents (string1); } static int string_compare (lisp string1, lisp string2, lisp keys, int &l) { const Char *p, *pe, *q, *qe; const Char *p0 = string_compare1 (string1, string2, keys, p, pe, q, qe); while (1) { if (p == pe) { l = p - p0; return q == qe ? 0 : -1; } if (q == qe) { l = p - p0; return 1; } if (*p != *q) { l = p - p0; return *p - *q; } p++; q++; } } static int string_comparep (lisp string1, lisp string2, lisp keys, int &l) { const Char *p, *pe, *q, *qe; const Char *p0 = string_compare1 (string1, string2, keys, p, pe, q, qe); while (1) { if (p == pe) { l = p - p0; return q == qe ? 0 : -1; } if (q == qe) { l = p - p0; return 1; } Char c1 = char_upcase (*p); Char c2 = char_upcase (*q); if (c1 != c2) { l = p - p0; return c1 - c2; } p++; q++; } } lisp Fstring_equal (lisp x, lisp y, lisp keys) { const Char *p, *pe, *q, *qe; string_compare1 (x, y, keys, p, pe, q, qe); return boole (pe - p == qe - q && !bcmp (p, q, pe - p)); } lisp Fstring_equalp (lisp x, lisp y, lisp keys) { const Char *p, *pe, *q, *qe; string_compare1 (x, y, keys, p, pe, q, qe); return boole (string_equalp (p, pe - p, q, qe - q)); } lisp Fstring_not_equal (lisp x, lisp y, lisp keys) { int l; return string_compare (x, y, keys, l) ? make_fixnum (l) : Qnil; } lisp Fstring_not_equalp (lisp x, lisp y, lisp keys) { int l; return string_comparep (x, y, keys, l) ? make_fixnum (l) : Qnil; } lisp Fstring_less (lisp x, lisp y, lisp keys) { int l; return string_compare (x, y, keys, l) < 0 ? make_fixnum (l) : Qnil; } lisp Fstring_lessp (lisp x, lisp y, lisp keys) { int l; return string_comparep (x, y, keys, l) < 0 ? make_fixnum (l) : Qnil; } lisp Fstring_greater (lisp x, lisp y, lisp keys) { int l; return string_compare (x, y, keys, l) > 0 ? make_fixnum (l) : Qnil; } lisp Fstring_greaterp (lisp x, lisp y, lisp keys) { int l; return string_comparep (x, y, keys, l) > 0 ? make_fixnum (l) : Qnil; } lisp Fstring_not_greater (lisp x, lisp y, lisp keys) { int l; return string_compare (x, y, keys, l) <= 0 ? make_fixnum (l) : Qnil; } lisp Fstring_not_greaterp (lisp x, lisp y, lisp keys) { int l; return string_comparep (x, y, keys, l) <= 0 ? make_fixnum (l) : Qnil; } lisp Fstring_not_less (lisp x, lisp y, lisp keys) { int l; return string_compare (x, y, keys, l) >= 0 ? make_fixnum (l) : Qnil; } lisp Fstring_not_lessp (lisp x, lisp y, lisp keys) { int l; return string_comparep (x, y, keys, l) >= 0 ? make_fixnum (l) : Qnil; } lisp subseq_string (lisp string, lisp lstart, lisp lend) { int start, end; string_start_end (string, start, end, lstart, lend); return make_string (xstring_contents (string) + start, end - start); } lisp Fsubstring (lisp string, lisp lstart, lisp lend) { check_string (string); int len = xstring_length (string); int start = fixnum_value (lstart); int end = lend && lend != Qnil ? fixnum_value (lend) : len; if (start < 0) start += len; if (end < 0) end += len; if (start < 0 || start > end) FErange_error (lstart); if (end > len) FErange_error (lend); return make_string (xstring_contents (string) + start, end - start); } static inline int match_char_bag (Char c, lisp bag) { assert (stringp (bag)); for (const Char *p = xstring_contents (bag), *pe = p + xstring_length (bag); p < pe; p++) if (c == *p) return 1; return 0; } static const Char * left_trim (const Char *p0, int l, lisp bag) { for (const Char *p = p0, *pe = p + l; p < pe; p++) if (!match_char_bag (*p, bag)) break; return p; } static const Char * right_trim (const Char *p0, int l, lisp bag) { for (const Char *p = p0 + l; p > p0; p--) if (!match_char_bag (p[-1], bag)) break; return p; } static inline int left_trim (lisp string, lisp bag) { assert (stringp (string)); return (left_trim (xstring_contents (string), xstring_length (string), bag) - xstring_contents (string)); } static inline int right_trim (lisp string, lisp bag) { assert (stringp (string)); return (right_trim (xstring_contents (string), xstring_length (string), bag) - xstring_contents (string)); } lisp Fstring_left_trim (lisp char_bag, lisp string) { string = Fstring (string); int start = left_trim (string, seq_to_string (char_bag)); return !start ? string : subseq_string (string, make_fixnum (start), Qnil); } lisp Fstring_right_trim (lisp char_bag, lisp string) { string = Fstring (string); int end = right_trim (string, seq_to_string (char_bag)); return (end == xstring_length (string) ? string : subseq_string (string, make_fixnum (0), make_fixnum (end))); } lisp Fstring_trim (lisp char_bag, lisp string) { string = Fstring (string); char_bag = seq_to_string (char_bag); int start = left_trim (string, char_bag); int end = right_trim (string, char_bag); if (start >= end) return make_string (""); return ((!start && end == xstring_length (string)) ? string : subseq_string (string, make_fixnum (start), make_fixnum (end))); } lisp Fstring_upcase (lisp string, lisp keys) { return Fnstring_upcase (coerce_to_string (string, 1), keys); } lisp Fstring_downcase (lisp string, lisp keys) { return Fnstring_downcase (coerce_to_string (string, 1), keys); } lisp Fstring_capitalize (lisp string, lisp keys) { return Fnstring_capitalize (coerce_to_string (string, 1), keys); } lisp Fnstring_upcase (lisp string, lisp keys) { int start, end; string_start_end (string, start, end, find_keyword (Kstart, keys, make_fixnum (0)), find_keyword (Kend, keys, Qnil)); for (Char *p = xstring_contents (string) + start, *pe = xstring_contents (string) + end; p < pe; p++) *p = char_upcase (*p); return string; } lisp Fnstring_downcase (lisp string, lisp keys) { int start, end; string_start_end (string, start, end, find_keyword (Kstart, keys, make_fixnum (0)), find_keyword (Kend, keys, Qnil)); for (Char *p = xstring_contents (string) + start, *pe = xstring_contents (string) + end; p < pe; p++) *p = char_downcase (*p); return string; } lisp Fnstring_capitalize (lisp string, lisp keys) { int start, end; string_start_end (string, start, end, find_keyword (Kstart, keys, make_fixnum (0)), find_keyword (Kend, keys, Qnil)); int f = 1; for (Char *p = xstring_contents (string) + start, *pe = xstring_contents (string) + end; p < pe; p++) { if (alphanumericp (*p)) { if (f) *p = char_upcase (*p); else *p = char_downcase (*p); f = 0; } else f = 1; } return string; } lisp Fstring (lisp x) { return coerce_to_string (x, symbolp (x)); } static void trim (const Char *&p0, const Char *&pe, lisp bag) { if (p0 != pe) { p0 = left_trim (p0, pe - p0, bag); pe = right_trim (p0, pe - p0, bag); } } lisp Fsplit_string (lisp string, lisp lsep, lisp ignore_empty, lisp char_bag) { string = Fstring (string); if (!charp (lsep) && !stringp (lsep)) FEtype_error (lsep, xsymbol_value (Qor_string_character)); int empty_ok = ignore_empty && ignore_empty != Qnil; if (char_bag == Qnil) char_bag = 0; else if (char_bag) { char_bag = Fstring (char_bag); if (!xstring_length (char_bag)) char_bag = 0; } const Char *p = xstring_contents (string); const Char *pe = p + xstring_length (string); if (p == pe) return Qnil; lisp result = Qnil; if (charp (lsep) || xstring_length (lsep) == 1) { Char sep = charp (lsep) ? xchar_code (lsep) : *xstring_contents (lsep); do { const Char *p0 = p; for (; p < pe && *p != sep; p++) ; const Char *pe = p; if (char_bag) trim (p0, pe, char_bag); if (p0 != pe || empty_ok) result = xcons (make_string (p0, pe - p0), result); } while (++p < pe); } else { if (!xstring_length (lsep)) return char_bag ? Fstring_trim (char_bag, string) : string; do { const Char *p0 = p; for (; p < pe && !match_char_bag (*p, lsep); p++) ; const Char *pe = p; if (char_bag) trim (p0, pe, char_bag); if (p0 != pe || empty_ok) result = xcons (make_string (p0, pe - p0), result); } while (++p < pe); } return Fnreverse (result); } lisp Fquote_string (lisp string, lisp search, lisp quote) { check_string (string); const Char *s = xstring_contents (string); const Char *se = s + xstring_length (string); check_char (search); Char sch = xchar_code (search); check_char (quote); Char qch = xchar_code (quote); int count = 0; while (s < se) if (*s++ == sch) count++; if (!count) return string; s = xstring_contents (string); lisp string2 = make_string (xstring_length (string) + count); Char *d = xstring_contents (string2); while (s < se) { Char c = *s++; if (c == sch) *d++ = qch; *d++ = c; } return string2; } lisp parse_integer (lisp string, int start, int &end, int radix, int junk_allowed) { const Char *p = xstring_contents (string) + start; const Char *pe = xstring_contents (string) + end; if (junk_allowed) { const readtab_rep *readtab = xreadtable_rep (current_readtable ()); for (; p < pe && stdchar_whitespace_p (readtab, *p); p++) ; for (; pe > p && stdchar_whitespace_p (readtab, pe[-1]); pe--) ; } if (p == pe) return Qnil; bignum_rep *rep; p = ato_bignum_rep (rep, p, pe - p, radix); end = p - xstring_contents (string); return p == pe ? make_integer (rep) : Qnil; } lisp Fparse_integer (lisp string, lisp keys) { int start, end; string_start_end (string, start, end, find_keyword (Kstart, keys, make_fixnum (0)), find_keyword (Kend, keys, Qnil)); lisp junk_allowed = find_keyword (Kjunk_allowed, keys, Qnil); int radix; lisp r = find_keyword (Kradix, keys); if (r == Qnil) radix = 10; else { radix = fixnum_value (r); if (radix < 2 || radix > 36) FErange_error (r); } lisp result = parse_integer (string, start, end, radix, junk_allowed != Qnil); if (result == Qnil && junk_allowed == Qnil) FEprogram_error (Einvalid_integer_format, string); multiple_value::count () = 2; multiple_value::value (1) = make_fixnum (end); return result; } int WINAPI abbreviate_string (HDC hdc, char *buf, int maxpxl, int is_pathname) { SIZE sz; int l = strlen (buf); GetTextExtentPoint32 (hdc, buf, l, &sz); if (sz.cx <= maxpxl) return 0; GetTextExtentPoint32 (hdc, "...", 3, &sz); maxpxl = (maxpxl - sz.cx); char *lb, *le; char *rb, *re; if (is_pathname) { lb = le = buf; re = buf + l; rb = find_last_slash (buf); if (rb) { GetTextExtentPoint32 (hdc, rb, re - rb, &sz); if (sz.cx > maxpxl) { rb++; goto trim_tail; } int pxl = sz.cx; int dev = 0; if (alpha_char_p (*lb & 255) && lb[1] == ':') dev = dir_separator_p (lb[2]) ? 3 : 2; else if (dir_separator_p (*lb) && dir_separator_p (lb[1])) { char *sl = find_slash (lb + 2); if (sl) sl = find_slash (sl + 1); if (sl && sl < rb) dev = sl - lb + 1; } if (dev) { GetTextExtentPoint32 (hdc, lb, dev, &sz); if (pxl + sz.cx > maxpxl) goto done; pxl += sz.cx; le = lb + dev; } while (rb > le) { char c = *rb; *rb = 0; char *slash = find_last_slash (buf); *rb = c; if (!slash) break; GetTextExtentPoint32 (hdc, slash, rb - slash, &sz); if (sz.cx + pxl > maxpxl) break; rb = slash; pxl += sz.cx; } } else { rb = buf; trim_tail: for (; re > rb; re = CharPrev (rb, re)) { GetTextExtentPoint32 (hdc, rb, re - rb, &sz); if (sz.cx <= maxpxl) { if (re - rb + 3 > l) return 0; *re = 0; strcpy (stpcpy (buf, rb), "..."); return 1; } } } } else { maxpxl /= 2; for (lb = buf, le = buf + l / 2; le > lb; le = CharPrev (lb, le)) { GetTextExtentPoint32 (hdc, lb, le - lb, &sz); if (sz.cx <= maxpxl) break; } for (rb = buf + l / 2, re = buf + l; rb < re; rb = CharNext (rb)) { GetTextExtentPoint32 (hdc, rb, re - rb, &sz); if (sz.cx <= maxpxl) break; } } done: if ((le - lb) + (re - rb) + 3 > l) return 0; strcpy (le, "..."); strcpy (le + 3, rb); return 1; } static int abbrev_string (char *buf, int maxl, int pathname_p) { HDC hdc (GetDC (0)); HGDIOBJ of (SelectObject (hdc, sysdep.ui_font ())); TEXTMETRIC tm; GetTextMetrics (hdc, &tm); int maxpxl = tm.tmAveCharWidth * maxl; int r = abbreviate_string (hdc, buf, maxpxl, pathname_p); SelectObject (hdc, of); ReleaseDC (0, hdc); return r; } lisp Fabbreviate_display_string (lisp string, lisp maxlen, lisp pathname_p) { check_string (string); int l = fixnum_value (maxlen); if (l <= 0) return make_string (""); char *buf = (char *)alloca (xstring_length (string) * 2 + 1); w2s (buf, string); if (!abbrev_string (buf, l, pathname_p && pathname_p != Qnil)) return string; return make_string (buf); } lisp Fabbreviate_string_column (lisp string, lisp column) { check_string (string); int n = fixnum_value (column); const Char *const p0 = xstring_contents (string); const Char *const pe = p0 + xstring_length (string); const Char *p = p0; for (int c = 0; c < n && p < pe; p++) { c += char_width (*p); if (c > n) break; } return p == pe ? string : make_string (p0, p - p0); } static int escseq_p (const Char *&p, const Char *pe) { if (p == pe) return -1; switch (*p) { default: return -1; case 'f': p++; return CC_FF; case 'n': p++; return CC_NL; case 'r': p++; return CC_CR; case 't': p++; return CC_HT; case 'v': p++; return CC_VT; case 'x': pe = min (p + 3, pe); break; case 'X': pe = min (p + 5, pe); break; } const Char *p1 = p + 1; if (p1 == pe) return -1; int n = digit_char (*p1); if (n >= 16) return -1; for (p1++; p1 < pe; p1++) { int x = digit_char (*p1); if (x >= 16) break; n = n * 16 + x; } p = p1; return n; } lisp Fdecode_escape_sequence (lisp string, lisp regexpp) { check_string (string); const Char *p = xstring_contents (string); const Char *const pe = p + xstring_length (string); char tem[1024]; StrBuf sb (tem, sizeof tem); int mod = 0; while (p < pe) { Char c = *p++; if (c == '\\' && p < pe) { if (*p == '\\') { p++; if (regexpp != Qnil) sb.add (c); else mod = 1; } else { int n = escseq_p (p, pe); if (n >= 0) { c = n; mod = 1; } } } sb.add (c); } return mod ? sb.make_string () : string; }
[ [ [ 1, 1253 ] ] ]
834ea40a2b8ad1ac652d6861bff14ad8c10014b0
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/archive/basic_xml_oarchive.hpp
3c256685b7ff6e17fe65b8ab6552a985f2df3344
[ "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,465
hpp
#ifndef BOOST_ARCHIVE_BASIC_XML_OARCHIVE_HPP #define BOOST_ARCHIVE_BASIC_XML_OARCHIVE_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 // basic_xml_oarchive.hpp // (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 <boost/config.hpp> #include <boost/archive/detail/common_oarchive.hpp> #include <boost/serialization/nvp.hpp> #include <boost/serialization/tracking.hpp> #include <boost/serialization/string.hpp> #include <boost/archive/detail/abi_prefix.hpp> // must be the last header namespace boost { namespace archive { ////////////////////////////////////////////////////////////////////// // class basic_xml_oarchive - write serialized objects to a xml output stream template<class Archive> class basic_xml_oarchive : public detail::common_oarchive<Archive> { protected: #if BOOST_WORKAROUND(BOOST_MSVC, <= 1300) public: #elif defined(BOOST_MSVC) // for some inexplicable reason insertion of "class" generates compile erro // on msvc 7.1 friend detail::interface_oarchive<Archive>; #else friend class detail::interface_oarchive<Archive>; #endif // special stuff for xml output unsigned int depth; bool indent_next; bool pending_preamble; BOOST_ARCHIVE_OR_WARCHIVE_DECL(void) indent(); BOOST_ARCHIVE_OR_WARCHIVE_DECL(void) init(); BOOST_ARCHIVE_OR_WARCHIVE_DECL(void) write_attribute( const char *attribute_name, int t, const char *conjunction = "=\"" ); BOOST_ARCHIVE_OR_WARCHIVE_DECL(void) write_attribute( const char *attribute_name, const char *key ); // helpers used below BOOST_ARCHIVE_OR_WARCHIVE_DECL(void) save_start(const char *name); BOOST_ARCHIVE_OR_WARCHIVE_DECL(void) save_end(const char *name); BOOST_ARCHIVE_OR_WARCHIVE_DECL(void) end_preamble(); // Anything not an attribute and not a name-value pair is an // error and should be trapped here. template<class T> void save_override(T & t, BOOST_PFTO int) { // If your program fails to compile here, its most likely due to // not specifying an nvp wrapper around the variable to // be serialized. BOOST_STATIC_ASSERT(0 == sizeof(T)); } // special treatment for name-value pairs. typedef detail::common_oarchive<Archive> detail_common_oarchive; template<class T> void save_override( #ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING const #endif ::boost::serialization::nvp<T> & t, int ){ save_start(t.name()); this->detail_common_oarchive::save_override(t.const_value(), 0); save_end(t.name()); } // specific overrides for attributes - not name value pairs so we // want to trap them before the above "fall through" BOOST_ARCHIVE_OR_WARCHIVE_DECL(void) save_override(const object_id_type & t, int); BOOST_ARCHIVE_OR_WARCHIVE_DECL(void) save_override(const object_reference_type & t, int); BOOST_ARCHIVE_OR_WARCHIVE_DECL(void) save_override(const version_type & t, int); BOOST_ARCHIVE_OR_WARCHIVE_DECL(void) save_override(const class_id_type & t, int); BOOST_ARCHIVE_OR_WARCHIVE_DECL(void) save_override(const class_id_optional_type & t, int); BOOST_ARCHIVE_OR_WARCHIVE_DECL(void) save_override(const class_id_reference_type & t, int); BOOST_ARCHIVE_OR_WARCHIVE_DECL(void) save_override(const class_name_type & t, int); BOOST_ARCHIVE_OR_WARCHIVE_DECL(void) save_override(const tracking_type & t, int); BOOST_ARCHIVE_OR_WARCHIVE_DECL(BOOST_PP_EMPTY()) basic_xml_oarchive(unsigned int flags); BOOST_ARCHIVE_OR_WARCHIVE_DECL(BOOST_PP_EMPTY()) ~basic_xml_oarchive(); }; } // namespace archive } // namespace boost #include <boost/archive/detail/abi_suffix.hpp> // pops abi_suffix.hpp pragmas #endif // BOOST_ARCHIVE_BASIC_XML_OARCHIVE_HPP
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 131 ] ] ]
4dee21ada2b606b8cf24fdb42e5f13950a956666
3b76b2980485417cb656215379b93b27d4444815
/7.Ung dung/Source code/Client/Client/Display.cpp
7e742be954411dbd0e541b8fe49d3d08f6ecc8ca
[]
no_license
hemprasad/lvmm-sc
48d48625b467b3756aa510b5586af250c3a1664c
7c68d1d3b1489787f5ec3d09bc15b4329b0c087a
refs/heads/master
2016-09-06T11:05:32.770867
2011-07-25T01:09:07
2011-07-25T01:09:07
38,108,101
0
0
null
null
null
null
UTF-8
C++
false
false
25,411
cpp
//////////////////////////////////////////////////////////////////// // Recording and playing Thread program concept is based on the // code by *** Paul Chauffers..***...from www.codeguru.com // // I am greatful to him for helping me to turn my dream project into reality. // // Display.cpp: implementation of the Display class. // ////////////////////////////////////////////////////////////////////// char mymesg[2020] ; #include<afxwin.h> #include<afxcmn.h> #include<afxdlgs.h> #include "about.h" #include "Display.h" #include "PlaySound1.h" #include "resource.h" #include "Volume.h" #include "Save.h" #include "WriteSound.h" #include "Broadcast.h" #include "StreamCipherProvider.h" #include "BlockCipherProvider.h" ////////////////////////// // MESSAGE MAPPING // ////////////////////////// BEGIN_MESSAGE_MAP(Display,CDialog) ON_COMMAND(IDC_BUTTON1,Onconnect) ON_COMMAND(IDC_BUTTON2,OnSave) ON_COMMAND(IDC_BUTTON3,OnVolume) ON_COMMAND(IDC_BUTTON4,OnPlay) ON_COMMAND(IDC_BUTTON5,OnStart) ON_COMMAND(IDC_BUTTON6,OnStop) ON_COMMAND_RANGE(IDC_RADIO1,IDC_RADIO2,OnChange) ON_WM_DESTROY() ON_WM_PAINT() //ON_WM_ERASEBKGND() ON_WM_CTLCOLOR() END_MESSAGE_MAP() bool isKey,isStream; CStreamCipherProvider scpTemp1,scpTemp2; CBlockCipherProvider bcpTemp1,bcpTemp2; // //Constructor // Display::Display(int n):CDialog(n) { isconnected=FALSE; sendcount=0; reccount=0; //create the buffers for playing.....buffers are reused.. PreCreateHeader(); log.Open("log.txt",CFile::modeCreate | CFile::modeWrite); } // // Destructor // Display::~Display() { log.WriteString("\n Deallocating the memory"); log.Close(); //if(anicon && success) //anicon->Close(); //Release the allocated memory for(int i=0;i<MAXBUFFER;i++) { if(playhead[i]->lpData) delete playhead[i]->lpData; if(playhead[i]) delete playhead[i]; } } /* */ /* This function precreates the waveblocks for storing */ /* voice data before playing.This will allow the REUSE of */ /* waveblocks. */ /* */ void Display::PreCreateHeader() { //Initial waveblock curhead=0; isstart=1; for(int i=0;i<MAXBUFFER;i++) { playhead[i] = new WAVEHDR; ZeroMemory(playhead[i], sizeof(WAVEHDR)); //Initialize it to zero char *temp=new char[PLAYBUFFER+50]; playhead[i]->lpData =temp; playhead[i]->dwBufferLength = PLAYBUFFER; playhead[i]->dwFlags=0; } } int Display::OnEraseBkgnd(CDC *pdc) { log.WriteString("\nIn the Onerase function"); return CDialog::OnEraseBkgnd(pdc); } /* */ /* This function does initial operations such */ /* creating Record and Play threads... */ /* */ int Display::OnInitDialog() { CFont myfont; isSave=FALSE; myfont.CreateFont(20,12,0,0,0,0,0,0,0,0,0,0,0,"System"); SetDlgItemText(IDC_EDIT1,"localhost"); SetDlgItemInt(IDC_EDIT2,1051); SetDlgItemText(IDC_EDIT3,"logname"); cbox=(CComboBox*)GetDlgItem(IDC_COMBO1); anicon=(CAnimateCtrl*)GetDlgItem(IDC_ANIMATE1); talk=(CAnimateCtrl*)GetDlgItem(IDC_ANIMATE2); if(!anicon->Open("conn.avi")) { success=FALSE; log.WriteString("\nUnable to open the avi file ****"); } else success=TRUE; if(!talk->Open("talk.avi")) { doit=FALSE; log.WriteString("\n Unable to open the talk.avi file"); } else doit=TRUE; // from=(CListBox *)GetDlgItem(IDC_LIST1); // from->SetFont(&myfont); curuser.Empty(); //Set the Icon for the application HICON m_hicon=AfxGetApp()->LoadIcon(IDI_ICON1); SetIcon(m_hicon,TRUE); SetIcon(m_hicon,FALSE); //Initializes socket if(!::AfxSocketInit()) { log.WriteString("\nSocket initialization failed"); return 0; } //Create Client socket object sockclt.setparent(this); sockclt.Create(); //Create and Start Recorder Thread record=new RecordSound(this); record->CreateThread(); //Create and Start Player Thread play=new PlaySound1(this); play->CreateThread(); //Create the Writer Thread to save the sound write=new WriteSound(); write->CreateThread(); selectflag=0; start=stop=NULL; radio3=(CButton*)GetDlgItem(IDC_RADIO_BLOCK); radio3->SetCheck(true); radio4=(CButton*)GetDlgItem(IDC_RADIO_STREAM); return CDialog::OnInitDialog(); } /* */ /* OnPaint() will fill the client area with */ /* the selected gradient color. */ /* */ void Display::OnPaint() { CRect r; CPen p[64]; int i,factor; //log.WriteString("\n In the OnPaint fun"); CPaintDC pdc(this); GetClientRect(&r); factor=r.bottom/63; for(i=0;i<64;i++) p[i].CreatePen(PS_SOLID,1,RGB(60,30,120+i*2)); for(i=0;i<r.bottom;i++) { pdc.SelectObject(&p[i/factor]); pdc.MoveTo(0,i); pdc.LineTo(r.right,i); } } /* */ /* This function will paint the bkgnd of individual */ /* components of dialog box */ /* */ HBRUSH Display::OnCtlColor(CDC *pdc,CWnd *pwnd,UINT ctrl) { int id=pwnd->GetDlgCtrlID(); //log.WriteString("\n In the on ctrl color fun"); pdc->SetTextColor(RGB(0,0,255)); switch(id) { case 1098:case 6051:case 1099:case 1086:case 1075:case 1071:case 1100: case IDC_CHECK: case IDC_RADIO1:case IDC_RADIO2:case IDC_RADIO_BLOCK: case IDC_RADIO_STREAM: pdc->SetBkMode(TRANSPARENT); HBRUSH hbr=CreateSolidBrush(RGB(50,160,254)); return hbr; } return NULL; } /* */ /* When user presses the Connect Button this */ /* method will be called */ /* */ bool HashSCKey (char *key , CString strkey) { strcpy (key,"qwertyuiopasdfghjk"); for (int i=0;i<strkey.GetLength();i++) key[i] = key[i] ^ strkey.GetAt(i); return true; } void Display::Onconnect() { int port; CString sername,username,mesg; //Write to log file log.WriteString("\n Connecting to Server"); //Get data from dialog box GetDlgItemText(IDC_EDIT1,sername); GetDlgItemText(IDC_EDIT3,username); port=GetDlgItemInt(IDC_EDIT2); if(username=="" || sername=="" ) { AfxMessageBox("Please Enter the data properly"); return; } if(success) { anicon->Play(0,-1,-1); log.WriteString("\n Playing data"); } //Connect the client to server username.MakeUpper(); sockclt.name=username; ///fix doan nay lai //B0 kiem tra checkbox CButton *x = (CButton*)GetDlgItem(IDC_CHECK); CString strKey; if (x->GetCheck()==1) { GetDlgItemText(IDC_EDIT_KEY,strKey); if(strKey=="" ) { AfxMessageBox("Please Enter the key"); return; } isKey=true; char key[129]; HashSCKey (key,strKey); if (radio3->GetCheck()) { bcpTemp1.Init(key); bcpTemp2.Init(key); isStream=false; } else { scpTemp1.Init(key); scpTemp2.Init(key); isStream=true; } } else isKey=false; //B1 nhap thong tin tu textbox //B2 bung key //B3 chuyen thanh khoa SetDlgItemText(IDC_BUTTON1,"Connecting"); if(sockclt.Connect(sername,port)) log.WriteString("\n Successfully Connected to Server"); else { SetDlgItemText(IDC_BUTTON1,"&Connect"); if(success) anicon->Stop(); MessageBox("Unable to Connect to Server\nVerify if Server name and Port are correct"); log.WriteString("\n Unable to connect to Server"); return; } isconnected=TRUE; if(success) anicon->Stop(); //Send the login message to server mesg="NEW:"+username; if(sockclt.Send(mesg,mesg.GetLength())) log.WriteString("\n login Mesg sent to Server"); else log.WriteString("\n Unable to send mesg to Server"); updateState(FALSE,TRUE); } /* */ /* This function updates the state of dialog box */ /* when the client is successfully connected to server. */ /* */ void Display::updateState(BOOL pstate,BOOL nstate) { CEdit *eser,*eport,*euser,*ekey; CStatic *sser,*sport,*suser,*sgroup1,*sgroup2,*skey; CButton *con,*check; //Destroy server related items con=(CButton*)GetDlgItem(IDC_BUTTON1); con->ShowWindow(pstate); eser=(CEdit*)GetDlgItem(IDC_EDIT1); eser->ShowWindow(pstate); eport=(CEdit*)GetDlgItem(IDC_EDIT2); eport->ShowWindow(pstate); euser=(CEdit*)GetDlgItem(IDC_EDIT3); euser->ShowWindow(pstate); ekey=(CEdit*)GetDlgItem(IDC_EDIT_KEY); ekey->ShowWindow(pstate); sser=(CStatic*)GetDlgItem(1098); sser->ShowWindow(pstate); suser=(CStatic*)GetDlgItem(1086); suser->ShowWindow(pstate); sport=(CStatic*)GetDlgItem(1099); sport->ShowWindow(pstate); skey=(CStatic*)GetDlgItem(1100); skey->ShowWindow(pstate); radio3=(CButton*)GetDlgItem(IDC_RADIO_BLOCK); radio4=(CButton*)GetDlgItem(IDC_RADIO_STREAM); radio3->ShowWindow(pstate); radio4->ShowWindow(pstate); check=(CButton*)GetDlgItem(IDC_CHECK); check->ShowWindow(pstate); sgroup1=(CStatic*)GetDlgItem(1097); sgroup1->ShowWindow(pstate); //Enable Send to items sgroup2=(CStatic*)GetDlgItem(1075); sgroup2->ShowWindow(nstate); radio1=(CButton*)GetDlgItem(IDC_RADIO1); radio2=(CButton*)GetDlgItem(IDC_RADIO2); start=(CButton*)GetDlgItem(IDC_BUTTON5); stop=(CButton*)GetDlgItem(IDC_BUTTON6); radio1->ShowWindow(nstate); radio2->ShowWindow(nstate); radio1->SetCheck(1); radio2->SetCheck(0); start->ShowWindow(nstate); cbox->ShowWindow(nstate); if(doit==TRUE) talk->ShowWindow(TRUE); anicon->ShowWindow(FALSE); } /* */ /* This function will be caled when the client */ /* receives message from server */ /* (called form "mysocket" OnReceive function ) */ /* */ void Display::Receive() { char buff[PLAYBUFFER+25],str[PLAYBUFFER+60]; int size=PLAYBUFFER+20,rcount,index,i,j,length; CString mesg,header,disp; rcount=sockclt.Receive(buff,size); if(rcount==SOCKET_ERROR) { log.WriteString("\nError in Receiving the data"); return; } if(rcount>(PLAYBUFFER+20)) { log.WriteString("\nMesg size exceeded buffer capacity"); return; } buff[rcount]=NULL; mesg=buff; // sprintf(str,"Received data len= %d , %s ",rcount,&buff[20]); // log.WriteString(str); index=mesg.Find(':'); //Invalid message Format --must have atleast one tag if(index==-1) return; header=mesg.Left(index); //Check if server has sent the list of clients if(header=="USER") { mesg=mesg.Right(mesg.GetLength()-index-1); updateList(mesg); return; } if(header=="WAIT") { if(isstart==0) //stop the chat OnStop(); start->EnableWindow(FALSE); mesg=mesg.Right(mesg.GetLength()-index-1); showFlash(); //disp=" Please wait....\n "+mesg+" is broadcasting"; //SetDlgItemText(6051,(char*)(LPCTSTR)disp); MessageBox("Please wait....\n "+mesg+" is broadcasting"); return; } if(header=="RESUME") { start->EnableWindow(TRUE); showFlash(); disp=" Broadcasting is over \n Now You can continue..."; SetDlgItemText(6051,(char*)(LPCTSTR)disp); // MessageBox(" Broadcasting is over \n Now You can continue..."); log.WriteString("\n****Received the resume message****"); return; } else //play the voice data { //No of messages received //*** Part of this code has to be removed later ***\\ //Get the legth of buffer length=0; sscanf(&buff[15],"%d",&length); if(length<1 || length>PLAYBUFFER) return; //If audio is not playing, start playing if(play->Playing==FALSE) play->PostThreadMessage(WM_PLAYSOUND_STARTPLAYING,0,0); LPWAVEHDR lpHdr=playhead[curhead]; curhead=(curhead+1)%MAXBUFFER; ////////////////////////////////////////////////////////// char newMesg[2000]; //pTemp2.Decrypt(mes,length,newMesg); if (isKey) { if (isStream) scpTemp2.Decrypt(&buff[20],length,newMesg); else bcpTemp2.CTRModeEncrypt(&buff[20],length,newMesg); for (i=0;i<length;i++) lpHdr->lpData[i]=newMesg[i]; } else { for(i=20,j=0;j<length;i++,j++) lpHdr->lpData[j]=buff[i]; } //////////////////////////////////////////////////////////////// // playmesg=new char[2020]; lpHdr->dwBufferLength=length; lpHdr->dwFlags=0; play->PostThreadMessage(WM_PLAYSOUND_PLAYBLOCK,0,(LPARAM)lpHdr); //If Save button is pressed.... //Save the Voice data from perticular user if(isSave==TRUE && writeuser.CompareNoCase(header)==0) { write->PostThreadMessage(WM_WRITESOUND_WRITEDATA,0,(LPARAM)lpHdr); log.WriteString("\n Writing to store"); } // log.WriteString("\nPlaying......"); disp=" "+header+" is talking..."; SetDlgItemText(6051,(char*)(LPCTSTR)disp); /* if(from->FindStringExact(-1,header)==LB_ERR) { from->ResetContent(); from->AddString(header); } */ // reccount++; // sprintf(str,"\n No of Messages received = %d ",reccount); // log.WriteString(str); } } /* */ /* This function will flash the window whenever */ /* important message has been received...shutdown,logout..etc */ /* */ void Display::showFlash() { //flash for 3 times FlashWindow(TRUE); Sleep(200); FlashWindow(TRUE); } // // After pressing the Save button ... // // void Display::OnStartWrite(char *name) { isSave=TRUE; log.WriteString("\n Calling create fun of thread"); write->PostThreadMessage(WM_WRITESOUND_CREATEFILE,0,(LPARAM)name); } // // After pressing the Save button ...later stop... // void Display::OnStopWrite() { isSave=FALSE; write->PostThreadMessage(WM_WRITESOUND_CLOSEFILE,0,0); } /* */ /* This function will be called whenever user */ /* selects one of the radio button (*all or *client) */ /* */ void Display::OnChange(int id) { CString bmesg; if(cbox->GetCount()<=0) return; if(id==IDC_RADIO1 && radio1->GetCheck()) //Send to client { cbox->EnableWindow(TRUE); if(cbox->GetCount()>=1) { curuser.Empty(); cbox->GetLBText(cbox->GetCurSel(),curuser); log.WriteString("\nConnected to user "+curuser); selectflag=1; startRecording(); } else { curuser.Empty(); selectflag=0; stopRecording(); //stopPlaying(); //****** REMOVED ******// } } if(id==IDC_RADIO2 && radio2->GetCheck()) //Send to All { curuser="ALL"; if(isstart==0) //Stop the record and play OnStop(); log.WriteString("\n Broadcasting message"); Broadcast bd(IDD_DIALOG5,this); bd.DoModal(); bmesg="OVER:"; selectflag=1; if(sockclt.Send(bmesg,bmesg.GetLength())) log.WriteString("\n Over Mesg sent to Server"); else log.WriteString("\n Unable to send over mesg to Server"); curuser.Empty(); radio1->SetCheck(1); radio2->SetCheck(0); } } /* */ /* This function will be called whenever client */ /* receives new userlist from the server and it will */ /* update the combo box */ /* */ void Display::updateList(CString mesg) { int index,num,prevcount; CString name; static int first=0; CString disp; //Clear the combo box contents prevcount=cbox->GetCount(); cbox->ResetContent(); do { index=mesg.Find(';'); if(index==-1) break; name=mesg.Left(index); if(name.CompareNoCase(sockclt.name)!=0) cbox->AddString(name); mesg=mesg.Right(mesg.GetLength()-index-1); } while(TRUE); if(cbox->GetCount()==1) { cbox->SetCurSel(0); cbox->GetLBText(0,curuser); selectflag=1; if(prevcount==0 && first==1) { showFlash(); disp="New user " + curuser + " logged in"; SetDlgItemText(6051,(char*)(LPCTSTR)disp); } } first=1; if(cbox->GetCount()>1) { if(curuser.IsEmpty()==FALSE) { if((num=cbox->FindStringExact(-1,curuser))>=0) { selectflag=1; cbox->SetCurSel(num); return; } } selectflag=0; OnStop(); // stopRecording(); cbox->SetCurSel(0); if(curuser.IsEmpty()==FALSE && curuser!="ALL" ) { showFlash(); disp=curuser+" logged out \n Please select the user"; SetDlgItemText(6051,(char*)(LPCTSTR)disp); // MessageBox(curuser+" logged out ......Please select the user"); } else if(curuser!="ALL") { showFlash(); disp="New user logged in"; SetDlgItemText(6051,(char*)(LPCTSTR)disp); //MessageBox("New user logged in...."); } } if(cbox->GetCount()==0) { OnStop(); //stopRecording(); //stopPlaying(); //******* REMOVED *******// if(curuser.IsEmpty()==FALSE && curuser!="ALL") { showFlash(); disp=curuser+" logged out"; SetDlgItemText(6051,(char*)(LPCTSTR)disp); // MessageBox(curuser+" logged out"); } //SetDlgItemText(6051,""); //from->ResetContent(); //Clear the From Listbox curuser.Empty(); } } /* */ /* This function will be called whenever user */ /* presses the start/stop button */ /* It updates the button status and starts recording and playing. */ /* */ void Display::OnStart() { if(cbox->GetCount()<1) { MessageBox("No users are present"); return; } if(!isstart) return; if(doit==TRUE) talk->Play(0,-1,-1); cbox->GetLBText(cbox->GetCurSel(),curuser); selectflag=1; //Start recording and playing... startRecording(); startPlaying(); log.WriteString("\n New Target user is "+ curuser); //change state isstart=0; start->ShowWindow(FALSE); stop->ShowWindow(TRUE); } /* */ /* This function will be called whenever user */ /* presses the Stop button */ /* */ void Display::OnStop() { if(isstart) return; if(doit==TRUE) talk->Stop(); stopRecording(); stopPlaying(); selectflag=0; //change state isstart=1; start->ShowWindow(TRUE); stop->ShowWindow(FALSE); } // //*** Part of this code needs to be removed later*** // void Display::startRecording() { if(record->recording==FALSE) { // if(sockclt.name.CompareNoCase("logname")==0) record->PostThreadMessage(WM_RECORDSOUND_STARTRECORDING,0,0); } } /* */ /* This function will stop the recording by sending */ /* stop message to recording thread */ /* */ void Display::stopRecording() { if(record->recording==TRUE) record->PostThreadMessage(WM_RECORDSOUND_STOPRECORDING,0,0); } /* */ /* This function will stop the playing by sending */ /* stop message to player thread. */ /* */ void Display::startPlaying() { if(play->Playing==FALSE) play->PostThreadMessage(WM_PLAYSOUND_STARTPLAYING,0,0); } /* */ /* This function will stop the playing by sending */ /* stop message to player thread. */ /* */ void Display::stopPlaying() { if(play->Playing==TRUE) play->PostThreadMessage(WM_PLAYSOUND_STOPPLAYING,0,0); } /* */ /* This function will send the voice data to the server */ /* (called from the Recorder Thread) */ /* */ void Display::sendMessage(char *mesg,int length) { char buflen[15]; char str[PLAYBUFFER+50]; int i,j; //If user not selected or no users are present return; if(selectflag==0 ) return; if(mesg==NULL) { log.WriteString("\nEmpty buffer received from recordsound"); return; } if(length<1 || length>PLAYBUFFER) { log.WriteString("\n Send : Length is more than the 2000 or less than 1"); return; } int size; length %4==0?size=length/4:size=length/4+1; if (isKey) { for (i=0;i<length;i++) mymesg[i]=mesg[i]; if (isStream) { scpTemp1.Encrypt(mymesg,length,mesg); length %4==0?size=length:size=(length/4+1)*4; } else { bcpTemp1.CTRModeEncrypt(mymesg,length,mesg); length %16==0?size=length:size=(length/16+1)*16; } } mesg=mesg-20; //First 15 bits contains the destination information //Next 5 bits contains the length of message //Remaining part contains the data if(curuser.IsEmpty()) { log.WriteString("\n Curuser is Empty- No user selected"); return; } for(i=0;i < curuser.GetLength();i++) mesg[i]=curuser[i]; mesg[i]=':'; sprintf(buflen,"%d",length); for(j=0,i=15;j<5;j++,i++) mesg[i]=buflen[j]; //Write to log file sprintf(str,"\n Sending message datalen = %d , mesg = %s",length,&mesg[20]); log.WriteString(str); // sendcount++; // sprintf(str,"\n No of Messages Sent = %d ",sendcount); // log.WriteString(str); if(sockclt.Send(mesg,size+20)!=SOCKET_ERROR ) log.WriteString("\n Data sent successfully to "+curuser); else log.WriteString("\n Data sent Error "); } /* */ /* Display the About Dialog Box */ /* */ void Display::OnAbout() { about my(IDD_DIALOG2); my.DoModal(); } /* */ /* Display the About Dialog Box */ /* */ void Display::OnSave() { if(curuser.IsEmpty()) { MessageBox("\n First connect to one of the user..."); return; } writeuser=curuser; Save sa(IDD_DIALOG4,this); sa.DoModal(); } /* */ /* This function will destroy the client window and */ /* closes all threads and socket connecion */ /* */ void Display::OnCancel() { log.WriteString("\n Closing the dialog box"); //Stop the recording and playing threads if(record->recording==TRUE) record->PostThreadMessage(WM_RECORDSOUND_STOPRECORDING,0,0); record->PostThreadMessage(WM_RECORDSOUND_ENDTHREAD,0,0); if(play->Playing==TRUE) play->PostThreadMessage(WM_PLAYSOUND_STOPPLAYING,0,0); play->PostThreadMessage(WM_PLAYSOUND_ENDTHREAD,0,0); write->PostThreadMessage(WM_WRITESOUND_ENDTHREAD,0,0); if(sockclt.closeflag==1) { showFlash(); MessageBox("Server has shutdown"); } if(isconnected==TRUE) sockclt.Close(); CDialog::OnCancel(); } /* */ /* This function will display the volume setting */ /* dialog box. */ /* */ void Display::OnVolume() { Volume vol(IDD_DIALOG3); vol.DoModal(); } /* */ /* This function will play the stored sound */ /* */ /* */ void Display::OnPlay() { CFileDialog fd(1,0,0,0,"Sound Files(*.wav)|*.wav|All Files|*.*||" ); fd.m_ofn.lpstrTitle="Browse"; if(isstart==0) { MessageBox("Please stop chatting..."); return; } if(fd.DoModal()==IDOK) { sndPlaySound(fd.GetPathName(),SND_ASYNC); } }
[ "funnyamauter@72c74e6c-5204-663f-ea46-ae2a288fd484" ]
[ [ [ 1, 1151 ] ] ]
6fb34826d4b6e5d782cca6d00ad77e5a96eb9382
119ba245bea18df8d27b84ee06e152b35c707da1
/qreal/qrgui/mainwindow/errorReporter.h
a12ac0737d783bb93899453394c7ebb3c7e0d5e2
[]
no_license
nfrey/qreal
05cd4f9b9d3193531eb68ff238d8a447babcb3d2
71641e6c5f8dc87eef9ec3a01cabfb9dd7b0e164
refs/heads/master
2020-04-06T06:43:41.910531
2011-05-30T19:30:09
2011-05-30T19:30:09
1,634,768
0
0
null
null
null
null
UTF-8
C++
false
false
1,188
h
#pragma once #include <QtCore/QString> #include <QtCore/QList> #include"mainwindow.h" #include "../kernel/ids.h" #include "../kernel/definitions.h" #include "error.h" #include "errorlistwidget.h" namespace qReal { namespace gui { class ErrorReporter : public QObject { Q_OBJECT public: ErrorReporter(); ErrorReporter(ErrorListWidget* const errorListWidget, QDockWidget* const errorList); void addInformation(QString const &message, Id const &position = Id::rootId()); void addWarning(QString const &message, Id const &position = Id::rootId()); void addError(QString const &message, Id const &position = Id::rootId()); void addCritical(QString const &message, Id const &position = Id::rootId()); bool showErrors(ErrorListWidget* const errorListWidget, QDockWidget* const errorList) const; void clear(); void clearErrors(); private: QList<Error> mErrors; ErrorListWidget* const mErrorListWidget; // Doesn't have ownership QDockWidget* const mErrorList; // Doesn't have ownership static QString severityMessage(Error const &error); void showError(Error const &error, ErrorListWidget* const errorListWidget) const; }; } }
[ "[email protected]", "26122006" ]
[ [ [ 1, 28 ], [ 30, 42 ] ], [ [ 29, 29 ] ] ]
97562d58794732f8eb2a9d882e1b4585aff43bb8
172e5e180659a6a7242f95a367f5a879114bc38d
/SlideList/DetailView.h
f56710a48e1d57ab40c912f72ec080d1e8fb4276
[]
no_license
urere/mfcslidelist
1e66fc1a7b34f7832f5d09d278d2dd145d30adec
7c7eb47122c6b7c3b52a93145ec8b2d6f2476519
refs/heads/master
2021-01-10T02:06:44.884376
2008-03-27T21:25:09
2008-03-27T21:25:09
47,465,994
0
0
null
null
null
null
UTF-8
C++
false
false
2,752
h
#if !defined(AFX_DETAILVIEW_H__B0F98C84_DB48_4FB1_AA8C_0072F783DDBC__INCLUDED_) #define AFX_DETAILVIEW_H__B0F98C84_DB48_4FB1_AA8C_0072F783DDBC__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // DetailView.h : header file // ///////////////////////////////////////////////////////////////////////////// // CDetailView view class CDetailView : public CScrollView { protected: CDetailView(); // protected constructor used by dynamic creation DECLARE_DYNCREATE(CDetailView) // Attributes public: CSlideListDoc* GetDocument(); // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CDetailView) protected: virtual void OnDraw(CDC* pDC); // overridden to draw this view virtual void OnInitialUpdate(); // first time after construct //}}AFX_VIRTUAL // Implementation protected: virtual ~CDetailView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif // Generated message map functions //{{AFX_MSG(CDetailView) // NOTE - the ClassWizard will add and remove member functions here. //}}AFX_MSG DECLARE_MESSAGE_MAP() // Private helper functions private: int DrawFilmDetails(CDC* pDC, CFilmDetails *pFilm ); int DrawPhotoDetails(CDC* pDC, CPhotoDetails *pPhoto ); int DrawFilmPhotoList(CDC* pDC, CFilmDetails *pFilm ); int OutputText( CDC* pDC, LPCTSTR pLocalFontName, LPCTSTR pText, int XPos = 0 ); int OutputParagraph( CDC* pDC, LPCTSTR pLocalFontName, LPCTSTR pText, int XPos = 0, int MaxWidth = 0 ); void NewLine ( LPCTSTR pLocalFontName = NULL ); BOOL AddFont( CDC *pDC, LPCTSTR pLocalName, LPCTSTR pFaceName, int PointSize, BOOL bBold = FALSE, BOOL bItalic = FALSE, BOOL bUnderLine = FALSE ); CFont *GetFont( LPCTSTR pLocalName ); TEXTMETRIC *GetFontInfo( LPCTSTR pLocalName ); int FontsInCache( void ) { return(m_FontCache.GetCount()); }; void DeleteFontCache(); // private attributes private: CMapStringToOb m_FontCache; // Cache of fonts CMapStringToPtr m_FontInfoCache; // Cache of LOGFONTS int m_TopMargin; int m_BottomMargin; int m_LeftMargin; int m_RightMargin; long int m_CurrentYPos; int m_CurrentRowHeight; }; #ifndef _DEBUG // debug version in DetailView.cpp inline CSlideListDoc* CDetailView::GetDocument() { return (CSlideListDoc*)m_pDocument; } #endif ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_DETAILVIEW_H__B0F98C84_DB48_4FB1_AA8C_0072F783DDBC__INCLUDED_)
[ "ratcliffe.gary@e6454d50-7149-0410-9942-4ffd99bf3498" ]
[ [ [ 1, 87 ] ] ]
33b82ff2e45741edf37227b482cd1a33188a3086
333b818a4cb8e9dc3ddcbdac65a11f1c52cd2985
/Donnee.h
d3f1f283ca38878de70bed231a995df119cbde97
[]
no_license
noullet/firesimulation
5ee51c0ed88d4807ad0fd3220b09d39324774be0
0a1e9dd7eaff3f20f01b8c97090fd12a3efcca82
refs/heads/master
2016-09-03T06:38:11.473207
2010-03-25T07:44:33
2010-03-25T07:44:33
32,204,918
0
0
null
null
null
null
ISO-8859-1
C++
false
false
842
h
///////////////////// // Fire Simulation // // Nicolas Noullet // // Bertrand Pagès // ///////////////////// #if !defined(_DONNEE_H) #define _DONNEE_H #include <iostream> using namespace std; class Donnee { public: string type; int x; int y; bool traite; string pompier; Donnee(string aType, int aX, int aY): type(aType), x(aX), y(aY), traite(false), pompier(""){}; void Donnee::afficher() { cout << type << "(" << x << ','<< y << ")" << endl; } bool Donnee::equals(Donnee * d) { if(d != NULL) { if(type != (*d).type) return false; if(x != (*d).x) return false; if(y != (*d).y) return false; return true; } return false; } }; #endif //_DONNEE_H
[ "pages.bertrand@6307593a-2cef-11df-aeb3-278f4910c8cc", "nicolas.noullet@6307593a-2cef-11df-aeb3-278f4910c8cc" ]
[ [ [ 1, 9 ], [ 12, 21 ], [ 26, 42 ] ], [ [ 10, 11 ], [ 22, 25 ] ] ]
f08940aab4e0ddbcb4a22c91e796475de874a468
b4bff7f61d078e3dddeb760e21174a781ed7f985
/Source/Base/Event/Producers/OSGEventProducer.inl
549817e43b216c5e8c486e3ff4e2d1eb0316e0c0
[]
no_license
Langkamp/OpenSGToolbox
8283edb6074dffba477c2c4d632e954c3c73f4e3
5a4230441e68f001cdf3e08e9f97f9c0f3c71015
refs/heads/master
2021-01-16T18:15:50.951223
2010-05-19T20:24:52
2010-05-19T20:24:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,200
inl
/*---------------------------------------------------------------------------*\ * OpenSG ToolBox Toolbox * * * * * * * * * * Authors: David Kabala * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * License * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Library General Public License as published * * by the Free Software Foundation, version 2. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * Changes * * * * * * * * * * * * * \*---------------------------------------------------------------------------*/ //--------------------------------------------------------------------------- // Includes //--------------------------------------------------------------------------- #include "OSGConfig.h" OSG_BEGIN_NAMESPACE inline const EventProducerType &EventProducer::getProducerClassType(void) { return _ProducerClassType; } inline UInt32 EventProducer::getProducerClassTypeId(void) { return _ProducerClassType.getId(); } inline const EventProducerType &EventProducer::getProducerType(void) const { return *_ProducerType; } inline UInt32 EventProducer::getNumProducedEvents(void) const { return getProducerType().getNumMethodDescs(); } inline const MethodDescription *EventProducer::getProducedEventDescription(const std::string &ProducedEventName) const { return getProducerType().findMethodDescription(ProducedEventName); } inline const MethodDescription *EventProducer::getProducedEventDescription(UInt32 ProducedEventId) const { return getProducerType().getMethodDescription(ProducedEventId); } //Activities inline EventConnection EventProducer::attachActivity(ActivityRefPtr TheActivity, const std::string &ProducedEventName) { return attachActivity(TheActivity, getProducedEventId(ProducedEventName)); } inline bool EventProducer::isActivityAttached(ActivityRefPtr TheActivity, const std::string &ProducedEventName) const { return isActivityAttached(TheActivity, getProducedEventId(ProducedEventName)); } inline UInt32 EventProducer::getNumActivitiesAttached(const std::string &ProducedEventName) const { return getNumActivitiesAttached(getProducedEventId(ProducedEventName)); } inline ActivityRefPtr EventProducer::getAttachedActivity(const std::string &ProducedEventName, UInt32 ActivityIndex) const { return getAttachedActivity(getProducedEventId(ProducedEventName), ActivityIndex); } inline void EventProducer::detachActivity(ActivityRefPtr TheActivity, const std::string &ProducedEventName) { return detachActivity(TheActivity, getProducedEventId(ProducedEventName)); } //EventListeners inline EventConnection EventProducer::attachEventListener(EventListenerPtr TheEventListener, const std::string &ProducedEventName) { return attachEventListener(TheEventListener, getProducedEventId(ProducedEventName)); } inline bool EventProducer::isEventListenerAttached(EventListenerPtr TheEventListener, const std::string &ProducedEventName) const { return isEventListenerAttached(TheEventListener, getProducedEventId(ProducedEventName)); } inline UInt32 EventProducer::getNumEventListenersAttached(const std::string &ProducedEventName) const { return getNumEventListenersAttached(getProducedEventId(ProducedEventName)); } inline EventListenerPtr EventProducer::getAttachedEventListener(const std::string &ProducedEventName, UInt32 EventListenerIndex) const { return getAttachedEventListener(getProducedEventId(ProducedEventName), EventListenerIndex); } inline void EventProducer::detachEventListener(EventListenerPtr TheEventListener, const std::string &ProducedEventName) { return detachEventListener(TheEventListener, getProducedEventId(ProducedEventName)); } inline void EventProducer::setType(const EventProducerType* TheProducerType) { _ProducerType = TheProducerType; } OSG_END_NAMESPACE
[ [ [ 1, 40 ], [ 42, 69 ], [ 71, 82 ], [ 84, 88 ], [ 90, 94 ], [ 96, 100 ], [ 102, 106 ], [ 108, 114 ], [ 116, 120 ], [ 122, 126 ], [ 128, 132 ], [ 134, 138 ], [ 140, 151 ] ], [ [ 41, 41 ], [ 70, 70 ], [ 83, 83 ], [ 89, 89 ], [ 95, 95 ], [ 101, 101 ], [ 107, 107 ], [ 115, 115 ], [ 121, 121 ], [ 127, 127 ], [ 133, 133 ], [ 139, 139 ] ] ]
e30b3fae113b54e088d02c5eff683b3459f0a100
6b75de27b75015e5622bfcedbee0bf65e1c6755d
/binary-tree/查找算法-错误很多啊.cpp
00ce64c652eeb754f1d4ae6f2dc8e64a6eebeaa1
[]
no_license
xhbang/data_structure
6e4ac9170715c0e45b78f8a1b66c838f4031a638
df2ff9994c2d7969788f53d90291608ac5b1ef2b
refs/heads/master
2020-04-04T02:07:18.620014
2011-12-05T09:39:34
2011-12-05T09:39:34
2,393,408
0
0
null
null
null
null
UTF-8
C++
false
false
895
cpp
#include <iostream.h> #include <string.h> int zheban(string *s,int sz,string source); int xianxing(string *s,string source); int main(){ string arr[10]={"auk","bat","cow","eel","elk","fox","gnu","pig","rat"}; int loc1,loc2; string source; cout<<"input the string to find"<<endl; cin>>source; loc1=zheban(arr,10,string source); loc2=xianxing(arr,string source); } int zheban(string *s,int sz,string source){ int middle,first,end,loc; bool found=false; first=0,end=sz-1,middle=(first+end)/2; while(first<=end && !found){ if(strcmp(s[middle],source)>0) last=middle-1; else(strcmp(s[middle,source])<0) first=middle+1; else found=true; } return first; } int xianxing(string *s,string source){ bool found=false; int i=0; if(*s && !found){ if(strcmp(s,source)==0) found=true; else{ s++; i++; } } return i; }
[ [ [ 1, 44 ] ] ]
aa71d6f88e20715b512b893374f21a2f938494a9
59957e5aa42be6037a8539d299ca741086b81761
/frmconfig.cpp
0bb5d47597772373809fb60da478c6401f50c3a1
[]
no_license
thiagomg/twithiago
4a1144ab904ba26b53a09e454f7d9c709984aefe
60b5f8da1a3bcc426916949a7e50944163874a28
refs/heads/master
2020-04-16T07:15:46.909318
2010-04-12T13:06:02
2010-04-12T13:06:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,141
cpp
#include "frmconfig.h" #include "ui_frmconfig.h" #include "Config.h" #include <QCloseEvent> FrmConfig::FrmConfig(QWidget *parent) : QDialog(parent), m_ui(new Ui::FrmConfig) { m_ui->setupUi(this); m_ui->lnePassword->setEchoMode( QLineEdit::Password ); m_ui->lneProxyPassword->setEchoMode( QLineEdit::Password ); m_ui->lneUser->setText( CONFIG.getUsername() ); m_ui->lnePassword->setText( CONFIG.getPassword() ); m_ui->lneProxyUser->setText( CONFIG.getProxyUsername() ); m_ui->lneProxyPassword->setText( CONFIG.getProxyPassword() ); } FrmConfig::~FrmConfig() { delete m_ui; } void FrmConfig::changeEvent(QEvent *e) { QDialog::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: m_ui->retranslateUi(this); break; default: break; } } void FrmConfig::closeEvent(QCloseEvent * event) { CONFIG.setUsername(m_ui->lneUser->text()); CONFIG.setPassword(m_ui->lnePassword->text()); CONFIG.setProxyUsername(m_ui->lneProxyUser->text()); CONFIG.setProxyPassword(m_ui->lneProxyPassword->text()); event->accept(); }
[ "thiedri@8854fccc-d45e-11de-bff8-d51c198f79d0" ]
[ [ [ 1, 48 ] ] ]
968aed9d9d736e2591314d2929e18e3fc1aa2103
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/3rdParty/boost/libs/iterator/test/filter_iterator_test.cpp
8f84f1a221111a02e20fd0d8a083aaa3a71ae2cc
[]
no_license
bugbit/cipsaoscar
601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4
52aa8b4b67d48f59e46cb43527480f8b3552e96d
refs/heads/master
2021-01-10T21:31:18.653163
2011-09-28T16:39:12
2011-09-28T16:39:12
33,032,640
0
0
null
null
null
null
UTF-8
C++
false
false
8,203
cpp
// Copyright David Abrahams 2003, Jeremy Siek 2004. // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <boost/iterator/filter_iterator.hpp> #include <boost/iterator/reverse_iterator.hpp> #include <boost/iterator/new_iterator_tests.hpp> #include <boost/type_traits/is_convertible.hpp> #include <boost/concept_check.hpp> #include <boost/concept_archetype.hpp> #include <boost/iterator/iterator_concepts.hpp> #include <boost/iterator/iterator_archetypes.hpp> #include <boost/cstdlib.hpp> #include <deque> #include <iostream> using boost::dummyT; struct one_or_four { bool operator()(dummyT x) const { return x.foo() == 1 || x.foo() == 4; } }; template <class T> struct undefined; template <class T> struct see_type; // Test filter iterator int main() { // Concept checks // Adapting old-style iterators { typedef boost::filter_iterator<one_or_four, boost::input_iterator_archetype<dummyT> > Iter; boost::function_requires< boost::InputIteratorConcept<Iter> >(); boost::function_requires< boost_concepts::ReadableIteratorConcept<Iter> >(); boost::function_requires< boost_concepts::SinglePassIteratorConcept<Iter> >(); } { typedef boost::filter_iterator<one_or_four, boost::input_output_iterator_archetype<dummyT> > Iter; boost::function_requires< boost::InputIteratorConcept<Iter> >(); boost::function_requires< boost::OutputIteratorConcept<Iter, dummyT> >(); boost::function_requires< boost_concepts::ReadableIteratorConcept<Iter> >(); boost::function_requires< boost_concepts::WritableIteratorConcept<Iter> >(); boost::function_requires< boost_concepts::SinglePassIteratorConcept<Iter> >(); } { typedef boost::filter_iterator<one_or_four, boost::forward_iterator_archetype<dummyT> > Iter; boost::function_requires< boost::ForwardIteratorConcept<Iter> >(); boost::function_requires< boost_concepts::ReadableIteratorConcept<Iter> >(); boost::function_requires< boost_concepts::ForwardTraversalConcept<Iter> >(); } { typedef boost::filter_iterator<one_or_four, boost::mutable_forward_iterator_archetype<dummyT> > Iter; boost::function_requires< boost::Mutable_ForwardIteratorConcept<Iter> >(); boost::function_requires< boost_concepts::ReadableIteratorConcept<Iter> >(); boost::function_requires< boost_concepts::WritableIteratorConcept<Iter> >(); boost::function_requires< boost_concepts::ForwardTraversalConcept<Iter> >(); } // Adapting new-style iterators { typedef boost::iterator_archetype< const dummyT , boost::iterator_archetypes::readable_iterator_t , boost::single_pass_traversal_tag > BaseIter; typedef boost::filter_iterator<one_or_four, BaseIter> Iter; boost::function_requires< boost::InputIteratorConcept<Iter> >(); boost::function_requires< boost_concepts::ReadableIteratorConcept<Iter> >(); boost::function_requires< boost_concepts::SinglePassIteratorConcept<Iter> >(); } #if !BOOST_WORKAROUND(BOOST_MSVC, == 1200) // Causes Internal Error in linker. { typedef boost::iterator_archetype< dummyT , boost::iterator_archetypes::readable_writable_iterator_t , boost::single_pass_traversal_tag > BaseIter; typedef boost::filter_iterator<one_or_four, BaseIter> Iter; boost::function_requires< boost::InputIteratorConcept<Iter> >(); boost::function_requires< boost::OutputIteratorConcept<Iter, dummyT> >(); boost::function_requires< boost_concepts::ReadableIteratorConcept<Iter> >(); boost::function_requires< boost_concepts::WritableIteratorConcept<Iter> >(); boost::function_requires< boost_concepts::SinglePassIteratorConcept<Iter> >(); } #endif { typedef boost::iterator_archetype< const dummyT , boost::iterator_archetypes::readable_iterator_t , boost::forward_traversal_tag > BaseIter; typedef boost::filter_iterator<one_or_four, BaseIter> Iter; boost::function_requires< boost::InputIteratorConcept<Iter> >(); boost::function_requires< boost_concepts::ReadableIteratorConcept<Iter> >(); boost::function_requires< boost_concepts::ForwardTraversalConcept<Iter> >(); } #if !BOOST_WORKAROUND(BOOST_MSVC, == 1200) // Causes Internal Error in linker. { typedef boost::iterator_archetype< dummyT , boost::iterator_archetypes::readable_writable_iterator_t , boost::forward_traversal_tag > BaseIter; typedef boost::filter_iterator<one_or_four, BaseIter> Iter; boost::function_requires< boost_concepts::ReadableIteratorConcept<Iter> >(); boost::function_requires< boost_concepts::WritableIteratorConcept<Iter> >(); boost::function_requires< boost_concepts::ForwardTraversalConcept<Iter> >(); } { typedef boost::iterator_archetype< const dummyT , boost::iterator_archetypes::readable_lvalue_iterator_t , boost::forward_traversal_tag > BaseIter; typedef boost::filter_iterator<one_or_four, BaseIter> Iter; boost::function_requires< boost::ForwardIteratorConcept<Iter> >(); boost::function_requires< boost_concepts::ReadableIteratorConcept<Iter> >(); boost::function_requires< boost_concepts::LvalueIteratorConcept<Iter> >(); boost::function_requires< boost_concepts::ForwardTraversalConcept<Iter> >(); } { typedef boost::iterator_archetype< dummyT , boost::iterator_archetypes::writable_lvalue_iterator_t , boost::forward_traversal_tag > BaseIter; typedef boost::filter_iterator<one_or_four, BaseIter> Iter; boost::function_requires< boost::Mutable_ForwardIteratorConcept<Iter> >(); boost::function_requires< boost_concepts::WritableIteratorConcept<Iter> >(); boost::function_requires< boost_concepts::LvalueIteratorConcept<Iter> >(); boost::function_requires< boost_concepts::ForwardTraversalConcept<Iter> >(); } #endif // Run-time tests dummyT array[] = { dummyT(0), dummyT(1), dummyT(2), dummyT(3), dummyT(4), dummyT(5) }; const int N = sizeof(array)/sizeof(dummyT); typedef boost::filter_iterator<one_or_four, dummyT*> filter_iter; boost::bidirectional_readable_iterator_test( filter_iter(one_or_four(), array, array+N) , dummyT(1), dummyT(4)); BOOST_STATIC_ASSERT( (!boost::is_convertible< boost::iterator_traversal<filter_iter>::type , boost::random_access_traversal_tag >::value )); //# endif // On compilers not supporting partial specialization, we can do more type // deduction with deque iterators than with pointers... unless the library // is broken ;-( std::deque<dummyT> array2; std::copy(array+0, array+N, std::back_inserter(array2)); boost::bidirectional_readable_iterator_test( boost::make_filter_iterator(one_or_four(), array2.begin(), array2.end()), dummyT(1), dummyT(4)); boost::bidirectional_readable_iterator_test( boost::make_filter_iterator(one_or_four(), array2.begin(), array2.end()), dummyT(1), dummyT(4)); boost::bidirectional_readable_iterator_test( boost::make_filter_iterator( one_or_four() , boost::make_reverse_iterator(array2.end()) , boost::make_reverse_iterator(array2.begin()) ), dummyT(4), dummyT(1)); boost::bidirectional_readable_iterator_test( filter_iter(array+0, array+N), dummyT(1), dummyT(4)); boost::bidirectional_readable_iterator_test( filter_iter(one_or_four(), array, array + N), dummyT(1), dummyT(4)); std::cout << "test successful " << std::endl; return boost::exit_success; }
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 197 ] ] ]
8a9641469b00cc999bcf879c3bf9fb30cca6d300
0b55a33f4df7593378f58b60faff6bac01ec27f3
/Konstruct/Server/LoginServer/PacketHandlers.cpp
0854cf33a3469f2bcf678043b54b33421c8ed6f9
[]
no_license
RonOHara-GG/dimgame
8d149ffac1b1176432a3cae4643ba2d07011dd8e
bbde89435683244133dca9743d652dabb9edf1a4
refs/heads/master
2021-01-10T21:05:40.480392
2010-09-01T20:46:40
2010-09-01T20:46:40
32,113,739
1
0
null
null
null
null
UTF-8
C++
false
false
520
cpp
#include "StdAfx.h" #include "Common/Network/kpnBaseSocket.h" DispatchFunction g_pClientHandlers[] = { /* GPID_IDENTITY */ 0, /* GPID_IDENTIFY */ 0, /* GPID_CONNECT */ 0, /* GPID_CONNECTED */ 0, }; DispatchFunction g_pWorldHandlers[] = { /* GPID_IDENTITY */ 0, /* GPID_IDENTIFY */ 0, /* GPID_CONNECT */ 0, /* GPID_CONNECTED */ 0, }; DispatchFunction g_pDBHandlers[] = { /* GPID_IDENTITY */ 0, /* GPID_IDENTIFY */ 0, /* GPID_CONNECT */ 0, /* GPID_CONNECTED */ 0, };
[ "acid1789@0c57dbdb-4d19-7b8c-568b-3fe73d88484e" ]
[ [ [ 1, 28 ] ] ]
e4c6c2c347699dd4adb6505ead94bd60db5f7003
8ade67ab53907d22e40286b377b86d1b1eeaf6f0
/optimize_ca/coverage/setCache.h
f807a06c1e180b594b86772d4fe9a2a711a68f26
[]
no_license
robbywalker/ca-phf-research
1483d1113abd865347c4f26934d4a5f43cd2e9b2
7bce5bde73bd6d7314902687b3323dcaf93941a6
refs/heads/master
2021-01-16T18:40:29.238236
2011-04-24T18:29:55
2011-04-24T18:29:55
1,657,333
1
0
null
null
null
null
UTF-8
C++
false
false
2,631
h
#pragma once #include "../tabu/util/cache.h" #include "../tabu/arrays/tuple.h" #include "../tabu/cphf/iterable_utuple.h" #include "../coverage/fhCache.h" #include <stdio.h> #include <stdlib.h> #include <direct.h> #include <utility> #include <set> namespace coverage { typedef std::set<int> intSet; typedef std::pair< arrays::tuple, cphf::iterable_utuple > setId; typedef util::cache< setId, intSet * > setCacheBase; class setCache : public setCacheBase { char filename[255]; const char * dir; public: setCache( ) : setCacheBase(100000) { } void setDir( const char * dir ) { this->dir = dir; } virtual intSet * populate( const setId & id ) { // create the filename getFilename( id ); FILE * f = fopen( filename, "rb" ); int count, i, temp; fread( &count, sizeof(int), 1, f ); intSet::iterator it; intSet * set = new intSet; for ( i = 0; i < count; i++ ) { fread( &temp, sizeof(int), 1, f ); if ( i == 0 ) { it = set->insert( temp ).first; } else { it = set->insert( it, temp ); } } fclose( f ); return set; } virtual void persist( const setId & id, intSet * value ) { // create the filename getFilename( id ); FILE * f = fopen( filename, "wb" ); int count, temp; count = (int) value->size(); fwrite( &count, sizeof(int), 1, f ); intSet::iterator it; for ( it = value->begin(); it != value->end(); ++it ) { temp = *it; fwrite( &temp, sizeof(int), 1, f ); } fclose( f ); } virtual void remove( const setId & id, intSet * value ) { delete value; } protected: inline void getFilename( const setId & id ) { int i; char tmp[20]; strcpy( filename, dir ); int strength = id.first.strength(); for ( i = 0; i < strength; i++ ) { itoa( id.first[i], tmp, 10); strcat( filename, tmp ); strcat( filename, "\\" ); } for ( i = 0; i < strength; i++ ) { itoa( id.second[i], tmp, 10 ); strcat( filename, tmp ); if ( i != strength - 1 ) { strcat( filename, "-" ); } } // create the file if it does not exist if ( _access( filename, 00 ) ) { char buffer[255]; strcpy( buffer, dir ); for ( i = 0; i < strength; i++ ) { itoa( id.first[i], tmp, 10); strcat( buffer, tmp ); _mkdir( buffer ); strcat( buffer, "\\" ); } FILE * f = fopen( filename, "wb" ); int count = 0; fwrite( &count, sizeof(int), 1, f ); fclose( f ); } } }; };
[ [ [ 1, 122 ] ] ]
da249d5c8464a5a169abcb8adb6b85aa66b08fe1
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/nGENE Proj/JointPrism.h
52deb8a5bf28c6d9b78c5befaba5d627bf69b364
[]
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
1,178
h
/* --------------------------------------------------------------------------- This source file is part of nGENE Tech. Copyright (c) 2006- Wojciech Toman This program is free software. File: JointPrism.h Version: 0.01 --------------------------------------------------------------------------- */ #pragma once #ifndef __INC_JOINTPRISM_H_ #define __INC_JOINTPRISM_H_ #include "Joint.h" #include "JointFactory.h" namespace nGENE { /** Prismatic joint. @remarks This kind of Joint allows relative movement along an axis between two bodies but permits relative rotation. */ class nGENEDLL JointPrism: public Joint { EXPOSE_TYPE private: /// PhysX box descriptor NxPrismaticJointDesc* m_pPrismDesc; public: JointPrism(NxScene* _scene, SJointDesc& _desc); virtual ~JointPrism(); void init(); void cleanup(); NxJointDesc* getJointDesc(); }; /// Factory to be used for creating spherical joints. class nGENEDLL JointPrismFactory: public JointFactory { public: JointPrismFactory(); ~JointPrismFactory(); Joint* createJoint(NxScene* _scene, JOINT_DESC& _desc); }; } #endif
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 59 ] ] ]
9f078b59b2e4e1aedae9e55d6cbb14fcc61d0f3f
c1b7571589975476405feab2e8b72cdd2a592f8f
/WPILib10/Vision/MonoImage.cpp
35094456a525f280bc6b54747afc6ce633ed8800
[]
no_license
chopshop-166/frc-2010
ea9cd83f85c9eb86cc44156f21894410a9a4b0b5
e15ceff05536768c29fad54fdefe65dba9a5fab5
refs/heads/master
2021-01-21T11:40:07.493930
2010-12-10T02:04:05
2010-12-10T02:04:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,268
cpp
#include "MonoImage.h" #include "NIVision.h" MonoImage::MonoImage() : ImageBase(IMAQ_IMAGE_U8) { } /** * Look for ellipses in an image. * Given some input parameters, look for any number of ellipses in an image. * @param ellipseDescriptor Ellipse descriptor * @param curveOptions Curve options * @param shapeDetectionOptions Shape detection options * @param roi Region of Interest * @returns a vector of EllipseMatch structures (0 length vector on no match) */ vector<EllipseMatch> * MonoImage::DetectEllipses( EllipseDescriptor *ellipseDescriptor, CurveOptions *curveOptions, ShapeDetectionOptions *shapeDetectionOptions, ROI *roi) { int numberOfMatches; EllipseMatch *e = imaqDetectEllipses(image, ellipseDescriptor, curveOptions, shapeDetectionOptions, roi, &numberOfMatches); vector<EllipseMatch> *ellipses = new vector<EllipseMatch>; if (e == NULL) { return ellipses; } for (int i = 0; i < numberOfMatches; i++) { ellipses->push_back(e[i]); } imaqDispose(e); return ellipses; } vector<EllipseMatch> * MonoImage::DetectEllipses( EllipseDescriptor *ellipseDescriptor) { vector<EllipseMatch> *ellipses = DetectEllipses(ellipseDescriptor, NULL, NULL, NULL); return ellipses; }
[ [ [ 1, 43 ] ] ]
7cc8393e334589d9bcf32baaa62ce4b828e47472
bc0a05b60c7ef7180120c577e377a977abd4c725
/GameBuildings.cpp
9bbcce515ea5ef79b8d27eb7a64f83db75c00dc2
[]
no_license
swak/stonesense
7f0b821d4dcd48ba02b4c0df2850cd7355b4f2fa
54b791c019d4874c0880fc44903b26af2925231f
refs/heads/master
2021-01-06T20:37:39.613771
2011-08-04T16:55:09
2011-08-04T16:55:09
42,753,526
0
0
null
null
null
null
UTF-8
C++
false
false
7,349
cpp
#include "common.h" #include "WorldSegment.h" #include "SpriteMaps.h" #include "GameBuildings.h" #include "BuildingConfiguration.h" #include "ContentLoader.h" #include "GUI.h" //vector<BuildingConfiguration> buildingTypes; //vector <string> v_buildingtypes;//should be empty for all buildings /* int BlockNeighbourhoodType_simple(WorldSegment* segment, Block* b, bool validationFuctionProc(Block*) ){ uint32_t x,y,z; x = b->x; y = b->y; z = b->z; bool n = validationFuctionProc( segment->getBlock( x, y-1, z, true) ); bool s = validationFuctionProc( segment->getBlock( x, y+1, z, true) ); bool e = validationFuctionProc( segment->getBlock( x+1, y, z, true) ); bool w = validationFuctionProc( segment->getBlock( x-1, y, z, true) ); //bool nw = validationFuctionProc( segment->getBlock(, x-1, y-1, z) ); //bool ne = validationFuctionProc( segment->getBlock(, x+1, y-1, z) ); //bool SW = validationFuctionProc( segment->getBlock(, x-1, y+1, z) ); //bool se = validationFuctionProc( segment->getBlock(, x+1, y+1, z) ); if(!n && !s && !w && !e) return eSimpleSingle; if( n && !s && !w && !e) return eSimpleN; if(!n && !s && w && !e) return eSimpleW; if(!n && s && !w && !e) return eSimpleS; if(!n && !s && !w && e) return eSimpleE; if( n && s && !w && !e) return eSimpleNnS; if(!n && !s && w && e) return eSimpleWnE; if( n && !s && w && !e) return eSimpleNnW; if(!n && s && w && !e) return eSimpleSnW; if(!n && s && !w && e) return eSimpleSnE; if( n && !s && !w && e) return eSimpleNnE; //.... return eSimpleSingle; }*/ bool blockHasBridge(Block* b){ if(!b) return 0; return b->building.info.type == BUILDINGTYPE_BRIDGE; } dirTypes findWallCloseTo(WorldSegment* segment, Block* b){ uint32_t x,y,z; x = b->x; y = b->y; z = b->z; bool n = hasWall( segment->getBlockRelativeTo( x, y, z, eUp) ); bool s = hasWall( segment->getBlockRelativeTo( x, y, z, eDown) ); bool w = hasWall( segment->getBlockRelativeTo( x, y, z, eLeft) ); bool e = hasWall( segment->getBlockRelativeTo( x, y, z, eRight) ); if(w) return eSimpleW; if(n) return eSimpleN; if(s) return eSimpleS; if(e) return eSimpleE; return eSimpleSingle; } void ReadBuildings(DFHack::Context& DF, vector<t_building>* buildingHolder) { if(config.skipBuildings) return; if(!buildingHolder) return; DFHack::Buildings * Bld; try { Bld = DF.getBuildings(); } catch (exception &e) { WriteErr("DFhack exeption: %s\n", e.what()); config.skipBuildings = true; return; } vector<string> dummy; uint32_t numbuildings = 0; try { if (!Bld->Start(numbuildings)) return; } catch (exception &e) { WriteErr("DFhack exeption: %s\n", e.what()); config.skipBuildings = true; return; } t_building tempbuilding; uint32_t index = 0; while(index < numbuildings){ try { Bld->Read(index, tempbuilding); } catch (exception &e) { WriteErr("DFhack exeption: %s\n", e.what()); config.skipBuildings = true; return; } buildingHolder->push_back(tempbuilding); index++; } Bld->Finish(); } void MergeBuildingsToSegment(vector<t_building>* buildings, WorldSegment* segment){ t_building tempbuilding; uint32_t numBuildings = (uint32_t)buildings->size(); for(uint32_t i=0; i < numBuildings; i++){ tempbuilding = (*buildings)[i]; //int bheight = tempbuilding.y2 - tempbuilding.y1; for(uint32_t yy = tempbuilding.y1; yy <= tempbuilding.y2; yy++) for(uint32_t xx = tempbuilding.x1; xx <= tempbuilding.x2; xx++){ Block* b; bool inside = segment->CoordinateInsideSegment(xx,yy, tempbuilding.z); if(inside){ //want hashtable :( // still need to test for b, because of ramp/building overlap b = segment->getBlock( xx, yy, tempbuilding.z); if(!b){ //inside segment, but no block to represent it b = new Block(segment); b->x = xx; b->y = yy; b->z = tempbuilding.z; segment->addBlock( b ); } if( b ){ //handle special case where zones and stockpiles overlap buildings, and try to replace them if(b->building.info.type != BUILDINGTYPE_NA && tempbuilding.type == TranslateBuildingName("building_civzonest", contentLoader.classIdStrings ) ) continue; if(b->building.info.type != BUILDINGTYPE_NA && tempbuilding.type == TranslateBuildingName("building_stockpilest", contentLoader.classIdStrings ) ) continue; b->building.index = i; b->building.info = tempbuilding; b->building.custom_building_type = contentLoader.Bld->GetCustomWorkshopType(tempbuilding); } } } } //all blocks in the segment now have their building info loaded. //now set their sprites /* for(uint32_t i=0; i < segment->getNumBlocks(); i++){ Block* b = segment->getBlock( i ); if( b->building.info.type != BUILDINGTYPE_NA && b->building.info.type != BUILDINGTYPE_BLACKBOX ) loadBuildingSprites( b ); } */ } void loadBuildingSprites ( Block* b){ bool foundBlockBuildingInfo = false; if (b == NULL) { WriteErr("Null Block skipped in loadBuildingSprites\n"); return; } if(b->building.custom_building_type == -1) { uint32_t numBuildings = (uint32_t)contentLoader.buildingConfigs.size(); for(uint32_t i = 0; i < numBuildings; i++){ BuildingConfiguration& conf = contentLoader.buildingConfigs[i]; if(b->building.info.type != conf.gameID) continue; //check all sprites for one that matches all conditions if (conf.sprites != NULL && conf.sprites->BlockMatches(b)) { foundBlockBuildingInfo = true; } break; } } else { uint32_t numCustBuildings = (uint32_t)contentLoader.customBuildingConfigs.size(); for(uint32_t i = 0; i < numCustBuildings; i++){ BuildingConfiguration& cust = contentLoader.customBuildingConfigs[i]; if(b->building.custom_building_type != cust.gameID) continue; //check all sprites for one that matches all conditions if (cust.sprites != NULL && cust.sprites->BlockMatches(b)) { foundBlockBuildingInfo = true; } break; } } //add yellow box, if needed. But only if the building was not found (this way we can have blank slots in buildings) if(b->building.sprites.size() == 0 && foundBlockBuildingInfo == false){ c_sprite unknownBuildingSprite; unknownBuildingSprite.set_defaultsheet(IMGObjectSheet); unknownBuildingSprite.set_fileindex(-1); unknownBuildingSprite.set_sheetindex(0); b->building.sprites.push_back( unknownBuildingSprite ); } } /*TODO: this function takes a massive amount of work, looping all buildings for every block*/ bool BlockHasSuspendedBuilding(vector<t_building>* buildingList, Block* b){ uint32_t num = (uint32_t)buildingList->size(); for(uint32_t i=0; i < num; i++){ t_building* building = &(*buildingList)[i]; //boundry check if(b->z != building->z) continue; if(b->x < building->x1 || b->x > building->x2) continue; if(b->y < building->y1 || b->y > building->y2) continue; if(building->type == TranslateBuildingName("building_bridgest", contentLoader.classIdStrings )){ return true; } if(building->type == TranslateBuildingName("building_civzonest", contentLoader.classIdStrings )) return true; } return false; }
[ "Japa.Mala.Illo@4d48de78-bd66-11de-9616-7b1d4728551e", "peterix@4d48de78-bd66-11de-9616-7b1d4728551e", "japa.mala.illo@4d48de78-bd66-11de-9616-7b1d4728551e" ]
[ [ [ 1, 6 ], [ 8, 64 ], [ 66, 148 ], [ 150, 167 ], [ 169, 174 ], [ 188, 189 ], [ 206, 207 ], [ 212, 234 ] ], [ [ 7, 7 ] ], [ [ 65, 65 ], [ 149, 149 ], [ 168, 168 ], [ 175, 187 ], [ 190, 205 ], [ 208, 211 ] ] ]
3b23f675a82d35706ba8b2400b39b40fee517ab6
2112057af069a78e75adfd244a3f5b224fbab321
/branches/ref1/src-root/src/common/world/client_zone.cpp
0f6076b8fb3308af47100ffb40c7b2d1bfa35067
[]
no_license
blockspacer/ireon
120bde79e39fb107c961697985a1fe4cb309bd81
a89fa30b369a0b21661c992da2c4ec1087aac312
refs/heads/master
2023-04-15T00:22:02.905112
2010-01-07T20:31:07
2010-01-07T20:31:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,274
cpp
/** * @file client_zone.cpp * Client-side zone class */ /* Copyright (C) 2005 ireon.org developers council * $Id$ * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ #include "stdafx.h" #include "world/client_zone.h" #include "world/client_static.h" #include "resource/resource_manager.h" CClientZone::CClientZone() { }; CClientZone::~CClientZone() { }; bool CClientZone::load(const String& resourceName) { CLog::instance()->log(CLog::msgFlagResources,CLog::msgLvlInfo,"Loading zone from '%s'.\n",resourceName.c_str()); DataPtr dPtr = CResourceManager::instance()->load(resourceName); if( !dPtr ) { CLog::instance()->log(CLog::msgLvlError,"Error loading zone: resource not found.\n",resourceName.c_str()); return false; } TiXmlDocument doc; std::stringstream buf; buf.write(dPtr->data(),dPtr->size()); buf >> doc; if (doc.Error()) { CLog::instance()->log(CLog::msgFlagResources, CLog::msgLvlError, _("Error loading zone: XML parser returned an error: %s\n"), doc.ErrorDesc()); return false; } TiXmlNode* root = doc.FirstChild(); while( root && root->Type() == TiXmlNode::DECLARATION ) root = root->NextSibling(); if( !root || root->Type() != TiXmlNode::ELEMENT || strcmp(root->ToElement()->Value(),"Zone") ) { CLog::instance()->log(CLog::msgFlagResources, CLog::msgLvlError, _("Error loading zone: resource isn't zone. %s\n"),root->Value()); return false; }; TiXmlNode* option; for( option = root->FirstChild(); option; option = option->NextSibling() ) if( !processOption(option) ) { CLog::instance()->log(CLog::msgFlagResources, CLog::msgLvlError, _("Error loading zone: error in file near '%s'.\n"),option->Value()); return false; }; return true; }; bool CClientZone::processOption(TiXmlNode* option) { if( !option ) return false; if( !option->Type() == TiXmlNode::ELEMENT ) return true; const char* name = option->Value(); if( !strcmp(name,"Static") ) { if( !processStatic(option) ) return false; } else { return false; } return true; }; bool CClientZone::processStatic(TiXmlNode *node) { TiXmlAttribute* attr = node->ToElement()->FirstAttribute(); StaticPtr st; while( attr ) { if( !attr || !attr->Name() || !attr->Value() ) return false; if( !st ) { if( !strcmp(attr->Name(),"Name") ) { StaticPrototypePtr prot = I_WORLD->getStaticPrototype(attr->Value()); if( prot ) st.reset( new CClientStaticObject(prot) ); } else if( !strcmp(attr->Name(),"Id") ) { StaticPrototypePtr prot = I_WORLD->getStaticPrototype(StringConverter::parseLong(attr->Value())); if( prot ) st.reset( new CClientStaticObject(prot) ); } } else { if( !strcmp(attr->Name(),"Position") ) { StringVector vec = StringConverter::parseStringVector(attr->Value()); if( vec.size() < 3 ) return false; Vector3 pos; pos.x = StringConverter::parseReal(vec[0]); pos.y = StringConverter::parseReal(vec[1]); pos.z = StringConverter::parseReal(vec[2]); st->setPosition(pos); } else if( !strcmp(attr->Name(),"Rotation") ) { Radian rot; rot = Radian(StringConverter::parseReal(attr->Value())); st->setRotation(rot); } } attr = attr->Next(); } if( st) { m_statics.push_back(st); I_WORLD->addStatic(st); } return true; }; void CClientZone::unload() { for( std::vector<StaticPtr>::iterator it = m_statics.begin(); it != m_statics.end(); ++it ) I_WORLD->removeStatic(*it); };
[ [ [ 1, 153 ] ] ]
f66302954c68dfcac6bd6680f9dcdefe7bdfc94b
c2d3b2484afb98a6447dfacfe733b98e8778e0a9
/src/Images/SEJpegImage.h
2ce53a7151a7ea711af123fabeb522671c11f25d
[]
no_license
soniccat/3dEngine
cfb73af5c9b25d61dd77e882a31f4a62fbd3f036
abf1d49a1756fb0217862f829b1ec7877a59eaf4
refs/heads/master
2020-05-15T07:07:22.751350
2010-03-27T13:05:38
2010-03-27T13:05:38
469,267
3
0
null
null
null
null
UTF-8
C++
false
false
285
h
#ifndef SEJpegImage_H #define SEJpegImage_H #include "SEIncludeLibrary.h" #include "SEDefinition.h" #include "SEImage.h" class SEJpegImage: public SEImage { public: SEJpegImage(void); ~SEJpegImage(void); void Load( const sechar* file ); }; #endif SEJpegImage_H
[ "[email protected]", "ALEX@.(none)" ]
[ [ [ 1, 17 ] ], [ [ 18, 18 ] ] ]
93c4a7dd94b0250040b265c432f5c4d34b7a1e21
9176b0fd29516d34cfd0b143e1c5c0f9e665c0ed
/CS_153_Data_Structures/assignment7/test_avl.cpp
0c2bd50c0b62d001aeb8ac20e51f774df275c1dd
[]
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
5,993
cpp
////////////////////////////////////////////////////////////////////// /// @file test_avl.cpp /// @author James Anderson Section A /// @brief Implementation file for test_avl class for assignment 7 ////////////////////////////////////////////////////////////////////// #include "test_avl.h" CPPUNIT_TEST_SUITE_REGISTRATION (Test_avl); void Test_avl::test_constructor () { Avl<int> test; // Constructor check CPPUNIT_ASSERT (test.size () == 0); } void Test_avl::test_insert () { Avl<int> test; Avl<int>::InOrder k; int fixed[15] = {16,8,24,4,12,20,28,2,6,10,14,18,22,26,30} ; int in[15] = {2,4,6,8,10,12,14,16,18,20,22,24,26,28,30} ; // Fill the avl for ( int i = 0 ; i < 15 ; i++ ) { test.insert(fixed[i]); CPPUNIT_ASSERT (test.size () == i+1 ); } int j = 0 ; //check the fill for ( k = test.in_begin() ; k != test.in_end() ; k++ ) { CPPUNIT_ASSERT (in[j] == *k); j++ ; } } void Test_avl::test_remove () { Avl<int> test; Avl<int>::InOrder k; int fixed[15] = {16,8,24,4,12,20,28,2,6,10,14,18,22,26,30} ; //try removing when empty try { test.remove(226) ; CPPUNIT_ASSERT (false); } catch (Exception& e) { CPPUNIT_ASSERT (CONTAINER_EMPTY == e.error_code ()); } // Fill the avl for ( int i = 0 ; i < 15 ; i++ ) { test.insert(fixed[i]); CPPUNIT_ASSERT (test.size () == i+1 ); } //test removing a value that dosent exist try { test.remove(226) ; CPPUNIT_ASSERT (false); } catch (Exception& e) { CPPUNIT_ASSERT (NOT_FOUND == e.error_code ()); } //test removing values test.remove (16) ; for ( k = test.in_begin() ; k != test.in_end() ; k++ ) { CPPUNIT_ASSERT (16 != *k); } //linked test.remove (24) ; for ( k = test.in_begin() ; k != test.in_end() ; k++ ) { CPPUNIT_ASSERT (24 != *k); } //leafe test.remove (2) ; for ( k = test.in_begin() ; k != test.in_end() ; k++ ) { CPPUNIT_ASSERT (2 != *k); } } void Test_avl::test_clear () { Avl<int> test; Avl<int>::InOrder k; int fixed[15] = {16,8,24,4,12,20,28,2,6,10,14,18,22,26,30} ; // Fill the avl for ( int i = 0 ; i < 15 ; i++ ) { test.insert(fixed[i]); CPPUNIT_ASSERT (test.size () == i+1 ); } //clear and test test.clear() ; CPPUNIT_ASSERT (test.size () == 0 ); CPPUNIT_ASSERT (test.empty () == 1 ); } void Test_avl::test_empty () { Avl<int> test; Avl<int>::InOrder k; int fixed[15] = {16,8,24,4,12,20,28,2,6,10,14,18,22,26,30} ; // Fill the avl for ( int i = 0 ; i < 15 ; i++ ) { test.insert(fixed[i]); CPPUNIT_ASSERT (test.size () == i+1 ); } //pretest empty CPPUNIT_ASSERT (test.empty () == 0 ); //clear and test test.clear() ; CPPUNIT_ASSERT (test.size () == 0 ); CPPUNIT_ASSERT (test.empty () == 1 ); } void Test_avl::test_size() { Avl<int> test; Avl<int>::InOrder k; int fixed[15] = {16,8,24,4,12,20,28,2,6,10,14,18,22,26,30} ; // Fill the avl for ( int i = 0 ; i < 15 ; i++ ) { test.insert(fixed[i]); CPPUNIT_ASSERT (test.size () == i+1 ); } //pretest size CPPUNIT_ASSERT (test.size () == 15 ); //clear and test test.clear() ; CPPUNIT_ASSERT (test.size () == 0 ); CPPUNIT_ASSERT (test.empty () == 1 ); } void Test_avl::test_pre () { Avl<int> test; Avl<int>::PreOrder k; int fixed[15] = {16,8,24,4,12,20,28,2,6,10,14,18,22,26,30} ; int pre[15] = {16,8,4,2,6,12,10,14,24,20,18,22,28,26,30} ; // Fill the avl for ( int i = 0 ; i < 15 ; i++ ) { test.insert(fixed[i]); CPPUNIT_ASSERT (test.size () == i+1 ); } int j = 0 ; //check the fill for ( k = test.pre_begin() ; k != test.pre_end() ; k++ ) { CPPUNIT_ASSERT (pre[j] == *k); j++ ; } } void Test_avl::test_in () { Avl<int> test; Avl<int>::InOrder k; int fixed[15] = {16,8,24,4,12,20,28,2,6,10,14,18,22,26,30} ; int in[15] = {2,4,6,8,10,12,14,16,18,20,22,24,26,28,30} ; // Fill the avl for ( int i = 0 ; i < 15 ; i++ ) { test.insert(fixed[i]); CPPUNIT_ASSERT (test.size () == i+1 ); } int j = 0 ; //check the fill for ( k = test.in_begin() ; k != test.in_end() ; k++ ) { CPPUNIT_ASSERT (in[j] == *k); j++ ; } } void Test_avl::test_post () { Avl<int> test; Avl<int>::PostOrder k; int fixed[15] = {16,8,24,4,12,20,28,2,6,10,14,18,22,26,30} ; int post[15] = {2,6,4,10,14,12,8,18,22,20,26,30,28,24,16} ; // Fill the avl for ( int i = 0 ; i < 15 ; i++ ) { test.insert(fixed[i]); CPPUNIT_ASSERT (test.size () == i+1 ); } int j = 0 ; //check the fill for ( k = test.post_begin() ; k != test.post_end() ; k++ ) { CPPUNIT_ASSERT (post[j] == *k); j++ ; } } void Test_avl::test_copy () { Avl<int> test; Avl<int>::InOrder k; Avl<int>::InOrder j; int fixed[15] = {16,8,24,4,12,20,28,2,6,10,14,18,22,26,30} ; // Fill the avl for ( int i = 0 ; i < 15 ; i++ ) { test.insert(fixed[i]); CPPUNIT_ASSERT (test.size () == i+1 ); } //preform copy constructor Avl<int> test2(test); //check that the two are the same j = test2.in_begin() ; for ( k = test.in_begin() ; k != test.in_end() ; k++ ) { CPPUNIT_ASSERT (*j == *k); j++ ; } CPPUNIT_ASSERT (*j == *k); } void Test_avl::test_assignment () { Avl<int> test1; Avl<int> test2; Avl<int>::InOrder k; Avl<int>::InOrder j; int fixed[15] = {16,8,24,4,12,20,28,2,6,10,14,18,22,26,30} ; int junk[15] = {45,25,21,48,16,79,1,3,2,4,7,6,8,18,26} ; // Fill both the bsts for ( int i = 0 ; i < 15 ; i++ ) { test1.insert(fixed[i]); test2.insert(junk[i]); CPPUNIT_ASSERT (test1.size () == i+1 ); CPPUNIT_ASSERT (test2.size () == i+1 ); } //preform assignment test2 = test1 ; //check that the two are the same j = test2.in_begin() ; for ( k = test1.in_begin() ; k != test1.in_end() ; k++ ) { CPPUNIT_ASSERT (*j == *k); j++ ; } CPPUNIT_ASSERT (*j == *k); }
[ [ [ 1, 285 ] ] ]
de728e40cf1bd06e117e61da26e6d982c9f0dd66
0ac07f6ce192d04485b494ade03577f3abaf145a
/test/test2.cpp
b9a1031433780156ddfe7385f1a74fd8f4676759
[]
no_license
pabloc11/CS249A-Assign2
7b22136a78db09b34f86eb3e44423675b29ed46b
3d29e53daa7f00027f75ad445327c01218189947
refs/heads/master
2021-01-10T20:59:22.131949
2011-12-09T07:43:31
2011-12-09T07:43:31
2,668,931
0
0
null
null
null
null
UTF-8
C++
false
false
11,679
cpp
#include <string> #include <ostream> #include <iostream> #include <string> #include "Instance.h" /** * sample test cases for CS249A aut11-12 students * author: anant bhardwaj * date: 11/7/2011 * */ using std::cout; using std::cerr; using std::endl; using std::string; int main(int argc, char *argv[]) { Ptr<Instance::Manager> manager = shippingInstanceManager(); if (manager == NULL) { cerr << "Unexpected NULL manager." << endl; return 1; } Ptr<Instance> stats = manager->instanceNew("myStats", "Stats"); if (stats == NULL) { cerr << "Unexpected NULL stats." << endl; return 1; } Ptr<Instance> fleet = manager->instanceNew("myFleet", "Fleet"); if (fleet == NULL) { cerr << "Unexpected NULL." << endl; return 1; } fleet->attributeIs("Boat, speed", "60"); fleet->attributeIs("Truck, speed", "70"); fleet->attributeIs("Boat, cost", "30"); fleet->attributeIs("Truck, cost", "50"); cout << "fleet->attribute('Boat, speed'): " << fleet->attribute("Boat, speed") << endl; cout << "fleet->attribute('Truck, speed'): " << fleet->attribute("Truck, speed") << endl; cout << "fleet->attribute('Boat, cost'): " << fleet->attribute("Boat, cost") << endl; cout << "fleet->attribute('Truck, cost'): " << fleet->attribute("Truck, cost") << endl; // --- Create instances // -- Locations // customers Ptr<Instance> customer1 = manager->instanceNew("customer1", "Customer"); // ports Ptr<Instance> port1 = manager->instanceNew("port1", "Port"); Ptr<Instance> port2 = manager->instanceNew("port2", "Port"); Ptr<Instance> port3 = manager->instanceNew("port3", "Port"); // Truck Terminal Ptr<Instance> truckTerminal1 = manager->instanceNew("truckterminal1", "Truck terminal"); // Boat Terminal Ptr<Instance> boatTerminal1 = manager->instanceNew("boatterminal1", "Boat terminal"); if (customer1 == NULL || port1 == NULL || port2 == NULL || port3 == NULL || truckTerminal1 == NULL || boatTerminal1 == NULL) { cerr << "Unexpected NULL customer or port." << endl; return 1; } // -- Segments // boat Ptr<Instance> boatSeg1 = manager->instanceNew("boatSeg1", "Boat segment"); Ptr<Instance> boatSeg2 = manager->instanceNew("boatSeg2", "Boat segment"); Ptr<Instance> boatSeg3 = manager->instanceNew("boatSeg3", "Boat segment"); Ptr<Instance> boatSeg4 = manager->instanceNew("boatSeg4", "Boat segment"); Ptr<Instance> boatSeg5 = manager->instanceNew("boatSeg5", "Boat segment"); Ptr<Instance> boatSeg6 = manager->instanceNew("boatSeg6", "Boat segment"); /*Ptr<Instance> boatSeg7 = manager->instanceNew("boatSeg6", "Boat segment"); if (boatSeg7 != NULL) { cout << "Creating instance with same name -- error \n"; }*/ // truck Ptr<Instance> truckSeg1 = manager->instanceNew("truckSeg1", "Truck segment"); Ptr<Instance> truckSeg2 = manager->instanceNew("truckSeg2", "Truck segment"); Ptr<Instance> truckSeg3 = manager->instanceNew("truckSeg3", "Truck segment"); Ptr<Instance> truckSeg4 = manager->instanceNew("truckSeg4", "Truck segment"); Ptr<Instance> truckSeg5 = manager->instanceNew("truckSeg5", "Truck segment"); Ptr<Instance> truckSeg6 = manager->instanceNew("truckSeg6", "Truck segment"); Ptr<Instance> truckSeg7 = manager->instanceNew("truckSeg7", "Truck segment"); Ptr<Instance> truckSeg8 = manager->instanceNew("truckSeg8", "Truck segment"); if (boatSeg1 == NULL || boatSeg2 == NULL || truckSeg1 == NULL || truckSeg2 == NULL) { cerr << "Unexpected NULL segment." << endl; return 1; } // connections // customer1 <---> port1 truckSeg1->attributeIs("source", "customer1"); truckSeg2->attributeIs("source", "port1"); truckSeg1->attributeIs("return segment", "truckSeg2"); cout << "truckSeg1->attribute('source'): " << truckSeg1->attribute("source") << endl; cout << "truckSeg2->attribute('source'): " << truckSeg2->attribute("source") << endl; cout << "truckSeg1->attribute('return segment'): " << truckSeg1->attribute("return segment") << endl; cout << "truckSeg2->attribute('return segment'): " << truckSeg2->attribute("return segment") << endl; // customer1 <---> truck terminal 1 truckSeg3->attributeIs("source", "port1"); truckSeg4->attributeIs("source", "truckterminal1"); truckSeg3->attributeIs("return segment", "truckSeg4"); cout << "truckSeg3->attribute('source'): " << truckSeg3->attribute("source") << endl; cout << "truckSeg4->attribute('source'): " << truckSeg4->attribute("source") << endl; cout << "truckSeg3->attribute('return segment'): " << truckSeg3->attribute("return segment") << endl; cout << "truckSeg4->attribute('return segment'): " << truckSeg4->attribute("return segment") << endl; // truck terminal 1 <---> port 2 truckSeg5->attributeIs("source", "truckterminal1"); truckSeg6->attributeIs("source", "port2"); truckSeg5->attributeIs("return segment", "truckSeg6"); cout << "truckSeg5->attribute('source'): " << truckSeg5->attribute("source") << endl; cout << "truckSeg6->attribute('source'): " << truckSeg6->attribute("source") << endl; cout << "truckSeg5->attribute('return segment'): " << truckSeg5->attribute("return segment") << endl; cout << "truckSeg6->attribute('return segment'): " << truckSeg6->attribute("return segment") << endl; // truck terminal 1 <---> port 3 truckSeg7->attributeIs("source", "truckterminal1"); truckSeg8->attributeIs("source", "port3"); truckSeg7->attributeIs("return segment", "truckSeg8"); cout << "truckSeg7->attribute('source'): " << truckSeg7->attribute("source") << endl; cout << "truckSeg8->attribute('source'): " << truckSeg8->attribute("source") << endl; cout << "truckSeg7->attribute('return segment'): " << truckSeg7->attribute("return segment") << endl; cout << "truckSeg8->attribute('return segment'): " << truckSeg8->attribute("return segment") << endl; // port2 <---> boat terminal 1 boatSeg1->attributeIs("source", "port2"); boatSeg2->attributeIs("source", "boatterminal1"); boatSeg1->attributeIs("return segment", "boatSeg2"); cout << "boatseg1->attribute('source'): " << boatSeg1->attribute("source") << endl; cout << "boatseg2->attribute('source'): " << boatSeg2->attribute("source") << endl; cout << "boatseg1->attribute('return segment'): " << boatSeg1->attribute("return segment") << endl; cout << "boatseg2->attribute('return segment'): " << boatSeg2->attribute("return segment") << endl; // port3 <---> boat terminal 1 boatSeg3->attributeIs("source", "boatterminal1"); boatSeg4->attributeIs("source", "port3"); boatSeg3->attributeIs("return segment", "boatSeg4"); cout << "boatseg3->attribute('source'): " << boatSeg3->attribute("source") << endl; cout << "boatseg4->attribute('source'): " << boatSeg4->attribute("source") << endl; cout << "boatseg3->attribute('return segment'): " << boatSeg3->attribute("return segment") << endl; cout << "boatseg4->attribute('return segment'): " << boatSeg4->attribute("return segment") << endl; // boat terminal 1 <---> customer1 boatSeg5->attributeIs("source", "boatterminal1"); boatSeg6->attributeIs("source", "customer1"); boatSeg5->attributeIs("return segment", "boatSeg6"); cout << "boatseg5->attribute('source'): " << boatSeg5->attribute("source") << endl; cout << "boatseg6->attribute('source'): " << boatSeg6->attribute("source") << endl; cout << "boatseg5->attribute('return segment'): " << boatSeg5->attribute("return segment") << endl; cout << "boatseg6->attribute('return segment'): " << boatSeg6->attribute("return segment") << endl; // -- Segment lengths boatSeg1->attributeIs("length", "400"); boatSeg2->attributeIs("length", "300"); boatSeg3->attributeIs("length", "200"); boatSeg4->attributeIs("length", "500"); boatSeg5->attributeIs("length", "600"); boatSeg6->attributeIs("length", "700"); truckSeg1->attributeIs("length", "800"); truckSeg2->attributeIs("length", "900"); truckSeg3->attributeIs("length", "200"); truckSeg4->attributeIs("length", "400"); truckSeg5->attributeIs("length", "500"); truckSeg6->attributeIs("length", "600"); truckSeg7->attributeIs("length", "800"); truckSeg8->attributeIs("length", "1000"); // -- Segment difficulties boatSeg1->attributeIs("difficulty", "1"); boatSeg2->attributeIs("difficulty", "1.4"); boatSeg3->attributeIs("difficulty", "1.8"); boatSeg4->attributeIs("difficulty", "2"); boatSeg5->attributeIs("difficulty", "4"); boatSeg6->attributeIs("difficulty", "3"); truckSeg1->attributeIs("difficulty", "2"); truckSeg2->attributeIs("difficulty", "3"); truckSeg3->attributeIs("difficulty", "4.5"); truckSeg4->attributeIs("difficulty", "5"); truckSeg5->attributeIs("difficulty", "1"); truckSeg6->attributeIs("difficulty", "1.5"); truckSeg7->attributeIs("difficulty", "1.5"); truckSeg8->attributeIs("difficulty", "1.7"); // -- Segment expedite support boatSeg1->attributeIs("expedite support", "yes"); boatSeg2->attributeIs("expedite support", "yes"); boatSeg3->attributeIs("expedite support", "yes"); boatSeg4->attributeIs("expedite support", "yes"); boatSeg5->attributeIs("expedite support", "yes"); boatSeg6->attributeIs("expedite support", "yes"); truckSeg1->attributeIs("expedite support", "yes"); truckSeg2->attributeIs("expedite support", "yes"); truckSeg3->attributeIs("expedite support", "yes"); truckSeg4->attributeIs("expedite support", "yes"); truckSeg5->attributeIs("expedite support", "yes"); truckSeg6->attributeIs("expedite support", "yes"); truckSeg7->attributeIs("expedite support", "yes"); truckSeg8->attributeIs("expedite support", "yes"); // -- Connectivity queries Ptr<Instance> conn = manager->instanceNew("myConn", "Conn"); if (conn == NULL) { cerr << "Unexpected NULL conn." << endl; return 1; } cout << "**** explore customer1 : expedited****" << endl; cout << conn->attribute("explore customer1 : expedited distance 10000 time 1000") << endl; cout << endl; cout << "*** connect port3 : truckterminal1 ****" << endl; cout << conn->attribute("connect port3 : truckterminal1") << endl; cout << endl; // -- Statistics queries cout << "===== Stats attributes =====" << endl; cout << " --- Segments --- " << endl; cout << "# Truck segments : " << stats->attribute("Truck segment") << endl; cout << "# Boat segments : " << stats->attribute("Boat segment") << endl; cout << "Expediting % : " << stats->attribute("expedite percentage") << endl; cout << " --- Terminals --- " << endl; cout << "# Plane terminals: " << stats->attribute("Plane terminal") << endl; cout << "# Truck terminals: " << stats->attribute("Truck terminal") << endl; cout << "# Boat terminals: " << stats->attribute("Boat terminal") << endl; cout << " --- Ports and customers --- " << endl; cout << "# Ports : " << stats->attribute("Port") << endl; cout << "# Customer : " << stats->attribute("Customer") << endl; cerr << "Done!" << endl; return 0; }
[ [ [ 1, 82 ], [ 84, 85 ], [ 87, 259 ] ], [ [ 83, 83 ], [ 86, 86 ] ] ]
15b45bc2e0164841750e0ff783a5dd6f9eb673b1
da9e4cd28021ecc9e17e48ac3ded33b798aae59c
/SRC/DRIVERS/DISPLAY/INC/regctrl_g2d.h
ba33f6aeb8f095980b762343021401d2aed74680
[]
no_license
hibive/sjmt6410pm090728
d45242e74b94f954cf0960a4392f07178088e560
45ceea6c3a5a28172f7cd0b439d40c494355015c
refs/heads/master
2021-01-10T10:02:35.925367
2011-01-27T04:22:44
2011-01-27T04:22:44
43,739,703
1
1
null
null
null
null
UTF-8
C++
false
false
3,416
h
// // Copyright (c) Samsung Electronics CO., LTD. All rights reserved. // /*++ THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. Module Name: regctrl_g2d.h Abstract: defines for FIMGSE-2D Graphics Accelerator Register Controller Notes: Header to define the FIMGSE-2D Register Controller class --*/ #ifndef __REGCTRL_G2D_H__ #define __REGCTRL_G2D_H__ #include <ceddk.h> #include <g2d_reg.h> /** * For Hardware Specific Macro **/ #define G2D_DE_STATUS_FA_BIT (1<<9) /// Each command will be issued to 2D engine. /// But if 2D engine is not idle, command will be pushed to COMMAND FIFO, /// and Related Parameter registers also will be pushed to COMMAND FIFO /// For each command, required FIFO size can be variable(?) #define G2D_COMMANDFIFO_SIZE (32) //< 32-word size #define G2D_OPERAND3_PAT_BIT (0<<13) #define G2D_OPERAND3_FG_BIT (1<<13) /** * @brief Rotation Degree and flip setting for register setting. FLIP_X means that up-down inversion, FLIP_Y means that left-right inversion */ typedef enum __G2D_ROT_TYPE { ROT_0=(0x1<<0), ROT_90=(0x1<<1), ROT_180=(0x1<<2), ROT_270=(0x1<<3), FLIP_X=(0x1<<4), FLIP_Y=(0x1<<5) } ROT_TYPE; typedef enum { G2D_OPERAND3_PAT, G2D_OPERAND3_FG } G2D_OPERAND3; class RegCtrlG2D { public: RegCtrlG2D(); virtual ~RegCtrlG2D(); /// For HW Control void WaitForIdleStatus(void); bool WaitForFinish(void); void WaitForEmptyFifo() { this->RequestEmptyFifo(G2D_COMMANDFIFO_SIZE);} int CheckFifo(); void IntEnable(void); void IntDisable(void); void IntPendingClear(void); void SetClipWindow(PRECTL prtClipWindow); void Set3rdOperand(G2D_OPERAND3 e3rdOp); protected: volatile G2D_REG * m_pG2DReg; void Reset(void); void SetEndian(bool bEndian); void SetRopValue(DWORD uRopVal); /// For Interrupt Handling void IntEnableForDeEngineFinish(void); void IntEnableForCmdFinish(void); void IntEnableForOverflow(bool bFifo, BYTE ucFifoLevel); void InterruptDisAll(void); int RequestEmptyFifo(DWORD uEmptyFifo); void SetFirstBitBLTData(DWORD uFirstData); void SetNextBitBLTData(DWORD uNextData); /// For Rotation Setting void SetRotationMode(ROT_TYPE uRotationType); void SetRotationOrg(WORD usRotOrgX, WORD usRotOrgY); void SetRotationOrgX(WORD usRotOrgX); void SetRotationOrgY(WORD usRotOrgY); /// For Stretching inline void SetXIncr(DWORD uXIncr) { m_pG2DReg->X_INCR = uXIncr; } inline void SetYIncr(DWORD uYIncr) { m_pG2DReg->Y_INCR = uYIncr; } /// For Transfer data region setting void SetCoordinateSrcBlock(DWORD uStartX, DWORD uStartY, DWORD uEndX, DWORD uEndY); void SetCoordinateDstBlock(DWORD uStartX, DWORD uStartY, DWORD uEndX, DWORD uEndY); }; #endif //__REGCTRL_G2D_H__
[ "jhlee74@a3c55b0e-9d05-11de-8bf8-05dd22f30006" ]
[ [ [ 1, 107 ] ] ]
eaa862e02a1170c7eb560970bc298bbfa0e046f5
521721c2e095daf757ad62a267b1c0f724561935
/bsRandomNumberGenerator.h
d2dec117fc97a292553ef8d923674e313007bf42
[]
no_license
MichaelSPG/boms
251922d78f2db85ece495e067bd56a1e9fae14b1
23a13010e0aaa79fea3b7cf1b23e2faab02fa5d4
refs/heads/master
2021-01-10T16:23:51.722062
2011-12-08T00:04:33
2011-12-08T00:04:33
48,052,727
1
0
null
null
null
null
UTF-8
C++
false
false
2,443
h
#pragma once #include <xnamath.h> #include "bsAssert.h" /* Very basic random number generator. Can generate random vectors and rotations. Based on fast_rand from http://software.intel.com/en-us/articles/fast-random-number-generator-on-the-intel-pentiumr-4-processor/ */ class bsRandomNumberGenerator { public: bsRandomNumberGenerator(unsigned int seed) : mSeed(seed) {} //Unsigned int in range [0, UINT_MAX). unsigned int uint() { mSeed = 214013 * mSeed + 2531011; return mSeed; } //Float in range [0, 1]. float float01() { const unsigned int randomUint32 = uint(); return (float)randomUint32 / (float)UINT_MAX; } //Float in range [-1, 1]. float float11() { return float01() * 2.0f - 1.0f; } //Float in range [min, max]. float range(float min, float max) { BS_ASSERT2(min < max, "Min must be less than max"); const float f01 = float01(); return min + f01 * (max - min); } //Returns int in range [min, max) int range(int min, int max) { BS_ASSERT2(min < max, "Min must be less than max"); const float f01 = float01(); return (int)(min + f01 * (max - min)); } //Vector with all 4 components in range [0, 1]. XMVECTOR vector01() { return XMVectorSet(float01(), float01(), float01(), float01()); } //Vector with all 4 components in range [-1, 1]. XMVECTOR vector11() { return XMVectorSet(float11(), float11(), float11(), float11()); } //Vector with components in range [min, max]. //Returned vector will have each of its components in ranges described by parameters. //x = randomRange(min.x, max.x), etc. XMVECTOR vectorRange(const XMVECTOR& min, const XMVECTOR& max) { BS_ASSERT2(XMVector4Less(min, max), "Min must be less than max"); const XMVECTOR delta = XMVectorSubtract(max, min); const XMVECTOR v01 = vector01(); return XMVectorAdd(min, XMVectorMultiply(delta, v01)); } //Vector wtih all 4 components in range [min, max]. XMVECTOR vectorRange(float min, float max) { BS_ASSERT2(min < max, "Min must be less than max"); return XMVectorSet(range(min, max), range(min, max), range(min, max), range(min, max)); } //Quaternion with normalized random rotation. XMVECTOR rotation() { const XMVECTOR rot = XMVectorSet(float11(), float11(), float11(), float11()); return XMQuaternionNormalize(rot); } private: unsigned int mSeed; };
[ [ [ 1, 100 ] ] ]
d55441dd440bdb69b8764e4997778adcb3bcd65f
c0e9f18941ca50892c0a37c55663a2f8f5afa10b
/XMega_Code/include/DallasTemperature.cpp
00adb8ceba0cf54dff9d9aebb7d635d5deae5e48
[]
no_license
sandro2/xmega-qrp
bc3bab64b2e8dc1cfd0b4915c5925fed7a2d36fe
8550a61f83333006a0233d33fabb60d733ff0f2d
refs/heads/master
2016-09-11T02:55:43.773029
2010-10-25T04:51:51
2010-10-25T04:51:51
34,281,354
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
17,924
cpp
// This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // 'Ported' to the XMega. // -- Mark Jessop, October 4, 2010 #include "DallasTemperature.h" #define F_CPU 32000000UL #include <util/delay.h> extern "C" { //#include "WConstants.h" } #define delay(time) _delay_ms(time) DallasTemperature::DallasTemperature(OneWire* _oneWire) #if REQUIRESALARMS : _AlarmHandler(&defaultAlarmHandler) #endif { _wire = _oneWire; devices = 0; parasite = false; conversionDelay = TEMP_9_BIT; } // initialize the bus void DallasTemperature::begin(void) { DeviceAddress deviceAddress; _wire->reset_search(); while (_wire->search(deviceAddress)) { if (validAddress(deviceAddress)) { if (!parasite && readPowerSupply(deviceAddress)) parasite = true; ScratchPad scratchPad; readScratchPad(deviceAddress, scratchPad); if (deviceAddress[0] == DS18S20MODEL) conversionDelay = TEMP_12_BIT; // 750 ms else if (scratchPad[CONFIGURATION] > conversionDelay) conversionDelay = scratchPad[CONFIGURATION]; devices++; } } } // returns the number of devices found on the bus uint8_t DallasTemperature::getDeviceCount(void) { return devices; } // returns true if address is valid bool DallasTemperature::validAddress(uint8_t* deviceAddress) { return (_wire->crc8(deviceAddress, 7) == deviceAddress[7]); } // finds an address at a given index on the bus // returns true if the device was found bool DallasTemperature::getAddress(uint8_t* deviceAddress, uint8_t index) { uint8_t depth = 0; _wire->reset_search(); while (depth <= index && _wire->search(deviceAddress)) { if (depth == index && validAddress(deviceAddress)) return true; depth++; } return false; } // attempt to determine if the device at the given address is connected to the bus bool DallasTemperature::isConnected(uint8_t* deviceAddress) { ScratchPad scratchPad; return isConnected(deviceAddress, scratchPad); } // attempt to determine if the device at the given address is connected to the bus // also allows for updating the read scratchpad bool DallasTemperature::isConnected(uint8_t* deviceAddress, uint8_t* scratchPad) { readScratchPad(deviceAddress, scratchPad); return (_wire->crc8(scratchPad, 8) == scratchPad[SCRATCHPAD_CRC]); } // read device's scratch pad void DallasTemperature::readScratchPad(uint8_t* deviceAddress, uint8_t* scratchPad) { // send the command _wire->reset(); _wire->select(deviceAddress); _wire->write(READSCRATCH); // read the response // byte 0: temperature LSB scratchPad[TEMP_LSB] = _wire->read(); // byte 1: temperature MSB scratchPad[TEMP_MSB] = _wire->read(); // byte 2: high alarm temp scratchPad[HIGH_ALARM_TEMP] = _wire->read(); // byte 3: low alarm temp scratchPad[LOW_ALARM_TEMP] = _wire->read(); // byte 4: // DS18S20: store for crc // DS18B20 & DS1822: configuration register scratchPad[CONFIGURATION] = _wire->read(); // byte 5: // internal use & crc scratchPad[INTERNAL_BYTE] = _wire->read(); // byte 6: // DS18S20: COUNT_REMAIN // DS18B20 & DS1822: store for crc scratchPad[COUNT_REMAIN] = _wire->read(); // byte 7: // DS18S20: COUNT_PER_C // DS18B20 & DS1822: store for crc scratchPad[COUNT_PER_C] = _wire->read(); // byte 8: // SCTRACHPAD_CRC scratchPad[SCRATCHPAD_CRC] = _wire->read(); _wire->reset(); } // writes device's scratch pad void DallasTemperature::writeScratchPad(uint8_t* deviceAddress, const uint8_t* scratchPad) { _wire->reset(); _wire->select(deviceAddress); _wire->write(WRITESCRATCH); _wire->write(scratchPad[HIGH_ALARM_TEMP]); // high alarm temp _wire->write(scratchPad[LOW_ALARM_TEMP]); // low alarm temp // DS18S20 does not use the configuration register if (deviceAddress[0] != DS18S20MODEL) _wire->write(scratchPad[CONFIGURATION]); // configuration _wire->reset(); // save the newly written values to eeprom _wire->write(COPYSCRATCH, parasite); if (parasite) delay(10); // 10ms delay _wire->reset(); } // reads the device's power requirements bool DallasTemperature::readPowerSupply(uint8_t* deviceAddress) { bool ret = false; _wire->reset(); _wire->select(deviceAddress); _wire->write(READPOWERSUPPLY); if (_wire->read_bit() == 0) ret = true; _wire->reset(); return ret; } // returns the current resolution, 9-12 uint8_t DallasTemperature::getResolution(uint8_t* deviceAddress) { if (deviceAddress[0] == DS18S20MODEL) return 9; // this model has a fixed resolution ScratchPad scratchPad; readScratchPad(deviceAddress, scratchPad); switch (scratchPad[CONFIGURATION]) { case TEMP_12_BIT: return 12; break; case TEMP_11_BIT: return 11; break; case TEMP_10_BIT: return 10; break; case TEMP_9_BIT: return 9; break; } } // set resolution of a device to 9, 10, 11, or 12 bits void DallasTemperature::setResolution(uint8_t* deviceAddress, uint8_t newResolution) { ScratchPad scratchPad; if (isConnected(deviceAddress, scratchPad)) { // DS18S20 has a fixed 9-bit resolution if (deviceAddress[0] != DS18S20MODEL) { switch (newResolution) { case 12: scratchPad[CONFIGURATION] = TEMP_12_BIT; break; case 11: scratchPad[CONFIGURATION] = TEMP_11_BIT; break; case 10: scratchPad[CONFIGURATION] = TEMP_10_BIT; break; case 9: default: scratchPad[CONFIGURATION] = TEMP_9_BIT; break; } writeScratchPad(deviceAddress, scratchPad); } } } // sends command for all devices on the bus to perform a temperature void DallasTemperature::requestTemperatures(void) { _wire->reset(); _wire->skip(); _wire->write(STARTCONVO, parasite); switch (conversionDelay) { case TEMP_9_BIT: delay(94); break; case TEMP_10_BIT: delay(188); break; case TEMP_11_BIT: delay(375); break; case TEMP_12_BIT: default: delay(750); break; } } // sends command for one device to perform a temperature by address void DallasTemperature::requestTemperaturesByAddress(uint8_t* deviceAddress) { _wire->reset(); _wire->select(deviceAddress); _wire->write(STARTCONVO, parasite); switch (conversionDelay) { case TEMP_9_BIT: delay(94); break; case TEMP_10_BIT: delay(188); break; case TEMP_11_BIT: delay(375); break; case TEMP_12_BIT: default: delay(750); break; } } // sends command for one device to perform a temp conversion by index void DallasTemperature::requestTemperaturesByIndex(uint8_t deviceIndex) { DeviceAddress deviceAddress; getAddress(deviceAddress, deviceIndex); requestTemperaturesByAddress(deviceAddress); } // Fetch temperature for device index float DallasTemperature::getTempCByIndex(uint8_t deviceIndex) { DeviceAddress deviceAddress; getAddress(deviceAddress, deviceIndex); return getTempC((uint8_t*)deviceAddress); } // Fetch temperature for device index float DallasTemperature::getTempFByIndex(uint8_t deviceIndex) { return DallasTemperature::toFahrenheit(getTempCByIndex(deviceIndex)); } // reads scratchpad and returns the temperature in degrees C float DallasTemperature::calculateTemperature(uint8_t* deviceAddress, uint8_t* scratchPad) { int16_t rawTemperature = (((int16_t)scratchPad[TEMP_MSB]) << 8) | scratchPad[TEMP_LSB]; switch (deviceAddress[0]) { case DS18B20MODEL: case DS1822MODEL: switch (scratchPad[CONFIGURATION]) { case TEMP_12_BIT: return (float)rawTemperature * 0.0625; break; case TEMP_11_BIT: return (float)(rawTemperature >> 1) * 0.125; break; case TEMP_10_BIT: return (float)(rawTemperature >> 2) * 0.25; break; case TEMP_9_BIT: return (float)(rawTemperature >> 3) * 0.5; break; } break; case DS18S20MODEL: /* Resolutions greater than 9 bits can be calculated using the data from the temperature, COUNT REMAIN and COUNT PER °C registers in the scratchpad. Note that the COUNT PER °C register is hard-wired to 16 (10h). After reading the scratchpad, the TEMP_READ value is obtained by truncating the 0.5°C bit (bit 0) from the temperature data. The extended resolution temperature can then be calculated using the following equation: COUNT_PER_C - COUNT_REMAIN TEMPERATURE = TEMP_READ - 0.25 + -------------------------- COUNT_PER_C */ // Good spot. Thanks Nic Johns for your contribution return (float)(rawTemperature >> 1) - 0.25 +((float)(scratchPad[COUNT_PER_C] - scratchPad[COUNT_REMAIN]) / (float)scratchPad[COUNT_PER_C] ); break; } } // returns temperature in degrees C or DEVICE_DISCONNECTED if the // device's scratch pad cannot be read successfully. // the numeric value of DEVICE_DISCONNECTED is defined in // DallasTemperature.h. it is a large negative number outside the // operating range of the device float DallasTemperature::getTempC(uint8_t* deviceAddress) { // TODO: Multiple devices (up to 64) on the same bus may take some time to negotiate a response // What happens in case of collision? ScratchPad scratchPad; if (isConnected(deviceAddress, scratchPad)) return calculateTemperature(deviceAddress, scratchPad); return DEVICE_DISCONNECTED; } // returns temperature in degrees F float DallasTemperature::getTempF(uint8_t* deviceAddress) { return toFahrenheit(getTempC(deviceAddress)); } // returns true if the bus requires parasite power bool DallasTemperature::isParasitePowerMode(void) { return parasite; } #if REQUIRESALARMS /* ALARMS: TH and TL Register Format BIT 7 BIT 6 BIT 5 BIT 4 BIT 3 BIT 2 BIT 1 BIT 0 S 2^6 2^5 2^4 2^3 2^2 2^1 2^0 Only bits 11 through 4 of the temperature register are used in the TH and TL comparison since TH and TL are 8-bit registers. If the measured temperature is lower than or equal to TL or higher than or equal to TH, an alarm condition exists and an alarm flag is set inside the DS18B20. This flag is updated after every temperature measurement; therefore, if the alarm condition goes away, the flag will be turned off after the next temperature conversion. */ // sets the high alarm temperature for a device in degrees celsius // accepts a float, but the alarm resolution will ignore anything // after a decimal point. valid range is -55C - 125C void DallasTemperature::setHighAlarmTemp(uint8_t* deviceAddress, char celsius) { // make sure the alarm temperature is within the device's range if (celsius > 125) celsius = 125; else if (celsius < -55) celsius = -55; ScratchPad scratchPad; if (isConnected(deviceAddress, scratchPad)) { scratchPad[HIGH_ALARM_TEMP] = (uint8_t)celsius; writeScratchPad(deviceAddress, scratchPad); } } // sets the low alarm temperature for a device in degreed celsius // accepts a float, but the alarm resolution will ignore anything // after a decimal point. valid range is -55C - 125C void DallasTemperature::setLowAlarmTemp(uint8_t* deviceAddress, char celsius) { // make sure the alarm temperature is within the device's range if (celsius > 125) celsius = 125; else if (celsius < -55) celsius = -55; ScratchPad scratchPad; if (isConnected(deviceAddress, scratchPad)) { scratchPad[LOW_ALARM_TEMP] = (uint8_t)celsius; writeScratchPad(deviceAddress, scratchPad); } } // returns a char with the current high alarm temperature or // DEVICE_DISCONNECTED for an address char DallasTemperature::getHighAlarmTemp(uint8_t* deviceAddress) { ScratchPad scratchPad; if (isConnected(deviceAddress, scratchPad)) return (char)scratchPad[HIGH_ALARM_TEMP]; return DEVICE_DISCONNECTED; } // returns a char with the current low alarm temperature or // DEVICE_DISCONNECTED for an address char DallasTemperature::getLowAlarmTemp(uint8_t* deviceAddress) { ScratchPad scratchPad; if (isConnected(deviceAddress, scratchPad)) return (char)scratchPad[LOW_ALARM_TEMP]; return DEVICE_DISCONNECTED; } // resets internal variables used for the alarm search void DallasTemperature::resetAlarmSearch() { alarmSearchJunction = -1; alarmSearchExhausted = 0; for(uint8_t i = 0; i < 7; i++) alarmSearchAddress[i] = 0; } // This is a modified version of the OneWire::search method. // // Also added the OneWire search fix documented here: // http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1238032295 // // Perform an alarm search. If this function returns a '1' then it has // enumerated the next device and you may retrieve the ROM from the // OneWire::address variable. If there are no devices, no further // devices, or something horrible happens in the middle of the // enumeration then a 0 is returned. If a new device is found then // its address is copied to newAddr. Use // DallasTemperature::resetAlarmSearch() to start over. bool DallasTemperature::alarmSearch(uint8_t* newAddr) { uint8_t i; char lastJunction = -1; uint8_t done = 1; if (alarmSearchExhausted) return false; if (!_wire->reset()) return false; // send the alarm search command _wire->write(0xEC, 0); for(i = 0; i < 64; i++) { uint8_t a = _wire->read_bit( ); uint8_t nota = _wire->read_bit( ); uint8_t ibyte = i / 8; uint8_t ibit = 1 << (i & 7); // I don't think this should happen, this means nothing responded, but maybe if // something vanishes during the search it will come up. if (a && nota) return false; if (!a && !nota) { if (i == alarmSearchJunction) { // this is our time to decide differently, we went zero last time, go one. a = 1; alarmSearchJunction = lastJunction; } else if (i < alarmSearchJunction) { // take whatever we took last time, look in address if (alarmSearchAddress[ibyte] & ibit) a = 1; else { // Only 0s count as pending junctions, we've already exhasuted the 0 side of 1s a = 0; done = 0; lastJunction = i; } } else { // we are blazing new tree, take the 0 a = 0; alarmSearchJunction = i; done = 0; } // OneWire search fix // See: http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1238032295 } if (a) alarmSearchAddress[ibyte] |= ibit; else alarmSearchAddress[ibyte] &= ~ibit; _wire->write_bit(a); } if (done) alarmSearchExhausted = 1; for (i = 0; i < 8; i++) newAddr[i] = alarmSearchAddress[i]; return true; } // returns true if device address has an alarm condition bool DallasTemperature::hasAlarm(uint8_t* deviceAddress) { ScratchPad scratchPad; if (isConnected(deviceAddress, scratchPad)) { float temp = calculateTemperature(deviceAddress, scratchPad); // check low alarm if ((char)temp <= (char)scratchPad[LOW_ALARM_TEMP]) return true; // check high alarm if ((char)temp >= (char)scratchPad[HIGH_ALARM_TEMP]) return true; } // no alarm return false; } // returns true if any device is reporting an alarm condition on the bus bool DallasTemperature::hasAlarm(void) { DeviceAddress deviceAddress; resetAlarmSearch(); return alarmSearch(deviceAddress); } // runs the alarm handler for all devices returned by alarmSearch() void DallasTemperature::processAlarms(void) { resetAlarmSearch(); DeviceAddress alarmAddr; while (alarmSearch(alarmAddr)) { if (validAddress(alarmAddr)) _AlarmHandler(alarmAddr); } } // sets the alarm handler void DallasTemperature::setAlarmHandler(AlarmHandler *handler) { _AlarmHandler = handler; } // The default alarm handler void DallasTemperature::defaultAlarmHandler(uint8_t* deviceAddress) { } #endif // Convert float celsius to fahrenheit float DallasTemperature::toFahrenheit(float celsius) { return (celsius * 1.8) + 32; } // Convert float fahrenheit to celsius float DallasTemperature::toCelsius(float fahrenheit) { return (fahrenheit - 32) / 1.8; } #if REQUIRESNEW // MnetCS - Allocates memory for DallasTemperature. Allows us to instance a new object void* DallasTemperature::operator new(unsigned int size) // Implicit NSS obj size { void * p; // void pointer p = malloc(size); // Allocate memory memset((DallasTemperature*)p,0,size); // Initalise memory //!!! CANT EXPLICITLY CALL CONSTRUCTOR - workaround by using an init() methodR - workaround by using an init() method return (DallasTemperature*) p; // Cast blank region to NSS pointer } // MnetCS 2009 - Unallocates the memory used by this instance void DallasTemperature::operator delete(void* p) { DallasTemperature* pNss = (DallasTemperature*) p; // Cast to NSS pointer pNss->~DallasTemperature(); // Destruct the object free(p); // Free the memory } #endif
[ "lenniethelemming@2f291951-c1d2-6b09-a047-4ba468d48a57" ]
[ [ [ 1, 624 ] ] ]
60926f2e13bc6085d3a974673dc67d2bf0a67b13
93a82c698a4bd16d5c7618f0851976d676388279
/shell/shell.cpp
118585e1ee11282470898d23a70862ab24731594
[ "MIT" ]
permissive
chenbk85/bitfsm
4aa026f29118141fe328b595c70faace97b0089f
36011de97a1b5906919f78278c8db6e2f12385ae
refs/heads/master
2021-01-21T00:58:59.286863
2011-06-11T17:09:09
2011-06-11T17:09:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,062
cpp
/* ** This source file is part of BITFSM ** ** For the latest info, see http://code.google.com/p/bitfsm/ ** ** Copyright (c) 2011 Tony & Tony's Toy Game Development Team ** ** Permission is hereby granted, free of charge, to any person obtaining a copy of ** this software and associated documentation files (the "Software"), to deal in ** the Software without restriction, including without limitation the rights to ** use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of ** the Software, and to permit persons to whom the Software is furnished to do so, ** subject to the following conditions: ** ** The above copyright notice and this permission notice shall be included in all ** copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS ** FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR ** COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER ** IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN ** CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdlib.h> #include <stdio.h> #include <string> #include "../bitfsm.h" struct ObjToStatus { int operator ()(const std::string &_obj) { if(_obj == "begin") { return 0; } else if(_obj == "1") { return 1; } else if(_obj == "2") { return 2; } else if(_obj == "3") { return 3; } else if(_obj == "end") { return 4; } return -1; } }; struct ObjToCommand { int operator ()(const std::string &_obj) { if(_obj == "_cmd0") { return 0; } else if(_obj == "_cmd1") { return 1; } else if(_obj == "_cmd2") { return 2; } else if(_obj == "_cmd3") { return 3; } else if(_obj == "_cmd4") { return 4; } else if(_obj == "_cmd5") { return 5; } return -1; } }; typedef fsm::FSM<5, 6, std::string, ObjToStatus, ObjToCommand> Fsm; class MyStepHandler : public Fsm::StepHandler { public: virtual void handleStep(const std::string &_srcTag, const std::string &_tgtTag) { printf("Status changed from %s to %s\n", _srcTag.c_str(), _tgtTag.c_str()); } }; class MyTagStreamer : public Fsm::TagStreamer { public: virtual void write(std::fstream &_fs, const std::string &_tag) { int _len = _tag.length() + 1; _fs.write((char*)&_len, sizeof(_len)); _fs.write(_tag.c_str(), _len); } virtual void read(std::fstream &_fs, std::string &_tag) { int _len = 0; char _buf[1024]; _fs.read((char*)&_len, sizeof(_len)); _fs.read(_buf, _len); _tag = _buf; } }; int main(int argc, char* argv[]) { bool done = false; Fsm::CommandParams params; Fsm sbs; Fsm::StepHandler* hdl = new MyStepHandler; Fsm::TagStreamer* str = new MyTagStreamer; sbs.setStepHandler(hdl); sbs.setTagStreamer(str); { sbs.registerRuleStepTag("begin"); sbs.registerRuleStepTag("1"); sbs.registerRuleStepTag("2"); sbs.registerRuleStepTag("3"); sbs.registerRuleStepTag("end"); } { sbs.setCurrentStep("begin"); sbs.setTerminalStep("end"); params.reset(); params.add("_cmd0"); sbs.addRuleStep("begin", params, "1"); params.reset(); params.add("_cmd1"); sbs.addRuleStep("begin", params, "2"); params.reset(); params.add("_cmd3"); sbs.addRuleStep("1", params, "3"); params.reset(); params.add("_cmd4"); sbs.addRuleStep("2", params, "3"); params.reset(); params.add("_cmd5"); sbs.addRuleStep("3", params, "end"); } { sbs.writeRuleSteps("backup.fsm"); sbs.reset(); sbs.readRuleSteps("backup.fsm"); } { sbs.setCurrentStep("begin"); sbs.walk("_cmd0"); done = sbs.terminated(); sbs.walk("_cmd3"); done = sbs.terminated(); sbs.walk("_cmd5"); done = sbs.terminated(); } delete hdl; delete str; system("pause"); return 0; }
[ "[email protected]@001d7d6d-0781-b1c3-2124-3c488e618438" ]
[ [ [ 1, 169 ] ] ]
5ba387d7c7083fb3a575fadcc3a1f0aee2d5a7a4
9b786d478560dfe2b99084f5d9338c0729634700
/vxWorks/cpp_test_src/inheritance/virtualFunction.cpp
2727e626869064b4eea8ad3a9008b6403629fd88
[]
no_license
hejunbok/demoCode
e33809c13f783cceb47d1bd2a57e2f07b31e42b9
fb7a7a9c87ba61d104dabf291805c99f76ae9aac
refs/heads/master
2021-01-18T08:33:07.654385
2011-04-25T06:27:11
2011-04-25T06:27:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,785
cpp
/* virtualFunction.cpp */ /* Copyright 2004 Wind River Systems, Inc. */ /* modification history -------------------- 01a,3March04,pp written. */ /* DESCRIPTION This test application has class hierarchy of following classes mentioned in oreder of hierarchy ( base class first, then derived class) virtSwitch , virtSwitch1, virtSwitch2, virtSwitch3, virtSwitch4, virtSwitch5 They have a virtual function increment() Objects of the above classes ( except virtswitch) are created , and base class pointer virtSwitch pointer point to the objects created , and virtual function increment is invoked through base class pointer.. */ class virtSwitch { public: virtual void increment(void) = 0; static int i; }; int virtSwitch::i =0; class virtSwitch1 : public virtSwitch { public: virtual void increment(void) { ++i; } }; class virtSwitch2 : public virtSwitch1 { public: virtual void increment(void) { i = i + 2; } }; class virtSwitch3 : public virtSwitch2 { public: virtual void increment(void) { i = i + 3; } }; class virtSwitch4 : public virtSwitch3 { public: virtual void increment(void) { i = i + 4; } }; class virtSwitch5 : public virtSwitch4 { public: virtual void increment(void) { i = i + 5; } }; virtSwitch *sw[5]; /* test routine */ int tdfeTestCase30Execute (void) { sw[0] = new virtSwitch1; sw[1] = new virtSwitch2; sw[2] = new virtSwitch3; sw[3] = new virtSwitch4; sw[4] = new virtSwitch5; sw[0]->increment(); sw[1]->increment(); sw[2]->increment(); sw[3]->increment(); sw[4]->increment(); return 0; }
[ [ [ 1, 109 ] ] ]
67adb88cd01d875f49a34da1c704b63b123fb741
203f8465075e098f69912a6bbfa3498c36ce2a60
/stacks/motion_planning/sbpl/src/utils/mdp.h
340de1fdd41a6842764764b40424272114c8f9a2
[]
no_license
robcn/personalrobots-pkg
a4899ff2db9aef00a99274d70cb60644124713c9
4dcf3ca1142d3c3cb85f6d42f7afa33c59e2240a
refs/heads/master
2021-06-20T16:28:29.549716
2009-09-04T23:56:10
2009-09-04T23:56:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,885
h
/* * Copyright (c) 2008, Maxim Likhachev * 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 University of Pennsylvania 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 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. */ #ifndef __MDP_H_ #define __MDP_H_ #include <cstdlib> #define EPS_ERROR 0.000001 //the maximum size of the heap #define MAXSTATESPACESIZE 20000000 class CMDPSTATE; class CMDPACTION { //data public: int ActionID; int SourceStateID; vector<int> SuccsID; vector<int> Costs; vector<float> SuccsProb; void* PlannerSpecificData; //constructors public: CMDPACTION(int ID, int sourcestateid) { ActionID = ID; SourceStateID = sourcestateid; PlannerSpecificData = NULL; }; ~CMDPACTION() { if(PlannerSpecificData != NULL) { fprintf(stderr, "ERROR: state deletion: planner specific data is not deleted\n"); exit(1); } }; //functions public: bool Delete(); bool IsValid(); void AddOutcome(int OutcomeStateID, int OutcomeCost, float OutcomeProb); int GetIndofMostLikelyOutcome(); int GetIndofOutcome(int OutcomeID); bool DeleteAllOutcomes(); private: //operators public: void operator = (const CMDPACTION& rhsaction); }; class CMDPSTATE { //data public: int StateID; vector<CMDPACTION*> Actions; vector<int> PredsID; void* PlannerSpecificData; //constructors public: CMDPSTATE(int ID) { StateID = ID; PlannerSpecificData = NULL; }; ~CMDPSTATE() { if(PlannerSpecificData != NULL) { fprintf(stderr, "ERROR: state deletion: planner specific data is not deleted\n"); exit(1); } }; //functions public: bool Delete(); CMDPACTION* AddAction(int ID); bool ContainsPred(int stateID); bool AddPred(int stateID); bool RemovePred(int stateID); bool RemoveAllActions(); CMDPACTION* GetAction(int actionID); private: //operators public: void operator = (const CMDPSTATE& rhsstate); }; class CMDP { //data public: vector<CMDPSTATE*> StateArray; //constructors public: CMDP() { }; ~CMDP() { }; //functions public: bool empty(); bool full(); //creates numofstates states. Their ids are their orderings for Original, Thresholded & Search MDPs bool Create(int numofstates); bool Delete(); void Print(FILE* fOut); CMDPSTATE* AddState(int StateID); private: //operators public: }; #endif
[ "maximl@f5854215-dd47-0410-b2c4-cdd35faa7885", "tfoote@f5854215-dd47-0410-b2c4-cdd35faa7885" ]
[ [ [ 1, 31 ], [ 34, 173 ] ], [ [ 32, 33 ] ] ]
964936a5df5d893777534095018c02e15ecc90ed
51c71b06d7fa1aa97df4ffe6782e9a4924480a33
/Calibration/Configuration.cpp
c8d59b9350d568ff8f0bf782e7668a075309732f
[]
no_license
alonf01/open-light
9eb8d185979cfa16797f9d2201cf192b3e91f270
685f974fcd7cc29b6bec00fa17804c5f2b7a83c3
refs/heads/master
2020-05-30T15:24:08.579565
2010-12-14T00:56:32
2010-12-14T00:56:32
35,759,673
0
0
null
null
null
null
UTF-8
C++
false
false
10,924
cpp
//////////////////////////////////////////////////////////////////////////////////////////////////// /// @file Calibration\Configuration.cpp /// /// @brief Implements the configuration class. //////////////////////////////////////////////////////////////////////////////////////////////////// #include "Configuration.h" #include "Calibration.h" #include "CalibrationExceptions.h" //////////////////////////////////////////////////////////////////////////////////////////////////// /// @fn public: Configuration(const char* filename, struct stParams* sl_params) /// /// @brief Constructor /// /// @author Brett Jones /// @date 12/12/2010 /// /// @param filename Configuration filename. /// @param [in,out] sl_params Paramaters. //////////////////////////////////////////////////////////////////////////////////////////////////// Configuration::Configuration(std::string filename, struct slParams* sl_params) { mFilename = filename; mSlParams = sl_params; } void Configuration::Load() { FILE* pFile = fopen(mFilename.c_str(), "r"); if(pFile != NULL){ fclose(pFile); printf("Reading configuration file \"%s\"...\n", mFilename); } else{ throw new FileNotFound("configuration file"); } // done to reuse existing code struct slParams* sl_params = mSlParams; // Open file storage for XML-formatted configuration file. CvFileStorage* fs = cvOpenFileStorage(mFilename.c_str(), 0, CV_STORAGE_READ); // Read output directory and object (or sequence) name. CvFileNode* m = cvGetFileNodeByName(fs, 0, "output"); strcpy(sl_params->outdir, cvReadStringByName(fs, m, "output_directory", "./output")); strcpy(sl_params->object, cvReadStringByName(fs, m, "object_name", "./output")); sl_params->save = (cvReadIntByName(fs, m, "save_intermediate_results", 0) != 0); // Read camera parameters. m = cvGetFileNodeByName(fs, 0, "camera"); sl_params->cam_w = cvReadIntByName(fs, m, "width", 960); sl_params->cam_h = cvReadIntByName(fs, m, "height", 720); sl_params->Logitech_9000 = (cvReadIntByName(fs, m, "Logitech_Quickcam_9000_raw_mode", 0) != 0); // Read projector parameters. m = cvGetFileNodeByName(fs, 0, "projector"); sl_params->proj_w = cvReadIntByName(fs, m, "width", 1024); sl_params->proj_h = cvReadIntByName(fs, m, "height", 768); sl_params->proj_invert = (cvReadIntByName(fs, m, "invert_projector", 0) != 0); // Read camera and projector gain parameters. m = cvGetFileNodeByName(fs, 0, "gain"); sl_params->cam_gain = cvReadIntByName(fs, m, "camera_gain", 50); sl_params->proj_gain = cvReadIntByName(fs, m, "projector_gain", 50); // Read distortion model parameters. m = cvGetFileNodeByName(fs, 0, "distortion_model"); sl_params->cam_dist_model[0] = (cvReadIntByName(fs, m, "enable_tangential_camera", 0) != 0); sl_params->cam_dist_model[1] = (cvReadIntByName(fs, m, "enable_6th_order_radial_camera", 0) != 0); sl_params->proj_dist_model[0] = (cvReadIntByName(fs, m, "enable_tangential_projector", 0) != 0); sl_params->proj_dist_model[1] = (cvReadIntByName(fs, m, "enable_6th_order_radial_projector", 0) != 0); // Read camera calibration chessboard parameters. m = cvGetFileNodeByName(fs, 0, "camera_chessboard"); sl_params->cam_board_w = cvReadIntByName(fs, m, "interior_horizontal_corners", 8); sl_params->cam_board_h = cvReadIntByName(fs, m, "interior_vertical_corners", 6); sl_params->cam_board_w_mm = (float)cvReadRealByName(fs, m, "square_width_mm", 30.0); sl_params->cam_board_h_mm = (float)cvReadRealByName(fs, m, "square_height_mm", 30.0); // Read projector calibration chessboard parameters. m = cvGetFileNodeByName(fs, 0, "projector_chessboard"); sl_params->proj_board_w = cvReadIntByName(fs, m, "interior_horizontal_corners", 8); sl_params->proj_board_h = cvReadIntByName(fs, m, "interior_vertical_corners", 6); sl_params->proj_board_w_pixels = cvReadIntByName(fs, m, "square_width_pixels", 75); sl_params->proj_board_h_pixels = cvReadIntByName(fs, m, "square_height_pixels", 75); // Read scanning and reconstruction parameters. m = cvGetFileNodeByName(fs, 0, "scanning_and_reconstruction"); sl_params->mode = cvReadIntByName(fs, m, "mode", 2); sl_params->scan_cols = (cvReadIntByName(fs, m, "reconstruct_columns", 1) != 0); sl_params->scan_rows = (cvReadIntByName(fs, m, "reconstruct_rows", 1) != 0); sl_params->delay = cvReadIntByName(fs, m, "frame_delay_ms", 200); sl_params->thresh = cvReadIntByName(fs, m, "minimum_contrast_threshold", 32); sl_params->dist_range[0] = (float) cvReadRealByName(fs, m, "minimum_distance_mm", 0.0); sl_params->dist_range[1] = (float) cvReadRealByName(fs, m, "maximum_distance_mm", 1.0e4); sl_params->dist_reject = (float) cvReadRealByName(fs, m, "maximum_distance_variation_mm", 10.0); sl_params->background_depth_thresh = (float) cvReadRealByName(fs, m, "minimum_background_distance_mm", 20.0); sl_params->generate_normals = (cvReadIntByName(fs, m, "generate_normals", 1) != 0); // Read visualization options. m = cvGetFileNodeByName(fs, 0, "visualization"); sl_params->display = (cvReadIntByName(fs, m, "display_intermediate_results", 1) != 0); sl_params->window_w = cvReadIntByName(fs, m, "display_window_width_pixels", 640); sl_params->window_offset_x = cvReadIntByName(fs, m, "window_offset_x", -13); sl_params->window_offset_y = cvReadIntByName(fs, m, "window_offset_y", -23); // Enable both row and column scanning, if "ray-ray" reconstruction mode is enabled. if(sl_params->mode == 2){ sl_params->scan_cols = true; sl_params->scan_rows = true; } // Set camera visualization window dimensions. sl_params->window_h = (int)ceil((float)sl_params->window_w*((float)sl_params->cam_h/(float)sl_params->cam_w)); // Close file storage for XML-formatted configuration file. cvReleaseFileStorage(&fs); } void Configuration::Save() { FILE* pFile = fopen(mFilename.c_str(), "r"); if(pFile != NULL){ fclose(pFile); printf("Reading configuration file \"%s\"...\n", mFilename); } else{ throw new FileNotFound("configuration file"); } // done to reuse existing code struct slParams* sl_params = mSlParams; // Create file storage for XML-formatted configuration file. CvFileStorage* fs = cvOpenFileStorage(mFilename.c_str(), 0, CV_STORAGE_WRITE); // Write output directory and object (or sequence) name. cvStartWriteStruct(fs, "output", CV_NODE_MAP); cvWriteString(fs, "output_directory", sl_params->outdir, 1); cvWriteString(fs, "object_name", sl_params->object, 1); cvWriteInt(fs, "save_intermediate_results", sl_params->save); cvEndWriteStruct(fs); // Write camera parameters. cvStartWriteStruct(fs, "camera", CV_NODE_MAP); cvWriteInt(fs, "width", sl_params->cam_w); cvWriteInt(fs, "height", sl_params->cam_h); cvWriteInt(fs, "Logitech_Quickcam_9000_raw_mode", sl_params->Logitech_9000); cvEndWriteStruct(fs); // Write projector parameters. cvStartWriteStruct(fs, "projector", CV_NODE_MAP); cvWriteInt(fs, "width", sl_params->proj_w); cvWriteInt(fs, "height", sl_params->proj_h); cvWriteInt(fs, "invert_projector", sl_params->proj_invert); cvEndWriteStruct(fs); // Write camera and projector gain parameters. cvStartWriteStruct(fs, "gain", CV_NODE_MAP); cvWriteInt(fs, "camera_gain", sl_params->cam_gain); cvWriteInt(fs, "projector_gain", sl_params->proj_gain); cvEndWriteStruct(fs); // Write distortion model parameters. cvStartWriteStruct(fs, "distortion_model", CV_NODE_MAP); cvWriteInt(fs, "enable_tangential_camera", sl_params->cam_dist_model[0]); cvWriteInt(fs, "enable_6th_order_radial_camera", sl_params->cam_dist_model[1]); cvWriteInt(fs, "enable_tangential_projector", sl_params->proj_dist_model[0]); cvWriteInt(fs, "enable_6th_order_radial_projector", sl_params->proj_dist_model[1]); cvEndWriteStruct(fs); // Write camera calibration chessboard parameters. cvStartWriteStruct(fs, "camera_chessboard", CV_NODE_MAP); cvWriteInt(fs, "interior_horizontal_corners", sl_params->cam_board_w); cvWriteInt(fs, "interior_vertical_corners", sl_params->cam_board_h); cvWriteReal(fs, "square_width_mm", sl_params->cam_board_w_mm); cvWriteReal(fs, "square_height_mm", sl_params->cam_board_h_mm); cvEndWriteStruct(fs); // Write projector calibration chessboard parameters. cvStartWriteStruct(fs, "projector_chessboard", CV_NODE_MAP); cvWriteInt(fs, "interior_horizontal_corners", sl_params->proj_board_w); cvWriteInt(fs, "interior_vertical_corners", sl_params->proj_board_h); cvWriteInt(fs, "square_width_pixels", sl_params->proj_board_w_pixels); cvWriteInt(fs, "square_height_pixels", sl_params->proj_board_h_pixels); cvEndWriteStruct(fs); // Write scanning and reconstruction parameters. cvStartWriteStruct(fs, "scanning_and_reconstruction", CV_NODE_MAP); cvWriteInt(fs, "mode", sl_params->mode); cvWriteInt(fs, "reconstruct_columns", sl_params->scan_cols); cvWriteInt(fs, "reconstruct_rows", sl_params->scan_rows); cvWriteInt(fs, "frame_delay_ms", sl_params->delay); cvWriteInt(fs, "minimum_contrast_threshold", sl_params->thresh); cvWriteReal(fs, "minimum_distance_mm", sl_params->dist_range[0]); cvWriteReal(fs, "maximum_distance_mm", sl_params->dist_range[1]); cvWriteReal(fs, "maximum_distance_variation_mm", sl_params->dist_reject); cvWriteReal(fs, "minimum_background_distance_mm", sl_params->background_depth_thresh); cvWriteInt(fs, "generate_normals", sl_params->generate_normals); cvEndWriteStruct(fs); // Write visualization options. cvStartWriteStruct(fs, "visualization", CV_NODE_MAP); cvWriteInt(fs, "display_intermediate_results", sl_params->display); cvWriteInt(fs, "display_window_width_pixels", sl_params->window_w); cvWriteInt(fs, "window_offset_x", sl_params->window_offset_x); cvWriteInt(fs, "window_offset_y", sl_params->window_offset_y); cvEndWriteStruct(fs); // Close file storage for XML-formatted configuration file. cvReleaseFileStorage(&fs); }
[ "b.jonessoda@8a600b9a-ddf7-11de-b878-c5ec750a8c44" ]
[ [ [ 1, 218 ] ] ]
1ea89b682044cb63bb283999f89f660a82fdfe4b
d418ee4fc1cea6246e8611b7b162abb03d0cd010
/nachos-csci402/code/userprog/SynchManager.cc
91433417e2a79163a2110dc024b451b112909e34
[ "MIT-Modern-Variant" ]
permissive
KWarp/cs402gregjustinkevin
873cf49460f0574402b141e8db348940a86bfaa3
a56dbfa3ae92c04c377b4cdeed9633ee58a578f8
refs/heads/master
2021-01-10T16:44:23.875963
2010-12-05T07:29:02
2010-12-05T07:29:02
53,481,712
0
0
null
null
null
null
UTF-8
C++
false
false
7,096
cc
/* SynchManager.cc */ #include "SynchManager.h" /* ============================================================= * Initialize * =============================================================*/ SynchManager::SynchManager() { lockBitMap = new BitMap(MaxNumLocks); cvBitMap = new BitMap(MaxNumLocks); lock_ForLockTable = new Lock("Lock for Lock Table"); lock_ForCVTable = new Lock("Lock for CV Table"); } /* ============================================================= * Uninitialize * =============================================================*/ SynchManager::~SynchManager() { delete lockBitMap; delete cvBitMap; delete lock_ForLockTable; delete lock_ForCVTable; delete[] lockEntries; delete[] cvEntries; } /* ============================================================= * Create * =============================================================*/ int SynchManager::CreateLock(char* name) { lock_ForLockTable->Acquire(); int lockIndex = lockBitMap->Find(); // Marks index if found one // check that I can create a lock if(lockIndex == -1) { printf("ERROR: Cannot create lock\n"); lock_ForLockTable->Release(); return -1; } // make a lock entry LockEntry* entry = new LockEntry(); entry->lock = new Lock(name); lockEntries[lockIndex] = entry; lock_ForLockTable->Release(); return lockIndex; } int SynchManager::CreateCondition(char* name) { lock_ForCVTable->Acquire(); int cvIndex = cvBitMap->Find(); // check that I can create a cv if(cvIndex == -1) { printf("ERROR: Cannot create Condition\n"); lock_ForCVTable->Release(); return -1; } // make a cv entry CVEntry* entry = new CVEntry(); entry->cv = new Condition(name); cvEntries[cvIndex] = entry; lock_ForCVTable->Release(); return cvIndex; } /* ============================================================= * Destroy * =============================================================*/ void SynchManager::DestroyLock(int index) { lock_ForLockTable->Acquire(); // validate if(index < 0 || index > MaxNumLocks || !lockBitMap->Test(index)) { printf("ERROR: No Lock to destroy\n"); lock_ForLockTable->Release(); return; } // if lock is free, delete immediately if(lockEntries[index]->ownerProcess == NULL && lockEntries[index]->toBeUsed == false) { delete lockEntries[index]; lockBitMap->Clear(index); } else { lockEntries[index]->toBeDeleted = true; } lock_ForLockTable->Release(); } void SynchManager::DestroyCondition(int index) { lock_ForCVTable->Acquire(); // validate if(index < 0 || index > MaxNumCVs || !cvBitMap->Test(index)) { printf("ERROR: No Condition to destroy\n"); lock_ForCVTable->Release(); return; } // if CV is free, delete immediately if(cvEntries[index]->ownerProcess == NULL && cvEntries[index]->toBeUsed == false) { delete cvEntries[index]; cvBitMap->Clear(index); } else { cvEntries[index]->toBeDeleted = true; } lock_ForCVTable->Release(); } /* ============================================================= * Acquire/Release * =============================================================*/ void SynchManager::Acquire(int lockIndex) { lock_ForLockTable->Acquire(); // validate if(lockIndex < 0 || lockIndex > MaxNumCVs || !lockBitMap->Test(lockIndex)) { printf("ERROR: No Lock available to Acquire\n"); return; } lockEntries[lockIndex]->toBeUsed = true; lock_ForLockTable->Release(); // acquire lock, set table values lockEntries[lockIndex]->lock->Acquire(); lockEntries[lockIndex]->ownerProcess = currentThread->space; lockEntries[lockIndex]->toBeUsed = false; // possible race condition } void SynchManager::Release(int lockIndex) { lock_ForLockTable->Acquire(); // validate if(lockIndex < 0 || lockIndex > MaxNumCVs || !lockBitMap->Test(lockIndex)) { printf("ERROR: No Lock available to Release\n"); return; } lockEntries[lockIndex]->lock->Release(); lockEntries[lockIndex]->ownerProcess = NULL; // at end of release, check if lock needs to be deleted if(lockEntries[lockIndex]->toBeDeleted) { delete lockEntries[lockIndex]; lockBitMap->Clear(lockIndex); } lock_ForLockTable->Release(); } /* ============================================================= * Wait/Signal/Broadcast * =============================================================*/ void SynchManager::Wait(int cvIndex, int lockIndex) { lock_ForCVTable->Acquire(); lock_ForLockTable->Acquire(); // validate if(cvIndex < 0 || cvIndex > MaxNumCVs || !cvBitMap->Test(cvIndex)) { printf("ERROR: No Condition to available for Wait\n"); lock_ForLockTable->Release(); lock_ForCVTable->Release(); return; } if(lockIndex < 0 || lockIndex > MaxNumCVs || !lockBitMap->Test(lockIndex)) { printf("ERROR: No Lock available for Wait\n"); lock_ForLockTable->Release(); lock_ForCVTable->Release(); return; } cvEntries[cvIndex]->toBeUsed = true; lock_ForLockTable->Release(); lock_ForCVTable->Release(); // ok to Wait cvEntries[cvIndex]->ownerProcess = currentThread->space; //printf("Kernel: Waiting on index %d\n", cvIndex); cvEntries[cvIndex]->cv->Wait(lockEntries[lockIndex]->lock); cvEntries[cvIndex]->ownerProcess = NULL; cvEntries[cvIndex]->toBeUsed = false; // possible race condition } void SynchManager::Signal(int cvIndex, int lockIndex) { lock_ForCVTable->Acquire(); lock_ForLockTable->Acquire(); // validate if(cvIndex < 0 || cvIndex > MaxNumCVs || !cvBitMap->Test(cvIndex)) { printf("ERROR: No Condition to available for Signal\n"); lock_ForLockTable->Release(); lock_ForCVTable->Release(); return; } if(lockIndex < 0 || lockIndex > MaxNumCVs || !lockBitMap->Test(lockIndex)) { printf("ERROR: No Lock available for Signal\n"); lock_ForLockTable->Release(); lock_ForCVTable->Release(); return; } // ok to Signal //printf("Kernel: Signaling from index %d\n", cvIndex); cvEntries[cvIndex]->cv->Signal(lockEntries[lockIndex]->lock); lock_ForLockTable->Release(); lock_ForCVTable->Release(); } void SynchManager::Broadcast(int cvIndex, int lockIndex) { lock_ForCVTable->Acquire(); lock_ForLockTable->Acquire(); // validate if(cvIndex < 0 || cvIndex > MaxNumCVs || !cvBitMap->Test(cvIndex)) { printf("ERROR: No Condition to available for Broadcast\n"); lock_ForLockTable->Release(); lock_ForCVTable->Release(); return; } if(lockIndex < 0 || lockIndex > MaxNumCVs || !lockBitMap->Test(lockIndex)) { printf("ERROR: No Lock available for Broadcast\n"); lock_ForLockTable->Release(); lock_ForCVTable->Release(); return; } // ok to Broadcast cvEntries[cvIndex]->cv->Broadcast(lockEntries[lockIndex]->lock); lock_ForLockTable->Release(); lock_ForCVTable->Release(); }
[ "KWarp11@64a47c91-1020-2430-03ac-642e8966e14f" ]
[ [ [ 1, 268 ] ] ]
0cfdced48dc17bc55be7b74f5d6de778f6ffe9ed
2d72b8eb524b1dfe596ba142827d0aaf6809b5a5
/XYCQ/OgreMax/OgreMaxTypes.hpp
1305b7b469d2edc0dbe90eb0d182b63d41d368c5
[]
no_license
sdfwds4/xuanyuanchuanqi
49194d5df8cb59224fb357e07a876729a19919fc
c4ebf9a1af46a270b74357aa2bb259ac4253bec6
refs/heads/master
2021-01-10T04:55:00.543614
2009-05-27T12:20:59
2009-05-27T12:20:59
46,041,443
0
0
null
null
null
null
UTF-8
C++
false
false
33,434
hpp
/* * OgreMaxViewer - An Ogre 3D-based viewer for .scene and .mesh files * Copyright 2008 Derek Nedelman * * This code is available under the OgreMax Free License: * -You may use this code for any purpose, commercial or non-commercial. * -If distributing derived works (that use this source code) in binary or source code form, * you must give the following credit in your work's end-user documentation: * "Portions of this work provided by OgreMax (www.ogremax.com)" * * Derek Nedelman assumes no responsibility for any harm caused by using this code. * * OgreMaxViewer was written by Derek Nedelman and released at www.ogremax.com */ #ifndef OgreMax_OgreMaxTypes_INCLUDED #define OgreMax_OgreMaxTypes_INCLUDED //Includes--------------------------------------------------------------------- #include "tinyxml/tinyxml.h" #include <OgreString.h> #include <OgreStringConverter.h> #include <OgreMaterial.h> #include <OgreVector3.h> #include <OgreVector4.h> #include <OgrePlane.h> #include <OgreQuaternion.h> #include <OgreHardwareBuffer.h> #include <OgreRenderQueue.h> #include <OgreLight.h> #include <OgreCamera.h> #include <OgreBillboardSet.h> #include <OgrePixelFormat.h> #include <OgreAnimation.h> #include <OgreAnimationState.h> #include <OgreTexture.h> #include <OgreSceneNode.h> #include <OgreEntity.h> #include <OgreTagPoint.h> #include <OgreSkeletonInstance.h> //Classes---------------------------------------------------------------------- namespace OgreMax { namespace Types { enum UpAxis { UP_AXIS_Y, UP_AXIS_Z }; enum NodeVisibility { NODE_VISIBILITY_DEFAULT, NODE_VISIBLE, NODE_HIDDEN, NODE_TREE_VISIBLE, NODE_TREE_HIDDEN }; enum ObjectVisibility { OBJECT_VISIBILITY_DEFAULT, OBJECT_VISIBLE, OBJECT_HIDDEN }; /** A custom parameter for renderables */ struct CustomParameter { size_t id; Ogre::Vector4 value; }; /** A simple bounding volume, centered around the owner's origin */ struct BoundingVolume { BoundingVolume() { this->type = NONE; this->sphereRadius = 0; this->boxSize = Ogre::Vector3::ZERO; } enum Type { NONE, SPHERE, BOX, MESH }; /** The bounding volume type */ Type type; /** The bounding sphere radius. Used when 'type' is SPHERE */ Ogre::Real sphereRadius; /** The bounding box size. Used when 'type' is BOX */ Ogre::Vector3 boxSize; /** A single face */ struct Face { Ogre::Vector3 vertex[3]; }; /** Faces of the mesh bounding volume. Used when 'type' is MESH */ std::vector<Face> meshFaces; }; /** A single note in a note track */ struct Note { Ogre::Real time; Ogre::String text; }; /** A collection of notes */ struct NoteTrack { Ogre::String name; std::vector<Note> notes; }; /** A collection of note tracks */ typedef std::vector<NoteTrack> NoteTracks; typedef Ogre::SharedPtr<NoteTracks> NoteTracksPtr; /** A single external item. */ struct ExternalItem { ExternalItem() { this->position = Ogre::Vector3::ZERO; this->scale = Ogre::Vector3::UNIT_SCALE; } Ogre::String name; Ogre::String type; Ogre::String file; Ogre::String userDataReference; Ogre::String userData; Ogre::Vector3 position; Ogre::Quaternion rotation; Ogre::Vector3 scale; BoundingVolume boundingVolume; NoteTracks noteTracks; }; /** * Extra data placed for a various object types. * Depending on the context and type of object, some of the fields in this structure might not be used */ struct ObjectExtraData { ObjectExtraData() { this->node = 0; this->object = 0; this->receiveShadows = false; } /** * Initializes the data from another data object * Note that the object/node fields aren't copied */ ObjectExtraData(ObjectExtraData& other) { this->node = 0; this->object = 0; this->id = other.id; this->userDataReference = other.userDataReference; this->userData = other.userData; this->receiveShadows = other.receiveShadows; this->receiveShadows = other.receiveShadows; this->noteTracks = other.noteTracks; } /** Determines if there is any user data */ bool HasUserData() const { return !this->id.empty() || !this->userDataReference.empty() || !this->userData.empty(); } /** If set, the extra data belongs to an Ogre::Node */ Ogre::Node* node; /** If set, the extra data belongs to an Ogre::MovableObject */ Ogre::MovableObject* object; Ogre::String id; Ogre::String userDataReference; Ogre::String userData; bool receiveShadows; NoteTracksPtr noteTracks; }; typedef Ogre::SharedPtr<ObjectExtraData> ObjectExtraDataPtr; struct FogParameters { FogParameters() { this->mode = Ogre::FOG_NONE; this->expDensity = .001; this->linearStart = 0; this->linearEnd = 1; this->color = Ogre::ColourValue::White; } Ogre::FogMode mode; Ogre::Real expDensity; Ogre::Real linearStart; Ogre::Real linearEnd; Ogre::ColourValue color; }; struct SkyBoxParameters { SkyBoxParameters() { this->enabled = true; this->distance = 0; this->drawFirst = true; } bool enabled; Ogre::String material; Ogre::Real distance; bool drawFirst; Ogre::Quaternion rotation; Ogre::String resourceGroupName; ObjectExtraData extraData; }; struct SkyDomeParameters { SkyDomeParameters() { this->enabled = true; this->curvature = 0; this->tiling = 0; this->distance = 0; this->drawFirst = true; this->xSegments = 0; this->ySegments = 0; } bool enabled; Ogre::String material; Ogre::Real curvature; Ogre::Real tiling; Ogre::Real distance; bool drawFirst; int xSegments; int ySegments; Ogre::Quaternion rotation; Ogre::String resourceGroupName; ObjectExtraData extraData; }; struct SkyPlaneParameters { SkyPlaneParameters() { this->enabled = true; this->scale = 1; this->bow = 0; this->tiling = 10; this->drawFirst = true; this->xSegments = 1; this->ySegments = 1; } bool enabled; Ogre::String material; Ogre::Plane plane; Ogre::Real scale; Ogre::Real bow; Ogre::Real tiling; bool drawFirst; int xSegments; int ySegments; Ogre::String resourceGroupName; ObjectExtraData extraData; }; struct ObjectParameters { enum ObjectType { NONE, ENTITY, LIGHT, CAMERA, PARTICLE_SYSTEM, BILLBOARD_SET, PLANE }; ObjectParameters() { this->objectType = NONE; this->renderQueue = Ogre::RENDER_QUEUE_MAIN; this->renderingDistance = 0; this->queryFlags = 0; this->visibilityFlags = 0; this->visibility = OBJECT_VISIBILITY_DEFAULT; } virtual ~ObjectParameters() { } /** Name of the object */ Ogre::String name; /** * The object type. * This can be used to determine which ObjectParameters subclass can be used */ ObjectType objectType; /** The object's extra data */ ObjectExtraDataPtr extraData; /** Object query flags */ Ogre::uint32 queryFlags; /** Object visibility flags */ Ogre::uint32 visibilityFlags; /** Indicates whether object is visible */ ObjectVisibility visibility; /** Rendering queue. Not used by all types */ Ogre::uint8 renderQueue; /** Rendering distance. Not used by all types */ Ogre::Real renderingDistance; typedef std::vector<CustomParameter> CustomParameters; /** Custom values. Not used by all types */ CustomParameters customParameters; }; struct EntityParameters : ObjectParameters { EntityParameters() { this->objectType = ENTITY; this->castShadows = true; this->vertexBufferUsage = Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY; this->indexBufferUsage = Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY; this->vertexBufferShadowed = true; this->indexBufferShadowed = true; } Ogre::String meshFile; Ogre::String materialFile; bool castShadows; Ogre::HardwareBuffer::Usage vertexBufferUsage; Ogre::HardwareBuffer::Usage indexBufferUsage; bool vertexBufferShadowed; bool indexBufferShadowed; Ogre::String resourceGroupName; struct Subentity { Ogre::String materialName; }; std::vector<Subentity> subentities; struct BoneAttachment { BoneAttachment() { this->object = 0; this->attachPosition = Ogre::Vector3::ZERO; this->attachScale = Ogre::Vector3::UNIT_SCALE; this->attachRotation = Ogre::Quaternion::IDENTITY; } ~BoneAttachment() { delete this->object; } /** Gets the name of the attachment itself */ const Ogre::String& GetName() const { return this->object != 0 ? this->object->name : this->name; } Ogre::String name; //Used if object is null Ogre::String boneName; ObjectParameters* object; Ogre::Vector3 attachPosition; Ogre::Vector3 attachScale; Ogre::Quaternion attachRotation; }; std::vector<BoneAttachment> boneAttachments; }; struct LightParameters : ObjectParameters { LightParameters() { this->objectType = LIGHT; this->lightType = Ogre::Light::LT_POINT; this->castShadows = false; this->power = 1; this->diffuseColor = Ogre::ColourValue::White; this->specularColor = Ogre::ColourValue::Black; this->spotlightInnerAngle = Ogre::Degree((Ogre::Real)40); this->spotlightOuterAngle = Ogre::Degree((Ogre::Real)30); this->spotlightFalloff = 1; this->attenuationRange = 100000; this->attenuationConstant = 1; this->attenuationLinear = 0; this->attenuationQuadric = 0; this->position = Ogre::Vector3::ZERO; this->direction = Ogre::Vector3::UNIT_Z; } Ogre::Light::LightTypes lightType; bool castShadows; Ogre::Real power; Ogre::ColourValue diffuseColor; Ogre::ColourValue specularColor; Ogre::Radian spotlightInnerAngle; Ogre::Radian spotlightOuterAngle; Ogre::Real spotlightFalloff; Ogre::Real attenuationRange; Ogre::Real attenuationConstant; Ogre::Real attenuationLinear; Ogre::Real attenuationQuadric; Ogre::Vector3 position; Ogre::Vector3 direction; }; struct CameraParameters : ObjectParameters { CameraParameters() { this->objectType = CAMERA; this->fov = Ogre::Radian(1.57); this->aspectRatio = (Ogre::Real)1.33; this->projectionType = Ogre::PT_PERSPECTIVE; this->nearClip = 100; this->farClip = 100000; this->position = Ogre::Vector3::ZERO; this->direction = Ogre::Vector3::NEGATIVE_UNIT_Z; } Ogre::Radian fov; Ogre::Real aspectRatio; Ogre::ProjectionType projectionType; Ogre::Real nearClip; Ogre::Real farClip; Ogre::Vector3 position; Ogre::Quaternion orientation; Ogre::Vector3 direction; }; struct ParticleSystemParameters : ObjectParameters { ParticleSystemParameters() { this->objectType = PARTICLE_SYSTEM; } Ogre::String file; }; struct BillboardSetParameters : ObjectParameters { BillboardSetParameters() { this->objectType = BILLBOARD_SET; this->commonDirection = Ogre::Vector3::UNIT_Z; this->commonUpVector = Ogre::Vector3::UNIT_Y; this->billboardType = Ogre::BBT_POINT; this->origin = Ogre::BBO_CENTER; this->rotationType = Ogre::BBR_TEXCOORD; this->poolSize = 0; this->autoExtendPool = true; this->cullIndividual = false; this->sort = false; this->accurateFacing = false; } Ogre::String material; Ogre::Real width; Ogre::Real height; Ogre::BillboardType billboardType; Ogre::BillboardOrigin origin; Ogre::BillboardRotationType rotationType; Ogre::Vector3 commonDirection; Ogre::Vector3 commonUpVector; Ogre::uint32 poolSize; bool autoExtendPool; bool cullIndividual; bool sort; bool accurateFacing; struct Billboard { Billboard() : texCoordRectangle(0, 0, 0, 0) { this->width = 0; this->height = 0; this->rotationAngle = Ogre::Radian(0); this->position = Ogre::Vector3::ZERO; this->color = Ogre::ColourValue::White; } Ogre::Real width; Ogre::Real height; Ogre::FloatRect texCoordRectangle; Ogre::Radian rotationAngle; Ogre::Vector3 position; Ogre::ColourValue color; }; std::vector<Billboard> billboards; }; struct PlaneParameters : ObjectParameters { PlaneParameters() { this->objectType = PLANE; this->xSegments = 0; this->ySegments = 0; this->numTexCoordSets = 0; this->uTile = 0; this->vTile = 0; this->normals = true; this->createMovablePlane = true; this->castShadows = true; this->normal = Ogre::Vector3::ZERO; this->upVector = Ogre::Vector3::UNIT_Z; this->vertexBufferUsage = Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY; this->indexBufferUsage = Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY; this->vertexBufferShadowed = true; this->indexBufferShadowed = true; } Ogre::String planeName; Ogre::Real distance; Ogre::Real width; Ogre::Real height; int xSegments; int ySegments; int numTexCoordSets; Ogre::Real uTile; Ogre::Real vTile; Ogre::String material; bool normals; bool createMovablePlane; bool castShadows; Ogre::Vector3 normal; Ogre::Vector3 upVector; Ogre::HardwareBuffer::Usage vertexBufferUsage; Ogre::HardwareBuffer::Usage indexBufferUsage; bool vertexBufferShadowed; bool indexBufferShadowed; Ogre::String resourceGroupName; }; struct NodeAnimationParameters { NodeAnimationParameters() { this->length = 0; this->interpolationMode = Ogre::Animation::IM_SPLINE; this->rotationInterpolationMode = Ogre::Animation::RIM_LINEAR; this->enable = true; this->looping = true; } Ogre::String name; Ogre::Real length; Ogre::Animation::InterpolationMode interpolationMode; Ogre::Animation::RotationInterpolationMode rotationInterpolationMode; bool enable; bool looping; struct KeyFrame { KeyFrame() { this->time = 0; this->translation = Ogre::Vector3::ZERO; this->scale = Ogre::Vector3::UNIT_SCALE; } Ogre::Real time; Ogre::Vector3 translation; Ogre::Quaternion rotation; Ogre::Vector3 scale; }; std::vector<KeyFrame> keyframes; }; struct NodeParameters { NodeParameters() { this->visibility = NODE_VISIBILITY_DEFAULT; this->position = Ogre::Vector3::ZERO; this->scale = Ogre::Vector3::UNIT_SCALE; } ~NodeParameters() { for (Objects::iterator objectIterator = this->objects.begin(); objectIterator != this->objects.end(); ++objectIterator) { delete *objectIterator; } } /** The nodes's extra data */ ObjectExtraDataPtr extraData; Ogre::String name; Ogre::String modelFile; NodeVisibility visibility; Ogre::Vector3 position; Ogre::Quaternion orientation; Ogre::Vector3 scale; std::vector<NodeParameters> childNodes; std::vector<NodeAnimationParameters> animations; typedef std::list<ObjectParameters*> Objects; Objects objects; }; struct RenderTextureParameters { RenderTextureParameters() { this->width = this->height = 512; this->pixelFormat = Ogre::PF_A8R8G8B8; this->textureType = Ogre::TEX_TYPE_2D; this->clearEveryFrame = true; this->autoUpdate = true; this->hideRenderObject = true; } Ogre::String name; int width; int height; Ogre::PixelFormat pixelFormat; Ogre::TextureType textureType; Ogre::String cameraName; Ogre::String scheme; Ogre::ColourValue backgroundColor; bool clearEveryFrame; bool autoUpdate; bool hideRenderObject; Ogre::String renderObjectName; Ogre::Plane renderPlane; std::vector<Ogre::String> hiddenObjects; std::vector<Ogre::String> exclusiveObjects; Ogre::String resourceGroupName; struct Material { Ogre::String name; unsigned short techniqueIndex; unsigned short passIndex; unsigned short textureUnitIndex; }; std::vector<Material> materials; }; struct ShadowParameters { ShadowParameters() { this->shadowTechnique = Ogre::SHADOWTYPE_NONE; this->selfShadow = true; this->farDistance = 0; this->textureSize = 512; this->textureCount = 2; this->textureOffset = (Ogre::Real).6; this->textureFadeStart = (Ogre::Real).7; this->textureFadeEnd = (Ogre::Real).9; this->pixelFormat = Ogre::PF_UNKNOWN; this->shadowColor = Ogre::ColourValue::Black; } Ogre::ShadowTechnique shadowTechnique; bool selfShadow; Ogre::Real farDistance; int textureSize; int textureCount; Ogre::Real textureOffset; Ogre::Real textureFadeStart; Ogre::Real textureFadeEnd; Ogre::String textureShadowCasterMaterial; Ogre::String textureShadowReceiverMaterial; Ogre::PixelFormat pixelFormat; Ogre::ColourValue shadowColor; Ogre::String cameraSetup; Ogre::Plane optimalPlane; }; struct LookTarget { /** * Initializes the LookTarget for a scene node or camera. * Either sourceNode or sourceCamera must be non-null */ LookTarget(Ogre::SceneNode* sourceNode, Ogre::Camera* sourceCamera) { this->sourceNode = sourceNode; this->sourceCamera = sourceCamera; this->relativeTo = Ogre::Node::TS_LOCAL; this->isPositionSet = false; this->position = Ogre::Vector3::ZERO; this->localDirection = Ogre::Vector3::NEGATIVE_UNIT_Z; } Ogre::SceneNode* sourceNode; Ogre::Camera* sourceCamera; Ogre::String nodeName; Ogre::Node::TransformSpace relativeTo; bool isPositionSet; Ogre::Vector3 position; Ogre::Vector3 localDirection; }; struct TrackTarget { /** * Initializes the TrackTarget for a scene node or camera. * Either sourceNode or sourceCamera must be non-null */ TrackTarget(Ogre::SceneNode* sourceNode, Ogre::Camera* sourceCamera) { this->sourceNode = sourceNode; this->sourceCamera = sourceCamera; this->offset = Ogre::Vector3::ZERO; this->localDirection = Ogre::Vector3::NEGATIVE_UNIT_Z; } Ogre::SceneNode* sourceNode; Ogre::Camera* sourceCamera; Ogre::String nodeName; Ogre::Vector3 offset; Ogre::Vector3 localDirection; }; struct SceneNodeArray : std::vector<Ogre::SceneNode*> { void Show() { for (size_t i = 0; i < size(); i++) (*this)[i]->setVisible(true, false); } void Hide() { for (size_t i = 0; i < size(); i++) (*this)[i]->setVisible(false, false); } }; /** A loaded render texture */ struct LoadedRenderTexture { enum {CUBE_FACE_COUNT = 6}; LoadedRenderTexture() { this->renderObjectNode = 0; this->renderPlane = 0; this->camera = 0; for (int index = 0; index < CUBE_FACE_COUNT; index++) { this->cubeFaceCameras[index] = 0; this->viewports[index] = 0; } } /** Sets the position of all cube face cameras */ void SetCubeFaceCameraPosition(const Ogre::Vector3& position) { for (int index = 0; index < CUBE_FACE_COUNT; index++) this->cubeFaceCameras[index]->setPosition(position); } /** * Gets the 'reference' position, which is used when updating a cube map render texture. * The preferred position is that of the render object. If there is no render object, the reference * camera is used. If there is no camera, the zero vector is used. * @param position [out] - The position. If there is no reference object, this is set to zero. * @return Returns true if there was a reference object to use, false otherwise. */ bool GetReferencePosition(Ogre::Vector3& position) const { bool result = true; if (this->renderObjectNode != 0) position = this->renderObjectNode->_getDerivedPosition(); else if (this->camera != 0) position = this->camera->getDerivedPosition(); else { position = Ogre::Vector3::ZERO; result = false; } return result; } RenderTextureParameters parameters; Ogre::TexturePtr renderTexture; Ogre::SceneNode* renderObjectNode; Ogre::MovablePlane* renderPlane; Ogre::Camera* camera; Ogre::Camera* cubeFaceCameras[CUBE_FACE_COUNT]; Ogre::Viewport* viewports[CUBE_FACE_COUNT]; SceneNodeArray hiddenObjects; SceneNodeArray exclusiveObjects; }; /** Maps a query flag bit to a name */ struct FlagAlias { FlagAlias() { this->bit = 0; } Ogre::String name; int bit; }; /** A collection of flag aliases */ struct FlagAliases : std::vector<FlagAlias> { /** * Gets the name that corresponds to the specified bit * @param bit [in] - The index of the bit to look up * @param name [out] - The name of the bit * @return Returns true if the bit's name was found, false otherwise */ bool GetBitName(int bit, Ogre::String& name) { for (size_t index = 0; index < size(); index++) { if ((*this)[index].bit == bit) { name = (*this)[index].name; return true; } } return false; } }; /** Used for attaching MovableObject instances to an owner */ struct MovableObjectOwner { /** No owner */ MovableObjectOwner() { this->node = 0; this->entity = 0; this->attachPosition = Ogre::Vector3::ZERO; this->attachScale = Ogre::Vector3::UNIT_SCALE; this->attachRotation = Ogre::Quaternion::IDENTITY; } /** The owner is a scene node */ MovableObjectOwner(Ogre::SceneNode* node) { this->node = node; this->entity = 0; this->attachPosition = Ogre::Vector3::ZERO; this->attachScale = Ogre::Vector3::UNIT_SCALE; this->attachRotation = Ogre::Quaternion::IDENTITY; } /** The owner is a bone within an entity's skeleton */ MovableObjectOwner ( Ogre::Entity* entity, const Ogre::String& boneName = Ogre::StringUtil::BLANK, const Ogre::Vector3& attachPosition = Ogre::Vector3::ZERO, const Ogre::Vector3& attachScale = Ogre::Vector3::UNIT_SCALE, const Ogre::Quaternion& attachRotation = Ogre::Quaternion::IDENTITY ) { this->node = 0; this->entity = entity; this->boneName = boneName; this->attachPosition = attachPosition; this->attachScale = attachScale; this->attachRotation = attachRotation; } /** Attaches the movable object to the owner */ void Attach(Ogre::MovableObject* object) const { if (this->node != 0) this->node->attachObject(object); else if (this->entity != 0 && !this->boneName.empty()) { //TODO: Modify Ogre to accept object->getName() when creating TagPoint Ogre::TagPoint* tagPoint = this->entity->attachObjectToBone(this->boneName, object); tagPoint->setPosition(this->attachPosition); tagPoint->setScale(this->attachScale); tagPoint->setOrientation(this->attachRotation); } } /** * Attaches an empty object to the owner. This has no effect if the owner is a node since * there's no notion of an "empty" object for nodes. For entities, an "empty" object corresponds * to a tag point that has no attachment */ void AttachEmpty(const Ogre::String& name = Ogre::StringUtil::BLANK) const { if (this->entity != 0 && !this->boneName.empty()) { Ogre::SkeletonInstance* skeleton = this->entity->getSkeleton(); Ogre::Bone* bone = skeleton->getBone(this->boneName); //TODO: Modify Ogre to accept name when creating TagPoint Ogre::TagPoint* tagPoint = skeleton->createTagPointOnBone(bone); tagPoint->setPosition(this->attachPosition); tagPoint->setScale(this->attachScale); tagPoint->setOrientation(this->attachRotation); } } Ogre::SceneNode* node; Ogre::Entity* entity; Ogre::String boneName; Ogre::Vector3 attachPosition; Ogre::Vector3 attachScale; Ogre::Quaternion attachRotation; }; } } #endif
[ "eplaylity@7a9255ae-169e-11de-b69a-45dc1c5e4070" ]
[ [ [ 1, 998 ] ] ]
b7036f44375b5ef2abcc00666e91f068ed43cedf
d22b77645ee83ee72fed70cb2a3ca4fb268ada4a
/admin/zone_admin/WindowsService.cpp
ae0a90387a357088a6a798ceb71a1678c7b77f82
[]
no_license
catid/Splane
8f94f7d8983cf994955e599fc53ce6f763157486
c9f79f0034d1762948b7c26e42f50f58793067ac
refs/heads/master
2020-04-26T00:28:48.571474
2010-06-02T05:37:43
2010-06-02T05:37:43
628,653
1
0
null
null
null
null
UTF-8
C++
false
false
8,873
cpp
/* Copyright (c) 2009-2010 Christopher A. Taylor. 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 LibCat 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. */ #include "WindowsService.hpp" using namespace cat; //// Entrypoint int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { if (!InitializeFramework("LoginDatabaseServer")) { FatalStop("Unable to initialize framework!"); } if (lpCmdLine && iStrEqual(lpCmdLine, "install")) { if (WindowsService::ref()->IsExistingService()) { WindowsService::ref()->RemoveService(); } if (!WindowsService::ref()->InstallService()) { MessageBoxA(0, "Unable to install service", "Cannot Install Server", 0); } } else if (lpCmdLine && iStrEqual(lpCmdLine, "remove")) { if (WindowsService::ref()->IsExistingService()) { if (!WindowsService::ref()->RemoveService()) { MessageBoxA(0, "Unable to remove service", "Cannot Remove Server", 0); } } else { MessageBoxA(0, "Service is not installed", "Cannot Remove Server", 0); } } else { if (!WindowsService::ref()->StartServiceMain()) { MessageBoxA(0, "Unable to initialize service.\n\nThe server should be started from an Administrator command prompt by typing\n\n\"zone_srv.exe install\"", "Cannot Start Server", 0); } } ShutdownFramework(true); return 0; } WindowsService::WindowsService() { const char *settings_service_name = Settings::ii->getStr("Service.Name", "LoginDatabaseServer"); CAT_STRNCPY(_service_name, settings_service_name, sizeof(_service_name)); _service_handle = 0; _server = 0; } WindowsService::~WindowsService() { } bool WindowsService::IsExistingService() { // If able to open Service Control Manager to check service, SC_HANDLE scm_check = OpenSCManager(0, 0, SC_MANAGER_CONNECT); if (scm_check) { // If service already exists, SC_HANDLE svc_check = OpenServiceA(scm_check, _service_name, SERVICE_QUERY_STATUS); if (svc_check) { CloseServiceHandle(svc_check); CloseServiceHandle(scm_check); return true; } CloseServiceHandle(scm_check); } else { FATAL("ServiceManager") << "IsExistingService(): Unable to connect Service Control Manager"; } return false; } bool WindowsService::InstallService() { // If able to open Service Control Manager to create service, SC_HANDLE scm_create = OpenSCManager(0, 0, SC_MANAGER_CREATE_SERVICE); if (scm_create) { char path[MAX_PATH+1]; // Get the path to this executable module DWORD len = GetModuleFileNameA(0, path, sizeof(path)); path[sizeof(path) - 1] = '\0'; if (len == strlen(path)) { // Create the service SC_HANDLE svc_create = CreateServiceA(scm_create, _service_name, _service_name, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_IGNORE, path, 0, 0, 0, 0, 0); if (svc_create) { INFO("ServiceManager") << "InstallService(): Starting service"; StartService(svc_create, 0, 0); CloseServiceHandle(svc_create); CloseServiceHandle(scm_create); return true; } else { FATAL("ServiceManager") << "InstallService(): Unable to create service"; } } else { FATAL("ServiceManager") << "InstallService(): Unable to get module file path"; } CloseServiceHandle(scm_create); } else { FATAL("ServiceManager") << "InstallService(): Unable to create Service Control Manager"; } return false; } bool WindowsService::RemoveService() { // If able to open Service Control Manager to create service, SC_HANDLE scm_remove = OpenSCManager(0, 0, STANDARD_RIGHTS_REQUIRED); if (scm_remove) { // If service already exists, SC_HANDLE svc_remove = OpenServiceA(scm_remove, _service_name, SERVICE_STOP | DELETE); if (svc_remove) { SERVICE_STATUS status; ControlService(svc_remove, SERVICE_CONTROL_STOP, &status); if (DeleteService(svc_remove)) { CloseServiceHandle(svc_remove); CloseServiceHandle(scm_remove); return true; } else { FATAL("ServiceManager") << "RemoveService(): Unable to delete service, error " << GetLastError(); } CloseServiceHandle(svc_remove); } else { FATAL("ServiceManager") << "RemoveService(): Unable to open service for deletion, error " << GetLastError(); } CloseServiceHandle(scm_remove); } else { FATAL("ServiceManager") << "RemoveService(): Unable to open Service Control Manager, error " << GetLastError(); } return false; } bool WindowsService::StartServiceMain() { _quit_handle = CreateEvent(0, FALSE, FALSE, 0); if (!_quit_handle) { FATAL("ServiceManager") << "StartServiceMain(): Unable to create quit event"; return false; } SERVICE_TABLE_ENTRYA table[] = { { (LPSTR)WindowsService::ii->_service_name, ServiceMain }, { 0, 0 } }; if (!StartServiceCtrlDispatcherA(table)) { FATAL("ServiceManager") << "StartServiceMain(): Unable to start service control dispatcher"; return false; } return true; } void WindowsService::OnControl(DWORD fdwControl) { switch (fdwControl) { case SERVICE_CONTROL_PAUSE: Pause(); break; case SERVICE_CONTROL_CONTINUE: Continue(); break; case SERVICE_CONTROL_SHUTDOWN: case SERVICE_CONTROL_STOP: Shutdown(); break; } } void WindowsService::OnMain(DWORD dwNumServicesArgs, LPSTR *lpServiceArgVectors) { _service_handle = RegisterServiceCtrlHandlerA(_service_name, ServiceHandler); if (!_service_handle) { FATAL("ServiceManager") << "ServiceMain(): Unable to register control handler for " << _service_name; return; } Startup(); // Wait until quit object is signaled WaitForSingleObject(_quit_handle, INFINITE); } void WINAPI WindowsService::ServiceHandler(DWORD fdwControl) { WindowsService::ii->OnControl(fdwControl); } void WINAPI WindowsService::ServiceMain(DWORD dwNumServicesArgs, LPSTR *lpServiceArgVectors) { WindowsService::ii->OnMain(dwNumServicesArgs, lpServiceArgVectors); } void WindowsService::SetState(DWORD state) { if (_service_handle) { SERVICE_STATUS serv_status; CAT_OBJCLR(serv_status); serv_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; serv_status.dwCurrentState = state; serv_status.dwControlsAccepted = SERVICE_ACCEPT_PAUSE_CONTINUE | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_STOP; SetServiceStatus(_service_handle, &serv_status); } } //// Service Events void WindowsService::Startup() { SetState(SERVICE_START_PENDING); _server = new LoginDatabaseServer; if (!_server) { Shutdown(); return; } if (!_server->Initialize()) { Shutdown(); return; } SetState(SERVICE_RUNNING); } void WindowsService::Shutdown() { SetState(SERVICE_STOP_PENDING); // If server is started, if (_server) { _server->Shutdown(); _server = 0; } SetEvent(_quit_handle); // Need to set state to stopped or else application will never terminate SetState(SERVICE_STOPPED); } void WindowsService::Pause() { SetState(SERVICE_PAUSE_PENDING); if (_server) { _server->Pause(); } SetState(SERVICE_PAUSED); } void WindowsService::Continue() { SetState(SERVICE_CONTINUE_PENDING); if (_server) { _server->Continue(); } SetState(SERVICE_RUNNING); }
[ "kuang@.(none)" ]
[ [ [ 1, 356 ] ] ]
917a94702f809c5dac40e18710db074bb769fd64
3ab5d507d11afdab41c8c1b509cc2a807d717897
/src/VoIPPacketsManager/NoSteg.h
e2274bf17b4217e0804e3a45242899a47a4620a0
[]
no_license
mkurdej/pwtinproject
73dd952ca7b18c36b0c68124bd4447c9741fa372
f11afa69776c9f9b55c3c3466544ed49e56ebdff
refs/heads/master
2016-09-05T18:39:33.692316
2010-01-19T10:16:55
2010-01-19T10:16:55
32,997,874
0
0
null
null
null
null
UTF-8
C++
false
false
1,299
h
/* * NoSteg.h * * Created on: 2010-01-14 * Author: Piotr Gwizda�a */ #ifndef NOSTEG_H_ #define NOSTEG_H_ #include "VoIPPacketsManager.h" #include "../Debug/Debug.h" #include "../Util/Timer.h" #include <vector> /** * \~ * \~polish * Implementacja @ref VoIPPacketsManager wysyłająca wyłącznie dane audio. * * Dzieli dane audio na pakiety i wysyła je w równych odstępach czasu. * Jest nieświadoma transmisji pakietów steganograficznych. * * \~english * Implementation of @ref VoIPPacketsManager that sends only audio data. * * Divides audio data into packets and sends them in equal time spans. * <code>NoSteg</code> is completely unaware of possible steganographic * data packets that it receives. * \~ * @see StegLACK */ class NoSteg: public VoIPPacketsManager { static const int DEFAULT_PACKET_DELAY = TIMESTAMP_INTERVAL_8KHZ; public: NoSteg(Config* cfg); virtual ~NoSteg(); virtual RTPPacket& getNextPacket(); virtual void putReceivedPacketData(RTPPacket& packet); private: /** * Counts the time that passed since last packet was read from the incoming queue */ Timer timeSinceLastQueueRead; /** * Incoming packets queue */ vector<RTPPacket> incQueue; }; #endif /* NOSTEG_H_ */
[ "gwizdek@f427f6ac-f01a-11de-af0a-9d584d74d99e", "marek.kurdej@f427f6ac-f01a-11de-af0a-9d584d74d99e" ]
[ [ [ 1, 4 ], [ 6, 11 ], [ 13, 15 ], [ 33, 33 ], [ 35, 37 ], [ 40, 56 ] ], [ [ 5, 5 ], [ 12, 12 ], [ 16, 32 ], [ 34, 34 ], [ 38, 39 ] ] ]
afee65c57a86c96fec03521ac27b20f39829f825
c1eae8224c4d3d380cc83ff6b218ba2a9df8d687
/Source Codes/MeshUI/MeshLib/MeshModelIO.cpp
a741cc4335e6982782776aaafaf9e0e8085075c7
[]
no_license
pizibing/noise-removal
15bad5c0fe1b3b5fb3f8b775040fc3dfeb48e49b
c087356bfa07305ce7ac6cce8745b1e676d6dc42
refs/heads/master
2016-09-06T17:40:15.754799
2010-03-05T06:47:59
2010-03-05T06:47:59
34,849,474
1
0
null
null
null
null
UTF-8
C++
false
false
13,797
cpp
/* ================== Library Information ================== */ // [Name] // MeshLib Library // // [Developer] // Xu Dong // State Key Lab of CAD&CG, Zhejiang University // // [Date] // 2005-08-05 // // [Goal] // A general, flexible, versatile and easy-to-use mesh library for research purpose. // Supporting arbitrary polygonal meshes as input, but with a // primary focus on triangle meshes. /* ================== File Information ================== */ // [Name] // MeshModelIO.cpp // // [Developer] // Xu Dong // State Key Lab of CAD&CG, Zhejiang University // // [Date] // 2005-08-05 // // [Goal] // Defining the input/output (I/O) functions of the kernel components of the mesh model // Supporting various 3D model files, including .tm, .obj, .off, etc #include "stdafx.h" #include "MeshModelIO.h" #include <iostream> #include <fstream> /* ================== Mesh Model I/O Functions ================== */ // Constructor MeshModelIO::MeshModelIO() { kernel = NULL; } // Destructor MeshModelIO::~MeshModelIO() { } // Initializer void MeshModelIO::ClearData() { } void MeshModelIO::AttachKernel(MeshModelKernel* pKernel /* = NULL */) { kernel = pKernel; } // General I/O functions, platform-dependent functions bool MeshModelIO::LoadModel(string filename) { // Resolve file name string file_path, file_title, file_ext; util.ResolveFileName(filename, file_path, file_title, file_ext); printf("Load Model %s... ", (file_title+file_ext).c_str()); // Set model informaion ModelInfo& mInfo = kernel->GetModelInfo(); mInfo.SetFileName(filename); // Load model util.MakeLower(file_ext); bool bOpenFlag; if(file_ext == ".tm") { bOpenFlag = OpenTmFile(filename); } else if(file_ext == ".ply2") { bOpenFlag = OpenPly2File(filename); } else if(file_ext == ".off") { bOpenFlag = OpenOffFile(filename); } else if(file_ext == ".obj") { bOpenFlag = OpenObjFile(filename); } else { bOpenFlag = false; } printf("%s\n", (bOpenFlag == true) ? "Success" : "Fail"); if(bOpenFlag) { size_t nVertex = kernel->GetVertexInfo().GetCoord().size(); size_t nFace = kernel->GetFaceInfo().GetIndex().size(); printf("#Vertex = %d, #Face = %d\n\n", nVertex, nFace); } return bOpenFlag; } bool MeshModelIO::StoreModel(string filename) { // Resolve file name string file_path, file_title, file_ext; util.ResolveFileName(filename, file_path, file_title, file_ext); printf("Store Model %s... ", (file_title+file_ext).c_str()); // Store model util.MakeLower(file_ext); bool bSaveFlag; if(file_ext == ".tm") { bSaveFlag = SaveTmFile(filename); } else if(file_ext == ".ply2") { bSaveFlag = SavePly2File(filename); } else if(file_ext == ".off") { bSaveFlag = SaveOffFile(filename); } else if(file_ext == ".obj") { bSaveFlag = SaveObjFile(filename); } else { bSaveFlag = false; } printf("%s\n", (bSaveFlag == true) ? "Success" : "Fail"); return bSaveFlag; } // .tm file I/O functions bool MeshModelIO::OpenTmFile(string filename) { // Read data from file FILE* fp; fopen_s(&fp, filename.c_str(), "r"); if(fp == NULL) return false; int nVertex, nFace, nReadFace; fscanf_s(fp, "%d", &nVertex); fscanf_s(fp, "%d", &nFace); fscanf_s(fp, "%d", &nReadFace); // Prepare for a new mesh model kernel->ClearData(); // Load vertex information VertexInfo& vInfo = kernel->GetVertexInfo(); CoordArray& vCoord = vInfo.GetCoord(); vCoord.resize(nVertex); int i; float coordPos0; float coordPos1; float coordPos2; for(i = 0; i < nVertex; ++ i) { Coord& v = vCoord[i]; fscanf_s(fp, "%f %f %f", &coordPos0, &coordPos1, &coordPos2); v[0] = coordPos0; v[1] = coordPos1; v[2] = coordPos2; } // Load face information FaceInfo& fInfo = kernel->GetFaceInfo(); PolyIndexArray& fIndex = fInfo.GetIndex(); fIndex.resize(nFace); int fv0; int fv1; int fv2; for(i = 0; i < nFace; ++ i) { IntArray& f = fIndex[i]; f.resize(3); fscanf_s(fp, "%d %d %d", &fv0, &fv1, &fv2); f[0] = fv0; f[1] = fv1; f[2] = fv2; } fclose(fp); return true; } bool MeshModelIO::SaveTmFile(string filename) { // Read data from file ofstream file(filename.c_str()); if(!file) return false; size_t nVertex, nFace; VertexInfo& vInfo = kernel->GetVertexInfo(); CoordArray& arrCoord = vInfo.GetCoord(); nVertex = arrCoord.size(); FaceInfo& fInfo = kernel->GetFaceInfo(); PolyIndexArray& arrIndex = fInfo.GetIndex(); nFace = arrIndex.size(); file << nVertex << ' ' << nFace << ' ' << nFace << '\n'; // Store vertex information size_t i, j; for(i = 0; i < nVertex; ++ i) { Coord& v = arrCoord[i]; for(j = 0; j < 3; ++ j) file << v[j] << ((j<2) ? ' ' : '\n'); } // Store face information for(i = 0; i < nFace; ++ i) { IntArray& f = arrIndex[i]; for(j = 0; j < 3; ++ j) file << f[j] << ((j<2) ? ' ' : '\n'); } file.close(); return true; } // .ply2 file I/O functions bool MeshModelIO::OpenPly2File(string filename) { // Read data from file ifstream file(filename.c_str()); if(! file) return false; int nVertex, nFace; file >> nVertex >> nFace; // Prepare for a new mesh model kernel->ClearData(); // Load vertex information VertexInfo& vInfo = kernel->GetVertexInfo(); CoordArray& vCoord = vInfo.GetCoord(); vCoord.resize(nVertex); int i, j, n; for(i = 0; i < nVertex; ++ i) { Coord& v = vCoord[i]; for(j = 0; j < 3; ++ j) file >> v[j]; } // Load face information FaceInfo& fInfo = kernel->GetFaceInfo(); PolyIndexArray& fIndex = fInfo.GetIndex(); fIndex.resize(nFace); for(i = 0; i < nFace; ++ i) { IntArray& f = fIndex[i]; file >> n; f.resize(n); for(j = 0; j < n; ++ j) file >> f[j]; } file.close(); return true; } bool MeshModelIO::SavePly2File(string filename) { // Read data from file ofstream file(filename.c_str()); if(!file) return false; size_t nVertex, nFace; VertexInfo& vInfo = kernel->GetVertexInfo(); CoordArray& arrCoord = vInfo.GetCoord(); nVertex = arrCoord.size(); FaceInfo& fInfo = kernel->GetFaceInfo(); PolyIndexArray& arrIndex = fInfo.GetIndex(); nFace = arrIndex.size(); file << nVertex << ' ' << nFace << '\n'; // Store vertex information size_t i, j, n; for(i = 0; i < nVertex; ++ i) { Coord& v = arrCoord[i]; for(j = 0; j < 3; ++ j) file << v[j] << ((j<2) ? ' ' : '\n'); } // Store face information for(i = 0; i < nFace; ++ i) { IntArray& f = arrIndex[i]; n = f.size(); file << n << ' '; for(j = 0; j < 3; ++ j) file << f[j] << ((j<2) ? ' ' : '\n'); } file.close(); return true; } // .off file I/O functions bool MeshModelIO::OpenOffFile(string filename) { // Read data from file FILE* fp; fopen_s(&fp, filename.c_str(), "r"); if(fp == NULL) return false; char format[10]; fscanf_s(fp, "%s", format); int nVertex, nFace, zero; fscanf_s(fp, "%d", &nVertex); fscanf_s(fp, "%d", &nFace); fscanf_s(fp, "%d", &zero); // Prepare for a new mesh model kernel->ClearData(); // Load vertex information VertexInfo& vInfo = kernel->GetVertexInfo(); CoordArray& vCoord = vInfo.GetCoord(); vCoord.resize(nVertex); int i, j, n; for(i = 0; i < nVertex; ++ i) { float tempCoord; Coord& v = vCoord[i]; for(j = 0; j < 3; ++ j) { fscanf_s(fp, "%f", &tempCoord); v[j] = tempCoord; } } // Load face information FaceInfo& fInfo = kernel->GetFaceInfo(); PolyIndexArray& fIndex = fInfo.GetIndex(); fIndex.resize(nFace); for(i = 0; i < nFace; ++ i) { IntArray& f = fIndex[i]; fscanf_s(fp, "%d", &n); f.resize(n); int vertexID; for(j = 0; j < n; ++ j) { fscanf_s(fp, "%d", &vertexID); f[j] = vertexID; } } fclose(fp); return true; } // .off file I/O functions bool MeshModelIO::SaveOffFile(string filename) { // Read data from file ofstream file(filename.c_str()); if(!file) return false; file << "OFF" << endl; size_t nVertex, nFace; VertexInfo& vInfo = kernel->GetVertexInfo(); CoordArray& arrCoord = vInfo.GetCoord(); nVertex = arrCoord.size(); FaceInfo& fInfo = kernel->GetFaceInfo(); PolyIndexArray& arrIndex = fInfo.GetIndex(); nFace = arrIndex.size(); file << nVertex << ' ' << nFace << ' ' << 0 <<'\n'; // Store vertex information size_t i, j, n; for(i = 0; i < nVertex; ++ i) { Coord& v = arrCoord[i]; for(j = 0; j < 3; ++ j) file << v[j] << ((j<2) ? ' ' : '\n'); } // Store face information for(i = 0; i < nFace; ++ i) { IntArray& f = arrIndex[i]; n = f.size(); file << n << ' '; for(j = 0; j < 3; ++ j) file << f[j] << ((j<2) ? ' ' : '\n'); } file.close(); return true; } bool MeshModelIO::OpenObjFile(string filename) { int nVertex = 0, nFace = 0; float coordPos0; float coordPos1; float coordPos2; int fv0; int fv1; int fv2; char format[10]; string str; ifstream ifs(filename.c_str()); if(ifs.fail()) return false; // find the vertex and face number here. while(!ifs.eof()) { getline(ifs, str, '\n'); if(ifs.fail()) break; if(str.empty()) continue; if(str[0] == '#') continue; if(str[0] == 'g') continue; if(str[0] == 'v' && str[1] == ' ') { ++nVertex; continue; } if(str[0] == 'f' && str[1] == ' ') { ++nFace; continue; } } ifs.clear(); ifs.seekg(0, ifstream::beg); // Prepare for a new mesh model kernel->ClearData(); // Load vertex information VertexInfo& vInfo = kernel->GetVertexInfo(); CoordArray& vCoord = vInfo.GetCoord(); vCoord.resize(nVertex); // Load face information FaceInfo& fInfo = kernel->GetFaceInfo(); PolyIndexArray& fIndex = fInfo.GetIndex(); fIndex.resize(nFace); size_t vn = 0, fn = 0; while(!ifs.eof()) { getline(ifs, str, '\n'); if(ifs.fail()) break; if(str.empty()) continue; if(str[0] == '#') continue; if(str[0] == 'g') continue; if(str[0] == 'o') continue; // read the vertex information here. if(str[0] == 'v' && str[1] == ' ') { sscanf_s(str.c_str(), "%s %f %f %f", format, sizeof(format), &coordPos0, &coordPos1, &coordPos2); Coord& v = vCoord[vn]; v[0] = coordPos0; v[1] = coordPos1; v[2] = coordPos2; ++vn; continue; } // read the face information here. if(str[0] == 'f' && str[1] == ' ') { vector<int> word_pos(1, 0); string delimit = " \t"; for(size_t i = 0; i < str.length(); ++i) { if(delimit.find(str[i]) == string::npos) continue; if(i+1 < str.length() && delimit.find(str[i+1]) == string::npos) word_pos.push_back((int) i+1); } if(word_pos.size() < 4) { cout << "bad polygon"; return false; } sscanf_s(str.c_str()+word_pos[1], "%d", &fv0); sscanf_s(str.c_str()+word_pos[2], "%d", &fv1); sscanf_s(str.c_str()+word_pos[3], "%d", &fv2); /* if (str.find("/") != string::npos) { sscanf(str.c_str(), "%s %d/%d %d/%d %d/%d", format, &fv0, &fn0, &fv1, &fn1, &fv2, &fn2); } else { sscanf(str.c_str(), "%s %d %d %d", format, &fv0, &fv1, &fv2); } */ IntArray& f = fIndex[fn]; f.resize(3); f[0] = fv0 - 1; f[1] = fv1 - 1; f[2] = fv2 - 1; ++fn; continue; } } ifs.close(); return true; } bool MeshModelIO::SaveObjFile(string filename) { ofstream file(filename.c_str()); if(!file) return false; file << "# " << endl; file << "# Wavefront OBJ file" << endl; file << "# object ..." + filename << endl; size_t nVertex, nFace; VertexInfo& vInfo = kernel->GetVertexInfo(); CoordArray& arrCoord = vInfo.GetCoord(); nVertex = arrCoord.size(); FaceInfo& fInfo = kernel->GetFaceInfo(); PolyIndexArray& arrIndex = fInfo.GetIndex(); nFace = arrIndex.size(); // Store vertex information size_t i, j; for(i = 0; i < nVertex; ++ i) { Coord& v = arrCoord[i]; file << "v "; for(j = 0; j < 3; ++ j) file << v[j] << ((j<2) ? ' ' : '\n'); } // Store face information for(i = 0; i < nFace; ++ i) { IntArray& f = arrIndex[i]; file << "f "; for(j = 0; j < 3; ++ j) file << f[j] + 1 << ((j<2) ? ' ' : '\n'); } file.close(); return true; }
[ "weihongyu1987@f7207f0a-2814-11df-8e46-3928208ddfa0" ]
[ [ [ 1, 611 ] ] ]
98719218d19beb59b61943d3adf9f110af617125
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Animation/Animation/Playback/Multithreaded/hkaMultithreadedAnimationUtils.h
7ddf8d2ff1c2443b2fee6e23d490f783031d1d25
[]
no_license
blockspacer/transporter-game
23496e1651b3c19f6727712a5652f8e49c45c076
083ae2ee48fcab2c7d8a68670a71be4d09954428
refs/heads/master
2021-05-31T04:06:07.101459
2009-02-19T20:59:59
2009-02-19T20:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,421
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_MUTLITHREADED_ANIMATION_UTILS_H #define HK_MUTLITHREADED_ANIMATION_UTILS_H #include <Common/Base/hkBase.h> #include <Animation/Animation/Playback/Multithreaded/hkaAnimationJobs.h> class hkaMultithreadedAnimationUtils { public: /* * Sample and Combine jobs */ /// Uses the memory manager to preallocate the animation control buffer static void HK_CALL allocateSampleAndCombineJob(const hkaAnimatedSkeleton* skeleton, hkaAnimationSampleAndCombineJob& jobOut); /// Frees the animation control buffer using the memory manager static void HK_CALL deallocateSampleAndCombineJob( hkaAnimationSampleAndCombineJob& jobOut); /// Grab the current data from the animated skeleton and fill in the job structure /// Note: the controlData pointer in the structure must be preallocated and capable of holding /// a number of entries equal to the number of active (non zero weight) controls. /// use allocateSampleAndCombineJob or allocate this manually static void HK_CALL createSampleAndCombineJob(const hkaAnimatedSkeleton* skeleton, hkUint32 maxBone, hkQsTransform* poseOut, hkUint32 maxFloat, hkReal* floatSlotsOut, hkInt16* parentIndicesForLocalToModel, hkaAnimationSampleAndCombineJob& jobOut); /// By default we use 75k max space (DEFAULT_MAX_COMPRESSED_ANIM_DATA) for animation buffer. /// which is very conservative. Use this method to get an upper bound on the size of the buffer required /// for a given hkaAnimationSampleAndCombineJob. Then set the job.m_bufferSize appropriately. static int HK_CALL getMaxSizeRequiredForSampleAndCombineJobBuffer(const hkaAnimatedSkeleton* skeleton); /// See getMaxSizeRequiredForSampleAndCombineJobBuffer(), but usable offline on a per-animation basis. /// At runtime, getMaxSizeRequiredForSampleAndCombineJobBuffer() called on an animated sksleton /// should return the same as the maximum of getConservativeMaxSizeRequiredForSampleAndCombineJobBuffer() /// over all animations used by the corresponding hkaAnimatedSkeleton. static int HK_CALL getConservativeMaxSizeRequiredForSampleAndCombineJobBuffer(const hkaSkeletalAnimation* animation); }; #endif // HK_MUTLITHREADED_ANIMATION_UTILS_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529) * * Confidential Information of Havok. (C) Copyright 1999-2008 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at * www.havok.com/tryhavok * */
[ "uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4" ]
[ [ [ 1, 64 ] ] ]
833a075f1f12583950209c6cdc0ccd5368bbb9ed
ad0076b418469ad3433daa809acba5fd2a9410e9
/board.h
635e99bbfcf402c120199e8f8b9255cfb90d3310
[]
no_license
PlumpMath/ergo
e3e8a4c43a81cb48671a13d6c7124e019b855fb7
dc2e9a96d23b46120af94aeedcbe81e8d602c640
refs/heads/master
2021-01-18T20:06:09.564888
2008-11-03T09:09:15
2008-11-03T09:09:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,239
h
#ifndef _BOARD_H #define _BOARD_H #include "position.h" #include "positionset.h" #include "positionstack.h" #include "config.h" class Simulator; #define NUM_HASHES 3 #define get_position(x,y) (&_positions[(x)*BOARD_SIZE + (y)]) #define get_neighbor(p,i) (_neighbors[((p)->value)][i]) #define neighbor_count(p) (_num_neighbors[(p->value)]) #define advance_hash() _hashes[(_curr_hash + 1)%NUM_HASHES] = _hashes[_curr_hash]; _curr_hash = (_curr_hash + 1) % NUM_HASHES; #define update_zobrist(p) _hashes[_curr_hash] ^= _zobrist[(p->value)]; #define check_ko() (_hashes[(_curr_hash + (NUM_HASHES-2))%NUM_HASHES] == _hashes[_curr_hash]) #define foreach_neighbor(p, n) int z = 0, n_count = neighbor_count(p); \ Position **neighbor_p; \ for (neighbor_p = &_neighbors[p->value][0], n = *neighbor_p; z < n_count; n = *(++neighbor_p), z++) #define BOARD_SAVE_SIZE (sizeof(Position)*NUM_POSITIONS + sizeof(PositionSet)+ sizeof(int)*3 + sizeof(long long)*NUM_HASHES) class Board { private: //These get saved Position _positions[NUM_POSITIONS]; PositionSet _eyes; int _score[2]; int _curr_hash; long long _hashes[NUM_HASHES]; //This is what they get saved to char _storage[BOARD_SAVE_SIZE]; //These are transient, and don't need to get saved PositionStack _dead_groups, _invalid_eyes, _new_eyes; Position *_neighbors[NUM_POSITIONS][4]; int _num_neighbors[NUM_POSITIONS]; long long _zobrist[NUM_POSITIONS]; Simulator *_simulator; public: // Board(); void register_simulator(Simulator* simulator); // void save_state(); void load_state(); // Color winner(); int score(Color stone); // bool move(enum Color stone, int position); // void print(); bool verify_state(); private: // Position* get_parent(Position *p); Position* get_parent_safe(Position *p); //Doesn't use path compression for easy move retraction void trim_parent(Position *p); // void remove_eye(Position *p); bool add_eye(Position *p); // void do_move(Position *p, enum Color stone); void retract_move(Position *p); // int clear(Position *p); }; #include "simulator.h" #endif
[ [ [ 1, 94 ] ] ]
a825b56a97d00c3dc336808338e6be972a7e64a2
c5ecda551cefa7aaa54b787850b55a2d8fd12387
/src/UILayer/Lists/DownloadListCtrl.h
22ceab5d68991356b07839e5c278ba0af27b3bac
[]
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,073
h
//this file is part of eMule //Copyright (C)2002-2006 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net ) // //This program is free software; you can redistribute it and/or //modify it under the terms of the GNU General Public License //as published by the Free Software Foundation; either //version 2 of the License, or (at your option) any later version. // //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // //You should have received a copy of the GNU General Public License //along with this program; if not, write to the Free Software //Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. #pragma once #include "MuleListCtrl.h" #include "TitleMenu.h" #include <map> #include "ListCtrlItemWalk.h" #define COLLAPSE_ONLY 0 #define EXPAND_ONLY 1 #define EXPAND_COLLAPSE 2 // Foward declaration class CPartFile; class CUpDownClient; class CDownloadListCtrl; class CToolTipCtrlX; /////////////////////////////////////////////////////////////////////////////// // CtrlItem_Struct enum ItemType { FILE_TYPE = 1, AVAILABLE_SOURCE = 2, UNAVAILABLE_SOURCE = 3,FILE_TASK = 4}; class CtrlItem_Struct : public CObject { DECLARE_DYNAMIC(CtrlItem_Struct) public: ~CtrlItem_Struct() { status.DeleteObject(); } ItemType type; CPartFile* owner; void* value; // could be both CPartFile or CUpDownClient CtrlItem_Struct* parent; DWORD dwUpdated; CBitmap status; }; /////////////////////////////////////////////////////////////////////////////// // CDownloadListListCtrlItemWalk class CDownloadListListCtrlItemWalk : public CListCtrlItemWalk { public: CDownloadListListCtrlItemWalk(CDownloadListCtrl* pListCtrl); virtual CObject* GetNextSelectableItem(); virtual CObject* GetPrevSelectableItem(); void SetItemType(ItemType eItemType) { m_eItemType = eItemType; } protected: CDownloadListCtrl* m_pDownloadListCtrl; ItemType m_eItemType; }; /////////////////////////////////////////////////////////////////////////////// // CDownloadListCtrl class CDownloadListCtrl : public CMuleListCtrl, public CDownloadListListCtrlItemWalk { DECLARE_DYNAMIC(CDownloadListCtrl) friend class CDownloadListListCtrlItemWalk; public: CDownloadListCtrl(); virtual ~CDownloadListCtrl(); UINT curTab; void UpdateItem(void* toupdate); void Init(); void AddFile(CPartFile* toadd); void AddSource(CPartFile* owner, CUpDownClient* source, bool notavailable); void RemoveSource(CUpDownClient* source, CPartFile* owner); bool RemoveFile(const CPartFile* toremove); void ClearCompleted(int incat=-2); void ClearCompleted(const CPartFile* pFile); void SetStyle(); void CreateMenues(); void Localize(); void ShowFilesCount(); void ChangeCategory(int newsel); CString getTextList(); void ShowSelectedFileDetails(); void HideFile(CPartFile* tohide); void ShowFile(CPartFile* tohide); void ExpandCollapseItem(int iItem, int iAction, bool bCollapseSource = false); void HideSources(CPartFile* toCollapse); void GetDisplayedFiles(CArray<CPartFile*, CPartFile*>* list); void MoveCompletedfilesCat(uint8 from, uint8 to); int GetCompleteDownloads(int cat,int &total); void UpdateCurrentCategoryView(); void UpdateCurrentCategoryView(CPartFile* thisfile); protected: CImageList m_ImageList; CTitleMenu m_PrioMenu; CTitleMenu m_FileMenu; CMenu m_SourcesMenu; CMenuXP* m_MenuXP; bool m_bRemainSort; typedef std::pair<void*, CtrlItem_Struct*> ListItemsPair; typedef std::multimap<void*, CtrlItem_Struct*> ListItems; ListItems m_ListItems; CFont m_fontBold; CToolTipCtrlX* m_tooltip; void ShowFileDialog(UINT uInvokePage); void ShowClientDialog(CUpDownClient* pClient); void SetAllIcons(); void DrawFileItem(CDC *dc, int nColumn, LPCRECT lpRect, CtrlItem_Struct *lpCtrlItem); void DrawSourceItem(CDC *dc, int nColumn, LPCRECT lpRect, CtrlItem_Struct *lpCtrlItem); int GetFilesCountInCurCat(); static int CALLBACK SortProc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort); static int Compare(const CPartFile* file1, const CPartFile* file2, LPARAM lParamSort); static int Compare(const CUpDownClient* client1, const CUpDownClient* client2, LPARAM lParamSort); virtual BOOL OnCommand(WPARAM wParam, LPARAM lParam); virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct); DECLARE_MESSAGE_MAP() afx_msg void OnSysColorChange(); afx_msg void OnItemActivate(NMHDR *pNMHDR, LRESULT *pResult); afx_msg void OnContextMenu(CWnd* pWnd, CPoint point); afx_msg void OnColumnClick( NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnListModified(NMHDR *pNMHDR, LRESULT *pResult); afx_msg void OnNMDblclkDownloadlist(NMHDR *pNMHDR, LRESULT *pResult); afx_msg void OnGetDispInfo(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnLvnGetInfoTip(NMHDR *pNMHDR, LRESULT *pResult); afx_msg void OnCommentClick(NMHDR *pNMHDR, LRESULT *pResult); public: afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct); afx_msg void OnMeasureItem(int nIDCtl, LPMEASUREITEMSTRUCT lpMeasureItemStruct); protected: typedef struct _ToolBarUI { int iFilesToCancel; int iFilesToStop; int iFilesToPause; int iFilesToResume; int iFilesToOpenFolder; } ToolBarUI; ToolBarUI m_ToolBarUI; public: CPartFile* m_pPartFile; CWnd* m_pDialog; protected: void UpdateToolBarItem(ToolBarUI* pToolBarUI); public: void UpdateToolBarItem(void); private: afx_msg LRESULT OnUpdateGUIStart(WPARAM wParam, LPARAM lParam); afx_msg LRESULT OnUpdateGUIStop(WPARAM wParam, LPARAM lParam); public: void OnNoComment(CHtmlCtrl *pHtml); int FindFile(CPartFile* pPartFile); int FindFile(CUpDownClient* pClient); };
[ "LanceFong@4a627187-453b-0410-a94d-992500ef832d" ]
[ [ [ 1, 183 ] ] ]
d508aa32872150e5613cba47a0baede908d0f7ae
62c9cb0899bbb36d3e742559831f84054b57d790
/DeviceAdapters/SimpleAF/SimpleAFImageUtils.h
3043f83bea55366bab0594040b6ed90c984788ff
[]
no_license
astraw/micromanager1.3
b1a245f676f32bbaf1cda7cecbaaf0a5c661ad6c
6032a1916442dfd1847bef0ed1d5bd1895334c1d
refs/heads/master
2020-06-05T02:37:31.526258
2009-04-28T16:58:58
2009-04-28T16:58:58
187,348
2
0
null
null
null
null
UTF-8
C++
false
false
9,577
h
/////////////////////////////////////////////////////////////////////////////// // FILE: SimpleAFImageUtils.h // PROJECT: Micro-Manager // SUBSYSTEM: DeviceAdapters //----------------------------------------------------------------------------- // DESCRIPTION: Image based autofocus module - Utilities // // AUTHOR: Prashanth Ravindran // [email protected], February, 2009 // // COPYRIGHT: 100X Imaging Inc, 2009, http://www.100ximaging.com // // 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 100X Imaging Inc 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 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. # ifndef _AFUTILS_H_ # define _AFUTILS_H_ # include <string> # include "../../MMDevice/MMDevice.h" # include "../../MMDevice/DeviceBase.h" # include "../../MMDevice/ImgBuffer.h" #include "../../MMDevice/ModuleInterface.h" # include <limits> # ifdef max # undef max # endif # ifdef min # undef min # endif ///////////////////////////////////////////////////////////// // AFHistogramStretcher: // --------------------- // Stretch the histogram based on cthe dynamic range of the // pixeltype. ///////////////////////////////////////////////////////////// template <typename PixelDataType> class AFHistogramStretcher { public: AFHistogramStretcher():fContentThreshold(0.001f),fStretchPercent(0.99f) ,operationmodel_(INPLACE),stretchingmodel_(HISTOGRAMEQUALIZATION){} typedef PixelDataType PixelType; float fContentThreshold; float fStretchPercent; enum OperationType {INPLACE, OUTOFPLACE}; enum StretchType {HISTOGRAMSTETCH, HISTOGRAMEQUALIZATION}; StretchType stretchingmodel_; OperationType operationmodel_; public: // NOTE:: This has to be declared in the header as declaring this in the cpp causes // linking problems. This is to do with the fact that the code is templated // and that, all the temlpate arguments have to be available at compile time // for the code to work. There is an ugly hack that involves calling the .cpp // file by some other name, and explicitly including it at the end of the header // file eg. At the end of this file we write # include "SimpleAFImageUtils.txx" // but it is not practiced in the MM codebase, so defining inline int Stretch(PixelDataType * src, int nWidth, int nHeight, PixelDataType * returnimage = 0) { double * histogram = new double[std::numeric_limits<PixelDataType>::max() + 1]; for(int i = 0; i <= std::numeric_limits<PixelDataType>::max(); ++i) { *(histogram + i) = 0.0f; } // Get the max and the minimum PixelType val_max = std::numeric_limits<PixelType>::min(), val_min = std::numeric_limits<PixelType>::max(), typemax = val_min, typemin = val_max; // Getting min and max in one pass for(long i = 0; i < nWidth * nHeight; ++i) { if(src[i] > val_max) val_max = src[i]; if(src[i] < val_min) val_min = src[i]; ++histogram[src[i]]; } // Go once through the histogram and get the x% content threshold double Observed = 0.0f; for(int i = std::numeric_limits<PixelDataType>::max(); i > 0 ; --i) { Observed+= histogram[i]; if(Observed >= (1.0f - fStretchPercent)*(nWidth*nHeight)) { val_max = i; break; } } // If the image has very low dynamic range.. do nothing, // you might just be amplifying the noise if(((float)abs(val_min - val_max)/(float)typemax) < fContentThreshold) { if(operationmodel_ == OUTOFPLACE) { memcpy(returnimage,src,nWidth*nHeight*sizeof(PixelType)); delete [] histogram; histogram = 0; } return 0; } if(stretchingmodel_ == HISTOGRAMSTETCH) { if(operationmodel_ == INPLACE) { float fFactor = ((float)typemax)/((float)(val_max-val_min)); // Setting the scaling again for(long i = 0; i < nWidth * nHeight; ++i) { float Pixel = (fFactor)*(src[i] - val_min); if(Pixel > std::numeric_limits<PixelDataType>::max()) { Pixel = std::numeric_limits<PixelDataType>::max(); } src[i] = static_cast<PixelType>(Pixel); } } else if(operationmodel_ == OUTOFPLACE) { float fFactor = ((float)typemax)/((float)(val_max-val_min)); // Setting the scaling again for(long i = 0; i < nWidth * nHeight; ++i) { float Pixel = (fFactor)*(src[i] - val_min); if(Pixel > std::numeric_limits<PixelDataType>::max()) { Pixel = std::numeric_limits<PixelDataType>::max(); } returnimage[i] = static_cast<PixelType>(Pixel); } } return 1; } else if(stretchingmodel_ == HISTOGRAMEQUALIZATION) { // Come in from the end and identify the cutoff point of the // histogram, which ensures that all hot pixels have been chucked out // Also the cdf (cumulative distribution function) is generated in the same pass long incidence = 0; long thresh = (long)((float)nWidth*(float)nHeight*(fStretchPercent)); long uppercutoff = 0; double * cdf = new double [std::numeric_limits<PixelType>::max()]; for(long i = 0; i < std::numeric_limits<PixelType>::max(); ++i) { incidence += (long)histogram[i]; if(incidence > thresh && uppercutoff == 0) { uppercutoff = i; } // CDF is generated here if(i > 0) cdf[i] = histogram[i] + cdf[i-1]; // For the later indices else cdf[i] = histogram[i]; // For the first index } for(long i = 0; i < nWidth * nHeight; ++i) { if(operationmodel_ == INPLACE) { src[i] = static_cast<PixelType>(cdf[src[i]]); } else if(operationmodel_ == OUTOFPLACE) { returnimage[i] = static_cast<PixelType>(cdf[src[i]]); } } delete[] cdf; cdf = 0; if(histogram != 0) { delete[] histogram; histogram = 0; } return 1; } return 1; } }; ////////////////////////////////////////////////////////////////// // Shutter Manager: // ---------------- // Open Shutter and remember state class ShutterManager { public: ShutterManager():initialized_(false),core_(0){} int OpenCoreShutter(); int RestoreCoreShutter(); void SetCore(MM::Core *); private: std::string shutterName_; std::string autoShutterState_; std::string shutterState_; bool initialized_; MM::Core * core_; }; ////////////////////////////////////////////////////////// // Exposure Manager: // ----------------- // Manages the exposure for autofocus /////////////////////////////////////////////////////////// class ExposureManager { public: ExposureManager():core_(0),working_(false){} void SetCore(MM::Core * ); int SetExposureToAF(double afExp); int RestoreExposure(); bool IsExposureManagerManagingExposure(); private: double systemExposure_; double autofocusExposure_; MM::Core * core_; bool working_; }; class ImageSharpnessScorer { public: ImageSharpnessScorer(); ~ImageSharpnessScorer(); void SetImage(ImgBuffer &); void MedianFilter(int xsize, int ysize); void LaplacianFilter(); double GetScore(); double GetScore(ImgBuffer & ); void SetCore(MM::Core * ); void SetImage(unsigned char * buffer, int width, int height, int depth); private: ImgBuffer buffer_; }; ///////////////////////////////////// // Reporting Manager // /////////////////////////////////////// class ReportingManager { public: ReportingManager():core_(0),bufferinitialized_(false) ,width_(0),height_(0),depth_(0){} void SetCore(MM::Core * ); int InitializeDebugStack(MM::Device * callee = 0); int InsertCurrentImageInDebugStack(Metadata & IMd); private: MM::Core * core_; MM::Device * callee_; bool bufferinitialized_; int width_; int height_; int depth_; }; # endif
[ "prashanth@d0ab736e-dc22-4aeb-8dc9-08def0aa14fd", "nico@d0ab736e-dc22-4aeb-8dc9-08def0aa14fd" ]
[ [ [ 1, 44 ], [ 49, 68 ], [ 70, 314 ] ], [ [ 45, 48 ], [ 69, 69 ], [ 315, 315 ] ] ]
364905cb54b7d067f02b8d7ce95477767b4e3c69
a0b7f1aaf8d8228943ee1de4abceb776c8bb531a
/main.cpp
dddc56faaa745d8c49125a2e7408ab872bdf0943
[]
no_license
wmeister-old/gosu-c---project-basis
3dadfc14b18c9cef5a88bf4b21e8b7b2943ea47e
84eb5adf088f238d598a4392fbfe314301c374d2
refs/heads/master
2021-05-28T09:31:46.260305
2011-09-21T22:33:48
2011-09-21T22:33:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
675
cpp
#include <iostream> #include <Gosu/Window.hpp> #include <Gosu/Directories.hpp> #include <Gosu/AutoLink.hpp> #include "character.hpp" using namespace std; class GameWindow : public Gosu::Window { public: GameWindow() : Window(640, 480, false, 20) { setCaption(L"Hello World!"); /* player::init(graphics()); player::pos.x = player::pos.y = 0; player::pos.z = 1;*/ } void upate() { } void draw() { //player::draw(); } }; int main() { //cout << "x=" << player::pos.x << " y=" << player::pos.y << " health=" << player::health << " visible=" << player::visible << endl; GameWindow window; window.show(); }
[ [ [ 1, 29 ] ] ]
b76876ca6aea3e73f04ade35174be118d01062b0
f8b364974573f652d7916c3a830e1d8773751277
/emulator/allegrex/instructions/MULT.h
bfc0afeafe4945f00d75172089441fde6ede58c1
[]
no_license
lemmore22/pspe4all
7a234aece25340c99f49eac280780e08e4f8ef49
77ad0acf0fcb7eda137fdfcb1e93a36428badfd0
refs/heads/master
2021-01-10T08:39:45.222505
2009-08-02T11:58:07
2009-08-02T11:58:07
55,047,469
0
0
null
null
null
null
UTF-8
C++
false
false
1,035
h
template< > struct AllegrexInstructionTemplate< 0x00000018, 0xfc00ffff > : AllegrexInstructionUnknown { static AllegrexInstructionTemplate &self() { static AllegrexInstructionTemplate insn; return insn; } static AllegrexInstruction *get_instance() { return &AllegrexInstructionTemplate::self(); } virtual AllegrexInstruction *instruction(u32 opcode) { return this; } virtual char const *opcode_name() { return "MULT"; } virtual void interpret(Processor &processor, u32 opcode); virtual void disassemble(u32 address, u32 opcode, char *opcode_name, char *operands, char *comment); protected: AllegrexInstructionTemplate() {} }; typedef AllegrexInstructionTemplate< 0x00000018, 0xfc00ffff > AllegrexInstruction_MULT; namespace Allegrex { extern AllegrexInstruction_MULT &MULT; } #ifdef IMPLEMENT_INSTRUCTION AllegrexInstruction_MULT &Allegrex::MULT = AllegrexInstruction_MULT::self(); #endif
[ [ [ 1, 41 ] ] ]
2fdcd7a82a8b5b065f2415c632ed37899c41f1f1
27bde5e083cf5a32f75de64421ba541b3a23dd29
/external/GameX/source/gamex-buffer.hpp
1f01aaea828e68c58c345c39971f3dd93fd8c828
[]
no_license
jbsheblak/fatal-inflation
229fc6111039aff4fd00bb1609964cf37e4303af
5d6c0a99e8c4791336cf529ed8ce63911a297a23
refs/heads/master
2021-03-12T19:22:31.878561
2006-10-20T21:48:17
2006-10-20T21:48:17
32,184,096
0
0
null
null
null
null
UTF-8
C++
false
false
7,503
hpp
// // GameX - Buffer Class Header // // Copyright (C) 2002 Rama C. Hoetzlein // // This software is released under the GameX GNU GPL // Open Source License. See the GameX documentation included // with this source code for terms of modification, // distribution and re-release. // #include <stdio.h> #include <stdlib.h> #include <string.h> #include <conio.h> #include "gamex-debug.hpp" #ifndef BUFFER_DEF #define BUFFER_DEF #define BUFFER_DEBUG // #define BUFFER_TESTER #ifndef XBYTE #define XBYTE unsigned __int8 #define XBYTE2 unsigned __int16 #define XBYTE4 unsigned __int32 #define XBYTE8 __int64 #endif #define FALSE 0 #define TRUE 1 #define BUFFER_ORDER_LBF 0 #define BUFFER_ORDER_MBF 1 #define BUFFER_EMPTY 0 #define BUFFER_DATA 1 #define BUFFER_STRING 2 #define BUFFER_CONSOLE 3 #define BUFFER_ARRAY 4 class Buffer { public: Buffer (void); // Initialize a TYPE_EMPTY buffer void CreateConsole (int r, int c); // Console Functions char *GetLine (void); // Get current line char *GetLineRelative (int n); // Get a line relative to the current line void AddChar (char ch); // Add a character void AddLine (char *line); // Add a line void Scroll (void); // Scroll the buffer void SetOrder (int order); // Set byte order for interpretation void Scale (XBYTE *in, int width, int scale); // Multiply each byte by 'scale' void Invert (XBYTE *in, int width); // Invert all bytes (255-x) int PackBits (XBYTE *in, XBYTE *out, int width); // Simple RLE encoding/decoding int UnpackBits (XBYTE *in, XBYTE *out, int width); /// int UnstuffBits (XBYTE *in, XBYTE *out, int width, unsigned char *stuff_info); int UnstuffEachBit (XBYTE *in, XBYTE *out, int width); int ReadWord (char *line, char *word); // Read words (space delimited) int ReadWord (char *line, char *word, char delim); // Read words (arbitrary delimited) // Read Bytes, Words, DWords, Ints, Floats, Doubles according to Byte Order inline unsigned char ReadC (XBYTE c) {return (*FuncReadC) (c);} inline signed char ReadSC (XBYTE c) {return (*FuncReadSC) (c);} inline unsigned short int ReadI (XBYTE2 c) {return (*FuncReadI) (c);} inline signed short int ReadSI (XBYTE2 c) {return (*FuncReadSI) (c);} inline unsigned long int ReadL (XBYTE4 c) {return (*FuncReadL) (c);} inline signed long int ReadSL (XBYTE4 c) {return (*FuncReadSL) (c);} inline float ReadF (XBYTE4 c) {return (*FuncReadF) (c);} inline double ReadD (XBYTE8 c) {return (*FuncReadD) (c);} // Write Bytes, Words, DWords, Ints, Floats, Doubles according to Byte Order inline XBYTE WriteC (unsigned char c) {return (*FuncWriteC) (c);} inline XBYTE WriteSC (signed char c) {return (*FuncWriteSC) (c);} inline XBYTE2 WriteI (unsigned short int c) {return (*FuncWriteI) (c);} inline XBYTE2 WriteSI (signed short int c) {return (*FuncWriteSI) (c);} inline XBYTE4 WriteL (unsigned long int c) {return (*FuncWriteL) (c);} inline XBYTE4 WriteSL (signed long int c) {return (*FuncWriteSL) (c);} inline XBYTE4 WriteF (float c) {return (*FuncWriteF) (c);} inline XBYTE8 WriteD (double c) {return (*FuncWriteD) (c);} private: int byte_order; short int buf_type; int rows, cols; int curr_row, curr_col; char *buf, *curr_pos; unsigned char (*FuncReadC) (XBYTE c); signed char (*FuncReadSC) (XBYTE c); unsigned short int (*FuncReadI) (XBYTE2 c); signed short int (*FuncReadSI) (XBYTE2 c); unsigned long int (*FuncReadL) (XBYTE4 c); signed long int (*FuncReadSL) (XBYTE4 c); float (*FuncReadF) (XBYTE4 c); double (*FuncReadD) (XBYTE8 c); XBYTE (*FuncWriteC) (unsigned char c); XBYTE (*FuncWriteSC) (signed char c); XBYTE2 (*FuncWriteI) (unsigned short int c); XBYTE2 (*FuncWriteSI) (signed short int c); XBYTE4 (*FuncWriteL) (unsigned long int c); XBYTE4 (*FuncWriteSL) (signed long int c); XBYTE4 (*FuncWriteF) (float c); XBYTE8 (*FuncWriteD) (double c); }; #ifndef BUFFER_STATIC #define BUFFER_STATIC static XBYTE Mask[8] = {128, 64, 32, 16, 8, 4, 2, 1}; #endif static inline unsigned char ReadC_LBF (XBYTE c) {return c;} static inline signed char ReadSC_LBF (XBYTE c) {return c;} static inline unsigned short int ReadI_LBF (XBYTE2 c) {return c;} static inline signed short int ReadSI_LBF (XBYTE2 c) {return c;} static inline unsigned long int ReadL_LBF (XBYTE4 c) {return c;} static inline signed long int ReadSL_LBF (XBYTE4 c) {return c;} static inline float ReadF_LBF (XBYTE4 c) {return (float) c;} static inline double ReadD_LBF (XBYTE8 c) {return (double) c;} static inline XBYTE WriteC_LBF (unsigned char c) {return c;} static inline XBYTE WriteSC_LBF (signed char c) {return c;} static inline XBYTE2 WriteI_LBF (unsigned short int c) {return c;} static inline XBYTE2 WriteSI_LBF (signed short int c) {return c;} static inline XBYTE4 WriteL_LBF (unsigned long int c) {return c;} static inline XBYTE4 WriteSL_LBF (signed long int c) {return c;} static inline XBYTE4 WriteF_LBF (float c) {return (XBYTE4) c;} static inline XBYTE8 WriteD_LBF (double c) {return (XBYTE8) c;} static inline unsigned char ReadC_MBF (XBYTE c) {return c;} static inline signed char ReadSC_MBF (XBYTE c) {return c;} static inline XBYTE WriteC_MBF (unsigned char c) {return c;} static inline XBYTE WriteSC_MBF (signed char c) {return c;} #define Int2to1(c) ((c & 0xFF00) >> 8) #define Int1to2(c) ((c & 0xFF) << 8) #define IntReverse(c) (Int2to1(c) | Int1to2(c)) static inline unsigned short int ReadI_MBF (XBYTE2 c) { return (unsigned short int) IntReverse(c); } static inline signed short int ReadSI_MBF (XBYTE2 c) { return (signed short int) IntReverse(c); } static inline XBYTE2 WriteI_MBF (unsigned short int c) { return (XBYTE2) IntReverse(c); } static inline XBYTE2 WriteSI_MBF (signed short int c) { return (XBYTE2) IntReverse(c); } #define Long4to1(c) ((c & 0xFF000000) >> 24) #define Long3to2(c) ((c & 0xFF0000) >> 8) #define Long2to3(c) ((c & 0xFF00) << 8) #define Long1to4(c) ((c & 0xFF) << 24) #define LongReverse(c) (Long4to1(c) | Long3to2(c) | Long2to3(c) | Long1to4(c)) static inline unsigned long int ReadL_MBF (XBYTE4 c) { return (unsigned long int) LongReverse(c); } static inline signed long int ReadSL_MBF (XBYTE4 c) { return (signed long int) LongReverse(c); } static inline float ReadF_MBF (XBYTE4 c) { return (float) LongReverse(c); } static inline XBYTE4 WriteL_MBF (unsigned long int c) { return (XBYTE4) LongReverse(c); } static inline XBYTE4 WriteSL_MBF (signed long int c) { return (XBYTE4) LongReverse(c); } static inline XBYTE4 WriteF_MBF (float c) { return (XBYTE4) LongReverse((XBYTE4) c); } #define DoubleHItoLO(c) ((c & 0xFFFFFFFF00000000) >> 32) #define DoubleLOtoHI(c) ((c & 0xFFFFFFFF) << 32) #define DoubleReverse(c) (DoubleHItoLO(LongReverse(c)) | DoubleLOtoHI(LongReverse(c)) ) static inline double ReadD_MBF (XBYTE8 c) { printf ("ReadD_MBF: Reversal of 8-bytes and conversion to double is not implemented.\n", c); // return (double) DoubleReverse(c); return (double) c; } static inline XBYTE8 WriteD_MBF (double c) { return (XBYTE4) DoubleReverse((XBYTE4) c); } #endif
[ "jbsheblak@5660b91f-811d-0410-8070-91869aa11e15" ]
[ [ [ 1, 192 ] ] ]
5dbc9869e9eafea22de1d3a4e7f23a76db60a56b
5f0b8d4a0817a46a9ae18a057a62c2442c0eb17e
/Include/event/MouseListener.cpp
183fb24843f3a9497f408ea340c751f54305bfe8
[ "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
1,615
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 "./MouseListener.h" // mouseListener is an interface.
[ "bs@bram.(none)" ]
[ [ [ 1, 30 ] ] ]
2f328038713f24e8e1ef83b31824117f1eec38be
709cd826da3ae55945fd7036ecf872ee7cdbd82a
/Term/WildMagic2/Source/ImageAnalysis/WmlExtractSurfaceTetra.cpp
892b684be6d1d8cd688ef03a23f946d377d4b9ed
[]
no_license
argapratama/kucgbowling
20dbaefe1596358156691e81ccceb9151b15efb0
65e40b6f33c5511bddf0fa350c1eefc647ace48a
refs/heads/master
2018-01-08T15:27:44.784437
2011-06-19T15:23:39
2011-06-19T15:23:39
36,738,655
0
0
null
null
null
null
UTF-8
C++
false
false
42,995
cpp
// Magic Software, Inc. // http://www.magic-software.com // http://www.wild-magic.com // Copyright (c) 2003. All Rights Reserved // // The Wild Magic Library (WML) source code is supplied under the terms of // the license agreement http://www.magic-software.com/License/WildMagic.pdf // and may not be copied or disclosed except in accordance with the terms of // that agreement. #include "WmlExtractSurfaceTetra.h" #include "WmlVETMesh.h" using namespace Wml; #include <algorithm> using namespace std; typedef map<Vector3f,int> VMap; typedef VMap::iterator VMapIterator; typedef map<TriangleKey,int> TMap; typedef TMap::iterator TMapIterator; //---------------------------------------------------------------------------- ExtractSurfaceTetra::ExtractSurfaceTetra (int iXBound, int iYBound, int iZBound, int* aiData) { assert( iXBound > 0 && iYBound > 0 && iZBound > 0 && aiData ); m_iXBound = iXBound; m_iYBound = iYBound; m_iZBound = iZBound; m_iXYBound = iXBound*iYBound; m_iXYZBound = m_iXYBound*iZBound; m_aiData = aiData; } //---------------------------------------------------------------------------- float ExtractSurfaceTetra::GetFunction (const Vector3f& rkP) const { int iX = (int) rkP.X(); if ( iX < 0 || iX >= m_iXBound-1 ) return 0.0f; int iY = (int) rkP.Y(); if ( iY < 0 || iY >= m_iYBound-1 ) return 0.0f; int iZ = (int) rkP.Z(); if ( iZ < 0 || iZ >= m_iZBound-1 ) return 0.0f; float fDX = rkP.X() - iX, fDY = rkP.Y() - iY, fDZ = rkP.Z() - iZ; int i000 = iX + m_iXBound*(iY + m_iYBound*iZ); int i100 = i000 + 1; int i010 = i000 + m_iXBound; int i110 = i100 + m_iXBound; int i001 = i000 + m_iXYBound; int i101 = i100 + m_iXYBound; int i011 = i010 + m_iXYBound; int i111 = i110 + m_iXYBound; float fF000 = (float) m_aiData[i000]; float fF100 = (float) m_aiData[i100]; float fF010 = (float) m_aiData[i010]; float fF110 = (float) m_aiData[i110]; float fF001 = (float) m_aiData[i001]; float fF101 = (float) m_aiData[i101]; float fF011 = (float) m_aiData[i011]; float fF111 = (float) m_aiData[i111]; float fC0, fC1, fC2, fInterp; if ( (iX & 1) ^ (iY & 1) ^ (iZ & 1) ) { if ( fDX - fDY - fDZ >= 0.0f ) { // 1205 fInterp = (1.0f-(1.0f-fDX)-fDY-fDZ)*fF100 + (1.0f-fDX)*fF000 + fDY*fF110 + fDZ*fF101; } else if ( fDX - fDY + fDZ <= 0.0f ) { // 3027 fInterp = (1.0f-fDX-(1.0f-fDY)-fDZ)*fF010 + fDX*fF110 + (1.0f-fDY)*fF000 + fDZ*fF011; } else if ( fDX + fDY - fDZ <= 0.0f ) { // 4750 fInterp = (1.0f-fDX-fDY-(1-fDZ))*fF001 + fDX*fF101 + fDY*fF011 + (1.0f-fDZ)*fF000; } else if ( fDX + fDY + fDZ >= 2.0f ) { // 6572 fInterp = (1.0f-(1.0f-fDX)-(1.0f-fDY)-(1.0f-fDZ))*fF111 + (1.0f-fDX)*fF011 + (1.0f-fDY)*fF101 + (1.0f-fDZ)*fF110; } else { // 0752 fC0 = 0.5f*(-fDX+fDY+fDZ); fC1 = 0.5f*(fDX-fDY+fDZ); fC2 = 0.5f*(fDX+fDY-fDZ); fInterp = (1.0f-fC0-fC1-fC2)*fF000 + fC0*fF011 + fC1*fF101 + fC2*fF110; } } else { if ( fDX + fDY + fDZ <= 1.0f ) { // 0134 fInterp = (1.0f-fDX-fDY-fDZ)*fF000 + fDX*fF100 + fDY*fF010 + fDZ*fF001; } else if ( fDX + fDY - fDZ >= 1.0f ) { // 2316 fInterp = (1.0f-(1.0f-fDX)-(1.0f-fDY)-fDZ)*fF110 + (1.0f-fDX)*fF010 + (1.0f-fDY)*fF100 + fDZ*fF111; } else if ( fDX - fDY + fDZ >= 1.0f ) { // 5461 fInterp = (1.0f-(1.0f-fDX)-fDY-(1.0f-fDZ))*fF101 + (1.0f-fDX)*fF001 + fDY*fF111 + (1.0f-fDZ)*fF100; } else if ( -fDX + fDY + fDZ >= 1.0f ) { // 7643 fInterp = (1.0f-fDX-(1.0f-fDY)-(1.0f-fDZ))*fF011 + fDX*fF111 + (1.0f-fDY)*fF001 + (1.0f-fDZ)*fF010; } else { // 6314 fC0 = 0.5f*((1.0f-fDX)-(1.0f-fDY)+(1.0f-fDZ)); fC1 = 0.5f*(-(1.0f-fDX)+(1.0f-fDY)+(1.0f-fDZ)); fC2 = 0.5f*((1.0f-fDX)+(1.0f-fDY)-(1.0f-fDZ)); fInterp = (1.0f-fC0-fC1-fC2)*fF111 + fC0*fF010 + fC1*fF100 + fC2*fF001; } } return fInterp; } //---------------------------------------------------------------------------- Vector3f ExtractSurfaceTetra::GetGradient (const Vector3f& rkP) const { int iX = (int) rkP.X(); if ( iX < 0 || iX >= m_iXBound-1 ) return Vector3f::ZERO; int iY = (int) rkP.Y(); if ( iY < 0 || iY >= m_iYBound-1 ) return Vector3f::ZERO; int iZ = (int) rkP.Z(); if ( iZ < 0 || iZ >= m_iZBound-1 ) return Vector3f::ZERO; float fDX = rkP.X() - iX, fDY = rkP.Y() - iY, fDZ = rkP.Z() - iZ; int i000 = iX + m_iXBound*(iY + m_iYBound*iZ); int i100 = i000 + 1; int i010 = i000 + m_iXBound; int i110 = i100 + m_iXBound; int i001 = i000 + m_iXYBound; int i101 = i100 + m_iXYBound; int i011 = i010 + m_iXYBound; int i111 = i110 + m_iXYBound; float fF000 = (float) m_aiData[i000]; float fF100 = (float) m_aiData[i100]; float fF010 = (float) m_aiData[i010]; float fF110 = (float) m_aiData[i110]; float fF001 = (float) m_aiData[i001]; float fF101 = (float) m_aiData[i101]; float fF011 = (float) m_aiData[i011]; float fF111 = (float) m_aiData[i111]; Vector3f kInterp; if ( (iX & 1) ^ (iY & 1) ^ (iZ & 1) ) { if ( fDX - fDY - fDZ >= 0.0f ) { // 1205 kInterp.X() = + fF100 - fF000; kInterp.Y() = - fF100 + fF110; kInterp.Z() = - fF100 + fF101; } else if ( fDX - fDY + fDZ <= 0.0f ) { // 3027 kInterp.X() = - fF010 + fF110; kInterp.Y() = + fF010 - fF000; kInterp.Z() = - fF010 + fF011; } else if ( fDX + fDY - fDZ <= 0.0f ) { // 4750 kInterp.X() = - fF001 + fF101; kInterp.Y() = - fF001 + fF011; kInterp.Z() = + fF001 - fF000; } else if ( fDX + fDY + fDZ >= 2.0f ) { // 6572 kInterp.X() = + fF111 - fF011; kInterp.Y() = + fF111 - fF101; kInterp.Z() = + fF111 - fF110; } else { // 0752 kInterp.X() = 0.5f*(-fF000-fF011+fF101+fF110); kInterp.Y() = 0.5f*(-fF000+fF011-fF101+fF110); kInterp.Z() = 0.5f*(-fF000+fF011+fF101-fF110); } } else { if ( fDX + fDY + fDZ <= 1.0f ) { // 0134 kInterp.X() = - fF000 + fF100; kInterp.Y() = - fF000 + fF010; kInterp.Z() = - fF000 + fF001; } else if ( fDX + fDY - fDZ >= 1.0f ) { // 2316 kInterp.X() = + fF110 - fF010; kInterp.Y() = + fF110 - fF100; kInterp.Z() = - fF110 + fF111; } else if ( fDX - fDY + fDZ >= 1.0f ) { // 5461 kInterp.X() = + fF101 - fF001; kInterp.Y() = - fF101 + fF111; kInterp.Z() = + fF101 - fF100; } else if ( -fDX + fDY + fDZ >= 1.0f ) { // 7643 kInterp.X() = - fF011 + fF111; kInterp.Y() = + fF011 - fF001; kInterp.Z() = + fF011 - fF010; } else { // 6314 kInterp.X() = 0.5f*(fF111-fF010+fF100-fF001); kInterp.Y() = 0.5f*(fF111+fF010-fF100-fF001); kInterp.Z() = 0.5f*(fF111-fF010-fF100+fF001); } } return kInterp; } //---------------------------------------------------------------------------- void ExtractSurfaceTetra::ExtractContour (int iLevel, vector<Vector3f>& rkVA, vector<TriangleKey>& rkTA) { // NOTE: Isolated edges are computed, but not reported to the caller. // You can modify the code to return these if so desired. VtxMap kVMap; ESet kESet; TSet kTSet; m_iNextIndex = 0; // adjust image so level set is F(x,y,z) = 0 int i; for (i = 0; i < m_iXYZBound; i++) m_aiData[i] = m_aiData[i] - iLevel; int iXBoundM1 = m_iXBound - 1; int iYBoundM1 = m_iYBound - 1; int iZBoundM1 = m_iZBound - 1; for (int iZ = 0, iZP = 1; iZ < iZBoundM1; iZ++, iZP++) { int iZParity = (iZ & 1); for (int iY = 0, iYP = 1; iY < iYBoundM1; iY++, iYP++) { int iYParity = (iY & 1); for (int iX = 0, iXP = 1; iX < iXBoundM1; iX++, iXP++) { int iXParity = (iX & 1); int i000 = iX + m_iXBound*(iY + m_iYBound*iZ); int i100 = i000 + 1; int i010 = i000 + m_iXBound; int i110 = i100 + m_iXBound; int i001 = i000 + m_iXYBound; int i101 = i100 + m_iXYBound; int i011 = i010 + m_iXYBound; int i111 = i110 + m_iXYBound; int iF000 = m_aiData[i000]; int iF100 = m_aiData[i100]; int iF010 = m_aiData[i010]; int iF110 = m_aiData[i110]; int iF001 = m_aiData[i001]; int iF101 = m_aiData[i101]; int iF011 = m_aiData[i011]; int iF111 = m_aiData[i111]; if ( iXParity ^ iYParity ^ iZParity ) { // 1205 ProcessTetrahedron(kVMap,kESet,kTSet, iXP,iY,iZ,iF100,iXP,iYP,iZ,iF110,iX,iY,iZ,iF000,iXP, iY,iZP,iF101); // 3027 ProcessTetrahedron(kVMap,kESet,kTSet, iX,iYP,iZ,iF010,iX,iY,iZ,iF000,iXP,iYP,iZ,iF110,iX, iYP,iZP,iF011); // 4750 ProcessTetrahedron(kVMap,kESet,kTSet, iX,iY,iZP,iF001,iX,iYP,iZP,iF011,iXP,iY,iZP,iF101,iX, iY,iZ,iF000); // 6572 ProcessTetrahedron(kVMap,kESet,kTSet, iXP,iYP,iZP,iF111,iXP,iY,iZP,iF101,iX,iYP,iZP,iF011, iXP,iYP,iZ,iF110); // 0752 ProcessTetrahedron(kVMap,kESet,kTSet, iX,iY,iZ,iF000,iX,iYP,iZP,iF011,iXP,iY,iZP,iF101,iXP, iYP,iZ,iF110); } else { // 0134 ProcessTetrahedron(kVMap,kESet,kTSet, iX,iY,iZ,iF000,iXP,iY,iZ,iF100,iX,iYP,iZ,iF010,iX,iY, iZP,iF001); // 2316 ProcessTetrahedron(kVMap,kESet,kTSet, iXP,iYP,iZ,iF110,iX,iYP,iZ,iF010,iXP,iY,iZ,iF100,iXP, iYP,iZP,iF111); // 5461 ProcessTetrahedron(kVMap,kESet,kTSet, iXP,iY,iZP,iF101,iX,iY,iZP,iF001,iXP,iYP,iZP,iF111, iXP,iY,iZ,iF100); // 7643 ProcessTetrahedron(kVMap,kESet,kTSet, iX,iYP,iZP,iF011,iXP,iYP,iZP,iF111,iX,iY,iZP,iF001,iX, iYP,iZ,iF010); // 6314 ProcessTetrahedron(kVMap,kESet,kTSet, iXP,iYP,iZP,iF111,iX,iYP,iZ,iF010,iXP,iY,iZ,iF100,iX, iY,iZP,iF001); } } } } // readjust image so level set is F(x,y,z) = L for (i = 0; i < m_iXYZBound; i++) m_aiData[i] = m_aiData[i] + iLevel; // pack vertices into an array rkVA.resize(kVMap.size()); if ( rkVA.size() > 0 ) { VtxMapIterator pkVIter; for (pkVIter = kVMap.begin(); pkVIter != kVMap.end(); pkVIter++) { const Vertex& rkV = pkVIter->first; rkV.GetTriple(rkVA[pkVIter->second]); } } // pack edges into an array (computed, but not reported to caller) vector<EdgeKey> kEA; kEA.resize(kESet.size()); if ( kEA.size() > 0 ) copy(kESet.begin(),kESet.end(),&kEA.front()); // pack triangles into an array rkTA.resize(kTSet.size()); if ( rkTA.size() > 0 ) copy(kTSet.begin(),kTSet.end(),&rkTA.front()); } //---------------------------------------------------------------------------- void ExtractSurfaceTetra::MakeUnique (vector<Vector3f>& rkVA, vector<TriangleKey>& rkTA) { int iVQuantity = (int)rkVA.size(); int iTQuantity = (int)rkTA.size(); if ( iVQuantity == 0 || iTQuantity == 0 ) return; // use a hash table to generate unique storage VMap kVMap; VMapIterator pkVIter; for (int iV = 0, iNextVertex = 0; iV < iVQuantity; iV++) { // keep only unique vertices pair<VMapIterator,bool> kResult = kVMap.insert( make_pair(rkVA[iV],iNextVertex)); if ( kResult.second == true ) iNextVertex++; } // use a hash table to generate unique storage TMap kTMap; TMapIterator pkTIter; for (int iT = 0, iNextTriangle = 0; iT < iTQuantity; iT++) { // replace old vertex indices by new ones TriangleKey& rkTri = rkTA[iT]; pkVIter = kVMap.find(rkVA[rkTri.V[0]]); assert( pkVIter != kVMap.end() ); rkTri.V[0] = pkVIter->second; pkVIter = kVMap.find(rkVA[rkTri.V[1]]); assert( pkVIter != kVMap.end() ); rkTri.V[1] = pkVIter->second; pkVIter = kVMap.find(rkVA[rkTri.V[2]]); assert( pkVIter != kVMap.end() ); rkTri.V[2] = pkVIter->second; // keep only unique triangles pair<TMapIterator,bool> kResult = kTMap.insert( make_pair(rkTri,iNextTriangle)); if ( kResult.second == true ) iNextTriangle++; } // pack the vertices rkVA.resize(kVMap.size()); for (pkVIter = kVMap.begin(); pkVIter != kVMap.end(); pkVIter++) rkVA[pkVIter->second] = pkVIter->first; // pack the triangles rkTA.resize(kTMap.size()); for (pkTIter = kTMap.begin(); pkTIter != kTMap.end(); pkTIter++) rkTA[pkTIter->second] = pkTIter->first; } //---------------------------------------------------------------------------- void ExtractSurfaceTetra::OrientTriangles (vector<Vector3f>& rkVA, vector<TriangleKey>& rkTA, bool bSameDir) { for (int i = 0; i < (int)rkTA.size(); i++) { TriangleKey& rkTri = rkTA[i]; // get triangle vertices Vector3f kV0 = rkVA[rkTri.V[0]]; Vector3f kV1 = rkVA[rkTri.V[1]]; Vector3f kV2 = rkVA[rkTri.V[2]]; // construct triangle normal based on current orientation Vector3f kEdge1 = kV1 - kV0; Vector3f kEdge2 = kV2 - kV0; Vector3f kNormal = kEdge1.Cross(kEdge2); // get the image gradient at the vertices Vector3f kGrad0 = GetGradient(kV0); Vector3f kGrad1 = GetGradient(kV1); Vector3f kGrad2 = GetGradient(kV2); // compute the average gradient Vector3f kGradAvr = (kGrad0 + kGrad1 + kGrad2)/3.0f; // compute the dot product of normal and average gradient float fDot = kGradAvr.Dot(kNormal); // choose triangle orientation based on gradient direction int iSave; if ( bSameDir ) { if ( fDot < 0.0f ) { // wrong orientation, reorder it iSave = rkTri.V[1]; rkTri.V[1] = rkTri.V[2]; rkTri.V[2] = iSave; } } else { if ( fDot > 0.0f ) { // wrong orientation, reorder it iSave = rkTri.V[1]; rkTri.V[1] = rkTri.V[2]; rkTri.V[2] = iSave; } } } } //---------------------------------------------------------------------------- void ExtractSurfaceTetra::ComputeNormals (const vector<Vector3f>& rkVA, const vector<TriangleKey>& rkTA, vector<Vector3f>& rkNA) { // maintain a running sum of triangle normals at each vertex int iVQuantity = (int)rkVA.size(); int iTQuantity = (int)rkTA.size(); rkNA.resize(iVQuantity); int i, j; for (i = 0; i < iVQuantity; i++) rkNA[i] = Vector3f::ZERO; for (i = 0, j = 0; i < iTQuantity; i++) { const TriangleKey& rkT = rkTA[i]; Vector3f kV0 = rkVA[rkT.V[0]]; Vector3f kV1 = rkVA[rkT.V[1]]; Vector3f kV2 = rkVA[rkT.V[2]]; // construct triangle normal Vector3f kEdge1 = kV1 - kV0; Vector3f kEdge2 = kV2 - kV0; Vector3f kNormal = kEdge1.Cross(kEdge2); // maintain the sum of normals at each vertex rkNA[rkT.V[0]] += kNormal; rkNA[rkT.V[1]] += kNormal; rkNA[rkT.V[2]] += kNormal; } // The normal vector storage was used to accumulate the sum of // triangle normals. Now these vectors must be rescaled to be // unit length. for (i = 0; i < iVQuantity; i++) rkNA[i].Normalize(); } //---------------------------------------------------------------------------- int ExtractSurfaceTetra::AddVertex (VtxMap& rkVMap, int iXNumer, int iXDenom, int iYNumer, int iYDenom, int iZNumer, int iZDenom) { Vertex kVertex(iXNumer,iXDenom,iYNumer,iYDenom,iZNumer,iZDenom); VtxMapIterator pkVIter = rkVMap.find(kVertex); if ( pkVIter != rkVMap.end() ) { // Vertex already in map, just return its unique index. return pkVIter->second; } else { // Vertex not in map, insert it and assign it a unique index. int i = m_iNextIndex++; rkVMap.insert(make_pair(kVertex,i)); return i; } } //---------------------------------------------------------------------------- void ExtractSurfaceTetra::AddEdge (VtxMap& rkVMap, ESet& rkESet, int iXNumer0, int iXDenom0, int iYNumer0, int iYDenom0, int iZNumer0, int iZDenom0, int iXNumer1, int iXDenom1, int iYNumer1, int iYDenom1, int iZNumer1, int iZDenom1) { int iV0 = AddVertex(rkVMap,iXNumer0,iXDenom0,iYNumer0,iYDenom0,iZNumer0, iZDenom0); int iV1 = AddVertex(rkVMap,iXNumer1,iXDenom1,iYNumer1,iYDenom1,iZNumer1, iZDenom1); rkESet.insert(EdgeKey(iV0,iV1)); } //---------------------------------------------------------------------------- void ExtractSurfaceTetra::AddTriangle (VtxMap& rkVMap, ESet& rkESet, TSet& rkTSet, int iXNumer0, int iXDenom0, int iYNumer0, int iYDenom0, int iZNumer0, int iZDenom0, int iXNumer1, int iXDenom1, int iYNumer1, int iYDenom1, int iZNumer1, int iZDenom1, int iXNumer2, int iXDenom2, int iYNumer2, int iYDenom2, int iZNumer2, int iZDenom2) { int iV0 = AddVertex(rkVMap,iXNumer0,iXDenom0,iYNumer0,iYDenom0,iZNumer0, iZDenom0); int iV1 = AddVertex(rkVMap,iXNumer1,iXDenom1,iYNumer1,iYDenom1,iZNumer1, iZDenom1); int iV2 = AddVertex(rkVMap,iXNumer2,iXDenom2,iYNumer2,iYDenom2,iZNumer2, iZDenom2); // nothing to do if triangle already exists TriangleKey kT(iV0,iV1,iV2); if ( rkTSet.find(kT) != rkTSet.end() ) return; // prevent double-sided triangles int iSave = kT.V[1]; kT.V[1] = kT.V[2]; kT.V[2] = iSave; if ( rkTSet.find(kT) != rkTSet.end() ) return; rkESet.insert(EdgeKey(iV0,iV1)); rkESet.insert(EdgeKey(iV1,iV2)); rkESet.insert(EdgeKey(iV2,iV0)); // compute triangle normal assuming counterclockwise ordering Vector3f kV0( iXNumer0/(float)iXDenom0, iYNumer0/(float)iYDenom0, iZNumer0/(float)iZDenom0); Vector3f kV1( iXNumer1/(float)iXDenom1, iYNumer1/(float)iYDenom1, iZNumer1/(float)iZDenom1); Vector3f kV2( iXNumer2/(float)iXDenom2, iYNumer2/(float)iYDenom2, iZNumer2/(float)iZDenom2); Vector3f kE0 = kV1 - kV0; Vector3f kE1 = kV2 - kV0; Vector3f kN = kE0.Cross(kE1); // choose triangle orientation based on gradient direction Vector3f kCentroid = (kV0+kV1+kV2)/3.0f; Vector3f kGrad = GetGradient(kCentroid); if ( kGrad.Dot(kN) <= 0.0f ) rkTSet.insert(TriangleKey(iV0,iV1,iV2)); else rkTSet.insert(TriangleKey(iV0,iV2,iV1)); } //---------------------------------------------------------------------------- void ExtractSurfaceTetra::ProcessTetrahedron (VtxMap& rkVM, ESet& rkES, TSet& rkTS, int iX0, int iY0, int iZ0, int iF0, int iX1, int iY1, int iZ1, int iF1, int iX2, int iY2, int iZ2, int iF2, int iX3, int iY3, int iZ3, int iF3) { int iXN0, iYN0, iZN0, iD0; int iXN1, iYN1, iZN1, iD1; int iXN2, iYN2, iZN2, iD2; int iXN3, iYN3, iZN3, iD3; if ( iF0 != 0 ) { // convert to case +*** if ( iF0 < 0 ) { iF0 = -iF0; iF1 = -iF1; iF2 = -iF2; iF3 = -iF3; } if ( iF1 > 0 ) { if ( iF2 > 0 ) { if ( iF3 > 0 ) { // ++++ return; } else if ( iF3 < 0 ) { // +++- iD0 = iF0 - iF3; iXN0 = iF0*iX3 - iF3*iX0; iYN0 = iF0*iY3 - iF3*iY0; iZN0 = iF0*iZ3 - iF3*iZ0; iD1 = iF1 - iF3; iXN1 = iF1*iX3 - iF3*iX1; iYN1 = iF1*iY3 - iF3*iY1; iZN1 = iF1*iZ3 - iF3*iZ1; iD2 = iF2 - iF3; iXN2 = iF2*iX3 - iF3*iX2; iYN2 = iF2*iY3 - iF3*iY2; iZN2 = iF2*iZ3 - iF3*iZ2; AddTriangle(rkVM,rkES,rkTS, iXN0,iD0,iYN0,iD0,iZN0,iD0, iXN1,iD1,iYN1,iD1,iZN1,iD1, iXN2,iD2,iYN2,iD2,iZN2,iD2); } else { // +++0 AddVertex(rkVM,iX3,1,iY3,1,iZ3,1); } } else if ( iF2 < 0 ) { iD0 = iF0 - iF2; iXN0 = iF0*iX2 - iF2*iX0; iYN0 = iF0*iY2 - iF2*iY0; iZN0 = iF0*iZ2 - iF2*iZ0; iD1 = iF1 - iF2; iXN1 = iF1*iX2 - iF2*iX1; iYN1 = iF1*iY2 - iF2*iY1; iZN1 = iF1*iZ2 - iF2*iZ1; if ( iF3 > 0 ) { // ++-+ iD2 = iF3 - iF2; iXN2 = iF3*iX2 - iF2*iX3; iYN2 = iF3*iY2 - iF2*iY3; iZN2 = iF3*iZ2 - iF2*iZ3; AddTriangle(rkVM,rkES,rkTS, iXN0,iD0,iYN0,iD0,iZN0,iD0, iXN1,iD1,iYN1,iD1,iZN1,iD1, iXN2,iD2,iYN2,iD2,iZN2,iD2); } else if ( iF3 < 0 ) { // ++-- iD2 = iF0 - iF3; iXN2 = iF0*iX3 - iF3*iX0; iYN2 = iF0*iY3 - iF3*iY0; iZN2 = iF0*iZ3 - iF3*iZ0; iD3 = iF1 - iF3; iXN3 = iF1*iX3 - iF3*iX1; iYN3 = iF1*iY3 - iF3*iY1; iZN3 = iF1*iZ3 - iF3*iZ1; AddTriangle(rkVM,rkES,rkTS, iXN0,iD0,iYN0,iD0,iZN0,iD0, iXN1,iD1,iYN1,iD1,iZN1,iD1, iXN2,iD2,iYN2,iD2,iZN2,iD2); AddTriangle(rkVM,rkES,rkTS, iXN1,iD1,iYN1,iD1,iZN1,iD1, iXN3,iD3,iYN3,iD3,iZN3,iD3, iXN2,iD2,iYN2,iD2,iZN2,iD2); } else { // ++-0 AddTriangle(rkVM,rkES,rkTS, iXN0,iD0,iYN0,iD0,iZN0,iD0, iXN1,iD1,iYN1,iD1,iZN1,iD1, iX3,1,iY3,1,iZ3,1); } } else { if ( iF3 > 0 ) { // ++0+ AddVertex(rkVM,iX2,1,iY2,1,iZ2,1); } else if ( iF3 < 0 ) { // ++0- iD0 = iF0 - iF3; iXN0 = iF0*iX3 - iF3*iX0; iYN0 = iF0*iY3 - iF3*iY0; iZN0 = iF0*iZ3 - iF3*iZ0; iD1 = iF1 - iF3; iXN1 = iF1*iX3 - iF3*iX1; iYN1 = iF1*iY3 - iF3*iY1; iZN1 = iF1*iZ3 - iF3*iZ1; AddTriangle(rkVM,rkES,rkTS, iXN0,iD0,iYN0,iD0,iZN0,iD0, iXN1,iD1,iYN1,iD1,iZN1,iD1, iX2,1,iY2,1,iZ2,1); } else { // ++00 AddEdge(rkVM,rkES,iX2,1,iY2,1,iZ2,1,iX3,1,iY3,1,iZ3,1); } } } else if ( iF1 < 0 ) { if ( iF2 > 0 ) { iD0 = iF0 - iF1; iXN0 = iF0*iX1 - iF1*iX0; iYN0 = iF0*iY1 - iF1*iY0; iZN0 = iF0*iZ1 - iF1*iZ0; iD1 = iF2 - iF1; iXN1 = iF2*iX1 - iF1*iX2; iYN1 = iF2*iY1 - iF1*iY2; iZN1 = iF2*iZ1 - iF1*iZ2; if ( iF3 > 0 ) { // +-++ iD2 = iF3 - iF1; iXN2 = iF3*iX1 - iF1*iX3; iYN2 = iF3*iY1 - iF1*iY3; iZN2 = iF3*iZ1 - iF1*iZ3; AddTriangle(rkVM,rkES,rkTS, iXN0,iD0,iYN0,iD0,iZN0,iD0, iXN1,iD1,iYN1,iD1,iZN1,iD1, iXN2,iD2,iYN2,iD2,iZN2,iD2); } else if ( iF3 < 0 ) { // +-+- iD2 = iF0 - iF3; iXN2 = iF0*iX3 - iF3*iX0; iYN2 = iF0*iY3 - iF3*iY0; iZN2 = iF0*iZ3 - iF3*iZ0; iD3 = iF2 - iF3; iXN3 = iF2*iX3 - iF3*iX2; iYN3 = iF2*iY3 - iF3*iY2; iZN3 = iF2*iZ3 - iF3*iZ2; AddTriangle(rkVM,rkES,rkTS, iXN0,iD0,iYN0,iD0,iZN0,iD0, iXN1,iD1,iYN1,iD1,iZN1,iD1, iXN2,iD2,iYN2,iD2,iZN2,iD2); AddTriangle(rkVM,rkES,rkTS, iXN1,iD1,iYN1,iD1,iZN1,iD1, iXN3,iD3,iYN3,iD3,iZN3,iD3, iXN2,iD2,iYN2,iD2,iZN2,iD2); } else { // +-+0 AddTriangle(rkVM,rkES,rkTS, iXN0,iD0,iYN0,iD0,iZN0,iD0, iXN1,iD1,iYN1,iD1,iZN1,iD1, iX3,1,iY3,1,iZ3,1); } } else if ( iF2 < 0 ) { iD0 = iF1 - iF0; iXN0 = iF1*iX0 - iF0*iX1; iYN0 = iF1*iY0 - iF0*iY1; iZN0 = iF1*iZ0 - iF0*iZ1; iD1 = iF2 - iF0; iXN1 = iF2*iX0 - iF0*iX2; iYN1 = iF2*iY0 - iF0*iY2; iZN1 = iF2*iZ0 - iF0*iZ2; if ( iF3 > 0 ) { // +--+ iD2 = iF1 - iF3; iXN2 = iF1*iX3 - iF3*iX1; iYN2 = iF1*iY3 - iF3*iY1; iZN2 = iF1*iZ3 - iF3*iZ1; iD3 = iF2 - iF3; iXN3 = iF2*iX3 - iF3*iX2; iYN3 = iF2*iY3 - iF3*iY2; iZN3 = iF2*iZ3 - iF3*iZ2; AddTriangle(rkVM,rkES,rkTS, iXN0,iD0,iYN0,iD0,iZN0,iD0, iXN1,iD1,iYN1,iD1,iZN1,iD1, iXN2,iD2,iYN2,iD2,iZN2,iD2); AddTriangle(rkVM,rkES,rkTS, iXN1,iD1,iYN1,iD1,iZN1,iD1, iXN3,iD3,iYN3,iD3,iZN3,iD3, iXN2,iD2,iYN2,iD2,iZN2,iD2); } else if ( iF3 < 0 ) { // +--- iD2 = iF3 - iF0; iXN2 = iF3*iX0 - iF0*iX3; iYN2 = iF3*iY0 - iF0*iY3; iZN2 = iF3*iZ0 - iF0*iZ3; AddTriangle(rkVM,rkES,rkTS, iXN0,iD0,iYN0,iD0,iZN0,iD0, iXN1,iD1,iYN1,iD1,iZN1,iD1, iXN2,iD2,iYN2,iD2,iZN2,iD2); } else { // +--0 AddTriangle(rkVM,rkES,rkTS, iXN0,iD0,iYN0,iD0,iZN0,iD0, iXN1,iD1,iYN1,iD1,iZN1,iD1, iX3,1,iY3,1,iZ3,1); } } else { iD0 = iF1 - iF0; iXN0 = iF1*iX0 - iF0*iX1; iYN0 = iF1*iY0 - iF0*iY1; iZN0 = iF1*iZ0 - iF0*iZ1; if ( iF3 > 0 ) { // +-0+ iD1 = iF1 - iF3; iXN1 = iF1*iX3 - iF3*iX1; iYN1 = iF1*iY3 - iF3*iY1; iZN1 = iF1*iZ3 - iF3*iZ1; AddTriangle(rkVM,rkES,rkTS, iXN0,iD0,iYN0,iD0,iZN0,iD0, iXN1,iD1,iYN1,iD1,iZN1,iD1, iX2,1,iY2,1,iZ2,1); } else if ( iF3 < 0 ) { // +-0- iD1 = iF3 - iF0; iXN1 = iF3*iX0 - iF0*iX3; iYN1 = iF3*iY0 - iF0*iY3; iZN1 = iF3*iZ0 - iF0*iZ3; AddTriangle(rkVM,rkES,rkTS, iXN0,iD0,iYN0,iD0,iZN0,iD0, iXN1,iD1,iYN1,iD1,iZN1,iD1, iX2,1,iY2,1,iZ2,1); } else { // +-00 AddTriangle(rkVM,rkES,rkTS, iXN0,iD0,iYN0,iD0,iZN0,iD0, iX2,1,iY2,1,iZ2,1, iX3,1,iY3,1,iZ3,1); } } } else { if ( iF2 > 0 ) { if ( iF3 > 0 ) { // +0++ AddVertex(rkVM,iX1,1,iY1,1,iZ1,1); } else if ( iF3 < 0 ) { // +0+- iD0 = iF0 - iF3; iXN0 = iF0*iX3 - iF3*iX0; iYN0 = iF0*iY3 - iF3*iY0; iZN0 = iF0*iZ3 - iF3*iZ0; iD1 = iF2 - iF3; iXN1 = iF2*iX3 - iF3*iX2; iYN1 = iF2*iY3 - iF3*iY2; iZN1 = iF2*iZ3 - iF3*iZ2; AddTriangle(rkVM,rkES,rkTS, iXN0,iD0,iYN0,iD0,iZN0,iD0, iXN1,iD1,iYN1,iD1,iZN1,iD1, iX1,1,iY1,1,iZ1,1); } else { // +0+0 AddEdge(rkVM,rkES,iX1,1,iY1,1,iZ1,1,iX3,1,iY3,1,iZ3,1); } } else if ( iF2 < 0 ) { iD0 = iF2 - iF0; iXN0 = iF2*iX0 - iF0*iX2; iYN0 = iF2*iY0 - iF0*iY2; iZN0 = iF2*iZ0 - iF0*iZ2; if ( iF3 > 0 ) { // +0-+ iD1 = iF2 - iF3; iXN1 = iF2*iX3 - iF3*iX2; iYN1 = iF2*iY3 - iF3*iY2; iZN1 = iF2*iZ3 - iF3*iZ2; AddTriangle(rkVM,rkES,rkTS, iXN0,iD0,iYN0,iD0,iZN0,iD0, iXN1,iD1,iYN1,iD1,iZN1,iD1, iX1,1,iY1,1,iZ1,1); } else if ( iF3 < 0 ) { // +0-- iD1 = iF0 - iF3; iXN1 = iF0*iX3 - iF3*iX0; iYN1 = iF0*iY3 - iF3*iY0; iZN1 = iF0*iZ3 - iF3*iZ0; AddTriangle(rkVM,rkES,rkTS, iXN0,iD0,iYN0,iD0,iZN0,iD0, iXN1,iD1,iYN1,iD1,iZN1,iD1, iX1,1,iY1,1,iZ1,1); } else { // +0-0 AddTriangle(rkVM,rkES,rkTS, iXN0,iD0,iYN0,iD0,iZN0,iD0, iX1,1,iY1,1,iZ1,1, iX3,1,iY3,1,iZ3,1); } } else { if ( iF3 > 0 ) { // +00+ AddEdge(rkVM,rkES,iX1,1,iY1,1,iZ1,1,iX2,1,iY2,1,iZ2,1); } else if ( iF3 < 0 ) { // +00- iD0 = iF0 - iF3; iXN0 = iF0*iX3 - iF3*iX0; iYN0 = iF0*iY3 - iF3*iY0; iZN0 = iF0*iZ3 - iF3*iZ0; AddTriangle(rkVM,rkES,rkTS, iXN0,iD0,iYN0,iD0,iZN0,iD0, iX1,1,iY1,1,iZ1,1, iX2,1,iY2,1,iZ2,1); } else { // +000 AddTriangle(rkVM,rkES,rkTS, iX1,1,iY1,1,iZ1,1, iX2,1,iY2,1,iZ2,1, iX3,1,iY3,1,iZ3,1); } } } } else if ( iF1 != 0 ) { // convert to case 0+** if ( iF1 < 0 ) { iF1 = -iF1; iF2 = -iF2; iF3 = -iF3; } if ( iF2 > 0 ) { if ( iF3 > 0 ) { // 0+++ AddVertex(rkVM,iX0,1,iY0,1,iZ0,1); } else if ( iF3 < 0 ) { // 0++- iD0 = iF2 - iF3; iXN0 = iF2*iX3 - iF3*iX2; iYN0 = iF2*iY3 - iF3*iY2; iZN0 = iF2*iZ3 - iF3*iZ2; iD1 = iF1 - iF3; iXN1 = iF1*iX3 - iF3*iX1; iYN1 = iF1*iY3 - iF3*iY1; iZN1 = iF1*iZ3 - iF3*iZ1; AddTriangle(rkVM,rkES,rkTS, iXN0,iD0,iYN0,iD0,iZN0,iD0, iXN1,iD1,iYN1,iD1,iZN1,iD1, iX0,1,iY0,1,iZ0,1); } else { // 0++0 AddEdge(rkVM,rkES,iX0,1,iY0,1,iZ0,1,iX3,1,iY3,1,iZ3,1); } } else if ( iF2 < 0 ) { iD0 = iF2 - iF1; iXN0 = iF2*iX1 - iF1*iX2; iYN0 = iF2*iY1 - iF1*iY2; iZN0 = iF2*iZ1 - iF1*iZ2; if ( iF3 > 0 ) { // 0+-+ iD1 = iF2 - iF3; iXN1 = iF2*iX3 - iF3*iX2; iYN1 = iF2*iY3 - iF3*iY2; iZN1 = iF2*iZ3 - iF3*iZ2; AddTriangle(rkVM,rkES,rkTS, iXN0,iD0,iYN0,iD0,iZN0,iD0, iXN1,iD1,iYN1,iD1,iZN1,iD1, iX0,1,iY0,1,iZ0,1); } else if ( iF3 < 0 ) { // 0+-- iD1 = iF1 - iF3; iXN1 = iF1*iX3 - iF3*iX1; iYN1 = iF1*iY3 - iF3*iY1; iZN1 = iF1*iZ3 - iF3*iZ1; AddTriangle(rkVM,rkES,rkTS, iXN0,iD0,iYN0,iD0,iZN0,iD0, iXN1,iD1,iYN1,iD1,iZN1,iD1, iX0,1,iY0,1,iZ0,1); } else { // 0+-0 AddTriangle(rkVM,rkES,rkTS, iXN0,iD0,iYN0,iD0,iZN0,iD0, iX0,1,iY0,1,iZ0,1, iX3,1,iY3,1,iZ3,1); } } else { if ( iF3 > 0 ) { // 0+0+ AddEdge(rkVM,rkES,iX0,1,iY0,1,iZ0,1,iX2,1,iY2,1,iZ2,1); } else if ( iF3 < 0 ) { // 0+0- iD0 = iF1 - iF3; iXN0 = iF1*iX3 - iF3*iX1; iYN0 = iF1*iY3 - iF3*iY1; iZN0 = iF1*iZ3 - iF3*iZ1; AddTriangle(rkVM,rkES,rkTS, iXN0,iD0,iYN0,iD0,iZN0,iD0, iX0,1,iY0,1,iZ0,1, iX2,1,iY2,1,iZ2,1); } else { // 0+00 AddTriangle(rkVM,rkES,rkTS, iX0,1,iY0,1,iZ0,1, iX2,1,iY2,1,iZ2,1, iX3,1,iY3,1,iZ3,1); } } } else if ( iF2 != 0 ) { // convert to case 00+* if ( iF2 < 0 ) { iF2 = -iF2; iF3 = -iF3; } if ( iF3 > 0 ) { // 00++ AddEdge(rkVM,rkES,iX0,1,iY0,1,iZ0,1,iX1,1,iY1,1,iZ1,1); } else if ( iF3 < 0 ) { // 00+- iD0 = iF2 - iF3; iXN0 = iF2*iX3 - iF3*iX2; iYN0 = iF2*iY3 - iF3*iY2; iZN0 = iF2*iZ3 - iF3*iZ2; AddTriangle(rkVM,rkES,rkTS, iXN0,iD0,iYN0,iD0,iZN0,iD0, iX0,1,iY0,1,iZ0,1, iX1,1,iY1,1,iZ1,1); } else { // 00+0 AddTriangle(rkVM,rkES,rkTS, iX0,1,iY0,1,iZ0,1, iX1,1,iY1,1,iZ1,1, iX3,1,iY3,1,iZ3,1); } } else if ( iF3 != 0 ) { // cases 000+ or 000- AddTriangle(rkVM,rkES,rkTS, iX0,1,iY0,1,iZ0,1, iX1,1,iY1,1,iZ1,1, iX2,1,iY2,1,iZ2,1); } else { // case 0000 AddTriangle(rkVM,rkES,rkTS, iX0,1,iY0,1,iZ0,1, iX1,1,iY1,1,iZ1,1, iX2,1,iY2,1,iZ2,1); AddTriangle(rkVM,rkES,rkTS, iX0,1,iY0,1,iZ0,1, iX1,1,iY1,1,iZ1,1, iX3,1,iY3,1,iZ3,1); AddTriangle(rkVM,rkES,rkTS, iX0,1,iY0,1,iZ0,1, iX2,1,iY2,1,iZ2,1, iX3,1,iY3,1,iZ3,1); AddTriangle(rkVM,rkES,rkTS, iX1,1,iY1,1,iZ1,1, iX2,1,iY2,1,iZ2,1, iX3,1,iY3,1,iZ3,1); } } //---------------------------------------------------------------------------- ExtractSurfaceTetra::Vertex::Vertex (int iXNumer, int iXDenom, int iYNumer, int iYDenom, int iZNumer, int iZDenom) { if ( iXDenom > 0 ) { m_iXNumer = iXNumer; m_iXDenom = iXDenom; } else { m_iXNumer = -iXNumer; m_iXDenom = -iXDenom; } if ( iYDenom > 0 ) { m_iYNumer = iYNumer; m_iYDenom = iYDenom; } else { m_iYNumer = -iYNumer; m_iYDenom = -iYDenom; } if ( iZDenom > 0 ) { m_iZNumer = iZNumer; m_iZDenom = iZDenom; } else { m_iZNumer = -iZNumer; m_iZDenom = -iZDenom; } } //---------------------------------------------------------------------------- bool ExtractSurfaceTetra::Vertex::operator< (const Vertex& rkVertex) const { unsigned int auiValue0[6] = { *(unsigned int*)&m_iXNumer, *(unsigned int*)&m_iXDenom, *(unsigned int*)&m_iYNumer, *(unsigned int*)&m_iYDenom, *(unsigned int*)&m_iZNumer, *(unsigned int*)&m_iZDenom }; unsigned int auiValue1[6] = { *(unsigned int*)&rkVertex.m_iXNumer, *(unsigned int*)&rkVertex.m_iXDenom, *(unsigned int*)&rkVertex.m_iYNumer, *(unsigned int*)&rkVertex.m_iYDenom, *(unsigned int*)&rkVertex.m_iZNumer, *(unsigned int*)&rkVertex.m_iZDenom }; for (int i = 0; i < 6; i++) { if ( auiValue0[i] < auiValue1[i] ) return true; if ( auiValue0[i] > auiValue1[i] ) return false; } return false; } //---------------------------------------------------------------------------- void ExtractSurfaceTetra::Vertex::GetTriple (Vector3f& rkMeshVertex) const { rkMeshVertex.X() = float(m_iXNumer)/float(m_iXDenom); rkMeshVertex.Y() = float(m_iYNumer)/float(m_iYDenom); rkMeshVertex.Z() = float(m_iZNumer)/float(m_iZDenom); } //----------------------------------------------------------------------------
[ [ [ 1, 1296 ] ] ]
ef27c494840ac4a0de9180b446b6fd224fed5cf2
94d9e8ec108a2f79068da09cb6ac903c16b77730
/sociarium/community_transition_diagram.h
a6293e88c974e304c4514303938872e8ae0888c5
[]
no_license
kiyoya/sociarium
d375c0e5abcce11ae4b087930677483d74864d09
b26c2c9cbd23c2f8ef219d0059e42370294865d1
refs/heads/master
2021-01-25T07:28:25.862346
2009-10-22T05:57:42
2009-10-22T05:57:42
318,115
1
0
null
null
null
null
UTF-8
C++
false
false
5,102
h
// s.o.c.i.a.r.i.u.m: community_transition_diagram.h // HASHIMOTO, Yasuhiro (E-mail: hy @ sys.t.u-tokyo.ac.jp) /* Copyright (c) 2005-2009, HASHIMOTO, Yasuhiro, 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 University of Tokyo 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 * 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. */ #ifndef INCLUDE_GUARD_SOCIARIUM_PROJECT_COMMUNITY_TRANSITION_DIAGRAM_H #define INCLUDE_GUARD_SOCIARIUM_PROJECT_COMMUNITY_TRANSITION_DIAGRAM_H #include <vector> #ifdef _MSC_VER #include <array> #include <memory> #else #include <tr1/array> #include <tr1/memory> #endif #include "../shared/vector2.h" #include "../shared/vector3.h" namespace hashimoto_ut { class SociariumGraphTimeSeries; class StaticNodeProperty; //////////////////////////////////////////////////////////////////////////////// class Trajectory { public: virtual ~Trajectory() {} virtual StaticNodeProperty* get_snp(void) const = 0; virtual std::pair<size_t, size_t> const& get_duration(void) const = 0; virtual std::pair<float, float> get_base_position(size_t index_of_layer) const = 0; virtual std::pair<float, float> get_interpolated_position(size_t index_of_point) const = 0; virtual Vector3<float> const& get_base_color(size_t index_of_layer) const = 0; virtual Vector3<float> const& get_interpolated_color(size_t index_of_point) const = 0; }; //////////////////////////////////////////////////////////////////////////////// class CommunityTransitionDiagram { public: virtual ~CommunityTransitionDiagram() {} virtual void read_lock(void) const = 0; virtual void read_unlock(void) const = 0; virtual void write_lock(void) const = 0; virtual void write_unlock(void) const = 0; virtual std::vector<std::tr1::shared_ptr<Trajectory> >::const_iterator trajectory_begin(void) const = 0; virtual std::vector<std::tr1::shared_ptr<Trajectory> >::const_iterator trajectory_end(void) const = 0; virtual void set_current_layer(size_t index_of_layer) = 0; virtual float get_max_bundle_size(void) const = 0; virtual void update(int mode) = 0; virtual void clear(void) = 0; virtual bool empty(void) const = 0; }; namespace sociarium_project_community_transition_diagram { //////////////////////////////////////////////////////////////////////////////// void initialize(void); std::tr1::shared_ptr<CommunityTransitionDiagram> get(void); int get_diagram_mode(void); //////////////////////////////////////////////////////////////////////////////// Vector2<double> const& get_frame_position(void); void set_frame_position(Vector2<double> const& pos); Vector2<double> const& get_frame_size(void); void set_frame_size(Vector2<double> size); //////////////////////////////////////////////////////////////////////////////// Vector2<double> const& get_default_frame_position(void); void set_default_frame_position(Vector2<double> const& pos); Vector2<double> const& get_default_frame_size(void); void set_default_frame_size(Vector2<double> size); //////////////////////////////////////////////////////////////////////////////// size_t get_resolution(void); void set_resolution(size_t resolution); std::pair<int, int> const& get_scope(void); void set_scope(int first_point, int last_point); } // The end of the namespace "sociarium_project_community_transition_diagram" } // The end of the namespace "hashimoto_ut" #endif // INCLUDE_GUARD_SOCIARIUM_PROJECT_COMMUNITY_TRANSITION_DIAGRAM_H
[ [ [ 1, 122 ] ] ]
85869163a954defa84d3022138352b8cfe332d5a
3bf3c2da2fd334599a80aa09420dbe4c187e71a0
/UI.h
ab7e7459e8a69bbdaa056c5364e81d2949ffb96f
[]
no_license
xiongchiamiov/virus-td
31b88f6a5d156a7b7ee076df55ddce4e1c65ca4f
a7b24ce50d07388018f82d00469cb331275f429b
refs/heads/master
2020-12-24T16:50:11.991795
2010-06-10T05:05:48
2010-06-10T05:05:48
668,821
1
0
null
null
null
null
UTF-8
C++
false
false
2,124
h
#pragma once #include <stdlib.h> #ifdef __unix__ #include <GL/glut.h> #endif #ifdef __APPLE__ #include "GLUT/glut.h" #endif #ifdef _WIN32 #include <gl/glut.h> #endif //#include <png.h> #include <stdio.h> #include <string.h> #include "lighting.h" #include "MyVector.h" #include "Camera.h" #include "GameObject.h" #include <vector> #include "textures.h" #include "Player.h" #include "constants.h" void initializeUI(void); void renderUI(int w, int h, Player* p, Player* opp, float time_left, GLuint mode); void resetUI(void); void mouseClick(int button, int state, int x, int y); void mouseMotion(int x, int y); void setOrthographicProjection(int w, int h); void resetPerspectiveProjection(); void drawMouseBox(bool click); void drawPanel(int w, int h, GLuint texture); void drawInfoPanel(GLfloat x, GLfloat y, GLfloat GW, GLfloat GH, int buttonNumber); void startPicking(int cursorX, int cursorY, GLuint buffer[], int bufferSize); GLint stopPicking(void); GLuint checkTowerClick(int x, int y); void processHits(GLint hits, GLuint buffer[]); GLuint processTowerHits(GLint hits, GLuint buffer[]); int determineClickedButton(int mouseX, int mouseY); void drawRectangle(float xp, float yp, float w, float h, GLuint texture); void renderBitmapString(float x, float y, void *font,char *string); int getBitmapStringWidth(void *font,char *string); void resetUIPosition(); float p2w_y(int y); float p2w_x(int x); extern bool placingTower; extern GLdouble worldX, worldY, worldZ; //variables to hold world x,y,z coordinates extern bool towerSelected; extern Tower *towerSelect; //void readPNG(file) class Button { private: int buttonNumber; GLfloat color[3]; GameObject * gameObj; public: Button(int bNum, GLfloat bColor[3], GameObject * obj); ~Button(void); void drawButton(int width, int height, GLuint bIcon); int getButtonNumber(); void setButtonNumer(int num); void setButtonColor(GLfloat color[3]); GameObject * getObject(); void setObject(GameObject * gObj); };
[ "kehung@05766cc9-4f33-4ba7-801d-bd015708efd9", "agonza40@05766cc9-4f33-4ba7-801d-bd015708efd9", "tcasella@05766cc9-4f33-4ba7-801d-bd015708efd9", "pearson@05766cc9-4f33-4ba7-801d-bd015708efd9" ]
[ [ [ 1, 1 ], [ 3, 11 ], [ 13, 14 ], [ 17, 18 ], [ 20, 21 ], [ 24, 25 ], [ 29, 33 ], [ 36, 36 ], [ 39, 39 ], [ 41, 41 ], [ 43, 43 ], [ 46, 47 ], [ 52, 56 ], [ 58, 59 ], [ 61, 64 ], [ 66, 69 ] ], [ [ 2, 2 ], [ 12, 12 ], [ 19, 19 ] ], [ [ 15, 15 ], [ 22, 23 ], [ 26, 28 ], [ 34, 35 ], [ 37, 38 ], [ 40, 40 ], [ 42, 42 ], [ 44, 45 ], [ 48, 51 ], [ 57, 57 ], [ 60, 60 ], [ 65, 65 ] ], [ [ 16, 16 ] ] ]
95c65f88728d294d08d04a2826877bbfb2f6c75c
fcf03ead74f6dc103ec3b07ffe3bce81c820660d
/AppFramework/UIControls/ControlFramework/inc/ControlFrameworkAppUi.h
885c26798c43715549d5d5346a25095c50f12388
[]
no_license
huellif/symbian-example
72097c9aec6d45d555a79a30d576dddc04a65a16
56f6c5e67a3d37961408fc51188d46d49bddcfdc
refs/heads/master
2016-09-06T12:49:32.021854
2010-10-14T06:31:20
2010-10-14T06:31:20
38,062,421
2
0
null
null
null
null
UTF-8
C++
false
false
669
h
// ControlFrameworkAppUi.h // // Copyright (c) 2006 Symbian Software Ltd. All rights reserved. // #ifndef __CONTROLFRAMEWORKAPPUI_H #define __CONTROLFRAMEWORKAPPUI_H #include <eikappui.h> class CControlFrameworkView; //Application UI class class CControlFrameworkAppUi : public CEikAppUi { public: CControlFrameworkAppUi(); ~CControlFrameworkAppUi(); void AddViewL(CControlFrameworkView* aView); enum TViews { EExampleView }; // from CEikAppUi void ConstructL(); private: void HandleCommandL(TInt); private: RPointerArray<CControlFrameworkView> iAppViews; }; #endif // __CONTROLFRAMEWORKAPPUI_H
[ "liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca" ]
[ [ [ 1, 37 ] ] ]
7d131efa818e72b861f77cee062e2b19dbedfa90
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/renaissance/rnsgameplay/src/ncpopulatorarea/ncpopulatorarea_cmds.cc
e5eda123aad7b0b620ca14922b79050b932032ef
[]
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
1,320
cc
#include "precompiled/pchrnsgameplay.h" //------------------------------------------------------------------------------ // ncpopulatorarea_cmds.cc // (C) Conjurer Services, S.A. 2006 //------------------------------------------------------------------------------ #include "ncpopulatorarea/ncpopulatorarea.h" //----------------------------------------------------------------------------- NSCRIPT_INITCMDS_BEGIN(ncPopulatorArea) NSCRIPT_ADDCMD_COMPOBJECT('IINA', bool, IsInside, 1, (const vector3&), 0, ()); NSCRIPT_ADDCMD_COMPOBJECT('ISSP', void, SetSpawner, 1, (nEntityObject*), 0, ()); NSCRIPT_ADDCMD_COMPOBJECT('IGSP', nEntityObject*, GetSpawner, 0, (), 0, ()); NSCRIPT_ADDCMD_COMPOBJECT('ISMI', void, SetMaxInhabitants, 1, (int), 0, ()); NSCRIPT_ADDCMD_COMPOBJECT('IGMI', int, GetMaxInhabitants, 0, (), 0, ()); NSCRIPT_ADDCMD_COMPOBJECT('IASI', bool, AddSpawnItem, 2, (const nString&, int), 0, ()); NSCRIPT_ADDCMD_COMPOBJECT('ICSI', bool, ChangeSpawnItem, 2, (const nString&, int), 0, ()); NSCRIPT_ADDCMD_COMPOBJECT('IRSI', bool, RemoveSpawnItem, 1, (const nString&), 0, ()); NSCRIPT_ADDCMD_COMPOBJECT('IGNS', int, GetNumberIndividuals, 1, (const nString&), 0, ()); /*NSCRIPT_ADDCMD_COMPOBJECT('IGBC', void, GetBreeds, 1, (nArray<nSpawnItem*>&), 0, ());*/ NSCRIPT_INITCMDS_END()
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 21 ] ] ]
e175ed0d0733df84047699a25d33d5c5c9d13487
7f6fe18cf018aafec8fa737dfe363d5d5a283805
/ntk/kernel/thread.h
16c2fc3034d813338c3b056fee4ff056e1a8c61a
[]
no_license
snori/ntk
4db91d8a8fc836ca9a0dc2bc41b1ce767010d5ba
86d1a32c4ad831e791ca29f5e7f9e055334e8fe7
refs/heads/master
2020-05-18T05:28:49.149912
2009-08-04T16:47:12
2009-08-04T16:47:12
268,861
2
0
null
null
null
null
UTF-8
C++
false
false
4,929
h
/****************************************************************************** The NTK Library Copyright (C) 1998-2003 Noritaka Suzuki $Id: thread.h,v 1.6 2003/11/11 12:07:09 nsuzuki Exp $ ******************************************************************************/ #pragma once #ifndef __NTK_KERNEL_THREAD_H__ #define __NTK_KERNEL_THREAD_H__ #ifndef __NTK_WINDOWS_WNIDOWS_H__ #include <ntk/windows/windows.h> #endif #ifndef __NTK_DEFS_H__ #include <ntk/defs.h> #endif #ifndef __NTK_SUPPORT_STRING_H__ #include <ntk/support/string.h> #endif #ifndef __NTK_SUPPORT_STATUS_H__ #include <ntk/support/status.h> #endif namespace ntk { //-------------------------------------------------------- // thread enum { // normal level priority // LOWEST_PRIORITY = THREAD_PRIORITY_LOWEST, LOW_PRIORITY = THREAD_PRIORITY_BELOW_NORMAL, NORMAL_PRIORITY = THREAD_PRIORITY_NORMAL, DISPLAY_PRIORITY = THREAD_PRIORITY_ABOVE_NORMAL, URGENT_DISPLAY_PRIORITY = THREAD_PRIORITY_HIGHEST, // real-time level priority // REAL_TIME_DISPLAY_PRIORITY = THREAD_PRIORITY_TIME_CRITICAL, URGENT_PRIORITY = THREAD_PRIORITY_TIME_CRITICAL, REAL_TIME_PRIORITY = THREAD_PRIORITY_TIME_CRITICAL, };// thread priority enum { BAD_THREAD_ID, BAD_THREAD_STATE, };//thread error codes typedef uint ThreadID; typedef uint (*ThreadFunc)(void*); NtkExport HANDLE spawn_thread( ThreadFunc func, const String& name, int priority = NORMAL_PRIORITY, void* data = NULL, status_t* status = NULL, ThreadID* return_id = NULL, bool close_handle_flag = true); NtkExport status_t suspend_thread(HANDLE handle); NtkExport status_t resume_thread(HANDLE handle); NtkExport bool kill_thread(HANDLE handle, ulong code = 1); NtkExport void exit_thread(uint return_value); NtkExport status_t wait_for_thread(HANDLE handle, uint* return_value = NULL); NtkExport bool set_thread_priority(HANDLE handle, int priority); NtkExport void snooze(bigtime_t milliseconds); class Thread { public: // // methods // NtkExport Thread( ThreadFunc func, const String& name, int priority = NORMAL_PRIORITY, void* data = NULL, status_t* status = NULL, bool close_handle_thread = true); NtkExport Thread( const String& name, int priority = NORMAL_PRIORITY, status_t* status = NULL, bool close_handle_thread = true); NtkExport virtual ~Thread(); NtkExport virtual uint proc(); NtkExport status_t run(); NtkExport status_t suspend(); NtkExport status_t resume(); NtkExport void snooze(bigtime_t milliseconds); NtkExport status_t wait_for(uint* return_value = NULL); // // accessors // NtkExport HANDLE thread_handle() const; NtkExport ThreadID thread_id() const; NtkExport bool is_suspended() const; private: // // class methods // static uint start_point_(void*); // // data // bool m_suspend; HANDLE m_thread_handle; ThreadID m_thread_id; };// class Thread //======================================================== // semaphore typedef void* SemID; NtkExport SemID create_sem(uint thread_count, const String& name = "", status_t* status = NULL); NtkExport status_t delete_sem(SemID sem_id); NtkExport status_t acquire_sem(SemID sem_id); NtkExport status_t acquire_sem(SemID sem_id, int count, bigtime_t time_out); NtkExport status_t release_sem(SemID sem_id); NtkExport status_t release_sem(SemID sem_id, int count); NtkExport status_t get_sem_count(SemID sem_id, int* thread_count); class Semaphore { public: // // methods // NtkExport Semaphore(uint thread_count, const String& name = "", status_t* status = NULL); NtkExport ~Semaphore(); NtkExport status_t acquire(); NtkExport status_t acquire(int count, bigtime_t time_out); NtkExport status_t release(); NtkExport status_t release(int count); // // accessors // NtkExport int count(status_t* status = NULL) const; private: // // data // SemID m_sem; };// class Semaphore #ifdef NTK_TYPEDEF_LOWERCASE_ONLY_TYPE_NAME typedef ThreadID thread_id_t; typedef ThreadFunc thread_func_t; typedef Thread thread_t; typedef SemID sem_id_t; typedef Semaphore semaphore_t; #endif } namespace Ntk = ntk; #ifdef NTK_TYPEDEF_TYPES_AS_GLOBAL_TYPE #ifdef NTK_TYPEDEF_GLOBAL_NCLASS typedef ntk::ThreadID NThreadID; typedef ntk::ThreadFunc NThreadFunc; typedef ntk::Thread NThread; typedef ntk::SemID NSemID; typedef ntk::Semaphore NSemaphore; #endif #ifdef NTK_TYPEDEF_LOWERCASE_ONLY_TYPE_NAME typedef ntk::ThreadID ntk_thread_id; typedef ntk::ThreadFunc ntk_thread_func; typedef ntk::Thread ntk_thread; typedef ntk::SemID ntk_sem_id; typedef ntk::Semaphore ntk_semaphore; #endif #endif #endif//EOH
[ [ [ 1, 210 ] ] ]
42922bfbf4477b6c75b8b30b9f03a785379c340b
52eec3f146a11a5092aeead6fb0ad9654c6e76f7
/ultracache/benchmark.cpp
09cbbda7c53c5ffb2614a202f0131d555c589fd0
[]
no_license
isabella232/ultracache
b497f54f5b8b6f3d6ca30a1188050170edde5ff0
ed03dc953c74bb2600c5eb54dfd5fe3ca1164216
refs/heads/master
2023-03-18T23:31:59.136171
2011-10-11T22:01:01
2011-10-11T22:01:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,831
cpp
#include "Server.h" #include "Client.h" #define CLIENT_COUNT 8 #define MULTI_GETS 64 void *ServerProc(void *arg) { Server *server = (Server *) arg; server->main(0, NULL); return NULL; } volatile UINT64 g_writeCount = 0; volatile UINT64 g_readCount = 0; void *ClientProc(void *arg) { srand(PortableGetCurrentThreadId()); struct sockaddr_in *remoteAddr = (sockaddr_in *) arg; Client client(1); client.connect(*remoteAddr); char value[64] = { 'Z' }; size_t valueLen = sizeof(value); size_t cCount = 0; while (cCount < 100000) { char strKey[17]; sprintf(strKey, "%08x%08x", PortableGetCurrentThreadId(), cCount); bool bResult = client.set(strKey, 16, value, valueLen, 0, 0, false); g_writeCount ++; if (!bResult && client.getError() == Client::SERVER_ERROR_OOM) { break; } cCount ++; } fprintf (stderr, "Switching to reads...\n"); while (true) { Client::MGETHANDLE handles[MULTI_GETS]; for (int index = 0; index < MULTI_GETS; index ++) { int key = rand () % cCount; char strKey[17]; sprintf(strKey, "%08x%08x", PortableGetCurrentThreadId(), key); handles[index] = client.getMulti(strKey, 16); } int offset = 0; void *pValue; size_t valueLen; int flags; UINT64 cas; while (client.readMulti(handles, MULTI_GETS, offset, NULL, 0, &pValue, &valueLen, &flags, &cas)) { g_readCount ++; } if (offset != MULTI_GETS) { fprintf (stderr, "Request lost at offset %d\n", offset); } } return NULL; } int benchmark (int argc, char **argv) { char *serverAddress = "192.168.1.174"; char *noserver = NULL; for (int index = 1; index < argc-1; index ++) { if (strcmp(argv[index], "-address") == 0) { serverAddress = argv[index + 1]; } else if (strcmp(argv[index], "-noserver") == 0) { noserver = argv[index + 1]; } } Server *server; JThread serverThread; if (!noserver) { server = new Server(); serverThread = JThread::createThread(ServerProc, server); MSECSleep(5000); } fprintf (stderr, "%s: Using server address %s\n", __FUNCTION__, serverAddress); JThread clients[CLIENT_COUNT]; struct sockaddr_in remoteAddr; memset (&remoteAddr, 0, sizeof(sockaddr_in)); remoteAddr.sin_family = AF_INET; remoteAddr.sin_port = htons(11211); remoteAddr.sin_addr.s_addr = inet_addr(serverAddress); for (int index = 0; index < CLIENT_COUNT; index ++) { clients[index] = JThread::createThread(ClientProc, &remoteAddr); } UINT64 wlast = 0; UINT64 rlast = 0; while (true) { fprintf (stderr, "%llu writes %llu reads/sec\n", g_writeCount - wlast, g_readCount - rlast); wlast = g_writeCount; rlast = g_readCount; MSECSleep(1000); } }
[ [ [ 1, 148 ] ] ]
03fb184828b1e9531eb2356b199ba76f3cd153d9
c930acc7d855f5082dfc598437dacd7d73718787
/util.h
2e4898ec2e0ab3f65c9c09a95f6213196b59508c
[]
no_license
giulianoxt/qassault
9db0c67c2122d41299e4f41e3bc5d985b8a7db7b
ff46426199e5336b64bd8eb70fce66d8e0212f83
refs/heads/master
2020-05-19T11:13:13.623501
2009-10-06T00:50:02
2009-10-06T00:50:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,945
h
#ifndef UTIL_H #define UTIL_H #include <QSlider> #include <QPixmap> #include <QString> #include <QColor> #include <QPoint> #include <QEvent> #include <QList> #include <QLabel> #include <QMovie> #include <QVariant> #include <QtSignalTransition> #include <cstdlib> #include <iostream> #include <algorithm> #define dump(x) cout << #x << " = " << (x) << endl; #define for_(i,a,b) for (int i = a; i < b; ++i) using namespace std; int randInt(int); double sliderRealValue(const QSlider&); void changeColors(QPixmap&, int, int); QPoint boardToScene(int, int); QPoint boardToScene(const QPoint&); ostream& operator<<(ostream&, const QPoint&); template<typename T> ostream& operator<<(ostream& out, const QList<T>& l) { out << '['; bool f = true; foreach(const T& x, l) { if (f) f = false; else out << ", "; out << x; } return out << ']'; } template<typename V, typename T> const QList<QVariant> toVariantList(const V& v) { QList<QVariant> l; foreach (const T& x, v) { QVariant v; v.setValue(x); l.push_back(v); } return l; } template<typename T> const QList<T> fromVariantList(const QVariant& v) { QList<T> l; foreach (const QVariant& x, v.toList()) l.push_back(x.value<T>()); return l; } template<typename T> void debug(const QString& msg, const T& s) { cout << "[" << msg.toStdString() << "] " << s << endl; } class MovieLoopLabel : public QLabel { Q_OBJECT Q_PROPERTY(bool running READ isRunning WRITE setRunning); public: MovieLoopLabel(QWidget*); void setMovie(const QString&); bool isRunning() const; void setRunning(bool); public slots: void loop(); protected: QMovie* movie; bool _running; }; #endif // UTIL_H
[ [ [ 1, 104 ] ] ]
39efb60eb90452139c8d669b72909ee2047ce3ae
1cf1543cd5460621f530f730a4f3969cfa74197c
/Token.h
16857f7c97667bded26c5f27723be6e37d92f01a
[]
no_license
derpepe/sysprog
042048d0c8f30fb26f0fb79a024530f67a852ca9
2fa6fb3b7c7f53b3fa8ff6aeb74d8d3e3331ba61
refs/heads/master
2021-01-18T14:01:45.742680
2010-02-23T22:23:25
2010-02-23T22:23:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
804
h
#pragma once #include <iostream> #include <string> #include <sstream> #include "Const.h" class Token { public: Token(tokenType myTokenType, std::string myTokenValue, int column, int line); int getLine(); int getColumn(); void setLine(int myLine); void setColumn(int myColumn); tokenType getTokenType(); void setTokenType(tokenType myTokenType); std::string getLexem(); // returns string value of token double getFloatValue(); std::string getFloatValueAsString(); int getIntValue(); std::string getIntValueAsString(); void setTokenValue(std::string myTokenValue); void setTokenValue(float myTokenFloatValue); void setTokenValue(int myTokenIntValue); private: int line; int column; tokenType myTokenType; std::string myTokenValue; };
[ [ [ 1, 41 ] ] ]
8f8625a22d5a61d051f28c456377e53c8bb2860d
fd47272bb959679789cf1c65afa778569886232f
/Geometry/Sphere.h
c2d93b8511f248b1c1661268c054d76546575ec8
[]
no_license
dicta/ray
5aeed98fe0cc76b7a5dea2c4b93c38caf0485b6c
5e6290077a92b8468877a8b6751f1ed13da81a43
refs/heads/master
2021-01-17T16:16:21.768537
2011-09-26T06:03:12
2011-09-28T04:36:22
2,471,865
0
0
null
null
null
null
UTF-8
C++
false
false
1,300
h
#ifndef _SPHERE_H_ #define _SPHERE_H_ #include "LightObject.h" #include "Math/Point3D.h" class Sampler; /** * Creates a sphere or a part sphere. * * Hash values: * - center [ x y z ] - Center of the sphere * - radius <i>value</i> - Sphere radius in world coordinates * - thetaRange [ min max ] - Optional Latitude range to include. Array of 2 daubles from 0 to 180. 0 is at the top of the sphere. * - phiRange [ min max ] - Optional Longitude range to include. Array of 2 doubles from 0 to 360. 0 is in the positive Z axis. */ class Sphere : public LightObject { public: Sphere(); Sphere(const Point3D& c, double r); virtual ~Sphere(); virtual bool hit(const Ray& ray, double& tmin, ShadeRecord& sr) const; virtual bool shadowHit(const Ray& ray, double& tmin) const; virtual void setHash(Hash* hash); virtual Point3D sample(const Point3D& hitPoint) const; virtual Vector3D getNormal(const Point3D& point) const; virtual double pdf(const ShadeRecord& sr) const; private: bool partCheck(const Ray& ray, double t) const; void getNormalFromMap(ShadeRecord& sr) const; Point3D center; double radius; bool thetaRange, phiRange; double cosThetaMin, cosThetaMax; double phiMin, phiMax; mutable Sampler* sampler; }; #endif
[ "esaari1@13d0956a-e706-368b-88ec-5b7e5bac2ff7", "[email protected]@13d0956a-e706-368b-88ec-5b7e5bac2ff7" ]
[ [ [ 1, 3 ], [ 8, 17 ], [ 20, 21 ], [ 24, 25 ], [ 33, 40 ], [ 43, 45 ] ], [ [ 4, 7 ], [ 18, 19 ], [ 22, 23 ], [ 26, 32 ], [ 41, 42 ] ] ]
f9bf834195002699dc24cacded70a6d88316b36e
463c3b62132d215e245a097a921859ecb498f723
/lib/dlib/sockstreambuf/sockstreambuf_kernel_abstract.h
04c337e5cfc4677ca8bd1bcda5f70a487012d426
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
athulan/cppagent
58f078cee55b68c08297acdf04a5424c2308cfdc
9027ec4e32647e10c38276e12bcfed526a7e27dd
refs/heads/master
2021-01-18T23:34:34.691846
2009-05-05T00:19:54
2009-05-05T00:19:54
197,038
4
1
null
null
null
null
UTF-8
C++
false
false
3,545
h
// Copyright (C) 2003 Davis E. King ([email protected]) // License: Boost Software License See LICENSE.txt for the full license. #undef DLIB_SOCKSTREAMBUF_KERNEl_ABSTRACT_ #ifdef DLIB_SOCKSTREAMBUF_KERNEl_ABSTRACT_ #include <iosfwd> #include <streambuf> #include "../sockets/sockets_kernel_abstract.h" namespace dlib { // ---------------------------------------------------------------------------------------- class sockstreambuf : public std::streambuf { /*! WHAT THIS OBJECT REPRESENTS This object represents a stream buffer capable of writing to and reading from TCP connections. NOTE: For a sockstreambuf EOF is when the connection has closed or otherwise returned some kind of error. Also note that any data written to the streambuf may be buffered internally. So if you need to ensure that data is actually sent then you should flush the stream. A read operation is guaranteed to block until the number of bytes requested has arrived on the connection. It will never keep blocking once enough data has arrived. THREADING generally speaking, this object has the same kind of threading restrictions as a connection object. those being: - do not try to write to a sockstreambuf from more than one thread - do not try to read from a sockstreambuf from more than one thread - you may call shutdown() on the connection object and this will cause any reading or writing calls to end. To the sockstreambuf it will appear the same as hitting EOF. (note that EOF for a sockstreambuf means that the connection has closed) - it is safe to read from and write to the sockstreambuf at the same time - it is not safe to try to putback a char and read from the stream from different threads !*/ public: sockstreambuf ( connection* con ); /*! requires - con == a valid connection object ensures - *this will read from and write to con throws - std::bad_alloc !*/ sockstreambuf ( const scoped_ptr<connection>& con ); /*! requires - con == a valid connection object ensures - *this will read from and write to con throws - std::bad_alloc !*/ ~sockstreambuf ( ); /*! requires - get_connection() object has not been deleted ensures - sockstream buffer is destructed but the connection object will NOT be closed. - Any buffered data is flushed to the connection. !*/ connection* get_connection ( ); /*! ensures - returns a pointer to the connection object which this buffer reads from and writes to !*/ }; // ---------------------------------------------------------------------------------------- } #endif // DLIB_SOCKSTREAMBUF_KERNEl_ABSTRACT_
[ "jimmy@DGJ3X3B1.(none)" ]
[ [ [ 1, 98 ] ] ]
205fdf74194b31b1aa0b71d63e744b615671e35c
09dfc0e039143673380a3d490c84b6c0d3d6ee6c
/surf_object_recognition/src/fasthessian.cpp
2721a0a80358176dc44f71a4d0ec48675cd9adc0
[]
no_license
vishu2287/ucsb-ros-pkg
8642a78ddbe352fcb544658fb23737cb3ce86f04
b2e34c76b362a69b6c2f3c34c9f5cee419aa9839
refs/heads/master
2016-09-10T04:40:42.981912
2011-03-16T07:40:18
2011-03-16T07:40:18
34,023,815
0
0
null
null
null
null
UTF-8
C++
false
false
12,292
cpp
/*********************************************************** * --- OpenSURF --- * * This library is distributed under the GNU GPL. Please * * use the contact form at http://www.chrisevansdev.com * * for more information. * * * * C. Evans, Research Into Robust Visual Features, * * MSc University of Bristol, 2008. * * * ************************************************************/ #include "integral.h" #include "ipoint.h" #include "utils.h" #include <vector> #include "responselayer.h" #include "fasthessian.h" using namespace std; //------------------------------------------------------- //! Constructor without image FastHessian::FastHessian(std::vector<Ipoint> &ipts, const int octaves, const int intervals, const int init_sample, const float thresh) : ipts(ipts), i_width(0), i_height(0) { // Save parameter set saveParameters(octaves, intervals, init_sample, thresh); } //------------------------------------------------------- //! Constructor with image FastHessian::FastHessian(IplImage *img, std::vector<Ipoint> &ipts, const int octaves, const int intervals, const int init_sample, const float thresh) : ipts(ipts), i_width(0), i_height(0) { // Save parameter set saveParameters(octaves, intervals, init_sample, thresh); // Set the current image setIntImage(img); } //------------------------------------------------------- FastHessian::~FastHessian() { for (unsigned int i = 0; i < responseMap.size(); ++i) { delete responseMap[i]; } } //------------------------------------------------------- //! Save the parameters void FastHessian::saveParameters(const int octaves, const int intervals, const int init_sample, const float thresh) { // Initialise variables with bounds-checked values this->octaves = (octaves > 0 && octaves <= 4 ? octaves : OCTAVES); this->intervals = (intervals > 0 && intervals <= 4 ? intervals : INTERVALS); this->init_sample = (init_sample > 0 && init_sample <= 6 ? init_sample : INIT_SAMPLE); this->thresh = (thresh >= 0 ? thresh : THRES); } //------------------------------------------------------- //! Set or re-set the integral image source void FastHessian::setIntImage(IplImage *img) { // Change the source image this->img = img; i_height = img->height; i_width = img->width; } //------------------------------------------------------- //! Find the image features and write into vector of features void FastHessian::getIpoints() { // filter index map static const int filter_map [OCTAVES][INTERVALS] = {{0,1,2,3}, {1,3,4,5}, {3,5,6,7}, {5,7,8,9}, {7,9,10,11}}; // Clear the vector of exisiting ipts ipts.clear(); // Build the response map buildResponseMap(); // Get the response layers ResponseLayer *b, *m, *t; for (int o = 0; o < octaves; ++o) for (int i = 0; i <= 1; ++i) { b = responseMap.at(filter_map[o][i]); m = responseMap.at(filter_map[o][i+1]); t = responseMap.at(filter_map[o][i+2]); // loop over middle response layer at density of the most // sparse layer (always top), to find maxima across scale and space for (int r = 0; r < t->height; ++r) { for (int c = 0; c < t->width; ++c) { if (isExtremum(r, c, t, m, b)) { interpolateExtremum(r, c, t, m, b); } } } } } //------------------------------------------------------- //! Build map of DoH responses void FastHessian::buildResponseMap() { // Calculate responses for the first 4 octaves: // Oct1: 9, 15, 21, 27 // Oct2: 15, 27, 39, 51 // Oct3: 27, 51, 75, 99 // Oct4: 51, 99, 147,195 // Oct5: 99, 195,291,387 // Deallocate memory and clear any existing response layers for(unsigned int i = 0; i < responseMap.size(); ++i) delete responseMap[i]; responseMap.clear(); // Get image attributes int w = (i_width / init_sample); int h = (i_height / init_sample); int s = (init_sample); // Calculate approximated determinant of hessian values if (octaves >= 1) { responseMap.push_back(new ResponseLayer(w, h, s, 9)); responseMap.push_back(new ResponseLayer(w, h, s, 15)); responseMap.push_back(new ResponseLayer(w, h, s, 21)); responseMap.push_back(new ResponseLayer(w, h, s, 27)); } if (octaves >= 2) { responseMap.push_back(new ResponseLayer(w/2, h/2, s*2, 39)); responseMap.push_back(new ResponseLayer(w/2, h/2, s*2, 51)); } if (octaves >= 3) { responseMap.push_back(new ResponseLayer(w/4, h/4, s*4, 75)); responseMap.push_back(new ResponseLayer(w/4, h/4, s*4, 99)); } if (octaves >= 4) { responseMap.push_back(new ResponseLayer(w/8, h/8, s*8, 147)); responseMap.push_back(new ResponseLayer(w/8, h/8, s*8, 195)); } if (octaves >= 5) { responseMap.push_back(new ResponseLayer(w/16, h/16, s*16, 291)); responseMap.push_back(new ResponseLayer(w/16, h/16, s*16, 387)); } // Extract responses from the image for (unsigned int i = 0; i < responseMap.size(); ++i) { buildResponseLayer(responseMap[i]); } } //------------------------------------------------------- //! Calculate DoH responses for supplied layer void FastHessian::buildResponseLayer(ResponseLayer *rl) { float *responses = rl->responses; // response storage unsigned char *laplacian = rl->laplacian; // laplacian sign storage int step = rl->step; // step size for this filter int b = (rl->filter - 1) / 2 + 1; // border for this filter int l = rl->filter / 3; // lobe for this filter (filter size / 3) int w = rl->filter; // filter size float inverse_area = 1.f/(w*w); // normalisation factor float Dxx, Dyy, Dxy; for(int r, c, ar = 0, index = 0; ar < rl->height; ++ar) { for(int ac = 0; ac < rl->width; ++ac, index++) { // get the image coordinates r = ar * step; c = ac * step; // Compute response components Dxx = BoxIntegral(img, r - l + 1, c - b, 2*l - 1, w) - BoxIntegral(img, r - l + 1, c - l / 2, 2*l - 1, l)*3; Dyy = BoxIntegral(img, r - b, c - l + 1, w, 2*l - 1) - BoxIntegral(img, r - l / 2, c - l + 1, l, 2*l - 1)*3; Dxy = + BoxIntegral(img, r - l, c + 1, l, l) + BoxIntegral(img, r + 1, c - l, l, l) - BoxIntegral(img, r - l, c - l, l, l) - BoxIntegral(img, r + 1, c + 1, l, l); // Normalise the filter responses with respect to their size Dxx *= inverse_area; Dyy *= inverse_area; Dxy *= inverse_area; // Get the determinant of hessian response & laplacian sign responses[index] = (Dxx * Dyy - 0.81f * Dxy * Dxy); laplacian[index] = (Dxx + Dyy >= 0 ? 1 : 0); #ifdef RL_DEBUG // create list of the image coords for each response rl->coords.push_back(std::make_pair<int,int>(r,c)); #endif } } } //------------------------------------------------------- //! Non Maximal Suppression function int FastHessian::isExtremum(int r, int c, ResponseLayer *t, ResponseLayer *m, ResponseLayer *b) { // bounds check int layerBorder = (t->filter + 1) / (2 * t->step); if (r <= layerBorder || r >= t->height - layerBorder || c <= layerBorder || c >= t->width - layerBorder) return 0; // check the candidate point in the middle layer is above thresh float candidate = m->getResponse(r, c, t); if (candidate < thresh) return 0; for (int rr = -1; rr <=1; ++rr) { for (int cc = -1; cc <=1; ++cc) { // if any response in 3x3x3 is greater candidate not maximum if ( t->getResponse(r+rr, c+cc) >= candidate || ((rr != 0 && cc != 0) && m->getResponse(r+rr, c+cc, t) >= candidate) || b->getResponse(r+rr, c+cc, t) >= candidate ) return 0; } } return 1; } //------------------------------------------------------- //! Interpolate scale-space extrema to subpixel accuracy to form an image feature. void FastHessian::interpolateExtremum(int r, int c, ResponseLayer *t, ResponseLayer *m, ResponseLayer *b) { // get the step distance between filters // check the middle filter is mid way between top and bottom int filterStep = (m->filter - b->filter); assert(filterStep > 0 && t->filter - m->filter == m->filter - b->filter); // Get the offsets to the actual location of the extremum double xi = 0, xr = 0, xc = 0; interpolateStep(r, c, t, m, b, &xi, &xr, &xc ); // If point is sufficiently close to the actual extremum if( fabs( xi ) < 0.5f && fabs( xr ) < 0.5f && fabs( xc ) < 0.5f ) { Ipoint ipt; ipt.x = static_cast<float>((c + xc) * t->step); ipt.y = static_cast<float>((r + xr) * t->step); ipt.scale = static_cast<float>((0.1333f) * (m->filter + xi * filterStep)); ipt.laplacian = static_cast<int>(m->getLaplacian(r,c,t)); ipts.push_back(ipt); } } //------------------------------------------------------- //! Performs one step of extremum interpolation. void FastHessian::interpolateStep(int r, int c, ResponseLayer *t, ResponseLayer *m, ResponseLayer *b, double* xi, double* xr, double* xc ) { CvMat* dD, * H, * H_inv, X; double x[3] = { 0 }; dD = deriv3D( r, c, t, m, b ); H = hessian3D( r, c, t, m, b ); H_inv = cvCreateMat( 3, 3, CV_64FC1 ); cvInvert( H, H_inv, CV_SVD ); cvInitMatHeader( &X, 3, 1, CV_64FC1, x, CV_AUTOSTEP ); cvGEMM( H_inv, dD, -1, NULL, 0, &X, 0 ); cvReleaseMat( &dD ); cvReleaseMat( &H ); cvReleaseMat( &H_inv ); *xi = x[2]; *xr = x[1]; *xc = x[0]; } //------------------------------------------------------- //! Computes the partial derivatives in x, y, and scale of a pixel. CvMat* FastHessian::deriv3D(int r, int c, ResponseLayer *t, ResponseLayer *m, ResponseLayer *b) { CvMat* dI; double dx, dy, ds; dx = (m->getResponse(r, c + 1, t) - m->getResponse(r, c - 1, t)) / 2.0; dy = (m->getResponse(r + 1, c, t) - m->getResponse(r - 1, c, t)) / 2.0; ds = (t->getResponse(r, c) - b->getResponse(r, c, t)) / 2.0; dI = cvCreateMat( 3, 1, CV_64FC1 ); cvmSet( dI, 0, 0, dx ); cvmSet( dI, 1, 0, dy ); cvmSet( dI, 2, 0, ds ); return dI; } //------------------------------------------------------- //! Computes the 3D Hessian matrix for a pixel. CvMat* FastHessian::hessian3D(int r, int c, ResponseLayer *t, ResponseLayer *m, ResponseLayer *b) { CvMat* H; double v, dxx, dyy, dss, dxy, dxs, dys; v = m->getResponse(r, c, t); dxx = m->getResponse(r, c + 1, t) + m->getResponse(r, c - 1, t) - 2 * v; dyy = m->getResponse(r + 1, c, t) + m->getResponse(r - 1, c, t) - 2 * v; dss = t->getResponse(r, c) + b->getResponse(r, c, t) - 2 * v; dxy = ( m->getResponse(r + 1, c + 1, t) - m->getResponse(r + 1, c - 1, t) - m->getResponse(r - 1, c + 1, t) + m->getResponse(r - 1, c - 1, t) ) / 4.0; dxs = ( t->getResponse(r, c + 1) - t->getResponse(r, c - 1) - b->getResponse(r, c + 1, t) + b->getResponse(r, c - 1, t) ) / 4.0; dys = ( t->getResponse(r + 1, c) - t->getResponse(r - 1, c) - b->getResponse(r + 1, c, t) + b->getResponse(r - 1, c, t) ) / 4.0; H = cvCreateMat( 3, 3, CV_64FC1 ); cvmSet( H, 0, 0, dxx ); cvmSet( H, 0, 1, dxy ); cvmSet( H, 0, 2, dxs ); cvmSet( H, 1, 0, dxy ); cvmSet( H, 1, 1, dyy ); cvmSet( H, 1, 2, dys ); cvmSet( H, 2, 0, dxs ); cvmSet( H, 2, 1, dys ); cvmSet( H, 2, 2, dss ); return H; } //-------------------------------------------------------
[ "[email protected]@0b0f7875-c668-5978-e4a7-07162229f4fe" ]
[ [ [ 1, 375 ] ] ]
76c59109f5ad7a9c675de72e0c92043ac5d0fc95
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/Game/wheel/NetWheelDirector/src/logic/Dan1Logic.cpp
32e7f374a3efd3a808d096a424603267a280f6f5
[]
no_license
dbabox/aomi
dbfb46c1c9417a8078ec9a516cc9c90fe3773b78
4cffc8e59368e82aed997fe0f4dcbd7df626d1d0
refs/heads/master
2021-01-13T14:05:10.813348
2011-06-07T09:36:41
2011-06-07T09:36:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
485
cpp
#include "NetWheelDirectorStableHeaders.h" #include "logic/AllLogic.h" #include "WheelEvents.h" #include "DUI/DUI.h" using namespace Orz; Dan1Logic::Dan1Logic(my_context ctx):LogicAdv(ctx) { DUI::getSingleton().setMenuDataVisible(true); } void Dan1Logic::exit(void) { DUI::getSingleton().setMenuDataVisible(false); } sc::result Dan1Logic::react(const LogicEvent::Dan1 & evt) { return transit<GameLogic>(); } Dan1Logic::~Dan1Logic(void) { }
[ [ [ 1, 29 ] ] ]
e7e31eb9359602b4b151baed8daf5361b3054c77
222bc22cb0330b694d2c3b0f4b866d726fd29c72
/src/brookbox/wm2/WmlLinearSystem.h
6c2ba1f105603c9591225215ff63095c682ee8ca
[ "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference" ]
permissive
darwin/inferno
02acd3d05ca4c092aa4006b028a843ac04b551b1
e87017763abae0cfe09d47987f5f6ac37c4f073d
refs/heads/master
2021-03-12T22:15:47.889580
2009-04-17T13:29:39
2009-04-17T13:29:39
178,477
2
0
null
null
null
null
UTF-8
C++
false
false
6,030
h
// Magic Software, Inc. // http://www.magic-software.com // http://www.wild-magic.com // Copyright (c) 2003. All Rights Reserved // // The Wild Magic Library (WML) source code is supplied under the terms of // the license agreement http://www.magic-software.com/License/WildMagic.pdf // and may not be copied or disclosed except in accordance with the terms of // that agreement. #ifndef WMLLINEARSYSTEM_H #define WMLLINEARSYSTEM_H #include "WmlBandedMatrix.h" #include "WmlGMatrix.h" #include <map> namespace Wml { template <class Real> class WML_ITEM LinearSystem { public: // 2x2 and 3x3 systems (avoids overhead of Gaussian elimination) static Real& Tolerance (); static bool Solve2 (const Real aafA[2][2], const Real afB[2], Real afX[2]); static bool Solve3 (const Real aafA[3][3], const Real afB[3], Real afX[3]); // Input: // A[iSize][iSize], entries are A[row][col] // Output: // return value is TRUE if successful, FALSE if pivoting failed // InvA[iSize][iSize], inverse matrix static bool Inverse (const GMatrix<Real>& rkA, GMatrix<Real>& rkInvA); // Input: // A[iSize][iSize] coefficient matrix, entries are A[row][col] // B[iSize] vector, entries are B[row] // Output: // return value is TRUE if successful, FALSE if pivoting failed // X[iSize] is solution X to AX = B static bool Solve (const GMatrix<Real>& rkA, const Real* afB, Real* afX); // Input: // Matrix is tridiagonal. // Lower diagonal A[iSize-1] // Main diagonal B[iSize] // Upper diagonal C[iSize-1] // Right-hand side R[iSize] // Output: // return value is TRUE if successful, FALSE if pivoting failed // U[iSize] is solution static bool SolveTri (int iSize, Real* afA, Real* afB, Real* afC, Real* afR, Real* afU); // Input: // Matrix is tridiagonal. // Lower diagonal is constant, A // Main diagonal is constant, B // Upper diagonal is constant, C // Right-hand side Rr[iSize] // Output: // return value is TRUE if successful, FALSE if pivoting failed // U[iSize] is solution static bool SolveConstTri (int iSize, Real fA, Real fB, Real fC, Real* afR, Real* afU); // Input: // A[iSize][iSize] symmetric matrix, entries are A[row][col] // B[iSize] vector, entries are B[row] // Output: // return value is TRUE if successful, FALSE if (nearly) singular // X[iSize] is solution X to AX = B static bool SolveSymmetric (const GMatrix<Real>& rkA, const Real* afB, Real* afX); // Input: // A[iSize][iSize] symmetric matrix, entries are A[row][col] // Output: // return value is TRUE if successful, FALSE if algorithm failed // InvA[iSize][iSize], inverse matrix static bool SymmetricInverse (const GMatrix<Real>& rkA, GMatrix<Real>& rkInvA); // Solution using the conjugate gradient method. // Input: // A[iSize][iSize] symmetrix matrix, entries are A[row][col] // B[iSize] vector, entries are B[row] // Output: // X[iSize] is the solution x to Ax = B static bool SolveSymmetricCG (const GMatrix<Real>& rkA, const Real* afB, Real* afX); // Conjugate gradient method for sparse, symmetric matrices. // Input: // The nonzero entries of the symmetrix matrix A are stored in a map // whose keys are pairs (i,j) and whose values are real numbers. The // pair (i,j) is the location of the value in the array. Only one of // (i,j) and (j,i) should be stored since A is symmetric. The code // assumes this is how you set up A. The column vector B is stored as // an array of contiguous values. // Output: // X[iSize] is the solution x to Ax = B typedef std::map<std::pair<int,int>,Real> SparseMatrix; static bool SolveSymmetricCG (int iSize, const SparseMatrix& rkA, const Real* afB, Real* afX); // solve banded matrix systems // Input: // A, a banded matrix // B[iSize] vector, entries are B[row] // Output: // return value is TRUE if successful, FALSE if pivoting failed // X[iSize] is solution X to AX = B static bool SolveBanded (const BandedMatrix<Real>& rkA, const Real* afB, Real* afX); // invert a banded matrix // Input: // A, a banded matrix // Output: // return value is TRUE if the inverse exists, FALSE otherwise // InvA, the inverse of A static bool Invert (const BandedMatrix<Real>& rkA, GMatrix<Real>& rkInvA); protected: // support for the conjugate gradient method for standard arrays static Real Dot (int iSize, const Real* afU, const Real* afV); static void Multiply (const GMatrix<Real>& rkA, const Real* afX, Real* afProd); static void UpdateX (int iSize, Real* afX, Real fAlpha, const Real* afP); static void UpdateR (int iSize, Real* afR, Real fAlpha, const Real* afW); static void UpdateP (int iSize, Real* afP, Real fBeta, const Real* afR); // support for the conjugate gradient method for sparse arrays static void Multiply (int iSize, const SparseMatrix& rkA, const Real* afX, Real* afProd); // support for banded matrices static bool ForwardEliminate (int iReduceRow, BandedMatrix<Real>& rkA, Real* afB); static bool ForwardEliminate (int iReduceRow, BandedMatrix<Real>& rkA, GMatrix<Real>& rkB); static void BackwardEliminate (int iReduceRow, BandedMatrix<Real>& rkA, GMatrix<Real>& rkB); // tolerance for 2x2 and 3x3 system solving static Real ms_fTolerance; }; typedef LinearSystem<float> LinearSystemf; typedef LinearSystem<double> LinearSystemd; } #endif
[ [ [ 1, 161 ] ] ]
b67c2ae350203098d7664a46b5f6697e5927de70
5a9924aff39460fa52f1f55ff387d9ab82c3470f
/tibia772/evrebot772/evrebot.cpp
23950e605300f3457b7ebc008cb7098dddb2efc3
[]
no_license
PimentelM/evremonde
170e4f1916b0a1007c6dbe52b578db53bc6e70de
6b56e8461a602ea56f0eae47a96d340487ba987d
refs/heads/master
2021-01-10T16:03:38.410644
2010-12-04T17:31:01
2010-12-04T17:31:01
48,460,569
0
1
null
null
null
null
UTF-8
C++
false
false
12,167
cpp
#include <iostream> #include <vector> #include <string> #include <sstream> #include <fstream> #include <windows.h> #include "tibia.h" #include "tibiapacket.h" /* Evre Bot by Evremonde for client version 7.72 */ // classes CTibia Tibia; CTibiaPacket Packet; // file std::string botFile = "evrebot.xml"; // booleans bool bLight = true; bool bClick = false; bool bBattleListAim = true; bool bAutoUh = true; bool bAutoSd = false; bool bLootItems = true; bool bStackItems = true; bool bEatItems = true; // variables int lightLevel = LIGHT_TORCH; int autoUhPercent = 75; // functions void botShootTarget(int itemId) { Packet.sendShootTarget(itemId, 0); } void botShootSelf(int itemId) { Packet.sendShootSelf(itemId, 0); } void botDrinkManaFluid() { Packet.sendShootSelf(ITEM_FLUID_VIAL, FLUID_MANA); } void botReloadAmmo() { Packet.sendDragToSlot(Tibia.getPlayerSlotAmmo(), "", SLOT_AMMO); } void botXRay() { Tibia.doXRay(); } void botLootItem(int itemId) { Packet.sendDragToSlot(itemId, "Dead", SLOT_BACKPACK); } void botStackItem(int itemId) { Packet.sendStack(itemId); } void botEatItem(int itemId) { Packet.sendUse(itemId); } std::string botGetBool(bool boolean) { if (boolean == true) return "On"; else return "Off"; } void botShowStatus() { std::stringstream buffer; buffer << "Player Name:\t" << Tibia.getPlayerName() << std::endl << std::endl << "Light Hack:\t" << botGetBool(bLight) << std::endl << "Light Level:\t" << lightLevel << std::endl << "Clicking Hack:\t" << botGetBool(bClick) << std::endl << "Battle List Aim:\t" << botGetBool(bBattleListAim) << std::endl << "Auto-UH:\t\t" << botGetBool(bAutoUh) << std::endl << "Auto-UH Percent:\t" << autoUhPercent << "%" << std::endl << "Auto-SD:\t\t" << botGetBool(bAutoSd) << std::endl << "Loot Items:\t" << botGetBool(bLootItems) << std::endl << "Stack Items:\t" << botGetBool(bStackItems) << std::endl << "Eat Items:\t" << botGetBool(bEatItems) << std::endl; MessageBox(Tibia.Trainer.hwnd, buffer.str().c_str(), "evrebot", MB_ICONINFORMATION); } void botShowExp() { int neededExp = Tibia.calcExpForLevel(Tibia.getPlayerLevel()+1); std::stringstream buffer; buffer << "Experience needed to level up: " << neededExp; Tibia.setStatusbar((char*)buffer.str().c_str()); } void botShowId() { int seeId = Tibia.getSeeId(); std::stringstream buffer; buffer << "ID: " << seeId; Tibia.setStatusbar((char*)buffer.str().c_str()); } void botToggleLight() { if (lightLevel == LIGHT_NONE) { lightLevel = LIGHT_TORCH; bLight = true; Tibia.setStatusbar("Light: Torch"); } else if (lightLevel == LIGHT_TORCH) { lightLevel = LIGHT_FULL; bLight = true; Tibia.setStatusbar("Light: Full"); } else if (lightLevel == LIGHT_FULL) { lightLevel = LIGHT_NONE; Tibia.setPlayerLight(LIGHT_NONE); bLight = false; Tibia.setStatusbar("Light: Off"); } } void botToggleClick() { if (bClick) { Tibia.setUseId(USE_NONE); bClick = false; Tibia.setStatusbar("Click: Off"); } else { bClick = true; Tibia.setStatusbar("Click: On"); } } void botToggleAutoUh() { if (bAutoUh) { bAutoUh = false; Tibia.setStatusbar("Auto-UH: Off"); } else { bAutoUh = true; Tibia.setStatusbar("Auto-UH: On"); } } void botToggleAutoSd() { if (bAutoSd) { bAutoSd = false; Tibia.setStatusbar("Auto-SD: Off"); } else { bAutoSd = true; Tibia.setStatusbar("Auto-SD: On"); } } // xml functions void xmlParseOptions() { // parse bot file std::ifstream file(botFile.c_str()); // read line by line std::string line; while (std::getline(file, line)) { // comments if (line.find("//") != std::string::npos) continue; // read token by token std::vector<std::string> tokens; std::string buffer; std::stringstream ss(line); while(ss >> buffer) tokens.push_back(buffer); // 3 variables; 0:definition 1:name 2:value if (tokens.size() == 3) { // get value std::stringstream stringToInt(tokens.at(2)); int value = 0; stringToInt >> value; if (tokens.at(0) == "option") { if (tokens.at(1) == "lightlevel") { // overflow if (value > MAX_LIGHT) value = MAX_LIGHT; // set light level lightLevel = (LightLevel_t)value; } else if (tokens.at(1) == "autouhpercent") { // overflow if (value > 100) value = 100; // set auto uh percent autoUhPercent = value; } } // if } // if } // while file.close(); } int xmlGetIdOfItem(std::string itemName) { // parse bot file std::ifstream file(botFile.c_str()); // read line by line std::string line; while (std::getline(file, line)) { // comments if (line.find("//") != std::string::npos) continue; // read token by token std::vector<std::string> tokens; std::string buffer; std::stringstream ss(line); while(ss >> buffer) tokens.push_back(buffer); // 3 variables; 0:definition 1:itemId 2:itemName if (tokens.size() == 3) { if (tokens.at(0) == "item") { if (tokens.at(2) == itemName) { file.close(); std::stringstream stringToInt(tokens.at(1)); int itemId = 0; stringToInt >> itemId; return itemId; } // if } // if } // if } // while file.close(); return 0; // not found } void xmlParseDefinition(std::string definition) { // parse bot file std::ifstream file(botFile.c_str()); // read line by line std::string line; while (std::getline(file, line)) { // comments if (line.find("//") != std::string::npos) continue; // read token by token std::vector<std::string> tokens; std::string buffer; std::stringstream ss(line); while(ss >> buffer) tokens.push_back(buffer); // 2 variables; 0:definition 1:itemName if (tokens.size() == 2) { if (tokens.at(0) == definition) { int itemId = xmlGetIdOfItem(tokens.at(1)); if (definition == "loot") botLootItem(itemId); else if (definition == "stack") botStackItem(itemId); else if (definition == "eat") botEatItem(itemId); } // if } // if } // while file.close(); } // hotkeys VOID CALLBACK timerHotkeys(HWND hWnd, UINT nMsg, UINT nIDEvent, DWORD dwTime) { // ultimate healing OR mana fluid if (GetAsyncKeyState(VK_INSERT)) { if (GetAsyncKeyState(VK_SHIFT)) botDrinkManaFluid(); else botShootSelf(ITEM_RUNE_ULTIMATE_HEALING); } // sudden death OR heavy magic missile if (GetAsyncKeyState(VK_DELETE)) { if (GetAsyncKeyState(VK_SHIFT)) botShootTarget(ITEM_RUNE_HEAVY_MAGIC_MISSILE); else botShootTarget(ITEM_RUNE_SUDDEN_DEATH); } // magic wall OR show bot status if (GetAsyncKeyState(VK_HOME)) { if (GetAsyncKeyState(VK_SHIFT)) botShowStatus(); else botShootTarget(ITEM_RUNE_MAGIC_WALL); } // explosion OR great fireball if (GetAsyncKeyState(VK_END)) { if (GetAsyncKeyState(VK_SHIFT)) botShootTarget(ITEM_RUNE_GREAT_FIREBALL); else botShootTarget(ITEM_RUNE_EXPLOSION); } // light hack OR show exp if (GetAsyncKeyState(VK_PRIOR)) // page up { if (GetAsyncKeyState(VK_SHIFT)) botShowExp(); else botToggleLight(); } // click hack or show id if (GetAsyncKeyState(VK_NEXT)) // page down { if (GetAsyncKeyState(VK_SHIFT)) botShowId(); else botToggleClick(); } // reload ammo or x-ray if (GetAsyncKeyState(VK_PAUSE)) { if (GetAsyncKeyState(VK_SHIFT)) botXRay(); else botReloadAmmo(); } // toggle auto uh OR toggle auto sd if (GetAsyncKeyState(VK_SCROLL)) { if (GetAsyncKeyState(VK_SHIFT)) botToggleAutoSd(); else botToggleAutoUh(); } } // battlelist aim VOID CALLBACK timerBattleListAim(HWND hWnd, UINT nMsg, UINT nIDEvent, DWORD dwTime) { if (!bBattleListAim) return; if (GetAsyncKeyState(VK_LBUTTON)) // left-click Packet.sendShootTargetBattleList(); } // light VOID CALLBACK timerLight(HWND hWnd, UINT nMsg, UINT nIDEvent, DWORD dwTime) { if (!bLight) return; Tibia.setPlayerLight((LightLevel_t)lightLevel); } // click VOID CALLBACK timerClick(HWND hWnd, UINT nMsg, UINT nIDEvent, DWORD dwTime) { if (!bClick) return; Tibia.setUseId(USE_USING); } // auto uh VOID CALLBACK timerAutoUh(HWND hWnd, UINT nMsg, UINT nIDEvent, DWORD dwTime) { if (!bAutoUh) return; if (Tibia.getPlayerHpBar() <= autoUhPercent) botShootSelf(ITEM_RUNE_ULTIMATE_HEALING); } // auto sd VOID CALLBACK timerAutoSd(HWND hWnd, UINT nMsg, UINT nIDEvent, DWORD dwTime) { if (!bAutoSd) return; // dont shoot if you need to auto uh if (bAutoUh && Tibia.getPlayerHpBar() <= autoUhPercent) return; botShootTarget(ITEM_RUNE_SUDDEN_DEATH); } // loot items VOID CALLBACK timerLootItems(HWND hWnd, UINT nMsg, UINT nIDEvent, DWORD dwTime) { if (!bLootItems) return; xmlParseDefinition("loot"); /* botLootItem(ITEM_MONEY_GOLD); botLootItem(ITEM_MONEY_PLATINUM); botLootItem(ITEM_MONEY_CRYSTAL); */ } // stack items VOID CALLBACK timerStackItems(HWND hWnd, UINT nMsg, UINT nIDEvent, DWORD dwTime) { if (!bStackItems) return; xmlParseDefinition("stack"); /* botStackItem(ITEM_MONEY_GOLD); botStackItem(ITEM_MONEY_PLATINUM); botStackItem(ITEM_MONEY_CRYSTAL); */ } // eat items VOID CALLBACK timerEatItems(HWND hWnd, UINT nMsg, UINT nIDEvent, DWORD dwTime) { if (!bEatItems) return; xmlParseDefinition("eat"); //botEatItem(ITEM_); } int main() { // introduction std::cout << "evrebot by Evremonde" << std::endl << "packet.dll by Azura" << std::endl << "for Tibia version 7.72" << std::endl << std::endl; // hotkey information std::cout << "Hotkeys:" << std::endl << "INSERT\t\tShoot Ultimate Healing at self" << std::endl << "SHIFT+INSERT\tDrink Manafluid" << std::endl << "DELETE\t\tShoot Sudden Death at target" << std::endl << "SHIFT+DELETE\tShoot Heavy Magic Missle at target" << std::endl << "HOME\t\tShoot Magic Wall in front of target" << std::endl << "SHIFT+HOME\tShow Bot status" << std::endl << "END\t\tShoot Explosion at target" << std::endl << "SHIFT+END\tShoot Great Fireball at target" << std::endl << "PAGEUP\t\tToggle Light hack" << std::endl << "SHIFT+PAGEUP\tShow experience needed to level up" << std::endl << "PAGEDN\t\tToggle Clicking hack" << std::endl << "SHIFT+PAGEDN\tShow ID of last seen tile or object" << std::endl << "PAUSE\t\tReload ammo slot from backpack" << std::endl << "SHIFT+PAUSE\tApply X-Ray to last seen tile" << std::endl << "SCRL\t\tToggle Auto-UH" << std::endl << "SHIFT+SCRL\tToggle Auto-SD" << std::endl; // find tibia window if (!Tibia.findTibia()) return ::MessageBox(0, "Tibia not found!", "evrebot", MB_ICONERROR); // name of player using bot if (Tibia.isOnline()) std::cout << std::endl << "Bot loaded for player: " << Tibia.getPlayerName() << std::endl; // loaded Tibia.setStatusbar("evrebot loaded!"); // parse bot file options xmlParseOptions(); // start timers UINT_PTR Timer; Timer = ::SetTimer(NULL, 0, 100, &timerHotkeys); Timer = ::SetTimer(NULL, 0, 100, &timerBattleListAim); Timer = ::SetTimer(NULL, 0, 500, &timerLight); Timer = ::SetTimer(NULL, 0, 100, &timerClick); Timer = ::SetTimer(NULL, 0, 100, &timerAutoUh); Timer = ::SetTimer(NULL, 0, 1000, &timerAutoSd); Timer = ::SetTimer(NULL, 0, 100, &timerLootItems); Timer = ::SetTimer(NULL, 0, 1000, &timerStackItems); Timer = ::SetTimer(NULL, 0, 100, &timerEatItems); // handle timers MSG Msg; while (::GetMessage(&Msg, NULL, 0, 0)) { ::TranslateMessage(&Msg); ::DispatchMessage(&Msg); } return 0; }
[ "evretibia@cc901e99-3b3f-0410-afbc-77a0fa429cc7" ]
[ [ [ 1, 542 ] ] ]
ee314adc625320f5d9816b1570c675c1fe31b614
47f89380f778b6ee8311678e48970ea710e8c1a8
/atask/Repair.h
6b911bd6b6c802d679fbd160e8cb3032f8f21c47
[]
no_license
hoijui/E323AI
f53a0fb388b67557fc92f38835343a85ef01135a
c4fcac72b77cff352350326c01ecab2d0ba9b388
refs/heads/master
2021-01-17T23:26:30.279240
2010-12-17T00:35:34
2010-12-17T00:35:34
358,032
0
0
null
null
null
null
UTF-8
C++
false
false
595
h
#ifndef E323_TASKREPAIR_H #define E323_TASKREPAIR_H #include "../ATask.h" class UnitType; struct RepairTask: public ATask { RepairTask(AIClasses* _ai): ATask(_ai) { t = TASK_REPAIR; } RepairTask(AIClasses* _ai, int target, CGroup& group); /* build type to string */ static std::map<buildType, std::string> buildStr; bool repairing; int target; /* overloaded */ void onUpdate(); /* overloaded */ bool onValidate(); /* overloaded */ void toStream(std::ostream& out) const; /* overloaded */ void onUnitDestroyed(int uid, int attacker); }; #endif
[ [ [ 1, 29 ] ] ]
e882726b0f10b7833a9e71fdaf2d80e209624c8d
5750620062af54ed24792c39d0bf19a6f8f1e3bf
/src/test/uint256_tests.cpp
f36660983949dfb5b7bb7eec57fcec45b81c40ca
[]
no_license
makomk/soldcoin
4088e49928efe7436eee8bae40b0b1b9ce9e2720
f964acdd1a76d58f7e27e386fffbed22a1916307
refs/heads/master
2021-01-17T22:18:53.603480
2011-09-04T19:29:57
2011-09-04T19:29:57
2,344,688
0
0
null
null
null
null
UTF-8
C++
false
false
364
cpp
#include <boost/test/unit_test.hpp> #include "../uint256.h" BOOST_AUTO_TEST_SUITE(uint256_tests) BOOST_AUTO_TEST_CASE(uint256_equality) { uint256 num1 = 10; uint256 num2 = 11; BOOST_CHECK(num1+1 == num2); uint64 num3 = 10; BOOST_CHECK(num1 == num3); BOOST_CHECK(num1+num2 == num3+num2); } BOOST_AUTO_TEST_SUITE_END()
[ [ [ 1, 18 ] ] ]
4970f286625c6e02f5b71a535620ab7cdb1e783a
90cbd4e222e9a625462f66eb5c36c8c2631df914
/community.cpp
5e0c860d5390c05c21041fa241d5cd1126343c7f
[]
no_license
eichert12/Blondel-Community
d155e05f5e5fe3ef97f530cf94852e734f01a1ca
05ad3a1a4e09ad67b1f094e434cd58bbe9d948d4
refs/heads/master
2020-05-27T22:42:10.102724
2010-02-23T19:32:29
2010-02-23T19:32:29
532,239
4
0
null
null
null
null
UTF-8
C++
false
false
7,813
cpp
// File: community.h // -- community detection source file //----------------------------------------------------------------------------- // Community detection // Based on the article "Fast unfolding of community hierarchies in large networks" // Copyright (C) 2008 V. Blondel, J.-L. Guillaume, R. Lambiotte, E. Lefebvre // // This program must not be distributed without agreement of the above mentionned authors. //----------------------------------------------------------------------------- // Author : E. Lefebvre, adapted by J.-L. Guillaume // Email : [email protected] // Location : Paris, France // Time : February 2008 //----------------------------------------------------------------------------- // see readme.txt for more details #include "community.h" using namespace std; Community::Community(char * filename, int type, int nbp, double minm) { g = Graph(filename, type); size = g.nb_nodes; n2c.resize(size); in.resize(size); tot.resize(size); for (int i=0 ; i<size ; i++) { n2c[i] = i; in[i] = g.nb_selfloops(i); tot[i] = g.weighted_degree(i); } nb_pass = nbp; min_modularity = minm; } Community::Community(Graph gc, int nbp, double minm) { g = gc; size = g.nb_nodes; n2c.resize(size); in.resize(size); tot.resize(size); for (int i=0 ; i<size ; i++) { n2c[i] = i; in[i] = g.nb_selfloops(i); tot[i] = g.weighted_degree(i); } nb_pass = nbp; min_modularity = minm; } void Community::display() { cerr << endl << "<" ; for (int i=0 ; i<size ; i++) cerr << " " << i << "/" << n2c[i] << "/" << in[i] << "/" << tot[i] ; cerr << ">" << endl; } double Community::modularity() { double q = 0.; double m2 = (double)g.total_weight; for (int i=0 ; i<size ; i++) { if (tot[i]>0) q += (double)in[i]/m2 - ((double)tot[i]/m2)*((double)tot[i]/m2); } return q; } map<int,int> Community::neigh_comm(int node) { map<int,int> res; pair<int *,int *> p = g.neighbors(node); int deg = g.nb_neighbors(node); res.insert(make_pair(n2c[node],0)); for (int i=0 ; i<deg ; i++) { int neigh = *(p.first+i); int neigh_comm = n2c[neigh]; int neigh_weight = (g.weights==NULL)?1:*(p.second+i); if (neigh!=node) { map<int,int>::iterator it = res.find(neigh_comm); if (it!=res.end()) it->second+=neigh_weight; else res.insert(make_pair(neigh_comm,neigh_weight)); } } return res; } void Community::partition2graph() { vector<int> renumber(size, -1); for (int node=0 ; node<size ; node++) { renumber[n2c[node]]++; } int final=0; for (int i=0 ; i<size ; i++) if (renumber[i]!=-1) renumber[i]=final++; for (int i=0 ; i<size ; i++) { pair<int *,int *> p = g.neighbors(i); int deg = g.nb_neighbors(i); for (int j=0 ; j<deg ; j++) { int neigh = *(p.first+j); cout << renumber[n2c[i]] << " " << renumber[n2c[neigh]] << endl; } } } void Community::display_partition() { vector<int> renumber(size, -1); for (int node=0 ; node<size ; node++) { renumber[n2c[node]]++; } int final=0; for (int i=0 ; i<size ; i++) if (renumber[i]!=-1) renumber[i]=final++; for (int i=0 ; i<size ; i++) cout << i << " " << renumber[n2c[i]] << endl; } // This function has to be revisited // malloc is dirty Graph Community::partition2graph_binary() { vector<int> renumber(size, -1); for (int node=0 ; node<size ; node++) { renumber[n2c[node]]++; } int final=0; for (int i=0 ; i<size ; i++) if (renumber[i]!=-1) renumber[i]=final++; // Compute communities vector<vector<int> > comm_nodes(final); for (int node=0 ; node<size ; node++) { comm_nodes[renumber[n2c[node]]].push_back(node); } // unweigthed to weighted Graph g2; g2.nb_nodes = comm_nodes.size(); g2.degrees = (int *)malloc(comm_nodes.size()*4); g2.links = (int *)malloc((long)10000000*8); g2.weights = (int *)malloc((long)10000000*8); long where = 0; int comm_deg = comm_nodes.size(); for (int comm=0 ; comm<comm_deg ; comm++) { map<int,int> m; map<int,int>::iterator it; int comm_size = comm_nodes[comm].size(); for (int node=0 ; node<comm_size ; node++) { pair<int *,int *> p = g.neighbors(comm_nodes[comm][node]); int deg = g.nb_neighbors(comm_nodes[comm][node]); for (int i=0 ; i<deg ; i++) { int neigh = *(p.first+i); int neigh_comm = renumber[n2c[neigh]]; int neigh_weight = (g.weights==NULL)?1:*(p.second+i); it = m.find(neigh_comm); if (it==m.end()) m.insert(make_pair(neigh_comm, neigh_weight)); else it->second+=neigh_weight; } } g2.degrees[comm]=(comm==0)?m.size():g2.degrees[comm-1]+m.size(); g2.nb_links+=m.size(); for (it = m.begin() ; it!=m.end() ; it++) { g2.total_weight += it->second; g2.links[where] = it->first; g2.weights[where] = it->second; where++; } } realloc(g.links, (long)g2.nb_links*4); realloc(g.weights, (long)g2.nb_links*4); return g2; } double Community::one_level() { bool improvement = false; int nb_pass_done = 0; double new_mod = modularity(); double cur_mod = new_mod; // repeat while // there is an improvement of modularity // or there is an improvement of modularity greater than a given epsilon // or a predefined number of pass have been done vector<int> random_order(size); for (int i=0 ; i<size ; i++) { random_order[i]=i; } for (int i=0 ; i<size-1 ; i++) { int rand_pos = rand()%(size-i)+i; int tmp = random_order[i]; random_order[i] = random_order[rand_pos]; random_order[rand_pos] = tmp; } do { cur_mod = new_mod; improvement = false; nb_pass_done++; // for each node: remove the node from its community and insert it in the best community for (int node_tmp=0 ; node_tmp<size ; node_tmp++) { int node = node_tmp; // int node = random_order[node_tmp]; // if (node%1000000==0) {fprintf(stderr,"%d ",node); fflush(stderr);} int node_comm = n2c[node]; // computation of all neighboring communities of current node map<int,int> ncomm = neigh_comm(node); // remove node from its current community remove(node, node_comm, ncomm.find(node_comm)->second); // compute the nearest community for node // default choice for future insertion is the former community int best_comm = node_comm; int best_nblinks = 0;//ncomm.find(node_comm)->second; double best_increase = 0.;//modularity_gain(node, best_comm, best_nblinks); for (map<int,int>::iterator it=ncomm.begin() ; it!=ncomm.end() ; it++) { double increase = modularity_gain(node, it->first, it->second); if (increase>best_increase) { best_comm = it->first; best_nblinks = it->second; best_increase = increase; } } // insert node in the nearest community // cerr << "insert " << node << " in " << best_comm << " " << best_increase << endl; insert(node, best_comm, best_nblinks); if (best_comm!=node_comm) improvement=true; } new_mod = modularity(); cerr << "pass number " << nb_pass_done << " of " << nb_pass << " : " << new_mod << " " << cur_mod << endl; } while (improvement && new_mod-cur_mod>min_modularity && nb_pass_done!=nb_pass); return new_mod; }
[ [ [ 1, 286 ] ] ]
16a9df27d90bbaa9af16657d1775188203253832
6bdb3508ed5a220c0d11193df174d8c215eb1fce
/Codes/Halak/IClassQueryable.cpp
644d27b96cb19df70530a531bdabed74b6af52d5
[]
no_license
halak/halak-plusplus
d09ba78640c36c42c30343fb10572c37197cfa46
fea02a5ae52c09ff9da1a491059082a34191cd64
refs/heads/master
2020-07-14T09:57:49.519431
2011-07-09T14:48:07
2011-07-09T14:48:07
66,716,624
0
0
null
null
null
null
UTF-8
C++
false
false
237
cpp
#include <Halak/PCH.h> #include <Halak/IClassQueryable.h> namespace Halak { const void* IClassQueryable::QueryClass(uint32 classID) const { return const_cast<IClassQueryable*>(this)->QueryClass(classID); } }
[ [ [ 1, 10 ] ] ]
03530c8aca0dfaa7e3967fa6c14142c0e0760826
b822313f0e48cf146b4ebc6e4548b9ad9da9a78e
/KylinSdk/Engine/Source/WeaponTrail.cpp
014afbe9157f06ba112000c49532459f6b03c98b
[]
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
7,643
cpp
#include "engpch.h" #include "WeaponTrail.h" //---------------------------------------------------------------------------// WeaponTrail::WeaponTrail(Ogre::String name, Ogre::SceneManager* s ) :m_TrailObject(0), m_MaxSegmentCount(30), mSceneMgr(s), m_IsActive(true) { m_SegmentStartColorChange = Ogre::ColourValue(1.0,1.0,1.0,1.0); m_SegmentEndColorChange = Ogre::ColourValue(1.0,1.0,1.0,1.0); m_SegmentStartInitialColor = Ogre::ColourValue(0.6,0.5,0.8,1); m_SegmentEndInitialColor = Ogre::ColourValue(1.0,0.2,1.0,1); m_SegmentStartColorChange *= 3.0; m_SegmentEndColorChange *= 3.0; m_Width = 30.0; setWeaponEntity(0); init(); } //---------------------------------------------------------------------------// WeaponTrail::~WeaponTrail() { uninit(); } //---------------------------------------------------------------------------// void WeaponTrail::init() { // create object m_TrailObject = mSceneMgr->createManualObject(mName); m_TrailObject->estimateVertexCount(m_MaxSegmentCount * 2); m_TrailObject->setDynamic(true); m_TrailObject->begin("mat_trail", Ogre::RenderOperation::OT_TRIANGLE_STRIP); // fill the object (the actual data does not matter here) for(int i=0; i<m_MaxSegmentCount; ++i) { m_TrailObject->position(0, 0, -i*20); m_TrailObject->textureCoord(0,0); m_TrailObject->colour(1,0,0,1); m_TrailObject->position(0, 30, -i*20); m_TrailObject->textureCoord(1,0); m_TrailObject->colour(1,0,0,1); } m_TrailObject->end(); // create node and attach object m_TrailNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); m_TrailNode->attachObject(m_TrailObject); m_TrailObject->setVisible(false); } //---------------------------------------------------------------------------// void WeaponTrail::uninit() { m_IsActive = false; // detach object and remove node m_TrailNode->detachObject(m_TrailObject); mSceneMgr->getRootSceneNode()-> removeAndDestroyChild(m_TrailNode->getName()); // remove object m_TrailObject->setVisible(false); mSceneMgr->destroyManualObject(m_TrailObject); } //---------------------------------------------------------------------------// void WeaponTrail::setWeaponEntity(Ogre::Entity* p_WeaponEntity) { m_WeaponEntity = p_WeaponEntity; if (m_WeaponEntity) { m_WeaponNode = m_WeaponEntity->getParentNode(); } else { m_WeaponNode = 0; } } //---------------------------------------------------------------------------// void WeaponTrail::onUpdate(float p_DeltaT) { // early out if(!isActive() && !isVisible()) { return; } if (!m_WeaponEntity || !m_WeaponNode) { return; } if (!m_TrailObject) { return; } m_TrailObject->setVisible(true); // iterate over the current segments, apply alpha change for(TrailSegmentList::iterator it = m_SegmentList.begin(); it != m_SegmentList.end();) { (*it).segmentStartColor -= m_SegmentStartColorChange * p_DeltaT; (*it).segmentEndColor -= m_SegmentEndColorChange * p_DeltaT; (*it).segmentStartColor.saturate(); (*it).segmentEndColor.saturate(); if((*it).segmentStartColor == Ogre::ColourValue::ZERO && (*it).segmentEndColor == Ogre::ColourValue::ZERO) { it = m_SegmentList.erase(it); } else { ++it; } } // throw away the last element if the maximum number of segments is used if(m_SegmentList.size() >= m_MaxSegmentCount) { m_SegmentList.pop_back(); } // only add a new segment if active if(isActive()) { // the segment to add to the trail TrailSegment newSegment; // initial the trail newSegment.segmentStartColor = getSegmentStartInitialColor(); newSegment.segmentEndColor = getSegmentEndInitialColor(); newSegment.segmentStart = m_WeaponNode->_getDerivedPosition(); Ogre::Vector3 pos = m_WeaponNode->getPosition(); // probably quite costly way to get the second position m_WeaponNode->translate(Ogre::Vector3(0, m_Width, 0), Ogre::SceneNode::TS_LOCAL); newSegment.segmentEnd = m_WeaponNode->_getDerivedPosition(); m_WeaponNode->setPosition(pos); Ogre::Vector3 _verDir = newSegment.segmentEnd - newSegment.segmentStart; _verDir.normalise(); newSegment.segmentEnd = newSegment.segmentStart + _verDir * m_Width; m_SegmentList.push_front(newSegment); } // update the manual object m_TrailObject->beginUpdate(0); int segmentCount = 0; for(TrailSegmentList::iterator it = m_SegmentList.begin(); it != m_SegmentList.end(); ++it) { m_TrailObject->position((*it).segmentStart); m_TrailObject->textureCoord(0,0); m_TrailObject->colour((*it).segmentStartColor); m_TrailObject->position((*it).segmentEnd); m_TrailObject->textureCoord(1,0); m_TrailObject->colour((*it).segmentEndColor); ++segmentCount; } // use the last position to render the invisible part of the trail // as degenerate triangles Ogre::Vector3 lastPos = Ogre::Vector3::ZERO; if(!m_SegmentList.empty()) { lastPos = m_SegmentList.back().segmentStart; } for(int i=segmentCount*2;i<m_MaxSegmentCount * 2;++i) { m_TrailObject->position(lastPos); } // end the update m_TrailObject->end(); } //---------------------------------------------------------------------------// void WeaponTrail::setMaterialName(const Ogre::String& p_MaterialName) { m_MaterialName = p_MaterialName; if(m_TrailObject) { m_TrailObject->setMaterialName(0, m_MaterialName); } } //---------------------------------------------------------------------------// void WeaponTrail::setSegmentStartColorChange(const Ogre::ColourValue& p_ColorChange) { m_SegmentStartColorChange = p_ColorChange; } //---------------------------------------------------------------------------// const Ogre::ColourValue& WeaponTrail::getSegmentStartColorChange() const { return m_SegmentStartColorChange; } //---------------------------------------------------------------------------// void WeaponTrail::setSegmentEndColorChange(const Ogre::ColourValue& p_ColorChange) { m_SegmentEndColorChange = p_ColorChange; } //---------------------------------------------------------------------------// const Ogre::ColourValue& WeaponTrail::getSegmentEndColorChange() const { return m_SegmentEndColorChange; } //---------------------------------------------------------------------------// void WeaponTrail::setSegmentStartInitialColor(const Ogre::ColourValue& p_Color) { m_SegmentStartInitialColor = p_Color; } //---------------------------------------------------------------------------// const Ogre::ColourValue& WeaponTrail::getSegmentStartInitialColor() const { return m_SegmentStartInitialColor; } //---------------------------------------------------------------------------// void WeaponTrail::setSegmentEndInitialColor(const Ogre::ColourValue& p_Color) { m_SegmentEndInitialColor = p_Color; } //---------------------------------------------------------------------------// const Ogre::ColourValue& WeaponTrail::getSegmentEndInitialColor() const { return m_SegmentEndInitialColor; } //---------------------------------------------------------------------------// void WeaponTrail::setActive(bool p_Active) { m_IsActive = p_Active; } //---------------------------------------------------------------------------// bool WeaponTrail::isActive() const { return m_IsActive; } //---------------------------------------------------------------------------// bool WeaponTrail::isVisible() const { return !m_SegmentList.empty(); } //---------------------------------------------------------------------------//
[ "apayaccount@5fe9e158-c84b-58b7-3744-914c3a81fc4f" ]
[ [ [ 1, 244 ] ] ]
3eb7909cac8f1c3e908df439980cc5b1028ab752
b8ac0bb1d1731d074b7a3cbebccc283529b750d4
/Code/controllers/Tcleaner/robotapi/DifferentialWheelsWOdometry.h
57f9d130ea327a0ae75837578519aec1112f1e4d
[]
no_license
dh-04/tpf-robotica
5efbac38d59fda0271ac4639ea7b3b4129c28d82
10a7f4113d5a38dc0568996edebba91f672786e9
refs/heads/master
2022-12-10T18:19:22.428435
2010-11-05T02:42:29
2010-11-05T02:42:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,184
h
#ifndef robotapi_DifferentialWheelsWOdometry_h #define robotapi_DifferentialWheelsWOdometry_h #include <robotapi/IDifferentialWheels.h> #include <utils/MyPoint.h> #include <utils/MyAngle.h> #include <WorldInfo.h> namespace robotapi { class DifferentialWheelsWOdometry : public robotapi::IDifferentialWheels { public: DifferentialWheelsWOdometry(WorldInfo * wi); // class destructor virtual ~DifferentialWheelsWOdometry(){}; virtual double getLeftEncoder(); virtual double getRightEncoder(); void computeOdometry(); double getOrientation(); utils::MyPoint * getPosition(); void setOrientation(double angle); void setPosition(utils::MyPoint * p); private: void computePosition(double ldist, double rdist); double distanceBetweenWheels; double leftWheelRadius; double rightWheelRadius; double encoderResolution; double lastLeftEncoder; double lastRightEncoder; robotapi::IDifferentialWheels * wheels; utils::MyPoint * lastPosition; utils::MyAngle * lastAngle; }; } /* End of namespace robotapi */ #endif // robotapi_DifferentialWheelsWOdometry_h
[ "guicamest@d69ea68a-f96b-11de-8cdf-e97ad7d0f28a" ]
[ [ [ 1, 45 ] ] ]
3bb9209d041ccf541f137071b7d1d6061934eece
854ee643a4e4d0b7a202fce237ee76b6930315ec
/arcemu_svn/src/arcemu-shared/Storage.h
ddf6dc847a9c2c8f0e087c985b1bfc86ea975cf8
[]
no_license
miklasiak/projekt
df37fa82cf2d4a91c2073f41609bec8b2f23cf66
064402da950555bf88609e98b7256d4dc0af248a
refs/heads/master
2021-01-01T19:29:49.778109
2008-11-10T17:14:14
2008-11-10T17:14:14
34,016,391
2
0
null
null
null
null
UTF-8
C++
false
false
18,847
h
/* * ArcEmu MMORPG Server * Copyright (C) 2008 <http://www.ArcEmu.org/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #ifndef STORAGE_H_ #define STORAGE_H_ #ifdef WIN32 #pragma warning(disable:4312) #endif // pooled allocations //#define STORAGE_ALLOCATION_POOLS 1 #define STORAGE_ARRAY_MAX 5000000 #ifdef STORAGE_ALLOCATION_POOLS template<class T> class SERVER_DECL StorageAllocationPool { T* _pool; uint32 _count; uint32 _max; public: void Init(uint32 count) { _pool = new T[count+100]; _count = 0; _max = count+100; } T * Get() { if( _count >= _max ) { printf("StorageAllocationPool Get() failed!\n"); return NULL; } return &_pool[_count++]; } void Free() { delete [] _pool; } }; #endif /** Base iterator class, returned by MakeIterator() functions. */ template<class T> class SERVER_DECL StorageContainerIterator { protected: /** Currently referenced object */ T * Pointer; public: virtual ~StorageContainerIterator() {} /** Returns the currently stored object */ ARCEMU_INLINE T * Get() { return Pointer; } /** Sets the current object to P */ ARCEMU_INLINE void Set(T * P) { Pointer = P; } /** Are we at the end of the storage container? */ ARCEMU_INLINE bool AtEnd() { return (Pointer == 0); } /** Virtual function to increment to the next element */ virtual bool Inc() = 0; /** Virtual function to destroy the iterator */ virtual void Destruct() = 0; }; template<class T> class SERVER_DECL ArrayStorageContainer { public: #ifdef STORAGE_ALLOCATION_POOLS StorageAllocationPool<T> _pool; void InitPool(uint32 cnt) { _pool.Init( cnt ); } #endif /** This is where the magic happens :P */ T ** _array; /** Maximum possible entry */ uint32 _max; /** Returns an iterator currently referencing the start of the container */ StorageContainerIterator<T> * MakeIterator(); /** Do we need to get the max? */ bool NeedsMax() { return true; } /** Creates the array with specified maximum */ void Setup(uint32 Max) { _array = new T*[Max]; _max = Max; memset(_array, 0, sizeof(T*) * Max); } /** Sets up the array with a different maximum */ void Resetup(uint32 Max) { if(Max < _max) return; // no need to realloc T ** a = new T*[Max]; memset(a,0,sizeof(T*)*Max); memcpy(a, _array, sizeof(T*) * _max); delete [] _array; _array = a; _max = Max; } /** Frees the container array and all elements inside it */ ~ArrayStorageContainer() { #ifndef STORAGE_ALLOCATION_POOLS for(uint32 i = 0; i < _max; ++i) if(_array[i] != 0) delete _array[i]; #else _pool.Free(); #endif delete [] _array; } /** Allocates entry Entry in the array and sets the pointer, and returns * the allocated memory. */ T * AllocateEntry(uint32 Entry) { if(Entry >= _max || _array[Entry] != 0) return reinterpret_cast<T*>(0); #ifndef STORAGE_ALLOCATION_POOLS _array[Entry] = new T; #else _array[Entry] = _pool.Get(); #endif return _array[Entry]; } /** Deallocates the entry Entry in the array and sets the pointer to null. */ bool DeallocateEntry(uint32 Entry) { if(Entry >= _max || _array[Entry] == 0) return false; #ifndef STORAGE_ALLOCATION_POOLS delete _array[Entry]; #endif _array[Entry] = 0; return true; } /** Looks up entry Entry and returns the pointer if it is existant, otherwise null. */ T * LookupEntry(uint32 Entry) { if(Entry >= _max) return reinterpret_cast<T*>(0); else return _array[Entry]; } /** Sets the pointer to entry Entry to Pointer, and if it already exists frees the existing * element. */ bool SetEntry(uint32 Entry, T * Pointer) { if(Entry > _max) return false; #ifndef STORAGE_ALLOCATION_POOLS if(_array[Entry] != 0) delete _array[Entry]; #endif _array[Entry] = Pointer; return true; } /** Returns the current pointer if it exists, otherwise allocates it. */ T * LookupEntryAllocate(uint32 Entry) { T * ret = LookupEntry(Entry); if(!ret) ret = AllocateEntry(Entry); return ret; } /** Deletes all entries in the container. */ void Clear() { for(uint32 i = 0; i < _max; ++i) { #ifndef STORAGE_ALLOCATION_POOLS if(_array[i] != 0) { delete _array[i]; } #endif _array[i] = 0; } } }; template<class T> class SERVER_DECL HashMapStorageContainer { public: #ifdef STORAGE_ALLOCATION_POOLS StorageAllocationPool<T> _pool; void InitPool(uint32 cnt) { _pool.Init( cnt ); } #endif typename HM_NAMESPACE::hash_map<uint32, T*> _map; /** Returns an iterator currently referencing the start of the container */ StorageContainerIterator<T> * MakeIterator(); /** Frees the container array and all elements inside it */ ~HashMapStorageContainer() { for(typename HM_NAMESPACE::hash_map<uint32, T*>::iterator itr = _map.begin(); itr != _map.end(); ++itr) delete itr->second; } /** Do we need to get the max? */ bool NeedsMax() { return false; } /** Creates the array with specified maximum */ void Setup(uint32 Max) { } void Resetup(uint32 Max) { } /** Allocates entry Entry in the array and sets the pointer, and returns * the allocated memory. */ T * AllocateEntry(uint32 Entry) { if(_map.find(Entry) != _map.end()) return reinterpret_cast<T*>(0); #ifdef STORAGE_ALLOCATION_POOLS T * n = _pool.Get(); #else T * n = new T; #endif _map.insert( make_pair( Entry, n ) ); return n; } /** Deallocates the entry Entry in the array and sets the pointer to null. */ bool DeallocateEntry(uint32 Entry) { typename HM_NAMESPACE::hash_map<uint32, T*>::iterator itr = _map.find(Entry); if(itr == _map.end()) return false; #ifndef STORAGE_ALLOCATION_POOLS delete itr->second; #endif _map.erase(itr); return true; } T * LookupEntry(uint32 Entry) { typename HM_NAMESPACE::hash_map<uint32, T*>::iterator itr = _map.find(Entry); if(itr == _map.end()) return reinterpret_cast<T*>(0); return itr->second; } /** Sets the pointer to entry Entry to Pointer, and if it already exists frees the existing * element. */ bool SetEntry(uint32 Entry, T * Pointer) { typename HM_NAMESPACE::hash_map<uint32, T*>::iterator itr = _map.find(Entry); if(itr == _map.end()) { _map.insert( make_pair( Entry, Pointer ) ); return true; } #ifndef STORAGE_ALLOCATION_POOLS delete itr->second; itr->second = Pointer; #endif return true; } /** Returns the current pointer if it exists, otherwise allocates it. */ T * LookupEntryAllocate(uint32 Entry) { T * ret = LookupEntry(Entry); if(!ret) ret = AllocateEntry(Entry); return ret; } /** Deletes all entries in the container. */ void Clear() { typename HM_NAMESPACE::hash_map<uint32, T*>::iterator itr = _map.begin(); for(; itr != _map.end(); ++itr) delete itr->second; _map.clear(); } }; template<class T> class SERVER_DECL ArrayStorageIterator : public StorageContainerIterator<T> { ArrayStorageContainer<T> * Source; uint32 MyIndex; public: /** Increments the iterator */ bool Inc() { GetNextElement(); if(StorageContainerIterator<T>::Pointer != 0) return true; else return false; } /** Frees the memory occupied by this iterator */ void Destruct() { delete this; } /** Constructor */ ArrayStorageIterator(ArrayStorageContainer<T> * S) : StorageContainerIterator<T>(), Source(S), MyIndex(0) { GetNextElement(); } /** Sets the next element pointer, or to 0 if we reached the end */ void GetNextElement() { while(MyIndex < Source->_max) { if(Source->_array[MyIndex] != 0) { StorageContainerIterator<T>::Set(Source->_array[MyIndex]); ++MyIndex; return; } ++MyIndex; } // reached the end of the array StorageContainerIterator<T>::Set(reinterpret_cast<T*>(0)); } }; template<class T> class SERVER_DECL HashMapStorageIterator : public StorageContainerIterator<T> { HashMapStorageContainer<T> * Source; typename HM_NAMESPACE::hash_map<uint32, T*>::iterator itr; public: /** Constructor */ HashMapStorageIterator(HashMapStorageContainer<T> * S) : StorageContainerIterator<T>(), Source(S) { itr = S->_map.begin(); if(itr == S->_map.end()) StorageContainerIterator<T>::Set(0); else StorageContainerIterator<T>::Set(itr->second); } /** Gets the next element, or if we reached the end sets it to 0 */ void GetNextElement() { ++itr; if(itr == Source->_map.end()) StorageContainerIterator<T>::Set(0); else StorageContainerIterator<T>::Set(itr->second); } /** Returns true if we're not at the end, otherwise false. */ bool Inc() { GetNextElement(); if(StorageContainerIterator<T>::Pointer != 0) return true; else return false; } /** Frees the memory occupied by this iterator */ void Destruct() { delete this; } }; #ifndef SCRIPTLIB template<class T> StorageContainerIterator<T> * ArrayStorageContainer<T>::MakeIterator() { return new ArrayStorageIterator<T>(this); } template<class T> StorageContainerIterator<T> * HashMapStorageContainer<T>::MakeIterator() { return new HashMapStorageIterator<T>(this); } #endif template<class T, class StorageType> class SERVER_DECL Storage { protected: StorageType _storage; char * _indexName; char * _formatString; public: ARCEMU_INLINE char * GetIndexName() { return _indexName; } ARCEMU_INLINE char * GetFormatString() { return _formatString; } /** False constructor to fool compiler */ Storage() {} virtual ~Storage() {} /** Makes an iterator, w00t! */ StorageContainerIterator<T> * MakeIterator() { return _storage.MakeIterator(); } /** Calls the storage container lookup function. */ T * LookupEntry(uint32 Entry) { return _storage.LookupEntry(Entry); } /** Reloads the content in this container. */ virtual void Reload() = 0; /** Loads the container using the specified name and format string */ virtual void Load(const char * IndexName, const char * FormatString) { _indexName = strdup(IndexName); _formatString = strdup(FormatString); } /** Frees the duplicated strings and all entries inside the storage container */ virtual void Cleanup() { printf("Deleting database cache of `%s`...\n", _indexName); StorageContainerIterator<T> * itr = _storage.MakeIterator(); while(!itr->AtEnd()) { FreeBlock(itr->Get()); if(!itr->Inc()) break; } itr->Destruct(); _storage.Clear(); free(_indexName); free(_formatString); } /** Frees any string elements inside blocks. */ void FreeBlock(T * Allocated) { char * p = _formatString; char * structpointer = (char*)Allocated; for(; *p != 0; ++p) { switch(*p) { case 's': // string is the only one we have to actually do anything for here free((*(char**)structpointer)); structpointer += sizeof(char*); break; case 'u': case 'i': case 'f': structpointer += sizeof(uint32); break; case 'h': structpointer += sizeof(uint16); break; case 'c': structpointer += sizeof(uint8); break; } } } }; template<class T, class StorageType> class SERVER_DECL SQLStorage : public Storage<T, StorageType> { public: SQLStorage() : Storage<T, StorageType>() {} ~SQLStorage() {} /** Loads the block using the format string. */ ARCEMU_INLINE void LoadBlock(Field * fields, T * Allocated) { char * p = Storage<T, StorageType>::_formatString; char * structpointer = (char*)Allocated; uint32 offset = 0; Field * f = fields; for(; *p != 0; ++p, ++f) { switch(*p) { case 'u': // Unsigned integer *(uint32*)&structpointer[offset] = f->GetUInt32(); offset += sizeof(uint32); break; case 'i': // Signed integer *(int32*)&structpointer[offset] = f->GetInt32(); offset += sizeof(int32); break; case 's': // Null-terminated string *(char**)&structpointer[offset] = strdup(f->GetString()); offset += sizeof(char*); break; case 'x': // Skip break; case 'f': // Float *(float*)&structpointer[offset] = f->GetFloat(); offset += sizeof(float); break; case 'c': // Char *(uint8*)&structpointer[offset] = f->GetUInt8(); offset += sizeof(uint8); break; case 'h': // Short *(uint16*)&structpointer[offset] = f->GetUInt16(); offset += sizeof(uint16); break; default: // unknown printf("Unknown field type in string: `%c`\n", *p); break; } } } /** Loads from the table. */ void Load(const char * IndexName, const char * FormatString) { //printf("Loading database cache from `%s`...\n", IndexName); Storage<T, StorageType>::Load(IndexName, FormatString); QueryResult * result; if(Storage<T, StorageType>::_storage.NeedsMax()) { result = WorldDatabase.Query("SELECT MAX(entry) FROM %s", IndexName); uint32 Max = STORAGE_ARRAY_MAX; if(result) { Max = result->Fetch()[0].GetUInt32() + 1; if(Max > STORAGE_ARRAY_MAX) { Log.Error("Storage", "The table, '%s', has a maximum entry of %u, which is less %u. Any items higher than %u will not be loaded.", IndexName, Max, STORAGE_ARRAY_MAX, STORAGE_ARRAY_MAX); Max = STORAGE_ARRAY_MAX; } delete result; } Storage<T, StorageType>::_storage.Setup(Max); } size_t cols = strlen(FormatString); result = WorldDatabase.Query("SELECT * FROM %s", IndexName); if (!result) return; Field * fields = result->Fetch(); if(result->GetFieldCount() != cols) { if(result->GetFieldCount() > cols) { Log.Warning("Storage", "Invalid format in %s (%u/%u), loading anyway because we have enough data\n", IndexName, (unsigned int)cols, (unsigned int)result->GetFieldCount()); } else { Log.Error("Storage", "Invalid format in %s (%u/%u), not enough data to proceed.\n", IndexName, (unsigned int)cols, (unsigned int)result->GetFieldCount()); delete result; return; } } uint32 Entry; T * Allocated; #ifdef STORAGE_ALLOCATION_POOLS Storage<T, StorageType>::_storage.InitPool( result->GetRowCount() ); #endif do { Entry = fields[0].GetUInt32(); Allocated = Storage<T, StorageType>::_storage.AllocateEntry(Entry); if(!Allocated) continue; LoadBlock(fields, Allocated); } while(result->NextRow()); Log.Notice("Storage", "%u entries loaded from table %s.", result->GetRowCount(), IndexName); delete result; //Log.Success("Storage", "Loaded database cache from `%s`.", IndexName); } void LoadAdditionalData(const char * IndexName, const char * FormatString) { Storage<T, StorageType>::Load(IndexName, FormatString); QueryResult * result; if(Storage<T, StorageType>::_storage.NeedsMax()) { result = WorldDatabase.Query("SELECT MAX(entry) FROM %s", IndexName); uint32 Max = STORAGE_ARRAY_MAX; if(result) { Max = result->Fetch()[0].GetUInt32() + 1; if(Max > STORAGE_ARRAY_MAX) { Log.Error("Storage", "The table, '%s', has a maximum entry of %u, which is less %u. Any items higher than %u will not be loaded.", IndexName, Max, STORAGE_ARRAY_MAX, STORAGE_ARRAY_MAX); Max = STORAGE_ARRAY_MAX; } delete result; } Storage<T, StorageType>::_storage.Resetup(Max); } size_t cols = strlen(FormatString); result = WorldDatabase.Query("SELECT * FROM %s", IndexName); if (!result) return; Field * fields = result->Fetch(); if(result->GetFieldCount() != cols) { if(result->GetFieldCount() > cols) { Log.Warning("Storage", "Invalid format in %s (%u/%u), loading anyway because we have enough data\n", IndexName, (unsigned int)cols, (unsigned int)result->GetFieldCount()); } else { Log.Error("Storage", "Invalid format in %s (%u/%u), not enough data to proceed.\n", IndexName, (unsigned int)cols, (unsigned int)result->GetFieldCount()); delete result; return; } } uint32 Entry; T * Allocated; do { Entry = fields[0].GetUInt32(); Allocated = Storage<T, StorageType>::_storage.LookupEntryAllocate(Entry); if(!Allocated) continue; LoadBlock(fields, Allocated); } while(result->NextRow()); Log.Notice("Storage", "%u entries loaded from table %s.", result->GetRowCount(), IndexName); delete result; } /** Reloads the storage container */ void Reload() { Log.Notice("Storage", "Reloading database cache from `%s`...\n", Storage<T, StorageType>::_indexName); QueryResult * result = WorldDatabase.Query("SELECT MAX(entry) FROM %s", Storage<T, StorageType>::_indexName); if(result == 0) return; uint32 Max = result->Fetch()[0].GetUInt32(); delete result; if(!Max) return; if(Storage<T, StorageType>::_storage.NeedsMax()) { if(Max > STORAGE_ARRAY_MAX) Max = STORAGE_ARRAY_MAX; Storage<T, StorageType>::_storage.Resetup(Max+1); } size_t cols = strlen(Storage<T, StorageType>::_formatString); result = WorldDatabase.Query("SELECT * FROM %s", Storage<T, StorageType>::_indexName); if (!result) return; Field * fields = result->Fetch(); if(result->GetFieldCount() != cols) { Log.Error("Storage", "Invalid format in %s (%u/%u).", Storage<T, StorageType>::_indexName, (unsigned int)cols, (unsigned int)result->GetFieldCount()); delete result; return; } uint32 Entry; T * Allocated; do { Entry = fields[0].GetUInt32(); Allocated = Storage<T, StorageType>::_storage.LookupEntryAllocate(Entry); if(Allocated) LoadBlock(fields, Allocated); } while(result->NextRow()); delete result; } }; #endif
[ "[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef", "[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef" ]
[ [ [ 1, 1 ], [ 4, 29 ], [ 31, 78 ], [ 80, 82 ], [ 84, 86 ], [ 88, 491 ], [ 494, 586 ], [ 588, 603 ], [ 605, 812 ] ], [ [ 2, 3 ], [ 30, 30 ], [ 79, 79 ], [ 83, 83 ], [ 87, 87 ], [ 492, 493 ], [ 587, 587 ], [ 604, 604 ] ] ]
3acc19fe483a1635b582df3acbe03132fd3140fc
61c263eb77eb64cf8ab42d2262fc553ac51a6399
/src/RandomSample.cpp
b234c63cee74e231c5525b905a24d76cf6b0f92e
[]
no_license
ycaihua/fingermania
20760830f6fe7c48aa2332b67f455eef8f9246a3
daaa470caf02169ea6533669aa511bf59f896805
refs/heads/master
2021-01-20T09:36:38.221802
2011-01-23T12:31:19
2011-01-23T12:31:19
40,102,565
1
0
null
null
null
null
UTF-8
C++
false
false
2,432
cpp
#include "global.h" #include "RandomSample.h" #include "RageSound.h" #include "RageUtil.h" #include "RageLog.h" RandomSample::RandomSample() { m_iIndexLastPlayed = -1; } RandomSample::~RandomSample() { UnloadAll(); } bool RandomSample::Load( RString sFilePath, int iMaxToLoad ) { if( GetExtension(sFilePath) == "" ) return LoadSoundDir( sFilePath, iMaxToLoad ); else return LoadSound( sFilePath ); } void RandomSample::UnloadAll() { for( unsigned i=0; i<m_pSamples.size(); i++ ) delete m_pSamples[i]; m_pSamples.clear(); } bool RandomSample::LoadSoundDir( RString sDir, int iMaxToLoad ) { if( sDir == "" ) return true; #if 0 if(IsADirectory(sDir) && sDir[sDir.size()-1] != "/" ) sDir += "/"; #else if( sDir.Right(1) != "/" ) sDir += "/"; #endif vector<RString> arraySoundFiles; GetDirListing( sDir + "*.mp3", arraySoundFiles ); GetDirListing( sDir + "*.ogg", arraySoundFiles ); GetDirListing( sDir + "*.wav", arraySoundFiles ); random_shuffle( arraySoundFiles.begin(), arraySoundFiles.end() ); arraySoundFiles.resize( min( arraySoundFiles.size(), (unsigned)iMaxToLoad ) ); for( unsigned i=0; i<arraySoundFiles.size(); i++ ) LoadSound( sDir + arraySoundFiles[i] ); return true; } bool RandomSample::LoadSound( RString sSoundFilePath ) { LOG->Trace( "RandomSample::LoadSound( %s )", sSoundFilePath.c_str() ); RageSound *pSS = new RageSound; if( !pSS->Load(sSoundFilePath) ) { LOG->Trace( "Error loading \"%s\": %s", sSoundFilePath.c_str(), pSS->GetError().c_str() ); delete pSS; return false; } m_pSamples.push_back( pSS ); return true; } int RandomSample::GetNextToPlay() { if( m_pSamples.empty() ) return -1; int iIndexToPlay = 0; for( int i=0; i<5; i++ ) { iIndexToPlay = RandomInt( m_pSamples.size() ); if( iIndexToPlay != m_iIndexLastPlayed ) break; } m_iIndexLastPlayed = iIndexToPlay; return iIndexToPlay; } void RandomSample::PlayRandom() { int iIndexToPlay = GetNextToPlay(); if( iIndexToPlay == -1 ) return; m_pSamples[iIndexToPlay]->Play(); } void RandomSample::PlayCopyOfRandom() { int iIndexToPlay = GetNextToPlay(); if( iIndexToPlay == -1 ) return; m_pSamples[iIndexToPlay]->PlayCopy(); } void RandomSample::Stop() { if( m_iIndexLastPlayed == -1 ) return; m_pSamples[m_iIndexLastPlayed]->Stop(); }
[ [ [ 1, 120 ] ] ]
ba852ad9017837b8f023e81a207f4d52f6f34b71
e443908057e5ef820cde73af431f5daa816094da
/hpstreecombobox.h
1cb714246986ceac75b44292a90539241fe594cb
[]
no_license
abho/HPicSync
a0c3f94f756a0387a3a2f5ba6b7204e002d8e2df
fddae986d4909e711260a61eacde6528be98137f
refs/heads/master
2021-01-15T13:18:29.309607
2011-09-30T14:09:27
2011-09-30T14:09:27
1,814,206
0
1
null
null
null
null
UTF-8
C++
false
false
1,615
h
// Code to create a QComboBox where multiple items can be selected and the items // are shown in a tree. // Written by Corwin Joy // code is hereby placed in the Public Domain. // code comes with no warranty of any kind, use at your own risk. #pragma once #include <QtGui/QComboBox> #include <QtCore/QList> #include <QtGui/QTreeView> #include <QStandardItem> #include <QListView> #include <QtCore/QStringList> #include "hpsknotdirmodel.h" class QStandardItemModel; class HPSTreeCombobox : public QComboBox { Q_OBJECT public: HPSTreeCombobox( QWidget* parent = 0); QStandardItemModel *standardModel() const; void setViewToTree(); void setViewToList(); bool eventFilter(QObject* object, QEvent* event); virtual void showPopup(); virtual void hidePopup(); void loadExpanded(); void findeAndSetCurrentItem(const QString &dir); void setCurrentItem(QStandardItem *item); const QString currentDir(); const QStringList &expandeDirs(); public Q_SLOTS: void updateText(); void blockLineEditChanged(const QString &); signals: void itemClicked( QModelIndex index); private slots: void saveExpandItem(const QModelIndex &index); void removeExpandItem(const QModelIndex &index); private: bool mSkipNextHide; QTreeView *mTreeView; QListView *mListView; QStandardItem* findIndex( QStandardItem *item,const QString &dir); void loadExpandedItem(QStandardItem * item); protected: QModelIndex mDefaultRootIndex; QModelIndex mCIndex; QStringList mExpandeDirs; };
[ [ [ 1, 58 ] ] ]
94a0885a7caa6d4802e31d0639116b7289b95fd0
37334008977a7a644cbbc2f2a828bc1d150c0638
/win32/MD/PlugDemo/codeGenerator.hpp
dca7b3d12db59682a90d50fb897dd8380ce3ccd3
[]
no_license
titanlab/neo-myth-plugins
91e797d69620981edf229c6186805bf0a49f0cc2
de41771c9772a5f02f165d4f36fb1ec6f134a29a
refs/heads/master
2021-09-08T12:17:24.494573
2011-11-19T15:17:42
2011-11-19T15:17:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
510
hpp
#ifndef __codeGenerator_hpp__ #define __codeGenerator_hpp__ #include "..\\PlugBase.h" void genCode(NeoResultBlock *src , std::vector<COpCode>& bc); const unsigned int buildHash(const std::string& in); bool isStreamEncoded(); bool isSMSStream(); const std::string& getPlugPath(); const std::string& getRomSuffix(); void forceEncodedStream(); void forceSMSStream(); void disableSMSStream(); void disableEncodedStream(); void muteOpCode(const int op,std::vector<COpCode>& bc); #endif
[ "conleon1988@bb221dbb-59eb-094c-fa1a-8ce0a11b4692" ]
[ [ [ 1, 16 ] ] ]