blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
listlengths
0
7
license_type
stringclasses
2 values
repo_name
stringlengths
6
79
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
4 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.07k
426M
star_events_count
int64
0
27
fork_events_count
int64
0
12
gha_license_id
stringclasses
3 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
6 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
20
6.28M
extension
stringclasses
20 values
content
stringlengths
20
6.28M
authors
listlengths
1
16
author_lines
listlengths
1
16
534e26c0d714e25ce4097fe5653f3aa5ca3ce911
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libc/testcapipc/inc/tipcserver.h
ff68fa1be7abfe2b24b41269799988f2148fde49
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
1,007
h
/* * Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ /* * ============================================================================== * Name : tstdioserver.h * Part of : teststdio * * Description : ?Description * Version: 0.5 * */ #ifndef __TipcSERVER_H__ #define __TipcSERVER_H__ #include <f32file.h> #include <test/TestExecuteServerBase.h> class CipcTestServer : public CTestServer { public: static CipcTestServer* NewL(); virtual CTestStep* CreateTestStep(const TDesC& aStepName); RFs& Fs() {return iFs;} private: RFs iFs; }; #endif //
[ "none@none" ]
[ [ [ 1, 47 ] ] ]
caa35ed8582fa7e7fd6da7e11b346dc91191e0d8
997e067ab6b591e93e3968ae1852003089dca848
/src/game/server/entities/trigger.cpp
89e1e6386cada6903f8fd3ee1580c7cb77819cee
[ "LicenseRef-scancode-other-permissive", "Zlib" ]
permissive
floff/ddracemax_old
06cbe9f60e7cef66e58b40c5f586921a1c881ff3
f1356177c49a3bc20632df9a84a51bc491c37f7d
refs/heads/master
2016-09-05T11:59:55.623581
2011-01-14T04:58:25
2011-01-14T04:58:25
777,555
1
0
null
null
null
null
UTF-8
C++
false
false
1,330
cpp
/* copyright (c) 2007 magnus auvinen, see licence.txt for more info */ #include <engine/e_config.h> #include <engine/e_server_interface.h> #include <game/generated/g_protocol.hpp> #include <game/server/gamecontext.hpp> #include "trigger.hpp" #include "door.hpp" ////////////////////////////////////////////////// // DOOR ////////////////////////////////////////////////// TRIGGER::TRIGGER(vec2 pos, ENTITY *target) : ENTITY(NETOBJTYPE_PICKUP) { this->pos = pos; this->target = target; game.world.insert_entity(this); } bool TRIGGER::hit_character() { CHARACTER *hit = game.world.closest_character(pos, 20.0f, 0); if(!hit) return false; return true; } void TRIGGER::open_door(int tick) { DOOR *tar = (DOOR*) target; tar->open(tick); } void TRIGGER::reset() { return; } void TRIGGER::tick() { if (server_tick() % 10 == 0) { if (hit_character()) open_door(server_tick()); } return; } void TRIGGER::snap(int snapping_client) { return; /* if(networkclipped(snapping_client,pos)) return; NETOBJ_PICKUP *up = (NETOBJ_PICKUP *)snap_new_item(NETOBJTYPE_PICKUP, id, sizeof(NETOBJ_PICKUP)); up->x = (int)pos.x; up->y = (int)pos.y; up->type = POWERUP_ARMOR; // TODO: two diffrent types? what gives? //up->subtype = subtype; */ }
[ [ [ 1, 68 ] ] ]
e9889cefdf76a146fc07e63199f1eca7c4604eb3
1d0aaab36740e9117022b3cf03029cede9f558ab
/Model.h
5b41b0abec06ae46cd8074fcf1cc9f85a8077378
[]
no_license
mikeqcp/superseaman
76ac7c4b4a19a705880a078ca66cfd8976fc07d1
bebeb48e90270dd94bb1c85090f12c4123002815
refs/heads/master
2021-01-25T12:09:29.096901
2011-09-13T21:44:33
2011-09-13T21:44:33
32,287,575
0
0
null
null
null
null
UTF-8
C++
false
false
2,233
h
#pragma once #include <vector> #include "includes.h" #include "Material.h" #include "ModelStuctures.h" #include "Mesh.h" using namespace std; class Model { protected: glm::mat4 P, V, M; glm::vec4 lightPos; glm::vec3 lookAtPos, viewPos; GLuint locP, locV, locM, locVertex, locNormal, locLighPos, locClipPlane, locTexCoord , locEnableTexturing[4], locTBN[3]; GLuint locLookAtPos, locViewPos; GLuint locMaterial[7]; GLuint vertexShader, fragmentShader, shaderProgram; GLuint bufVertices, bufIndices, bufNormals, bufTexCoords, vao; GLuint bufTBNCol1, bufTBNCol2, bufTBNCol3; GLuint verticesBufferType; GLuint verticesCount, normalsCount, indicesCount; glm::vec4 clipPlane; GLfloat *vertices, *normals, *texturesCoords; GLfloat *matTBNcol1, *matTBNcol2, *matTBNcol3; glm::vec3 *tangent, *bitangent, *norm; glm::vec4 *originalVertices; unsigned originalVerticesCount; GLuint *indices; Mesh *meshes; unsigned meshCount; Texture *textures; unsigned textureCount; Material *materials; int materialCount; GLfloat rotationAngle; glm::vec3 rotationAxis; GLuint LoadShader(GLenum shaderType, string fileName); void SetupBuffers(); void CleanShaders(); void SetupUniformVariables(); void SetupShaders(string vshaderFile, string fshaderFile); void CleanBuffers(); public: Model(); Model(string fileName, glm::mat4 P, glm::mat4 V, glm::mat4 M, string vshaderFile, string fshaderFile); ~Model(void); void Update(glm::mat4 P, glm::mat4 V, glm::mat4 M, glm::vec4 lightPos); void UpdateMesh(string name, glm::mat4 P, glm::mat4 V, glm::mat4 M, glm::vec4 lightPos); void Draw(); void DrawReflection(); void Load(string fileName, Texture *textures, int textureCount); void UpdateRotation(GLfloat angle, glm::vec3 axis); glm::mat4 GetModelMatrix(); glm::vec4 *GetSegment(string mname, string msname, int *length); void SetTextures(Texture *textures, unsigned textureCount); void SetClipPlane(glm::vec4 clipPlane){ this ->clipPlane = clipPlane; }; void SetLookAt(glm::vec3 lookAtPos){ this ->lookAtPos = lookAtPos; }; void SetViewPos(glm::vec3 viewPos){ this ->viewPos = viewPos; }; };
[ "[email protected]@a54423c0-632b-0463-fc5f-a1ef5643ace0" ]
[ [ [ 1, 92 ] ] ]
c27a9bdaec41370f566d0e0fa4c7a6c344e5657e
222bc22cb0330b694d2c3b0f4b866d726fd29c72
/src/brookbox/wm2/WmlLightState.h
2ad6339fd841ae968ac0907bc83ad57a5499359d
[ "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference" ]
permissive
darwin/inferno
02acd3d05ca4c092aa4006b028a843ac04b551b1
e87017763abae0cfe09d47987f5f6ac37c4f073d
refs/heads/master
2021-03-12T22:15:47.889580
2009-04-17T13:29:39
2009-04-17T13:29:39
178,477
2
0
null
null
null
null
UTF-8
C++
false
false
1,784
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 WMLLIGHTSTATE_H #define WMLLIGHTSTATE_H #include "WmlLight.h" #include "WmlRenderState.h" namespace Wml { WmlSmartPointer(LightState); class WML_ITEM LightState : public RenderState { WmlDeclareDefaultState(LightState); WmlDeclareRTTI; WmlDeclareStream; public: LightState (); virtual ~LightState (); virtual Type GetType () const; enum { MAX_LIGHTS = 8 }; int Attach (Light* pkLight); int Detach (Light* pkLight); LightPtr Detach (int i); void DetachAll (); int GetQuantity () const; Light* Get (int i); // support for searching by name virtual Object* GetObjectByName (const char* acName); virtual void GetAllObjectsByName (const char* acName, std::vector<Object*>& rkObjects); protected: // Support for the UpdateRS pass. The input parameters are the stack of // LightState objects visited during the recursive traversal. When the // traversal reaches a Geometry leaf node, the accumulated lights are // combined into a single LightState object that represents the light // state at that leaf. This function returns that object to the Geometry // object. virtual RenderState* Extract (int iLastIndex, RenderState* apkState[]); LightPtr m_aspkLight[MAX_LIGHTS]; }; WmlRegisterStream(LightState); } #endif
[ [ [ 1, 65 ] ] ]
962c57b21fafcab155d36d4338866fe5d2618d97
d115cf7a1b374d857f6b094d4b4ccd8e9b1ac189
/tags/pyplusplus_dev_0.9.5/unittests/data/casting_to_be_exported.hpp
60d03395f5518e2c7b1f6696ff089832d14c3c63
[ "BSL-1.0" ]
permissive
gatoatigrado/pyplusplusclone
30af9065fb6ac3dcce527c79ed5151aade6a742f
a64dc9aeeb718b2f30bd6a5ff8dcd8bfb1cd2ede
refs/heads/master
2016-09-05T23:32:08.595261
2010-05-16T10:53:45
2010-05-16T10:53:45
700,369
4
2
null
null
null
null
UTF-8
C++
false
false
1,034
hpp
// Copyright 2004-2008 Roman Yakovenko. // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef __casting_to_be_exported_hpp__ #define __casting_to_be_exported_hpp__ namespace casting{ struct y{}; struct x{ x() : value(0) {} explicit x( int i ) : value( i ) {} x( bool b ) : value( b ) {} operator int() const { return value; } operator y(){ return y(); } int value; }; int identity( int z ){ return z; } int x_value(const x& d ){ return d.value; } struct vector{ vector(){} vector( double ){} vector( const vector& ){} }; struct float_vector{ float_vector(){} float_vector( const float_vector& ){} float_vector( const vector& ){} float_vector( float ){} }; inline void do_nothing(){ float_vector( 5.0 ); } } #endif//__casting_to_be_exported_hpp__
[ "roman_yakovenko@dc5859f9-2512-0410-ae5c-dd123cda1f76" ]
[ [ [ 1, 57 ] ] ]
97e1cd05d3ebeb6a9ad7f172f4184444683093e4
3276915b349aec4d26b466d48d9c8022a909ec16
/数据结构/图/图--邻接表存储结构.cpp
e4de6c9a52350982277e5c635d8790ab8d801670
[]
no_license
flyskyosg/3dvc
c10720b1a7abf9cf4fa1a66ef9fc583d23e54b82
0279b1a7ae097b9028cc7e4aa2dcb67025f096b9
refs/heads/master
2021-01-10T11:39:45.352471
2009-07-31T13:13:50
2009-07-31T13:13:50
48,670,844
0
0
null
null
null
null
GB18030
C++
false
false
2,835
cpp
#include<iostream.h> #include<iostream> // 图的邻接矩阵存储结构 #define max 50 typedef char datatype; typedef struct lnode { int number; //节点要存储其编号 int weight; //节点存储边的权值 struct lnode *next; //指向下一个节点 }lnode; typedef struct node { int number; //节点要存储其编号 datatype inf; //节点信息 lnode *first; //指向节点的邻接点 }node; typedef struct graph //定义图 { int n,e; //图的节点数与边数 node vex[max]; //存储节点的信息以及序号,first }G; void creatgraph0(G & l) { int i=0,j=0,b=0,t=0,w=0;lnode * p,* q; cout<<"输入图的顶点数与边数:"; cin>>l.n>>l.e; cout<<"该图有"<<l.n<<"个顶点"<<l.e<<"条边"<<endl; for(;i<l.n;i++) { cout<<"请输入第"<<i<<"个节点的信息,输入序号_节点内容:"; cin>>l.vex[i].number>>l.vex[i].inf; l.vex[i].first=NULL; } for(j=0;j<l.e;j++) { cout<<"输入边的信息,起点序号_终点_权值:"; cin>>b>>t>>w; if(b<0||b>=l.n) cout<<"起点不在搜索范围内."<<endl; if(t<0||t>=l.n) cout<<"终点不在搜索范围内."<<endl; p=(lnode *)malloc(sizeof(lnode)); p->number=t;p->weight=w; p->next=l.vex[b].first; l.vex[b].first=p; q=(lnode *)malloc(sizeof(lnode)); q->number=b;q->weight=w; q->next=l.vex[t].first; l.vex[t].first=q; } cout<<"建立邻接无向表完毕."<<endl; } void creatgraph1(G & l) { int i=0,j=0,b=0,t=0,w=0;lnode * p; cout<<"输入图的顶点数与边数:"; cin>>l.n>>l.e; cout<<"该图有"<<l.n<<"个顶点"<<l.e<<"条边"<<endl; for(;i<l.n;i++) { cout<<"请输入第"<<i<<"个节点的信息,输入序号_节点内容:"; cin>>l.vex[i].number>>l.vex[i].inf; l.vex[i].first=NULL; } for(j=0;j<l.e;j++) { cout<<"输入边的信息,起点序号_终点_权值:"; cin>>b>>t>>w; if(b<0||b>=l.n) cout<<"起点不在搜索范围内."<<endl; if(t<0||t>=l.n) cout<<"终点不在搜索范围内."<<endl; p=(lnode *)malloc(sizeof(lnode)); p->number=t;p->weight=w; p->next=l.vex[b].first; l.vex[b].first=p; } cout<<"建立有向邻接表完毕."<<endl; } void disp(G l) { int i=0;lnode * p; cout<<"输出格式:"<<"节点序号_节点信息+邻接点序号_该边的权值+........."<<endl; for(i;i<l.n;i++) { cout<<l.vex[i].number<<" "<<l.vex[i].inf<<" "; p=l.vex[i].first; while(p!=NULL) { cout<<p->number<<" "<<p->weight<<" "; p=p->next; } cout<<endl; } } void main() { G l; creatgraph0(l); disp(l); }
[ [ [ 1, 126 ] ] ]
70c8d874d86fb33181bbafb832295413a7441b74
d01196cdfc4451c4e1c88343bdb1eb4db9c5ac18
/source/client/hud/hud_text.cpp
83e66b28ca8ceadc06511a6d4e0438c394f92806
[]
no_license
ferhan66h/Xash3D_ancient
7491cd4ff1c7d0b48300029db24d7e08ba96e88a
075e0a6dae12a0952065eb9b2954be4a8827c72f
refs/heads/master
2021-12-10T07:55:29.592432
2010-05-09T00:00:00
2016-07-30T17:37:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,100
cpp
/*** * * Copyright (c) 1996-2002, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * Use, distribution, and modification of this source code and/or resulting * object code is restricted to non-commercial enhancements to products from * Valve LLC. All other use, distribution, or modification is prohibited * without written permission from Valve LLC. * ****/ // // text_message.cpp // // implementation of CHudTextMessage class // // this class routes messages through titles.txt for localisation // #include "extdll.h" #include "utils.h" #include "hud.h" DECLARE_MESSAGE( m_TextMessage, TextMsg ); int CHudTextMessage::Init(void) { HOOK_MESSAGE( TextMsg ); gHUD.AddHudElem( this ); Reset(); return 1; }; // Searches through the string for any msg names (indicated by a '#') // any found are looked up in titles.txt and the new message substituted // the new value is pushed into dst_buffer char *CHudTextMessage::LocaliseTextString( const char *msg, char *dst_buffer, int buffer_size ) { char *dst = dst_buffer; for ( char *src = (char*)msg; *src != 0 && buffer_size > 0; buffer_size-- ) { if ( *src == '#' ) { // cut msg name out of string static char word_buf[255]; char *wdst = word_buf, *word_start = src; for ( ++src ; (*src >= 'A' && *src <= 'z') || (*src >= '0' && *src <= '9'); wdst++, src++ ) { *wdst = *src; } *wdst = 0; // lookup msg name in titles.txt client_textmessage_t *clmsg = TextMessageGet( word_buf ); if ( !clmsg || !(clmsg->pMessage) ) { src = word_start; *dst = *src; dst++, src++; continue; } // copy string into message over the msg name for ( char *wsrc = (char*)clmsg->pMessage; *wsrc != 0; wsrc++, dst++ ) { *dst = *wsrc; } *dst = 0; } else { *dst = *src; dst++, src++; *dst = 0; } } dst_buffer[buffer_size-1] = 0; // ensure null termination return dst_buffer; } // As above, but with a local static buffer char *CHudTextMessage::BufferedLocaliseTextString( const char *msg ) { static char dst_buffer[1024]; LocaliseTextString( msg, dst_buffer, 1024 ); return dst_buffer; } // Simplified version of LocaliseTextString; assumes string is only one word char *CHudTextMessage::LookupString( const char *msg, int *msg_dest ) { if ( !msg ) return ""; // '#' character indicates this is a reference to a string in titles.txt, and not the string itself if ( msg[0] == '#' ) { // this is a message name, so look up the real message client_textmessage_t *clmsg = TextMessageGet( msg+1 ); if ( !clmsg || !(clmsg->pMessage) ) return (char*)msg; // lookup failed, so return the original string if ( msg_dest ) { // check to see if titles.txt info overrides msg destination // if clmsg->effect is less than 0, then clmsg->effect holds -1 * message_destination if ( clmsg->effect < 0 ) // *msg_dest = -clmsg->effect; } return (char*)clmsg->pMessage; } else { // nothing special about this message, so just return the same string return (char*)msg; } } void StripEndNewlineFromString( char *str ) { int s = strlen( str ) - 1; if ( str[s] == '\n' || str[s] == '\r' ) str[s] = 0; } // converts all '\r' characters to '\n', so that the engine can deal with the properly // returns a pointer to str char* ConvertCRtoNL( char *str ) { for ( char *ch = str; *ch != 0; ch++ ) if ( *ch == '\r' ) *ch = '\n'; return str; } // Message handler for text messages // displays a string, looking them up from the titles.txt file, which can be localised // parameters: // byte: message direction ( HUD_PRINTCONSOLE, HUD_PRINTNOTIFY, HUD_PRINTCENTER, HUD_PRINTTALK ) // string: message // optional parameters: // string: message parameter 1 // string: message parameter 2 // string: message parameter 3 // string: message parameter 4 // any string that starts with the character '#' is a message name, and is used to look up the real message in titles.txt // the next (optional) one to four strings are parameters for that string (which can also be message names if they begin with '#') int CHudTextMessage::MsgFunc_TextMsg( const char *pszName, int iSize, void *pbuf ) { BEGIN_READ( pszName, iSize, pbuf ); int msg_dest = READ_BYTE(); static char szBuf[6][128]; char *msg_text = LookupString( READ_STRING(), &msg_dest ); msg_text = strcpy( szBuf[0], msg_text ); // keep reading strings and using C format strings for subsituting the strings into the localised text string char *sstr1 = LookupString( READ_STRING() ); sstr1 = strcpy( szBuf[1], sstr1 ); StripEndNewlineFromString( sstr1 ); // these strings are meant for subsitution into the main strings, so cull the automatic end newlines char *sstr2 = LookupString( READ_STRING() ); sstr2 = strcpy( szBuf[2], sstr2 ); StripEndNewlineFromString( sstr2 ); char *sstr3 = LookupString( READ_STRING() ); sstr3 = strcpy( szBuf[3], sstr3 ); StripEndNewlineFromString( sstr3 ); char *sstr4 = LookupString( READ_STRING() ); sstr4 = strcpy( szBuf[4], sstr4 ); StripEndNewlineFromString( sstr4 ); char *psz = szBuf[5]; switch ( msg_dest ) { case HUD_PRINTCENTER: sprintf( psz, msg_text, sstr1, sstr2, sstr3, sstr4 ); CenterPrint( ConvertCRtoNL( psz ) ); break; case HUD_PRINTNOTIFY: psz[0] = 1; // mark this message to go into the notify buffer sprintf( psz+1, msg_text, sstr1, sstr2, sstr3, sstr4 ); ConsolePrint( ConvertCRtoNL( psz ) ); break; case HUD_PRINTTALK: sprintf( psz, msg_text, sstr1, sstr2, sstr3, sstr4 ); gHUD.m_SayText.SayTextPrint( ConvertCRtoNL( psz ), 128 ); break; case HUD_PRINTCONSOLE: sprintf( psz, msg_text, sstr1, sstr2, sstr3, sstr4 ); ConsolePrint( ConvertCRtoNL( psz ) ); break; } END_READ(); return 1; }
[ [ [ 1, 204 ] ] ]
8239cba932464ca56009e4afbdd66f2cb09de318
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Common/Base/System/Io/FileSystem/hkNativeFileSystem.h
0cd3ffe16cf8e2a2f3b4e0bc7e230233e77e3292
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
6,326
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_DEFAULTFILESYSTEM #define HK_DEFAULTFILESYSTEM #include <Common/Base/hkBase.h> #include <Common/Base/System/Io/Reader/hkStreamReader.h> #include <Common/Base/System/Io/Writer/hkStreamWriter.h> #include <Common/Base/System/Io/FileSystem/hkFileSystem.h> #include <Common/Base/System/Io/Reader/Buffered/hkBufferedStreamReader.h> #include <Common/Base/System/Io/Writer/Buffered/hkBufferedStreamWriter.h> #if defined(HK_PLATFORM_PSP) || defined(HK_PLATFORM_PS2) || defined(HK_PLATFORM_UNIX) || defined(HK_PLATFORM_MAC386) || defined(HK_PLATFORM_MACPPC) || defined(HK_PLATFORM_LRB) # include <Common/Base/System/Io/Reader/Posix/hkPosixStreamReader.h> # include <Common/Base/System/Io/Writer/Posix/hkPosixStreamWriter.h> # if defined (HK_PLATFORM_UNIX) || defined(HK_PLATFORM_MAC386) || defined(HK_PLATFORM_MACPPC) || defined(HK_PLATFORM_LRB) # include <Common/Base/System/Io/Directory/Posix/hkPosixListDirectory.h> # else # include <Common/Base/System/Io/Directory/EmptyImpl/hkListDirectoryEmptyImpl.h> # endif #elif defined(HK_PLATFORM_WIN32) || defined(HK_PLATFORM_XBOX) || defined(HK_PLATFORM_XBOX360) # include <Common/Base/System/Io/Reader/Stdio/hkStdioStreamReader.h> # include <Common/Base/System/Io/Writer/Stdio/hkStdioStreamWriter.h> # include <Common/Base/System/Io/Directory/Win32/hkWin32ListDirectory.h> #elif defined(HK_PLATFORM_PS3_PPU) # include <Common/Base/System/Io/Reader/Stdio/hkStdioStreamReader.h> # include <Common/Base/System/Io/Writer/Stdio/hkStdioStreamWriter.h> # include <Common/Base/System/Io/Directory/Ps3/hkPs3ListDirectory.h> # include <sys/paths.h> #else # include <Common/Base/System/Io/Reader/Stdio/hkStdioStreamReader.h> # include <Common/Base/System/Io/Writer/Stdio/hkStdioStreamWriter.h> #endif // FileSystem class implementation for native file systems. // Uses default reader, writer and file system browsers for each platform // All the paths and file names must be in Havok standard format i.e. the // only character accepted as a separator is '/'. // e.g. A valid path is Dir/SubDir/SubSubDir/Filename class hkNativeFileSystem : public hkFileSystem { public: // Function pointer type for directory listing. typedef hkResult (HK_CALL *ListDirectoryFunType)( const char* pathIn, hkFileSystem::DirectoryListing& directoryListingOut ); // Function pointer type for converting Havok paths to platform paths. typedef const char* (HK_CALL *HavokToPlatformConvertPathFunType)( const char* pathIn, hkStringBuf& buffer ); // Function pointer type for converting platform paths to Havok paths. typedef const char* (HK_CALL *PlatformToHavokConvertPathFunType)( const char* pathIn, hkStringBuf& buffer ); // Function pointer for directory listing. // Replace the function to modify listDirectory behavior. static ListDirectoryFunType s_listDirectory; // Pointer to function for converting Havok paths to platform paths. // Replace the function to modify havokToPlatformConvertPath behavior. static HavokToPlatformConvertPathFunType s_havokToPlatformConvert; // Pointer to function for converting platform paths to Havok paths. // Replace the function to modify platformToHavokConvertPath behavior. static PlatformToHavokConvertPathFunType s_platformToHavokConvert; // Default conversions functions static const char* HK_CALL nativeHavokToPlatformConvertPath( const char* pathIn, hkStringBuf& buffer ); static const char* HK_CALL nativePlatformToHavokConvertPath( const char* pathIn, hkStringBuf& buffer ); virtual hkStreamReader* openReader( const char* name ) { hkStringBuf buffer; hkStreamReader* s = new DefaultFileReader( havokToPlatformConvertPath( name, buffer ) ); if( s->markSupported() == false ) { hkStreamReader* b = new hkBufferedStreamReader(s); s->removeReference(); return b; } return s; } virtual hkStreamWriter* openWriter( const char* name ) { hkStringBuf buffer; hkStreamWriter* s = new DefaultFileWriter( havokToPlatformConvertPath( name, buffer ) ); hkStreamWriter* b = new hkBufferedStreamWriter(s); s->removeReference(); return b; } static hkReferencedObject* create() { return new hkNativeFileSystem(); } // Converts a Havok path to platform path. Set s_havokToPlatformConvert HK_FORCE_INLINE static const char* HK_CALL havokToPlatformConvertPath( const char* pathIn, hkStringBuf& buffer ) { return s_havokToPlatformConvert( pathIn, buffer ); } // Converts a platform path to Havok path HK_FORCE_INLINE static const char* HK_CALL platformToHavokConvertPath( const char* pathIn, hkStringBuf& buffer ) { return s_platformToHavokConvert( pathIn, buffer ); } /// list all the directories and files in the "basePath" directory, /// returns HK_FAILURE if the path is not valid /// basePath must be in Havok format, all the generated paths and file names /// in listingOut will be in Havok format too. virtual hkResult listDirectory(const char* basePath, DirectoryListing& listingOut) { return s_listDirectory( basePath, listingOut ); } }; #endif //HK_DEFAULTFILESYSTEM /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ [ [ 1, 139 ] ] ]
758cc7db9aba1c2d50f1db682e98e6d8bdcd00dd
de0881d85df3a3a01924510134feba2fbff5b7c3
/apps/addonsExamples/vectorGraphicsExample/src/main.cpp
5b645ab60e2d8bd8ccc4086405cd92a3f465c2f8
[]
no_license
peterkrenn/ofx-dev
6091def69a1148c05354e55636887d11e29d6073
e08e08a06be6ea080ecd252bc89c1662cf3e37f0
refs/heads/master
2021-01-21T00:32:49.065810
2009-06-26T19:13:29
2009-06-26T19:13:29
146,543
1
1
null
null
null
null
UTF-8
C++
false
false
415
cpp
#include "ofMain.h" #include "testApp.h" #include "ofAppGlutWindow.h" //======================================================================== int main( ){ ofAppGlutWindow window; ofSetupOpenGL(&window, 680,800, OF_WINDOW); // <-------- setup the GL context // this kicks off the running of my app // can be OF_WINDOW or OF_FULLSCREEN // pass in width and height too: ofRunApp( new testApp()); }
[ [ [ 1, 16 ] ] ]
aa477df8db8302a9b756282ed0ca5eea1f16ff53
021e8c48a44a56571c07dd9830d8bf86d68507cb
/build/vtk/vtkXRenderWindowInteractor.h
469a8b36d8c3cd9241846570a7e42d575d84b0c6
[ "BSD-3-Clause" ]
permissive
Electrofire/QdevelopVset
c67ae1b30b0115d5c2045e3ca82199394081b733
f88344d0d89beeec46f5dc72c20c0fdd9ef4c0b5
refs/heads/master
2021-01-18T10:44:01.451029
2011-05-01T23:52:15
2011-05-01T23:52:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,752
h
/*========================================================================= Program: Visualization Toolkit Module: vtkXRenderWindowInteractor.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkXRenderWindowInteractor - an X event driven interface for a RenderWindow // .SECTION Description // vtkXRenderWindowInteractor is a convenience object that provides event // bindings to common graphics functions. For example, camera and actor // functions such as zoom-in/zoom-out, azimuth, roll, and pan. IT is one of // the window system specific subclasses of vtkRenderWindowInteractor. Please // see vtkRenderWindowInteractor documentation for event bindings. // // .SECTION see also // vtkRenderWindowInteractor vtkXRenderWindow // I've been though this and deleted all I think should go, tried to create // the basic structure and if you're lucky it might even work! // but frankly I doubt it #ifndef __vtkXRenderWindowInteractor_h #define __vtkXRenderWindowInteractor_h //=========================================================== // now we define the C++ class #include "vtkRenderWindowInteractor.h" #include <X11/StringDefs.h> // Needed for X types in the public interface #include <X11/Intrinsic.h> // Needed for X types in the public interface class vtkCallbackCommand; class vtkXRenderWindowInteractorInternals; //BTX // Forward declare internal friend functions. void VTK_RENDERING_EXPORT vtkXRenderWindowInteractorCallback(Widget,XtPointer, XEvent *,Boolean *); void VTK_RENDERING_EXPORT vtkXRenderWindowInteractorTimer(XtPointer,XtIntervalId *); //ETX class VTK_RENDERING_EXPORT vtkXRenderWindowInteractor : public vtkRenderWindowInteractor { public: static vtkXRenderWindowInteractor *New(); vtkTypeMacro(vtkXRenderWindowInteractor,vtkRenderWindowInteractor); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Initializes the event handlers without an XtAppContext. This is // good for when you don't have a user interface, but you still // want to have mouse interaction. virtual void Initialize(); // Description: // Break the event loop on 'q','e' keypress. Want more ??? void TerminateApp(); // Description: // The BreakLoopFlag is checked in the Start() method. // Setting it to anything other than zero will cause // the interactor loop to terminate and return to the // calling function. vtkGetMacro(BreakLoopFlag, int); void SetBreakLoopFlag(int); void BreakLoopFlagOff(); void BreakLoopFlagOn(); // Description: // Initializes the event handlers using an XtAppContext that you have // provided. This assumes that you want to own the event loop. virtual void Initialize(XtAppContext app); vtkGetMacro( App, XtAppContext ); // Description: // Enable/Disable interactions. By default interactors are enabled when // initialized. Initialize() must be called prior to enabling/disabling // interaction. These methods are used when a window/widget is being // shared by multiple renderers and interactors. This allows a "modal" // display where one interactor is active when its data is to be displayed // and all other interactors associated with the widget are disabled // when their data is not displayed. virtual void Enable(); virtual void Disable(); // Description: // This will start up the X event loop and never return. If you // call this method it will loop processing X events until the // application is exited. virtual void Start(); // Description: // Update the Size data member and set the associated RenderWindow's // size. virtual void UpdateSize(int,int); // Description: // Specify the Xt widget to use for interaction. This method is // one of a couple steps that are required for setting up a // vtkRenderWindowInteractor as a widget inside of another user // interface. You do not need to use this method if the render window // will be a stand-alone window. This is only used when you want the // render window to be a subwindow within a larger user interface. // In that case, you must tell the render window what X display id // to use, and then ask the render window what depth, visual and // colormap it wants. Then, you must create an Xt TopLevelShell with // those settings. Then you can create the rest of your user interface // as a child of the TopLevelShell you created. Eventually, you will // create a drawing area or some other widget to serve as the rendering // window. You must use the SetWidget method to tell this Interactor // about that widget. It's X and it's not terribly easy, but it looks cool. virtual void SetWidget(Widget); Widget GetWidget() {return this->Top;}; // Description // This method will store the top level shell widget for the interactor. // This method and the method invocation sequence applies for: // 1 vtkRenderWindow-Interactor pair in a nested widget hierarchy // multiple vtkRenderWindow-Interactor pairs in the same top level shell // It is not needed for // 1 vtkRenderWindow-Interactor pair as the direct child of a top level shell // multiple vtkRenderWindow-Interactor pairs, each in its own top level shell // // The method, along with EnterNotify event, changes the keyboard focus among // the widgets/vtkRenderWindow(s) so the Interactor(s) can receive the proper // keyboard events. The following calls need to be made: // vtkRenderWindow's display ID need to be set to the top level shell's // display ID. // vtkXRenderWindowInteractor's Widget has to be set to the vtkRenderWindow's // container widget // vtkXRenderWindowInteractor's TopLevel has to be set to the top level // shell widget // note that the procedure for setting up render window in a widget needs to // be followed. See vtkRenderWindowInteractor's SetWidget method. // // If multiple vtkRenderWindow-Interactor pairs in SEPARATE windows are desired, // do not set the display ID (Interactor will create them as needed. Alternatively, // create and set distinct DisplayID for each vtkRenderWindow. Using the same // display ID without setting the parent widgets will cause the display to be // reinitialized every time an interactor is initialized), do not set the // widgets (so the render windows would be in their own windows), and do // not set TopLevelShell (each has its own top level shell already) virtual void SetTopLevelShell(Widget); Widget GetTopLevelShell() {return this->TopLevelShell;}; // Description: // Re-defines virtual function to get mouse position by querying X-server. virtual void GetMousePosition(int *x, int *y); // Description: // Functions that are used internally. friend void vtkXRenderWindowInteractorCallback(Widget,XtPointer, XEvent *,Boolean *); friend void vtkXRenderWindowInteractorTimer(XtPointer,XtIntervalId *); protected: vtkXRenderWindowInteractor(); ~vtkXRenderWindowInteractor(); //Using static here to avoid detroying context when many apps are open: static XtAppContext App; static int NumAppInitialized; Display *DisplayId; Window WindowId; Atom KillAtom; Widget Top; int OwnTop; int OwnApp; int PositionBeforeStereo[2]; Widget TopLevelShell; int TimerId; vtkXRenderWindowInteractorInternals* Internal; // Description: // X-specific internal timer methods. See the superclass for detailed // documentation. virtual int InternalCreateTimer(int timerId, int timerType, unsigned long duration); virtual int InternalDestroyTimer(int platformTimerId); XtIntervalId AddTimeOut(XtAppContext app_context, unsigned long interval, XtTimerCallbackProc proc, XtPointer client_data) ; void Timer(XtPointer client_data, XtIntervalId *id); void Callback(Widget w, XtPointer client_data, XEvent *event, Boolean *ctd); int BreakLoopFlag; private: vtkXRenderWindowInteractor(const vtkXRenderWindowInteractor&); // Not implemented. void operator=(const vtkXRenderWindowInteractor&); // Not implemented. }; #endif
[ "ganondorf@ganondorf-VirtualBox.(none)" ]
[ [ [ 1, 200 ] ] ]
093f0a4b37f72fb50a6cc659b452245b08d35cea
b210a790232ea8ad98d222a857409f0bb6003881
/templates/cpp_source_template.cpp
88274b8caca00ac230febc377176ead762d16fe9
[]
no_license
BackupTheBerlios/madcmd-svn
5712a2f41b9449da03e68b6f6935241ac6859ddd
a9e1e303f83664ab5cd2949949e6a3b15d55872e
refs/heads/master
2016-08-02T23:23:06.481321
2006-08-27T23:54:35
2006-08-27T23:54:35
40,824,366
0
0
null
null
null
null
UTF-8
C++
false
false
965
cpp
// // Copyright (C) 2006 by MadCmd DeveloperTeam // More info at: // http://developer.berlios.de/projects/madcmd // http://madcmd.berlios.de // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the // Free Software Foundation, Inc., // 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "ClassNameh.h"
[ "jjhop@7883ff62-561b-0410-b58a-f87089525366" ]
[ [ [ 1, 22 ] ] ]
978f3b9e50e286041319fe8c3aaaafcb465eea4d
9ef88cf6a334c82c92164c3f8d9f232d07c37fc3
/Source/Input/OISInputManager.cpp
abf7523a8438f8bdb20a3764bca51f385904edee
[]
no_license
Gussoh/bismuthengine
eba4f1d6c2647d4b73d22512405da9d7f4bde88a
4a35e7ae880cebde7c557bd8c8f853a9a96f5c53
refs/heads/master
2016-09-05T11:28:11.194130
2010-01-10T14:09:24
2010-01-10T14:09:24
33,263,368
0
0
null
null
null
null
UTF-8
C++
false
false
1,324
cpp
/** * @file Template.cpp */ #include "stdafx.h" #include "OISInputManager.h" using namespace Bismuth; using namespace Bismuth::Input; OISInputManager::OISInputManager(int windowHandle, int width, int height) { inputManager = OIS::InputManager::createInputSystem(windowHandle); mouse = (OIS::Mouse*)inputManager->createInputObject(OIS::OISMouse, true); keyboard = (OIS::Keyboard*)inputManager->createInputObject(OIS::OISKeyboard, true); const OIS::MouseState &ms = mouse->getMouseState(); ms.width = width; ms.height = height; } OISInputManager::~OISInputManager() { OIS::InputManager::destroyInputSystem(inputManager); } void OISInputManager::update() { mouse->capture(); keyboard->capture(); } Ogre::Vector3 OISInputManager::getRelativeMousePosition() { OIS::MouseState ms = mouse->getMouseState(); return Ogre::Vector3(ms.X.rel, ms.Y.rel, ms.Z.rel); } Ogre::Vector3 OISInputManager::getMousePosition() { OIS::MouseState ms = mouse->getMouseState(); return Ogre::Vector3(ms.X.abs, ms.Y.abs, ms.Z.abs); } bool OISInputManager::isKeyDown(KeyCode keyCode) { return keyboard->isKeyDown(OIS::KeyCode(keyCode)); } bool OISInputManager::isMouseButtonDown(MouseButtonID buttonId) { return mouse->getMouseState().buttonDown((OIS::MouseButtonID)buttonId); }
[ "[email protected]@aefdbfa2-c794-11de-8410-e5b1e99fc78e", "andreas.duchen@aefdbfa2-c794-11de-8410-e5b1e99fc78e" ]
[ [ [ 1, 42 ] ], [ [ 43, 47 ] ] ]
c78ba1572626dea340ae9cc37f92b38e24acea06
a36d7a42310a8351aa0d427fe38b4c6eece305ea
/core_billiard/MyOpenALImp.h
a98c6103e4b5b501a11261a5817991d198b03894
[]
no_license
newpolaris/mybilliard01
ca92888373c97606033c16c84a423de54146386a
dc3b21c63b5bfc762d6b1741b550021b347432e8
refs/heads/master
2020-04-21T06:08:04.412207
2009-09-21T15:18:27
2009-09-21T15:18:27
39,947,400
0
0
null
null
null
null
UTF-8
C++
false
false
1,250
h
#pragma once namespace my_open_al_imp { class MyOpenALImp : IMPLEMENTS_INTERFACE( MyOpenAL ) { public: virtual SoundHandle * createSoundHandle( wstring filename ) OVERRIDE; virtual bool destroySoundHandle( SoundHandle * ) OVERRIDE; public: MyOpenALImp(); ~MyOpenALImp(); private: void setListenerValues(); ALuint * createBufferFromWave( wstring filename ); ALuint * createSource( ALuint * buffer ); void clearErrorLog(); private: ALfloat sourcePos_[3]; ALfloat sourceVel_[3]; ALfloat listenerPos_[3]; ALfloat listenerVel_[3]; ALfloat listenerOri_[6]; private: MY_SMART_PTR( ALuint ); typedef map< wstring, ALuintPtr > Buffers; Buffers buffers_; typedef list< ALuintPtr > Sources; Sources sources_; typedef list< SoundHandlePtr > SoundHandles; SoundHandles soundHandles_; private: static struct BufferDestoryer { void operator()( ALuint * ptr ) { alDeleteBuffers( 1, ptr ); delete ptr; } }; static struct SourceDestoryer { void operator()( ALuint * ptr ) { alDeleteSources( 1, ptr ); delete ptr; } }; }; }
[ "wrice127@af801a76-7f76-11de-8b9f-9be6f49bd635" ]
[ [ [ 1, 56 ] ] ]
9cbc912c46ec5c9d5cc036dda6b9c565d0649e32
c58f258a699cc866ce889dc81af046cf3bff6530
/include/qmlib/ilog.hpp
b219bf3a7da449994b6fb78c1f24666226cb705d
[]
no_license
KoWunnaKo/qmlib
db03e6227d4fff4ad90b19275cc03e35d6d10d0b
b874501b6f9e537035cabe3a19d61eed7196174c
refs/heads/master
2021-05-27T21:59:56.698613
2010-02-18T08:27:51
2010-02-18T08:27:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
703
hpp
#ifndef __ILOG_QM_HPP__ #define __ILOG_QM_HPP__ #include <qmlib/definitions.hpp> QM_NAMESPACE class ilog { public: void info(const qm_string& msg) {m_msg = "Info: " + msg; this->fire();} void critical(const qm_string& msg) {m_msg = "CRITICAL: " + msg; this->fire();} void warning(const qm_string& msg) {m_msg = "Warning: " + msg; this->fire();} void error(const qm_string& msg) {m_msg = "ERROR: " + msg; this->fire();} void debug(const qm_string& msg) {m_msg = "Debug: " + msg; this->fire();} const qm_string& msg() const {return m_msg;} virtual void fire() {} protected: qm_string m_msg; }; QM_NAMESPACE_END #endif // __ILOG_QM_HPP__
[ [ [ 1, 32 ] ] ]
3f93ecf4580df0427eabc95f84bbe9af99f924fd
fd38f7ddcc307fdb03b5d349f723a042358e3a35
/VBLex/Tokens.h
b533127c2043c03e37eb4d99bc6de63719dc557e
[ "MIT" ]
permissive
snaka/VBLex
73d93f060b81f792f6bca2a7a5d4320d3846bdea
ee504b88c9a5f57b0a5003ad2e173e06da152047
refs/heads/master
2020-04-14T05:08:36.152267
2010-06-06T15:37:48
2010-06-06T15:37:48
695,835
2
1
null
null
null
null
SHIFT_JIS
C++
false
false
2,000
h
// Tokens.h : CTokens の宣言 #pragma once #include "resource.h" // メイン シンボル #include <vector> #include "VBLex_i.h" #if defined(_WIN32_WCE) && !defined(_CE_DCOM) && !defined(_CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA) #error "DCOM の完全サポートを含んでいない Windows Mobile プラットフォームのような Windows CE プラットフォームでは、単一スレッド COM オブジェクトは正しくサポートされていません。ATL が単一スレッド COM オブジェクトの作成をサポートすること、およびその単一スレッド COM オブジェクトの実装の使用を許可することを強制するには、_CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA を定義してください。ご使用の rgs ファイルのスレッド モデルは 'Free' に設定されており、DCOM Windows CE 以外のプラットフォームでサポートされる唯一のスレッド モデルと設定されていました。" #endif // CTokens class ATL_NO_VTABLE CTokens : public CComObjectRootEx<CComSingleThreadModel>, public CComCoClass<CTokens, &CLSID_Tokens>, public IDispatchImpl<ITokens, &IID_ITokens, &LIBID_VBLexLib, /*wMajor =*/ 1, /*wMinor =*/ 0> { public: CTokens() { } DECLARE_REGISTRY_RESOURCEID(IDR_TOKENS) BEGIN_COM_MAP(CTokens) COM_INTERFACE_ENTRY(ITokens) COM_INTERFACE_ENTRY(IDispatch) END_COM_MAP() DECLARE_PROTECT_FINAL_CONSTRUCT() HRESULT FinalConstruct() { return S_OK; } void FinalRelease() { // vectorのオブジェクトを開放 std::vector<IToken*>::iterator it; for (it = m_vector.begin(); it != m_vector.end(); it++) (*it)->Release(); } public: STDMETHOD(Item)(VARIANT Index, VARIANT* pItem); STDMETHOD(Add)(IToken* pToken); STDMETHOD(get_Count)(LONG* pVal); STDMETHOD(get__NewEnum)(LPUNKNOWN* pVal); private: std::vector<IToken*> m_vector; }; OBJECT_ENTRY_AUTO(__uuidof(Tokens), CTokens)
[ "snaka@snaka-7.(none)" ]
[ [ [ 1, 65 ] ] ]
9b1339c959c6a597d6a3683d31b9b483fe2891bc
2fe1bab56e0e08499b167f2b4a293e2f16c951a0
/Sim65Main.h
1b929c3dd15d224100ddd5b6e981f086addb712c
[]
no_license
g6ujj/sim6502
24096d523634d8be8717f5e32c56568c04bd33df
9d036bb27815c73c6a52d0577e83422ea43b4b8d
refs/heads/master
2021-01-01T17:28:38.007286
2011-11-26T22:51:07
2011-11-26T22:51:07
2,858,152
0
1
null
null
null
null
UTF-8
C++
false
false
970
h
/*************************************************************** * Name: Sim65Main.h * Purpose: Defines Application Frame * Author: Neil Stoker ([email protected]) * Created: 2011-11-26 * Copyright: Neil Stoker (https://sites.google.com/site/g6ujjcode/) * License: **************************************************************/ #ifndef SIM65MAIN_H #define SIM65MAIN_H #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include "wx/sizer.h" #include "Sim65App.h" class Sim65Frame: public wxFrame { public: Sim65Frame(wxFrame *frame, const wxString& title); ~Sim65Frame(); private: enum { idMenuQuit = 1000, idMenuAbout }; wxFlegGridSizer *fgs; void OnClose(wxCloseEvent& event); void OnQuit(wxCommandEvent& event); void OnAbout(wxCommandEvent& event); DECLARE_EVENT_TABLE() }; #endif // SIM65MAIN_H
[ [ [ 1, 39 ] ] ]
cd3b455dc9fcea5b0b1d0599196cf05578bbd44e
12203ea9fe0801d613bbb2159d4f69cab3c84816
/Export/cpp/windows/obj/src/nme/text/FontStyle.cpp
892b0e60e3f0866f4e430b74a53dd7cf75c22920
[]
no_license
alecmce/haxe_game_of_life
91b5557132043c6e9526254d17fdd9bcea9c5086
35ceb1565e06d12c89481451a7bedbbce20fa871
refs/heads/master
2016-09-16T00:47:24.032302
2011-10-10T12:38:14
2011-10-10T12:38:14
2,547,793
0
0
null
null
null
null
UTF-8
C++
false
false
2,522
cpp
#include <hxcpp.h> #ifndef INCLUDED_nme_text_FontStyle #include <nme/text/FontStyle.h> #endif namespace nme{ namespace text{ ::nme::text::FontStyle FontStyle_obj::BOLD; ::nme::text::FontStyle FontStyle_obj::BOLD_ITALIC; ::nme::text::FontStyle FontStyle_obj::ITALIC; ::nme::text::FontStyle FontStyle_obj::REGULAR; HX_DEFINE_CREATE_ENUM(FontStyle_obj) int FontStyle_obj::__FindIndex(::String inName) { if (inName==HX_CSTRING("BOLD")) return 0; if (inName==HX_CSTRING("BOLD_ITALIC")) return 1; if (inName==HX_CSTRING("ITALIC")) return 2; if (inName==HX_CSTRING("REGULAR")) return 3; return super::__FindIndex(inName); } int FontStyle_obj::__FindArgCount(::String inName) { if (inName==HX_CSTRING("BOLD")) return 0; if (inName==HX_CSTRING("BOLD_ITALIC")) return 0; if (inName==HX_CSTRING("ITALIC")) return 0; if (inName==HX_CSTRING("REGULAR")) return 0; return super::__FindArgCount(inName); } Dynamic FontStyle_obj::__Field(const ::String &inName) { if (inName==HX_CSTRING("BOLD")) return BOLD; if (inName==HX_CSTRING("BOLD_ITALIC")) return BOLD_ITALIC; if (inName==HX_CSTRING("ITALIC")) return ITALIC; if (inName==HX_CSTRING("REGULAR")) return REGULAR; return super::__Field(inName); } static ::String sStaticFields[] = { HX_CSTRING("BOLD"), HX_CSTRING("BOLD_ITALIC"), HX_CSTRING("ITALIC"), HX_CSTRING("REGULAR"), ::String(null()) }; static void sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(FontStyle_obj::BOLD,"BOLD"); HX_MARK_MEMBER_NAME(FontStyle_obj::BOLD_ITALIC,"BOLD_ITALIC"); HX_MARK_MEMBER_NAME(FontStyle_obj::ITALIC,"ITALIC"); HX_MARK_MEMBER_NAME(FontStyle_obj::REGULAR,"REGULAR"); }; static ::String sMemberFields[] = { ::String(null()) }; Class FontStyle_obj::__mClass; Dynamic __Create_FontStyle_obj() { return new FontStyle_obj; } void FontStyle_obj::__register() { Static(__mClass) = hx::RegisterClass(HX_CSTRING("nme.text.FontStyle"), hx::TCanCast< FontStyle_obj >,sStaticFields,sMemberFields, &__Create_FontStyle_obj, &__Create, &super::__SGetClass(), &CreateFontStyle_obj, sMarkStatics); } void FontStyle_obj::__boot() { Static(BOLD) = hx::CreateEnum< FontStyle_obj >(HX_CSTRING("BOLD"),0); Static(BOLD_ITALIC) = hx::CreateEnum< FontStyle_obj >(HX_CSTRING("BOLD_ITALIC"),1); Static(ITALIC) = hx::CreateEnum< FontStyle_obj >(HX_CSTRING("ITALIC"),2); Static(REGULAR) = hx::CreateEnum< FontStyle_obj >(HX_CSTRING("REGULAR"),3); } } // end namespace nme } // end namespace text
[ [ [ 1, 83 ] ] ]
a6cc86c30a2ebf878e587103d7d2466ef4e04d28
3eae1d8c99d08bca129aceb7c2269bd70e106ff0
/trunk/Codes/DeviceCode/Drivers/FS/FAT/FAT_FS.cpp
7bb0ed3e31018cc24310f191d69f727b37a9bf1d
[]
no_license
yuaom/miniclr
9bfd263e96b0d418f6f6ba08cfe4c7e2a8854082
4d41d3d5fb0feb572f28cf71e0ba02acb9b95dc1
refs/heads/master
2023-06-07T09:10:33.703929
2010-12-27T14:41:18
2010-12-27T14:41:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,299
cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "tinyhal.h" #include "FAT_FS.h" #include "FAT_FS_Utility.h" #include "TinyCLR_Interop.h" //--// //////////////////////////////////////////////////////////////////////////////////////////////////// // // FAT_MBR member function // //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL FAT_MBR::IsValid() { return (EndingFlag == 0xaa55) && (Partitions[0].BootIndicator == 0x00 || Partitions[0].BootIndicator == 0x80) && (Partitions[0].Get_RelativeSector() > 0) && (Partitions[0].Get_TotalSector() > 0); } //////////////////////////////////////////////////////////////////////////////////////////////////// // // FAT_DBR member function // //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL FAT_DBR::IsValid( BOOL* isFAT16 ) { if(!(//check DBR end flag--0x55 AA (EndingFlag == 0xaa55) && //check jump instruction at DBR beginning (BS_JmpBoot[0] == 0xeb || BS_JmpBoot[0] == 0xe9) && //now only support FAT FS with 512 bytes per sector (Get_BPB_BytsPerSec() == 512) && // Check for SecPerClus, legal values are 1, 2, 4, 8, 16, 32, 64, and 128 (BPB_SecPerClus != 0 && ((BPB_SecPerClus - 1) & BPB_SecPerClus) == 0) && // Rerserved sector count must be at least 1 (32 typically) (BPB_RsvdSecCnt > 0) && // now only supprt FAT FS with 2 FATs (BPB_NumFATs == 2))) { return FALSE; } UINT32 countOfClusters = GetCountOfClusters(); if(countOfClusters < 4085) { // FAT12, not supported return FALSE; } else if(countOfClusters < 65525) { // FAT16 *isFAT16 = TRUE; return ( // now only support FAT16 FS with 512 RootEntCnt (Get_BPB_RootEntCnt() == 512) && // FATSz16 needs to be greater than 0 for FAT16 (BPB_FATSz16 > 0) && // One of TotSec16 or TotSec32 needs to be 0 for FAT16 (Get_BPB_TotSec16() == 0 || BPB_TotSec32 == 0) ); } else { // FAT32 *isFAT16 = FALSE; return ( // RootEntCnt needs to be 0 for FAT32 (Get_BPB_RootEntCnt() == 0) && // TotSec16 needs to be 0 for FAT32 (Get_BPB_TotSec16() == 0) && // FATSz16 needs to be 0 for FAT32 (BPB_FATSz16 == 0) && // TotSec32 must be greater than 0 (BPB_TotSec32 > 0) && // FATSz32 must be greater than 0 (DBRUnion.FAT32.BPB_FATSz32 > 0) ); } } //////////////////////////////////////////////////////////////////////////////////////////////////// // // FAT_FSINFO member function // //////////////////////////////////////////////////////////////////////////////////////////////////// void FAT_FSINFO::Initialize( UINT32 freeCount, UINT32 nxtFree ) { memset( this, 0, sizeof(FAT_FSINFO) ); FSI_LeadSig = 0x41615252; FSI_StrucSig = 0x61417272; FSI_Free_Count = freeCount; FSI_Nxt_free = nxtFree; FSI_TrailSig = 0xAA550000; } BOOL FAT_FSINFO::IsValid() { return( (FSI_LeadSig == 0x41615252) && (FSI_StrucSig == 0x61417272) && (FSI_TrailSig == 0xAA550000) ); } //////////////////////////////////////////////////////////////////////////////////////////////////// // // FAT_Directory member function // //////////////////////////////////////////////////////////////////////////////////////////////////// void FAT_Directory::Initialize() { memset( this, 0, sizeof(FAT_Directory) ); } void FAT_Directory::SetName( LPCWSTR name, UINT32 nameLen ) { char c; int j; // Copy the base name for(j = 0; j < SHORTNAME_SIZE && nameLen > 0; j++) { c = (char)(*name); name++; nameLen--; // stop if we see the "." if(c == '.') break; if(j == 0 && c == 0xE5) c = 0x05; DIR_Name[j] = c; } // Fill the rest of the base name with blanks for(; j < SHORTNAME_SIZE; j++) { DIR_Name[j] = WHITESPACE_CHAR; } // Only copy the extension if there is one if(nameLen > 0) { // skip the '.' if we haven't already if(*name == '.') name++; // Copy the extension for(; j < SHORTNAME_FULL_SIZE && nameLen > 0; j++) { c = (char)(*name); name++; nameLen--; DIR_Name[j] = c; } } // Fill the rest of the extension with blanks for(; j < SHORTNAME_FULL_SIZE; j++) { DIR_Name[j] = WHITESPACE_CHAR; } } BOOL FAT_Directory::IsName( LPCWSTR name, UINT32 nameLen ) { char c; int j; // Compare the base name for(j = 0; j < SHORTNAME_SIZE && nameLen > 0; j++) { c = (char)(*name); name++; nameLen--; // stop if we see the "." if(c == '.') break; if(c >= 'a' && c <= 'z') c -= 'a' - 'A'; else if(j == 0 && c == 0xE5) c = 0x05; if(DIR_Name[j] != c) return FALSE; } // the rest of the base name has to be blanks for(; j < 8; j++) { if(DIR_Name[j] != WHITESPACE_CHAR) return FALSE; } // Only compare the extension if there is one if(nameLen > 0) { // skip the '.' if we haven't already if(*name == '.') name++; // Compare the extension for(; j < SHORTNAME_FULL_SIZE && nameLen > 0; j++) { c = (char)(*name); name++; nameLen--; if(c >= 'a' && c <= 'z') c -= 'a' - 'A'; if(DIR_Name[j] != c) return FALSE; } } // the rest of the extension has to be blanks for(; j < 11; j++) { if(DIR_Name[j] != WHITESPACE_CHAR) return FALSE; } return TRUE; } void FAT_Directory::CopyName( WCHAR* name ) { int j; // Copy the base name for(j = 0; j < 8; j++) { if(DIR_Name[j] == WHITESPACE_CHAR) break; *name = (j == 0 && DIR_Name[j] == 0x05) ? 0xE5 : DIR_Name[j]; name++; } // Only add the dot if there's an extension if(DIR_Name[8] != WHITESPACE_CHAR) { *name = '.'; name++; } // Copy the extension for(j = 8; j < 11; j++) { if(DIR_Name[j] == WHITESPACE_CHAR) break; *name = DIR_Name[j]; name++; } // Terminate the string *name = 0; } UINT32 FAT_Directory::GetNameLength() { int j; UINT32 len = 0; // Count the base name for(j = 0; j < 8; j++) { if(DIR_Name[j] == WHITESPACE_CHAR) break; len++; } // Only add the dot if there's an extension if(DIR_Name[8] != WHITESPACE_CHAR) { len++; } // Count the extension for(j = 8; j < 11; j++) { if(DIR_Name[j] == WHITESPACE_CHAR) break; len++; } return len; } //////////////////////////////////////////////////////////////////////////////////////////////////// // // FAT_LONG_Directory member function // //////////////////////////////////////////////////////////////////////////////////////////////////// void FAT_LONG_Directory::Initialize( BYTE ord, LPCWSTR name, UINT32 nameLen, BYTE chksum ) { LDIR_Ord = ord; LDIR_Chksum = chksum; LDIR_Attr = ATTR_LONG_NAME; LDIR_Type = 0; LDIR_FstClusLO = 0; SetName( name, nameLen ); } void FAT_LONG_Directory::SetName( LPCWSTR name, UINT32 nameLen ) { WCHAR tempName[13]; if(nameLen < 13) { int i; for(i = 0; i < nameLen; i++) { tempName[i] = name[i]; } tempName[i] = 0; i++; for(; i < 13; i++) { tempName[i] = 0xFFFF; } name = tempName; } int j; for(j = 0; j < LDIR_Name1__size; j += 2) { // LDIR_Name1 is in BYTEs because it's not UINT16 aligned LDIR_Name1[j ] = (BYTE)(*name & 0xFF); LDIR_Name1[j+1] = (BYTE)(*name >> 8); name++; } for(j = 0; j < LDIR_Name2__size / sizeof(UINT16); j++) { LDIR_Name2[j] = *name; name++; } for(j = 0; j < LDIR_Name3__size / sizeof(UINT16); j++) { LDIR_Name3[j] = *name; name++; } } BOOL FAT_LONG_Directory::IsName( LPCWSTR name, UINT32 nameLen ) { int j; WCHAR c; for(j = 0; j < LDIR_Name1__size; j += 2) { // LDIR_Name1 is in BYTEs because it's not UINT16 aligned c = ((UINT16)LDIR_Name1[j]) | ((UINT16)LDIR_Name1[j+1]) << 8; if(c == 0 && nameLen == 0) { return TRUE; } else if(nameLen == 0 || MF_towupper( c ) != MF_towupper( *name )) { return FALSE; } name++; nameLen--; } for(j = 0; j < LDIR_Name2__size / sizeof(UINT16); j++) { if(LDIR_Name2[j] == 0 && nameLen == 0) { return TRUE; } else if(nameLen == 0 || MF_towupper( LDIR_Name2[j] ) != MF_towupper( *name )) { return FALSE; } name++; nameLen--; } for(j = 0; j < LDIR_Name3__size / sizeof(UINT16); j++) { if(LDIR_Name3[j] == 0 && nameLen == 0) { return TRUE; } else if(nameLen == 0 || MF_towupper( LDIR_Name3[j] ) != MF_towupper( *name )) { return FALSE; } name++; nameLen--; } return TRUE; } void FAT_LONG_Directory::CopyName( WCHAR* name ) { int j; for(j = 0; j < LDIR_Name1__size; j += 2) { // LDIR_Name1 is in BYTEs because it's not UINT16 aligned *name = ((UINT16)LDIR_Name1[j]) | (((UINT16)LDIR_Name1[j+1]) << 8); if(*name == 0) { return; } name++; } for(j = 0; j < LDIR_Name2__size / sizeof(UINT16); j++) { *name = LDIR_Name2[j]; if(*name == 0) { return; } name++; } for(j = 0; j < LDIR_Name3__size / sizeof(UINT16); j++) { *name = LDIR_Name3[j]; if(*name == 0) { return; } name++; } } UINT32 FAT_LONG_Directory::GetNameLength() { int j; UINT32 len = 0; for(j = 0; j < LDIR_Name1__size; j += 2) { if(LDIR_Name1[j] == 0 && LDIR_Name1[j+1] == 0) { return len; } len++; } for(j = 0; j < LDIR_Name2__size / sizeof(UINT16); j++) { if(LDIR_Name2[j] == 0) { return len; } len++; } for(j = 0; j < LDIR_Name3__size / sizeof(UINT16); j++) { if(LDIR_Name3[j] == 0) { return len; } len++; } return len; } //--// FAT_FINDFILES* FAT_FINDFILES::FindOpen( FAT_LogicDisk* logicDisk, UINT32 clusIndex ) { FAT_FINDFILES* findFiles = (FAT_FINDFILES*)FAT_MemoryManager::AllocateHandle(); if(findFiles == NULL) return NULL; findFiles->m_entryEnum.Initialize( logicDisk, logicDisk->ClusToSect( clusIndex ), 0 ); findFiles->m_logicDisk = logicDisk; return findFiles; } HRESULT FAT_FINDFILES::FindNext( FS_FILEINFO *fi, BOOL *fileFound ) { TINYCLR_HEADER(); FAT_FILE fileInfo; FAT_Directory* dirEntry; if(!fi || !fileFound) { TINYCLR_SET_AND_LEAVE(CLR_E_FILE_IO); } do { if(fileInfo.Parse( m_logicDisk, &m_entryEnum ) != S_OK) { *fileFound = FALSE; TINYCLR_SET_AND_LEAVE(S_OK); } dirEntry = fileInfo.GetDirectoryEntry(); if(!dirEntry) TINYCLR_SET_AND_LEAVE(CLR_E_FILE_IO); } while(dirEntry->DIR_Name[0] == '.' || dirEntry->DIR_Attr == ATTR_VOLUME_ID); // Skip the "." and ".." and the Volume_ID entries fi->Attributes = dirEntry->DIR_Attr; fi->Size = dirEntry->DIR_FileSize; fi->CreationTime = FAT_Utility::FATTimeToTicks( dirEntry->DIR_CrtDate , dirEntry->DIR_CrtTime, dirEntry->DIR_CrtTimeTenth ); fi->LastAccessTime = FAT_Utility::FATTimeToTicks( dirEntry->DIR_LstAccDate, 0 , 0 ); fi->LastWriteTime = FAT_Utility::FATTimeToTicks( dirEntry->DIR_WrtDate , dirEntry->DIR_WrtTime, 0 ); TINYCLR_CHECK_HRESULT(fileInfo.CopyFileName( (LPWSTR)(fi->FileName), fi->FileNameSize )); *fileFound = TRUE; TINYCLR_NOCLEANUP(); } HRESULT FAT_FINDFILES::FindClose() { FAT_MemoryManager::FreeHandle( this ); return S_OK; } //--// void FAT_EntryEnumerator::Initialize( FAT_LogicDisk* logicDisk, UINT32 sectIndex, UINT32 dataIndex, BOOL extend ) { m_logicDisk = logicDisk; m_clusIndex = logicDisk->SectToClus( sectIndex ); m_sectIndex = sectIndex; m_dataIndex = dataIndex; m_flag = Flag_First; if(extend) m_flag |= Flag_Extend; } FAT_Directory* FAT_EntryEnumerator::GetNext( BOOL forWrite ) { if((m_flag & Flag_First) == Flag_First) { m_flag &= ~Flag_First; } else if((m_flag & Flag_Done) == Flag_Done) { return NULL; } else { //move to next dir_entry position m_dataIndex += sizeof(FAT_Directory); if(m_dataIndex >= m_logicDisk->m_bytesPerSector) { UINT32 flags = (m_flag & Flag_Extend) ? FAT_LogicDisk::GetNextSect__CREATE | FAT_LogicDisk::GetNextSect__CLEAR : FAT_LogicDisk::GetNextSect__NONE; if(m_logicDisk->GetNextSect( &m_clusIndex, &m_sectIndex, flags ) != S_OK) { m_flag |= Flag_Done; return NULL; } m_dataIndex = 0; } } return (FAT_Directory*)(&(m_logicDisk->SectorCache.GetSector( m_sectIndex, forWrite ))[m_dataIndex]); } void FAT_EntryEnumerator::GetIndices( UINT32* sectIndex, UINT32* dataIndex ) { *sectIndex = m_sectIndex; *dataIndex = m_dataIndex; }
[ [ [ 1, 607 ] ] ]
10c6e14fb301acb98e5d7c93a20503a3d2655956
8ade67ab53907d22e40286b377b86d1b1eeaf6f0
/tabu/phf/check.h
e807c5ef7de6096d812f87b6575c7b31f6fbb9ba
[]
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
1,464
h
#pragma once #include <vector> #include "../arrays/intsymbol.h" namespace phf { template <class Symbol> class phf_Check { public: phf_Check() { } inline bool good( const Symbol * slice, int size ) { for ( int i = 0; i < (size - 1); i++ ) { for ( int j = i+1; j < size; j++ ) { if ( slice[i] == slice[j] ) { return false; } } } return true; } inline bool good( const std::vector<Symbol> & slice ) { int size = (int) slice.size(); for ( int i = 0; i < (size - 1); i++ ) { for ( int j = i+1; j < size; j++ ) { if ( slice[i] == slice[j] ) { return false; } } } return true; } }; template <> class phf_Check<arrays::int_Symbol> { public: phf_Check() { } inline bool good( const arrays::int_Symbol * slice, int size ) { int val; for ( int i = 0; i < (size - 1); i++ ) { val = slice[i].value; for ( int j = i+1; j < size; j++ ) { if ( val == slice[j].value ) { return false; } } } return true; } inline bool good( const std::vector<arrays::int_Symbol> & slice ) { int size = (int) slice.size(); int val; for ( int i = 0; i < (size - 1); i++ ) { val = slice[i].value; for ( int j = i+1; j < size; j++ ) { if ( val == slice[j].value ) { return false; } } } return true; } }; };
[ [ [ 1, 72 ] ] ]
52b5229b910f3e52059df2360c999073e9bf6903
f429bb939d1f5d08cdf7545fac45564065481d96
/DLLSrc/GetPrinterDriver/StdAfx.cpp
f9803e7b74d9fc65156a7a1e3b7bc47bee010151
[]
no_license
vinhnguyenhoan/swt-printdialog-extension
dbc7e8b19bab2766601cba21239c300cb0e33e89
56166f97fa6a735ae8871fd185f71261febf3561
refs/heads/master
2021-01-21T22:55:29.666226
2010-06-01T12:37:09
2010-06-01T12:37:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
218
cpp
// stdafx.cpp : source file that includes just the standard includes // GetPrinterDriver.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
[ "huangjun78@22bbe126-0c1a-11de-a6c4-5ba5c67cbe75" ]
[ [ [ 1, 8 ] ] ]
f6022a8792b146b77005edb52fcfff640d25b06b
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/addons/pa/ParticleUniverse/include/ParticleUniverseNoise.h
388beefba23d5a4a4b222a6ea4bded532cc168f9
[]
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,897
h
/* ----------------------------------------------------------------------------------------------- This source file is part of the Particle Universe product. Copyright (c) 2010 Henry van Merode The Noise algorithm however is based on the Improved Noise reference implementation by Ken Perlin (copyright by Ken Perlin (c) 2002) Usage of this program is licensed under the terms of the Particle Universe Commercial License. You can find a copy of the Commercial License in the Particle Universe package. ----------------------------------------------------------------------------------------------- */ #ifndef __PU_NOISE_H__ #define __PU_NOISE_H__ #include "ParticleUniversePrerequisites.h" namespace ParticleUniverse { class _ParticleUniverseExport Noise3D { public: /* Constructor / Destructor */ Noise3D(void); virtual ~Noise3D(void); /* Inititialises the noise function */ void initialise(Ogre::ushort octaves, double frequency = 1.0, double amplitude = 1.0, double persistence = 1.0); /* Returns a noise value between [0, 1] @remarks The noise is calculated in realtime */ double noise(double x, double y, double z); /* Returns a noise value between [0, 1] @remarks The noise is calculated in realtime */ double noise(const Ogre::Vector3& position); /* Creates an image file to test the noise */ void noise2img(Ogre::ushort dimension = 255); protected: int p[512]; Ogre::ushort mOctaves; double mFrequency; double mAmplitude; double mPersistence; /* Returns a noise value between [0, 1] @remarks The noise is calculated in realtime */ double _noise(double x, double y, double z); double _fade(double t); double _lerp(double t, double a, double b); double _grad(int hash, double x, double y, double z); }; } #endif
[ [ [ 1, 65 ] ] ]
f982748913d782a1bac0d250c37e8280b6dcd500
b47e38256ce41d17fa8cbc7cbb46f8c4394b1e79
/BQhistory.cpp
ca5fa800416d2411ccdadd3535d03a7acc86121f
[]
no_license
timothyha/ppc-bq
b54162c6e117d6df9849054e75bc7da06d630c1a
144c3a00bd130fc34831f530e2c7207edaa8ee7e
refs/heads/master
2020-05-16T14:25:31.426285
2010-09-04T06:03:47
2010-09-04T06:03:47
32,114,289
0
0
null
null
null
null
UTF-8
C++
false
false
560
cpp
#include "BQhistory.h" int BQhistory::load(CString file){ return 0; } int BQhistory::save(int depth){ return 0; } int BQhistory::back(void){ if(position>0)position--; return 0; } int BQhistory::forward(void){ if(position<count)position++; return 0; } int BQhistory::insert(const char*mod, int bk, int ch, int scr){ if(position+1>limit){ // shift } if(position+1>allocated){ // add 10 } if(position+1<count){ list[count] = new BQposition(); list[count++]->set(mod, bk, ch, scr); } position++; return true; }
[ "nuh.ubf@e3e9064e-3af0-11de-9146-fdf1833cc731" ]
[ [ [ 1, 30 ] ] ]
c8ffe62b38b5cc6deb6610cbf3aaeb8b13ff8615
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/SMDK/TransCritical/TTechQAL/QALPrecip.cpp
8067238acc2fa7e9abadb53b255f8ecbb0082808
[]
no_license
abcweizhuo/Test3
0f3379e528a543c0d43aad09489b2444a2e0f86d
128a4edcf9a93d36a45e5585b70dee75e4502db4
refs/heads/master
2021-01-17T01:59:39.357645
2008-08-20T00:00:29
2008-08-20T00:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
38,569
cpp
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // QAL Classifier Model 2004 - Transcritical Technologies/ QAL // Time-stamp: <2007-05-22 23:24:35 Rod Stephenson Transcritical Pty Ltd> // Copyright (C) 2005 by Transcritical Technologies Pty Ltd and KWA // $Nokeywords: $ //=========================================================================== #include "stdafx.h" #define __QALPRECIP_CPP #include "qalprecip.h" static MInitialiseTest InitTest("Precip"); //static MSpeciePtr spAlumina (InitTest, "NaAl[OH]4(l)", false); //static MSpeciePtr spTHA (InitTest, "Al[OH]3(s)", false); static MAqSpeciePtr spAlumina (InitTest, "NaAl[OH]4(l)", false); static MSpeciePtr spWater (InitTest, "H2O(l)", false); static MSpeciePtr spWaterVapor (InitTest, "H2O(g)", false); static MSpeciePtr spTHA (InitTest, "Al[OH]3(s)", false); static MAqSpeciePtr spCausticSoda (InitTest, "NaOH(l)", false); static MSpeciePtr spOccSoda (InitTest, "Na2O(s)", false); static MAqSpeciePtr spCarbonate (InitTest, "Na2CO3(l)", false); static MSpeciePtr spBoundSoda (InitTest, "NaOH*(s)", false); static MSpeciePtr spOrganics (InitTest, "Na2C5.2O7.2(l)", false); static MSpeciePtr spBoundOrganics (InitTest, "Na2C5.2O7.2*(s)", false); static MSpeciePtr spOxalate (InitTest, "Na2C2O4(s)", false); enum PrecipMethod {GRM_Fixed, GRM_White, GRM_CAR_QAL, GRM_TTTest}; enum CoolType{COOL_dQ, COOL_dT, COOL_Hx}; enum EvapType{EVAP_NONE, EVAP_FIXED, EVAP_dT}; enum ICool{COOL_NONE, COOL_INTERNAL, COOL_EXTERNAL}; enum PrecipComponents {iALUMINA, iOCC_SODA, iBOUND_ORGANICS, iWATER, nPRECIPCOMPS}; enum {GRM_AAEq, GRM_sigma}; enum {PB_None, PB_SSA, PB_PSD}; // Particle balance model enum {idFeed, idUflow, idOflow}; enum ThermalHeatLossMethods {THL_None, THL_TempDrop, THL_FixedHeatFlow, THL_Ambient, THL_FixedTemp}; /// Utility Class for heat exchanger static double LMTD(double TbTi, double TbTo, double ShTi, double ShTo) { double gttd = ShTo - TbTi; double lttd = ShTi - TbTo; return (gttd==lttd) ? gttd : (gttd-lttd)/log(GTZ(fabs(gttd))/(GTZ(fabs(lttd)))); } class CCoolerFn : public MRootFinder { public: CCoolerFn(double _UA, MStream &TubeI, MStream &ShellI, MStream &TubeO, MStream &ShellO) : MRootFinder("Basic Hx calc" ,s_Tol), UA(_UA), m_TubeI(TubeI), m_ShellI(ShellI), m_TubeO(TubeO), m_ShellO(ShellO) { } double Function(double TubeTOut) { double q = m_TubeI.totHz(MP_All, TubeTOut)-m_TubeI.totHz(MP_All); m_TubeO.Set_totHz(m_TubeI.totHz()+q); m_ShellO.Set_totHz(m_ShellI.totHz()-q); double lmtd=LMTD(m_TubeI.T, TubeTOut, m_ShellI.T , m_ShellO.T); double qp = UA*lmtd; return q-qp; }; public: MStream &m_TubeI; MStream &m_ShellI; MStream &m_TubeO; MStream &m_ShellO; // double Duty; double UA; static MToleranceBlock s_Tol; }; MToleranceBlock CCoolerFn::s_Tol(TBF_Both, "Precip:Simple", 0.00005, 0, 100); static MInOutDefStruct s_IODefs[]= { { "Feed", "Feed", idFeed, 1, 10, 0, 1.0f, MIO_In |MIO_Material }, { "Underflow", "UFlow", idUflow, 1, 1, 0, 1.0f, MIO_Out|MIO_Material }, { "Overflow", "OFlow", idOflow, 0, 1, 1, 1.0f, MIO_Out|MIO_Material }, { NULL }, }; double Drw_CPrecipitator[] = { MDrw_Poly, -5,10, -5,-10, 5,-10, 5,10, MDrw_End }; //--------------------------------------------------------------------------- DEFINE_TRANSFER_UNIT(CPrecipitator, "Precipitator", DLL_GroupName) void CPrecipitator_UnitDef::GetOptions() { SetDefaultTag("PC"); SetDrawing("Tank", Drw_CPrecipitator); SetTreeDescription("QAL:Precipitator"); SetDescription("TODO: QAL PB Model"); SetModelSolveMode(MSolveMode_All); SetModelGroup(MGroup_Alumina); SetModelLicense(MLicense_HeatExchange|MLicense_Alumina); }; //--------------------------------------------------------------------------- double calcVol(double *N) { double v = 0.0; for (int i=0; i<nClasses; i++) { v += pow(D[i], 3)*N[i]; } return v; } CPrecipitator::CPrecipitator(MUnitDefBase *pUnitDef, TaggedObject * pNd) : MBaseMethod(pUnitDef, pNd) { //default values... m_bEvapConnected = 0; bKernelOK = false; bOnLine = 1; dTempDropRqd = 0.5; dFixedTempRqd = C2K(70); dThermalLossRqd = 1500.0; iThermalLossMethod = THL_TempDrop; iCoolMethod=0; dTankVol = 3000; dAggMinLim = .5; iPSD=0; dSolPrecip = 0.0; dGrowthRate = 0.0; dGrowthRateFactor = 0.0; dYield = 0.0; dTin = C2K(25.0); dTout = C2K(25.0); dDiamin = 0.0; dSALin = 0.0; dQvin = 0.0; dQvout = 0.0; dACin = 0.0; dACout = 0.0; dResidenceTime = 0.0; dThermalLoss = 0.0; dReactionHeat = 0.0; m_dCoolOutTotHz = 0.0; dtact = 0.5; m_ddeltaT = 1.; ER_White = 7200.0; K_White = 1.96e9; gF_White = 1.0; m_dSurfaceAct = 1.0; m_dSodaConst = 9e-3; dGrowthRateFactor = 1.0; dAgglRateFactor = 1.0; dNuclRateFactor = 1.0; m_dConvergenceLimit = 1.0e-6; alreadySolved = false; m_lItermax = 1000; } //--------------------------------------------------------------------------- CPrecipitator::~CPrecipitator() { // delete[] x; // delete[] xo; } bool CPrecipitator::ValidateDataFields() {//ensure parameters are within expected ranges return true; } //--------------------------------------------------------------------------- void CPrecipitator::Init() { SetIODefinition(s_IODefs); #ifdef TTDEBUG dbg.tcltk_init(); #endif } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- // Modified for NaAl[OH]4 as primary species. void CPrecipitator::AdjustMasses(MStream & Prod) { const double &InAluminaMass = Feed.MassVector[spAlumina]; // NaAl[OH]4(l) const double &InWaterMass = Feed.MassVector[spWater]; // H2O const double &InTHAMass = Feed.MassVector[spTHA]; // NaAl[OH]3(s) const double &InCausticMass = Feed.MassVector[spCausticSoda]; // NaOH const double &InBoundSodaMass = Feed.MassVector[spBoundSoda]; const double &InOrganicMass = Feed.MassVector[spOrganics]; const double &InBoundOrganicMass = Feed.MassVector[spBoundOrganics]; MVDouble AluminaMass (Prod,spAlumina); // NaAl[OH]4(l) MVDouble WaterMass (Prod,spWater); // H2O MVDouble THAMass (Prod,spTHA); // NaAl[OH]3(s) MVDouble CausticMass (Prod,spCausticSoda); // NaOH MVDouble BoundSodaMass (Prod,spBoundSoda); MVDouble OrganicMass (Prod,spOrganics); MVDouble BoundOrganicMass (Prod,spBoundOrganics); if (m_dMassDamping>0.0) { // Mass damping terms... may only be needed at very high rates for (int i=0; i<nPRECIPCOMPS; i++) x[i] = xo[i]*m_dMassDamping+x[i]*(1-m_dMassDamping); } /// // adjust masses... x is mass of precipitated Gibbsite AluminaMass = InAluminaMass - Alpha*x[iALUMINA]; THAMass = InTHAMass + x[iALUMINA]; CausticMass = InCausticMass + x[iALUMINA]*(Alpha-1) - x[iOCC_SODA]; OrganicMass = InOrganicMass - x[iBOUND_ORGANICS]; BoundOrganicMass = InBoundOrganicMass + x[iBOUND_ORGANICS]; BoundSodaMass = InBoundSodaMass + x[iOCC_SODA]; WaterMass = InWaterMass - x[3]; // Water is only lost through evaporation // if (m_bUpdateT) Prod.MarkStateChanged(); // Manual fixup of heat loads eventually... } void CPrecipitator::AdjustT(MStream &Prod) { double dHeatIn = Feed.totHz(); dReactionHeat = x[iALUMINA]*GibbsiteHOR(K2C(Prod.T)); double newTotDH = m_dOldTotDH*m_dDamping+(m_dTotThermalLoss-dReactionHeat)*(1-m_dDamping); if (iThermalLossMethod == THL_TempDrop) Tank.T = Feed.T - dTempDropRqd; else if (iThermalLossMethod == THL_FixedTemp) Tank.T = dFixedTempRqd; else Tank.Set_totHz(dHeatIn - newTotDH); m_dOldTotDH = newTotDH; } void CPrecipitator::AdjustSSA(MStream &Prod) { } //--------------------------------------------------------------------------- // All the precipitation rate calcs are done in this routine // Takes the product composition and calculates rates from this // Rates (in kg/s) are put into global x //--------------------------------------------------------------------------- void CPrecipitator::EvalPrecipRates(MStream & Prod, double T) { PBRates(); double deltaT = m_ddeltaT; for (int i=0; i<nClasses; i++) { if (Ndot[i] < 0) { double dtm = -n[i]*(1.0 - 0.7)/Ndot[i]; if (dtm < deltaT) deltaT = dtm; } } double sumar = 0.0, sumv = 0.0, sumn = 0.0; for (int i=0; i<nClasses; i++) { NewN[i] = n[i] + Ndot[i]*deltaT; double dd = D[i]; double dd2 = dd*dd; double dd3=dd2*dd; sumar+= dd2*NewN[i]; sumv += dd3*NewN[i]; sumn += NewN[i]; } double newVol = PI/6*sumv*DIST_CORR*1.0e-18; xo[0] = x[0]; xo[1]=x[1]; xo[2]=x[2]; xo[3]=x[3]; m_dSolidsOut = newVol*Tank.Mass()*2420; //Tank.Density(MP_Sol); x[iALUMINA] = (m_dSolidsOut-m_dSolidsIn); // Precipitation is as trihydrate x[iBOUND_ORGANICS]=0.; //x[iOCC_SODA]=x[iALUMINA]*dSoda/100.; //x[iOCC_SODA] = 0; //x[iALUMINA] -= x[iOCC_SODA]; x[iWATER]= 0.0; } //--------------------------------------------------------------------------- // All the thermal loss calcs are done in this routine // Also calculate the water loss through evaporation // m_dTotThermalLoss is the total thermal loss, //--------------------------------------------------------------------------- void CPrecipitator::EvalLosses(MStream & Prod) { double T = Prod.T; double TA = AmbientTemp(); /// Heat Loss to internal cooling, eg Barriquands if (!m_bCoolerOn && iCoolMethod==COOL_Hx) { m_dLiquorTout = Prod.T; m_dLMTD = 0.0; m_dCoolWaterTout = CoolIn.T; } m_dIntCoolRate=0.0; if (m_bCoolerOn && iCoolType==COOL_INTERNAL && bCoolIn && iCoolMethod == COOL_Hx ) { MStreamI TubeIn; MStreamI TubeOut; MStreamI CoolOut; if (m_bByVolFlow) m_dCoolFlow = m_dIntCoolVolFlow*Prod.Density(); else m_dIntCoolVolFlow = m_dCoolFlow/Prod.Density(); TubeIn.SetM(Prod, MP_All, m_dCoolFlow); TubeOut.SetF(TubeIn, MP_All, 1.0); CoolOut.SetF(CoolIn, MP_All, 1.0); if (TubeIn.MassFlow()>0 && CoolIn.MassFlow()>0) { m_dUA=m_dCoolArea*m_dCoolHTC; CCoolerFn Fn(m_dUA, TubeIn, CoolIn, TubeOut, CoolOut); double TubeOutT; double MxTbOutT=TubeIn.T;// No Transfer double MnTbOutT=CoolIn.T+0.001; double qShell=-CoolIn.totHz()+CoolOut.totHz(MP_All, TubeIn.T); double qTube= -TubeIn.totHz(MP_All, CoolIn.T)+TubeIn.totHz(); if (qShell<qTube) // Limited By Shell - Tube TOut Limited MnTbOutT=MxTbOutT - (qShell)/GTZ(qTube)*(MxTbOutT-MnTbOutT); switch (Fn.FindRoot(0, MnTbOutT, MxTbOutT)) { case RF_OK: TubeOutT = Fn.Result(); break; case RF_LoLimit: TubeOutT = MnTbOutT; break; case RF_HiLimit: TubeOutT = MxTbOutT; break; default: Log.Message(MMsg_Error, "TubeOutT not found - RootFinder:%s", Fn.ResultString(Fn.Error())); TubeOutT=Fn.Result(); break; } TubeOut.T = TubeOutT; m_dIntCoolRate = TubeIn.totHz() - TubeOut.totHz(); m_dCoolWaterTout = CoolOut.T; m_dCoolWaterTin = CoolIn.T; m_dCoolWaterFlow = CoolIn.Mass(); m_dCoolWaterFlowVol = CoolIn.Volume(); m_dLiquorTout = TubeOut.T; m_dLMTD=fabs(LMTD(TubeIn.T, TubeOut.T, CoolIn.T, CoolOut.T)); } } if (iCoolType==COOL_INTERNAL && iCoolMethod == COOL_dQ ) { m_dIntCoolRate = m_dCooldQ; } switch (iCoolType) { case COOL_NONE: m_dCoolRate = 0; break; case COOL_EXTERNAL: m_dCoolRate = m_dExtCoolRate; // kW break; case COOL_INTERNAL: /// Heat Loss to internal cooling, eg draft tube coolers m_dCoolRate = m_dIntCoolRate; break; } /// Evaporation Rate switch (iEvapMethod) { case EVAP_dT: m_dEvapRate = m_dEvapRateK*(T-TA); // kg/s x[3] = m_dEvapRate; break; case EVAP_FIXED: x[3] = m_dEvapRate; break; case EVAP_NONE: x[3] = 0; m_dEvapRate = 0.0; } /// Evaporative Heat Loss ... need to fix this up using stream enthalpies m_dEvapThermalLoss = 2300*m_dEvapRate; // kW... /// Heat Loss to ambient cooling m_dEnvironmentLoss = 0.0; switch (iThermalLossMethod) { case THL_Ambient: m_dEnvironmentLoss = (T-TA)*dThermalLossAmbient; //kW break; case THL_FixedHeatFlow: m_dEnvironmentLoss = dThermalLossRqd; break; } m_dTotThermalLoss = m_dEnvironmentLoss + m_dEvapThermalLoss + m_dCoolRate; } void CPrecipitator::AdjustPSD(MStream & Prod) { putN(Prod); } //------------------------------------------------------------------------ // Check for convergence of the iteration // // //------------------------------------------------------------------------ bool CPrecipitator::ConvergenceTest() { double xmag = (x[0]*x[0]+x[1]*x[1]+x[2]*x[2]); double err = (Sqr(x[0]-xo[0]) + Sqr(x[1]-xo[1]) +Sqr(x[2]-xo[2]))/GTZ(xmag); //double err = 0.0; double nn=0; double nt =0; for (int i=0; i<nClasses; i++) { if (NewN[i]==0 && n[i]==0) {} else err += Sqr((NewN[i]-n[i])/GTZ(NewN[i]+n[i])); // nn+= Sqr(NewN[i]); // nt+= Sqr(NewN[i]-n[i]); } // err += nt/GTZ(nn); for (int i=0; i<nClasses; i++) n[i] = NewN[i]; if (err < m_dConvergenceLimit) return true; else return false; } void CPrecipitator::DoResults(MStream & Prod) { //m_dNuclN = m_PSDin.getN()-m_PSD.getN(); MIBayer & FeedB=Feed.IF<MIBayer>(false); MIBayer & ProdB=Prod.IF<MIBayer>(false); dACin = FeedB.AtoC(); dACout = ProdB.AtoC(); dQvin = Feed.Volume(); dQvout = Prod.Volume(); dQmin = Feed.Mass(); dQmout = Prod.Mass(); double dQvout25 = Prod.Volume(MP_All, C2K(25)); double Cout = ProdB.CausticConc(Prod.T); m_dACeq = ProdB.AluminaConcSat(Prod.T)/Cout; m_dSSat = ProdB.AtoC()/m_dACeq; dYield = Cout*(dACin-dACout); double SolIn = Feed.MassVector[spTHA]; double SolOut = Prod.MassVector[spTHA]; dTHAPrecip = SolOut - SolIn; dAlPrecip = dTHAPrecip*102/156; SolIn = Feed.Mass(MP_Sol); SolOut = Prod.Mass(MP_Sol); dSolPrecip = SolOut - SolIn; dSolConc = Prod.Mass(MP_Sol)/dQvout25; m_dLiquorTin = Prod.T; dTin = Feed.T; dTout = Prod.T; m_dNucleation = m_dNuclN * PI/6*1.4618*Sqr(L1)*L1*1e-18*Prod.Density(MP_Sol); dResidenceTime = dTankVol/GTZ(Prod.Volume(MP_SL)); dFeedNTot = Feed.Volume(MP_All, C2K(25))*fpsd.getNTot(); dProdNTot = Prod.Volume(MP_All, C2K(25))*m_dNumber; } void CPrecipitator::EvalProducts() { try { x[0] = x[1] = x[2] = x[3] = 0.0; FlwIOs.AddMixtureIn_Id(Feed, idFeed); MStream & UFlow = FlwIOs[FlwIOs.First[idUflow]].Stream; //Reference to the output stream MStream & OFlow = FlwIOs[FlwIOs.First[idOflow]].Stream; //Reference to the output stream // if (!alreadySolved || UFlow.MassFlow() < 1.0e-3) Tank = Feed; //else //Tank = UFlow; UFlow = Tank; OFlow = Tank; OFlow.SetF(Tank, MP_All, 0.0); UFlow.SetF(Tank, MP_All, 1.0); bool streamOK=true; if (!bOnLine) return; // Check for existence of Bayer Property... MIBayer & FeedB=Feed.IF<MIBayer>(false); // Do the checks up front Log.SetCondition(IsNothing(FeedB), 1, MMsg_Warning, "Bad Feed Stream - Not BATC Bayer Model"); // Try PSD MIPSD & FeedPSD = Feed.IF<MIPSD>(false); if (!IsNothing(FeedPSD)) lPBType = PB_PSD; else { // Try SSA... MISSA & FeedSSA = Feed.IF<MISSA>(false); if (!IsNothing(FeedSSA)) lPBType = PB_SSA; else lPBType = PB_None; } Log.SetCondition(lPBType==PB_None, 1, MMsg_Warning, "Bad Feed Stream - No PSD or SSA Property"); if (IsNothing(FeedB) || IsNothing(FeedPSD)) streamOK = false; if (!IsNothing(FeedPSD)) { displayPSD(Feed, 2); } if (bOnLine && streamOK) { // Online and have Bayer and SSA properties... fpsd =QALPSD(Feed); m_dSolidsIn = fpsd.getVol()*Feed.Mass()*2420; // Feed.Density(MP_Sol); if (!bKernelOK) { AgglomKernel(); BinFactors(); bKernelOK = true; } DoPrecip(Tank); displayPSD(Feed, 4); displayPSD(Tank, 5); DoResults(Tank); UFlow = Tank; alreadySolved = true; } else { // Just tidy up and put some sensible stuff in the results... Log.Message(MMsg_Warning, "Stream Problem..."); } } catch (MMdlException &e) { Log.Message(MMsg_Error, e.Description); } catch (MFPPException &e) { e.ClearFPP(); Log.Message(MMsg_Error, e.Description); } catch (MSysException &e) { Log.Message(MMsg_Error, e.Description); } catch (...) { Log.Message(MMsg_Error, "Some Unknown Exception occured"); } } //-------------------------------------------------------------------------- void CPrecipitator::ClosureInfo(MClosureInfo & CI) {//ensure heat balance if (CI.DoFlows()) { CI.AddPowerIn(0, -dThermalLoss); } } void CPrecipitator::DoPrecip(MStream & Prod) { bool converged = false; int Iter=0; // Number of iterations in main loop m_dOldTotDH = 0.0; getN(Prod); m_dSSA = m_dArea; while (!converged && Iter < m_lItermax) { // Main iterative loop on final temperature and concentration EvalPrecipRates(Prod); /// Determine the precipitation rates EvalLosses(Prod); /// Evaluate the thermal losses AdjustMasses(Prod); /// Adjust the mass flows AdjustT(Prod); /// Adjust temperature for thermal losses, reaction heats etc // AdjustSSA(Prod); /// Adjust SSA //AdjustPSD(Prod); /// Adjust PSD converged = ConvergenceTest(); //// Final convergence test Iter++; } if (Iter==m_lItermax) {/// Convergence Failure, automatically increase damping and iterations??? } putN(Prod); m_lIterations = Iter; Log.SetCondition(Iter==m_lItermax, 4, MMsg_Warning, "Precip loop failed to converge...."); } // Precalculate Agglomeration Kernel and bin split factors void CPrecipitator::AgglomKernel() { for (int i=0; i<nClasses; i++) { for (int j=0; j<=i; j++) { beta[i][j] = beta[j][i] = exp(-(D[i]*D[i]+D[j]*D[j])/1600.); // dbg.log("i, j = %3d %3d %12.5g", i, j, beta[i][j]); } } } void CPrecipitator::BinFactors() { int k; double alpha = 2; double a1 = alpha-1; for (int i=0; i<nClasses; i++) { for (int j=0; j<i; j++) { k = klf(i,j); bsplit[i][j] = (alpha - pow(alpha, i-k) - pow(alpha, j-k))/a1; // dbg.log("i, j = %3d %3d %12.5g", i, j, bsplit[i][j]); } bsplit[i][i] = .5; } } void CPrecipitator::displayPSD(MStream &ms, int scrn) { MIPSD & mpsd = ms.IF<MIPSD>(false); /// Does the mud stream have PSD... int ic = mpsd.getSizeCount(); if (ic>40) ic=40; double x=0.0; QALPSD ps(ms); for (int i=0; i<ic; i++) { switch (iPSD) { case 0: x = ps.getFrac(i); break; case 1: x = ps.getN(i); break; case 2: x = mpsd.getSize(i); break; } dd[scrn][i]=x; } } // Ilievski Correlation (1991) // Note this uses Caustic as Na2O double CPrecipitator::AgglomRate() { double ssat = m_dSSat/(MW_Na2O/(2*MW_NaOH)); // Caustic as Na2O dAgglomRate = 5.0e-10*pow(ssat, 4)/3600; return dAgglomRate; } // Just the White method ala CAR for the moment... double CPrecipitator::GrowthRate() { const double T = Tank.T; switch (iGrowthRateMethod) { case GRM_Fixed: // dGrowthRate given directly in access window return dGrowthRate; case GRM_White: { double ssat=m_dSSat; if (ssat < 0) ssat=0.0; dGrowthRate = gF_White*K_White*Exps(-ER_White/Tank.T)*Sqr(ssat)/1000000./3600.; // m/s } case GRM_CAR_QAL: { MIBayer & TankB = Tank.IF<MIBayer>(false); double C = TankB.CausticConc(T); double C25 = TankB.CausticConc(C2K(25)); double CtoS = TankB.CtoS(); double S_out = C25/CtoS; // double FC = TankB.FreeCaustic(T); double FC = TankB.FreeCaustic(C2K(25)); double ACeq = TankB.AluminaConcSat(T)/C; double TOOC=TankB.TOC(C2K(25))*MW_Na2CO3/MW_C; double a=Exps(-m_dActivationEnergy/T); double b=Exps(-TOOC*m_dk_TOC); double c=Pow(GTZ(S_out), m_dn_s); double d=Pow(GTZ(FC), m_dn_fc); double e=Pow(GTZ(ACeq), m_dn_eq); double K = m_dK0*a*b*c*d*e; double ACout = TankB.AtoC(); double VLiq = Tank.Volume()*3600.; double MSolids = Tank.MassVector[spTHA]*3600.0/1000.0; double Sol = MSolids*1000.0/GTZ(VLiq); double deltaAC = K * dResidenceTime/3600 * Pow(GTZ(ACout-ACeq),m_dn_) * Pow(GTZ(Sol),m_dn_sol) * Pow(GTZ(m_dSSA),m_dn_ssa); const double denS = Tank.Density(MP_Sol); const double XG = Tank.MassVector[spAlumina]/Tank.MassVector[spTHA]; const double alpha = 117.963/77.963; dGrowthRate = 2./denS*XG/alpha/ACout/m_dArea*deltaAC; } } dGrowthYield = m_dArea*dGrowthRate/2*2420; // kg hydrate /s /kg slurry return dGrowthRate; } // Misra 1970 double CPrecipitator::NucleationRate() { if (iGrowthRateMethod==GRM_CAR_QAL) { MIBayer & TankB=Tank.IF<MIBayer>(false); const double T = Tank.T; const double SPO = Tank.MassVector[spOxalate]/Tank.MassVector[spAlumina]; const double A = TankB.AluminaConc(T); const double ASAT = TankB.AluminaConcSat(T); const double ssat = A/ASAT; /// Insert Code here.... dNuclRate = (1+1500*SPO)*exp(2100*(1./343. - 1/T))*pow(ssat-1, 6)*TankB.SodaConc(T); return dNuclRate*m_dArea/3600*1000000; } else { double ssat=m_dSSat; if (ssat < 0) ssat=0.0; dNuclRate = 5.0e8*pow(ssat,4)*m_dSSA/3600; return dNuclRate; } } // Calculate numbers for agglomeration... // Loop over all pairs of bins < NClasses // Calculate agglomeration rate for these bins // and destination bin(s) void CPrecipitator::Agglomeration() { for (int i=0; i<nClasses-1; i++) { // Special case when j=i // ie agglomeration of particles of equal sizes. int k = i+1; double NN = beta[i][i]*Sqr(n[i])*dAgglRateFactor*dAgglomRate; Ndot[i] -= NN; Ndot[k] += bsplit[i][i]*NN; // And the rest for (int j=0; j<i; j++) { k = i; // Destination bin if (k+1 < nClasses) { NN = beta[i][j]*n[i]*n[j]*dAgglRateFactor*dAgglomRate; Ndot[i] -= NN; Ndot[j] -= NN; Ndot[k] += bsplit[i][j]*NN; Ndot[k+1] += (1-bsplit[i][j])*NN; //dbg.log("i,j %3d, %3d, NN = %12.5g", i, j, NN); } } } } // Numbers for Growth void CPrecipitator::Growth() { for (int i = 1; i<nClasses-1; i++) { double g = n[i]*AREA_CORR/DIST_CORR*dGrowthRate/D[i]*1.0e6*dGrowthRateFactor; Ndot[i] -= g; Ndot[i+1] += g; } } void CPrecipitator::Nucleation() { Ndot[1] += dNuclRate*dNuclRateFactor; dNuclYield = PI/6.*pow(D[1],3)*2420*dNuclRate*dNuclRateFactor*1.0e-18/3600; } void CPrecipitator::Attrition() {} void CPrecipitator::AttritionRate() {} /// Calculate all the particle balance rates... /// Ndot[i] ... rate of change of n[i], #/s/kg void CPrecipitator::PBRates() { for (int i=0; i<nClasses; i++) Ndot[i] = (Feed.Mass()*fpsd.getN(i) - Tank.Mass()*n[i])/(Tank.Density()*dTankVol); if (bAgglomOn) { AgglomRate(); Agglomeration(); } if (bNuclOn) { NucleationRate(); Nucleation(); } if (bGrowthOn) { GrowthRate(); Growth(); } if(bAttritionOn) { AttritionRate(); Attrition(); } // Save the values for display for (int i=0; i<nClasses; i++) { switch (iDType) { case 0: dd[6][i]=0; break; case 1: dd[6][i]=0; break; case 2: dd[6][i]=Ndot[i]; break; case 3: dd[6][i]=n[i]; break; case 4: dd[6][i]=NewN[i]; break; } } } void CPrecipitator::getN(MStream &s) { QALPSD p(s); for (int i=0; i<nClasses; i++) n[i] = p.getN(i); m_dArea = p.getArea(); m_dVol = p.getVol(); m_dNumber = p.getNTot(); } // Fetch all the numbers to local N, return total void CPrecipitator::putN(MStream &s) { MIPSD & sP = s.IF<MIPSD>(false); double solidsContent = s.MassVector[spTHA]/GTZ(s.Mass()); if (fabs(solidsContent) < 1.0e-10) return; double avvol = PI/6.*D[0]*D[0]*D[0]*.125*1.0e-18; double z = n[0]*avvol*2420/solidsContent; sP.putFrac(0, z); for (int i=1; i<nClasses; i++) { avvol = PI/6.*pow(D[i],3)*DIST_CORR*1.0e-18; double z = n[i]*avvol*2420/solidsContent; sP.putFrac(i, z); } } // Put local N to stream void CPrecipitator::BuildDataFields() { static MDDValueLst DDB1[]={ {GRM_Fixed, "Fixed" }, {GRM_White, "White"}, {GRM_CAR_QAL, "CAR-QAL"}, {0}}; static MDDValueLst DDB2[]={ {0, "Fraction" }, {1, "Number"}, {2, "F*"}, {0}}; static MDDValueLst DDB3[]={ {THL_None, "None" }, {THL_TempDrop, "TempDrop"}, {THL_FixedHeatFlow, "FixedLoss"}, {THL_Ambient, "Ambient"}, {0}}; static MDDValueLst DDB5[]={ { COOL_dQ, "Fixed.dQ"}, { COOL_dT, "Fixed.dT" }, { COOL_Hx, "HeatExchange"}, {0}}; static MDDValueLst DDB6[]={ { EVAP_NONE, "None"}, { EVAP_FIXED, "Fixed"}, { EVAP_dT, "Ambient" }, {0}}; static MDDValueLst DDB7[]={ { COOL_NONE, "None"}, { COOL_INTERNAL, "Internal"}, { COOL_EXTERNAL, "External" }, {0}}; static MDDValueLst DDB14[]={ {0, "Growth" }, {1, "Aggl (N/s/m^3)"}, {2, "deltaN"}, {3, "oldN"}, {4, "newN"}, {0}}; DD.Text (""); #ifdef TTDEBUG DD.CheckBox("TTDBG", "", &bTTDebug, MF_PARAMETER); #endif DD.CheckBox("On", "", &bOnLine, MF_PARAMETER|MF_SET_ON_CHANGE); // DD.CheckBox("Int.Cooling", "", &m_bInternalCool, MF_PARAMETER|MF_SET_ON_CHANGE); //DD.CheckBox("Ext.Cooling", "", &m_bExternalCool, MF_PARAMETER|MF_SET_ON_CHANGE); DD.Text(""); DD.CheckBox("Growth.On", "", &bGrowthOn, MF_PARAMETER|MF_SET_ON_CHANGE); DD.CheckBox("Agglom.On", "", &bAgglomOn, MF_PARAMETER|MF_SET_ON_CHANGE); DD.CheckBox("Nucleation.On", "", &bNuclOn, MF_PARAMETER|MF_SET_ON_CHANGE); DD.CheckBox("Attrition.On", "", &bAttritionOn, MF_PARAMETER|MF_SET_ON_CHANGE); DD.Long ("Cooling", "", &iCoolType, MF_PARAMETER|MF_SET_ON_CHANGE, DDB7); //m_RB.OnOffCheckBox(); DD.Long ("Evaporation", "", &iEvapMethod , MF_PARAMETER|MF_SET_ON_CHANGE, DDB6); DD.Show(iEvapMethod!=EVAP_NONE); DD.Double("Evap.Rate", "", &m_dEvapRate ,iEvapMethod==EVAP_FIXED?MF_PARAMETER:MF_RESULT, MC_Qm("kg/s")); DD.Show(iEvapMethod==EVAP_dT); DD.Double("Evap.Per.degK", "", &m_dEvapRateK ,MF_PARAMETER, MC_Qm("kg/s")); DD.Show(); DD.Long ("ThermalLossMethod", "",&iThermalLossMethod, MF_PARAMETER|MF_SET_ON_CHANGE, DDB3); DD.Show(iThermalLossMethod==THL_TempDrop); DD.Double("Temp_Drop", "", &dTempDropRqd ,MF_PARAMETER, MC_dT("C")); DD.Show(iThermalLossMethod==THL_FixedHeatFlow); DD.Double("ThermalLossRqd", "", &dThermalLossRqd ,MF_PARAMETER, MC_Pwr("kW")); DD.Show(iThermalLossMethod==THL_Ambient); DD.Double("ThermalLossAmbient", "", &dThermalLossAmbient ,MF_PARAMETER, MC_UA); DD.Show(); DD.Text(""); DD.Text ("Requirements"); DD.Double("TankVol", "", &dTankVol ,MF_PARAMETER, MC_Vol("m^3")); DD.Text (""); DD.Text ("Results Tank"); DD.Double("ResidenceTime", "", &dResidenceTime ,MF_RESULT, MC_Time("h")); DD.Double("SuperSat", "", &m_dSSat, MF_RESULT, MC_); DD.Double("Yield", "", &dYield ,MF_RESULT, MC_Conc("kg/m^3")); DD.Double("SolidsIn", "", &m_dSolidsIn, MF_RESULT, MC_Qm("kg/s")); DD.Double("SolidsOut", "", &m_dSolidsOut, MF_RESULT, MC_Qm("kg/s")); DD.Double("NucleationYield", "", &dNuclYield, MF_RESULT, MC_Qm("kg/s")); DD.Double("GrowthYield", "", &dGrowthYield, MF_RESULT, MC_Qm("kg/s")); DD.Double("THA.Precip", "", &dTHAPrecip ,MF_RESULT, MC_Qm("kg/s")); DD.Double("Solids.Precip", "", &dSolPrecip ,MF_RESULT, MC_Qm("kg/s")); DD.Double("Solids.Conc", "", &dSolConc ,MF_RESULT, MC_Conc("kg/m^3")); DD.Text ("Results"); DD.Show(); DD.Double("Vol_FlowIn", "", &dQvin ,MF_RESULT, MC_Qv("L/s")); DD.Double("Vol_FlowOut", "", &dQvout ,MF_RESULT, MC_Qv("L/s")); DD.Double("MassFlowIn", "", &dQmin ,MF_RESULT, MC_Qm("t/d")); DD.Double("MassFlowOut", "", &dQmout ,MF_RESULT, MC_Qm("t/d")); DD.Double("ACin", "", &dACin ,MF_RESULT, MC_); DD.Double("ACout", "", &dACout ,MF_RESULT, MC_); DD.Double("ACequil", "", &m_dACeq ,MF_RESULT, MC_); DD.Double("TempIn", "", &dTin ,MF_RESULT, MC_T("C")); DD.Double("TempOut", "", &dTout ,MF_RESULT, MC_T("C")); DD.Text(""); DD.Page("Precip"); DD.Long ("GrowthMethod", "", (long*)&iGrowthRateMethod, MF_PARAMETER|MF_SET_ON_CHANGE, DDB1); DD.Double("Convergence.Limit", "", &m_dConvergenceLimit, MF_PARAMETER|MF_INIT_HIDDEN, MC_); DD.Double("Acceleration", "", &m_ddeltaT, MF_PARAMETER|MF_INIT_HIDDEN, MC_); DD.Double("Thermal.Damping", "", &m_dDamping, MF_PARAMETER|MF_INIT_HIDDEN, MC_Frac("%")); DD.Double("Mass.Damping", "", &m_dMassDamping, MF_PARAMETER|MF_INIT_HIDDEN, MC_Frac("%")); DD.Long("Iterations", "", &m_lIterations, MF_RESULT|MF_NO_FILING); DD.Long("IterMax", "", &m_lItermax, MF_PARAMETER); // DD.Double("Vol.Damping", "", &m_dVolDamping, MF_PARAMETER|MF_INIT_HIDDEN, MC_Frac("%")); DD.Show (iGrowthRateMethod==GRM_Fixed); DD.Double("Precip.Rate", "", &dGrowthRate ,MF_PARAMETER, MC_Ldt("um/h")); DD.Show (iGrowthRateMethod==GRM_White); DD.Double("ER_White", "", &ER_White ,MF_PARAMETER, MC_T("K")); DD.Double("K_White", "", &K_White ,MF_PARAMETER, MC_); DD.Double("gF_White", "", &gF_White ,MF_PARAMETER, MC_); DD.Show (iGrowthRateMethod==GRM_CAR_QAL); DD.Double("ActivationEnergy", "", &m_dActivationEnergy ,MF_PARAMETER, MC_T("K")); DD.Double("K0", "", &m_dK0 ,MF_PARAMETER, MC_); //DD.Double("K1", "", &m_dK1 ,MF_PARAMETER, MC_); DD.Double("k_TOC", "", &m_dk_TOC ,MF_PARAMETER, MC_); DD.Double("n_s", "", &m_dn_s ,MF_PARAMETER, MC_); DD.Double("n_fc", "", &m_dn_fc ,MF_PARAMETER, MC_); DD.Double("n_eq", "", &m_dn_eq ,MF_PARAMETER, MC_); DD.Double("n_", "", &m_dn_ ,MF_PARAMETER, MC_); DD.Double("n_sol", "", &m_dn_sol ,MF_PARAMETER, MC_); DD.Double("n_ssa", "", &m_dn_ssa ,MF_PARAMETER, MC_); DD.Show(); DD.Text("Fudge Factors"); DD.Double("Growth.Rate.Factor", "", &dGrowthRateFactor, MF_PARAMETER, MC_); DD.Double("Agglom.Rate.Factor", "", &dAgglRateFactor, MF_PARAMETER, MC_); DD.Double("Nucl.Rate.Factor", "", &dNuclRateFactor, MF_PARAMETER, MC_); DD.Show(); DD.Text("Results"); DD.Double("Growth.Rate", "", &dGrowthRate ,MF_RESULT|MF_NO_FILING, MC_Ldt("um/h")); DD.Double("Agglom.Rate", "", &dAgglomRate ,MF_RESULT|MF_NO_FILING, MC_); DD.Double("Nucl.Rate", "", &dNuclRate ,MF_RESULT|MF_NO_FILING, MC_); DD.Double("SSAin", "", &m_dSSAin ,MF_RESULT, MC_);//SurfAreaM); DD.Double("SSA", "", &m_dSSA ,MF_RESULT, MC_);//SurfAreaM); DD.Text("Thermal and Mass Balance"); DD.Double("Mass.Flow.In", "", &dQmin ,MF_RESULT|MF_NO_FILING, MC_Qm("t/d")); DD.Double("Mass.Flow.Out", "", &dQmout ,MF_RESULT|MF_NO_FILING, MC_Qm("t/d")); DD.Show(iEvapMethod); DD.Double("Evap.Mass.Loss", "", &m_dEvapRate, MF_RESULT, MC_Qm("kg/s")); DD.Double("Evap.Thermal.Loss", "", &m_dEvapThermalLoss ,MF_RESULT, MC_Pwr("kW")); DD.Show(iThermalLossMethod==THL_Ambient); DD.Double("Env.Thermal.Loss", "", &m_dEnvironmentLoss, MF_RESULT, MC_Pwr("kW")); DD.Show(iCoolType); DD.Double("Cooler.Thermal.Loss", "", &m_dCoolRate, MF_RESULT, MC_Pwr("kW")); // Ext Cooling Rate DD.Double("ReactionHeat", "", &dReactionHeat ,MF_RESULT, MC_Pwr("kW")); DD.Double("Total.Thermal.Loss", "", &m_dTotThermalLoss, MF_RESULT, MC_Pwr("kW")); DD.Text("Stream.Enthalpy"); DD.Double("HzIn", "", &m_dHIn, MF_RESULT, MC_Pwr); DD.Double("HzEvap", "", &m_dHEvap, MF_RESULT, MC_Pwr); DD.Double("HzOut", "", &m_dHOut, MF_RESULT, MC_Pwr); DD.Double("HzBal", "", &m_dHBal, MF_RESULT, MC_Pwr); DD.Show(); DD.Page("Size Inlet"); DD.Long("PSD.Display", "", &iPSD, MF_PARAMETER|MF_SET_ON_CHANGE, DDB2); const int NumSpecies = gs_MVDefn.Count(); for (int i=0; i<nClasses; i++) { std::stringstream os; os << "Size " << std::setw(3) << i << std::setw(12) << D[i] ; DD.Double(os.str().c_str(), "", dd[2]+i, MF_RESULT|MF_NO_FILING, MC_None); } // DD.Page("Size In"); // for (int i=0; i<nClasses; i++) { // std::stringstream os; // os << "Size " << std::setw(3) << i; // DD.Double(os.str().c_str(), "", dd[4]+i, MF_RESULT|MF_NO_FILING, MC_None); // } // DD.Text(""); // DD.Double("Number", "", dd[4]+26, MF_RESULT|MF_NO_FILING, MC_None); // DD.Double("Area", "", dd[4]+27, MF_RESULT|MF_NO_FILING, MC_None); // DD.Double("Vol", "", dd[4]+28, MF_RESULT|MF_NO_FILING, MC_None); // DD.Double("Mass", "", dd[4]+29, MF_RESULT|MF_NO_FILING, MC_None); DD.Page("Size Tank"); for (int i=0; i<nClasses; i++) { std::stringstream os; os << "Size " << std::setw(3) << i; DD.Double(os.str().c_str(), "", dd[5]+i, MF_RESULT|MF_NO_FILING, MC_None); } DD.Text(""); DD.Double("Number", "", dd[5]+26, MF_RESULT|MF_NO_FILING, MC_None); DD.Double("Area", "", dd[5]+27, MF_RESULT|MF_NO_FILING, MC_None); DD.Double("Vol", "", dd[5]+28, MF_RESULT|MF_NO_FILING, MC_None); DD.Double("Mass", "", dd[5]+29, MF_RESULT|MF_NO_FILING, MC_None); DD.Page("Numbers..."); // DD.Page(DDB14[iDType].m_pStr); DD.Long("DType", "", &iDType, MF_PARAMETER|MF_SET_ON_CHANGE, DDB14); for (int i=0; i<nClasses; i++) { std::stringstream os; os << "Size " << std::setw(3) << i; DD.Double(os.str().c_str(), "", dd[6]+i, MF_RESULT|MF_NO_FILING, MC_None); } DD.Show(iCoolType); DD.Page("Cooler"); DD.Show(iCoolType==COOL_INTERNAL); DD.CheckBox("Cooler.On", "", &m_bCoolerOn, MF_PARAMETER); DD.Long ("Cooling.Type", "", (long*)&iCoolMethod, MF_PARAMETER|MF_SET_ON_CHANGE, DDB5); DD.Show(iCoolType==COOL_INTERNAL && (iCoolMethod==COOL_dT)); DD.Double("dT", "", &m_dCooldT, MF_PARAMETER, MC_dT("C")); DD.Show(iCoolType==COOL_INTERNAL && (iCoolMethod==COOL_dQ)); DD.Double("dQ", "", &m_dCooldQ, MF_PARAMETER, MC_Pwr("kW")); DD.Show(iCoolType==COOL_INTERNAL && (iCoolMethod==COOL_Hx)); DD.Double("HX.Area", "", &m_dCoolArea, MF_PARAMETER, MC_Area("m^2")); DD.Double("HX.HTC", "", &m_dCoolHTC, MF_PARAMETER, MC_HTC); DD.Show(iCoolType==COOL_EXTERNAL || (iCoolType==COOL_INTERNAL && (iCoolMethod==COOL_Hx))); DD.CheckBox("By.Vol.Flow", "", &m_bByVolFlow, MF_PARAMETER|MF_SET_ON_CHANGE); DD.Show(iCoolType==COOL_INTERNAL && (iCoolMethod==COOL_Hx)); DD.Double("Cooling.Flow", "", &m_dCoolFlow, m_bByVolFlow ? MF_RESULT : MF_PARAMETER, MC_Qm("kg/s")); // Internal cooling flow DD.Double("Int.Vol.Flow", "", &m_dIntCoolVolFlow, m_bByVolFlow ? MF_PARAMETER : MF_RESULT, MC_Qv("m^3/s")); // By Volume DD.Double("Hx.UA", "", &m_dUA, MF_RESULT, MC_UA); DD.Double("Hx.LMTD", "", &m_dLMTD, MF_RESULT, MC_dT); DD.Double("Water.Flow", "", &m_dCoolWaterFlow, MF_RESULT, MC_Qm("kg/s")); DD.Double("Water.Vol.Flow", "", &m_dCoolWaterFlowVol, MF_RESULT, MC_Qv); DD.Double("Water.Tin", "", &m_dCoolWaterTin, MF_RESULT, MC_T("C")); DD.Double("Water.Tout", "", &m_dCoolWaterTout, MF_RESULT, MC_T("C")); DD.Double("Liquor.Tin", "", &m_dLiquorTin, MF_RESULT, MC_T("C")); DD.Double("Liquor.Tout", "", &m_dLiquorTout, MF_RESULT, MC_T("C")); DD.Show(iCoolType==COOL_EXTERNAL); DD.Double("Ext.Vol.Flow", "", &m_dExtCoolVolFlow, m_bByVolFlow ? MF_PARAMETER : MF_RESULT, MC_Qv("m^3/s")); // Ext Cooling.Flow DD.Double("Ext.Cooling.Flow", "", &m_dExtCoolFlow, m_bByVolFlow ? MF_RESULT : MF_PARAMETER, MC_Qm("kg/s")); // Ext Cooling.Flow DD.Double("Ext.Cooling.Temp", "", &m_dExtCoolTemp, MF_RESULT, MC_T("C")); // Ext Cooling.Temp DD.Double("Ext.Cooling.totHz", "", &m_dCoolOutTotHz , MF_RESULT, MC_Pwr("kW")); // Ext Cooling Rate DD.Show(iCoolType); DD.Double("Cooling.Rate", "", &m_dCoolRate, MF_RESULT, MC_Pwr("kW")); // Ext Cooling Rate if (!m_bEvapConnected && iEvapMethod!=EVAP_NONE) //if optional Evap is NOT connected and evaporation functionality is required show the output stream DD.Object(Evap, MDD_RqdPage); //DD.Show(m_RB.Enabled()); //DD.Page("RB"); //m_RB.BuildDataFields(); //DD.Show(); }
[ [ [ 1, 2 ], [ 4, 19 ], [ 21, 23 ], [ 25, 25 ], [ 27, 122 ], [ 124, 500 ], [ 502, 504 ], [ 506, 510 ], [ 512, 576 ], [ 579, 584 ], [ 586, 632 ], [ 635, 825 ], [ 830, 923 ], [ 925, 967 ], [ 971, 971 ], [ 975, 975 ], [ 979, 989 ] ], [ [ 3, 3 ], [ 123, 123 ], [ 501, 501 ], [ 505, 505 ], [ 511, 511 ], [ 577, 578 ], [ 585, 585 ], [ 633, 634 ], [ 826, 829 ], [ 924, 924 ], [ 968, 970 ], [ 972, 974 ], [ 976, 978 ], [ 990, 1280 ] ], [ [ 20, 20 ], [ 24, 24 ], [ 26, 26 ] ] ]
8894515525e04ad7709178ac7226821c7f8cd4b7
508a24127b2dc947f2dec5e14e67ae6fe019d5f3
/STSLib/bufferGenerator.cc
79c923b6178337e10e854ca5c262a8a5ff8fe232
[ "MIT" ]
permissive
dhendriks/STSLib
d728c4d4443d23319dd8ae9af22ad4a02e138066
62f094fc3a191f7c3eb0cb0d760d37bb450e0dee
refs/heads/master
2020-12-25T08:28:22.150923
2010-08-26T14:01:40
2010-08-26T14:01:40
871,966
1
0
null
null
null
null
UTF-8
C++
false
false
1,267
cc
#include "bufferGenerator.h" bufferGenerator::bufferGenerator(string const& name, int bufferSize, vector<event_type>const& in, vector<event_type>const& out, vector<event_type>const& self) { set_name(name); // name int stateSize = bufferSize+1; set_state_size(stateSize); // state size automaton::state_type s=0; insert_marker_state(s); // marker state: state 0 is the marker state as well. // handle the events that incease buffer count. note that the last state has no events from 'in' trans_node tn; for(int i=0; i<stateSize-1; i++) { tn.t= i+1; for(vector<event_type>::const_iterator ei=in.begin(); ei!=in.end(); ei++) { tn.e=*ei; insert_transition(i,tn); } } // handle the events that decrease buffer count. note that state 0 has no events from 'out' for(int i=1; i<stateSize; i++) { tn.t= i-1; for(vector<event_type>::const_iterator ei=out.begin(); ei!=out.end(); ei++) { tn.e=*ei; insert_transition(i,tn); } } //handle selfloop events for(int i=0; i<stateSize; i++) { tn.t= i; for(vector<event_type>::const_iterator ei=self.begin(); ei!=self.end(); ei++) { tn.e=*ei; insert_transition(i,tn); } } } bufferGenerator::~bufferGenerator() { }
[ [ [ 1, 46 ] ] ]
9a05ec73b0e16645a5f9e283da016f07b5fa67e6
8ade67ab53907d22e40286b377b86d1b1eeaf6f0
/tabu/alo/tabustatus.h
3b34f315ef3e2da4c26058deee456ef18c510a1a
[]
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
7,224
h
#pragma once #include "../arrays/array.h" #include "../arrays/tuple.h" #include "../arrays/symbol.h" #include "../tabu/search.h" #include "tupleMap.h" #include <set> namespace alo { typedef std::set<int> rowset; template <class RowChecker, class Symbol, class Tuple=arrays::tuple> class tabuStatus : public tabu::tabuStatus<Symbol> { int strength; typename Tuple::initParams params; tupleMap<rowset,Tuple> goods; std::set<Tuple> bads; arrays::Array<Symbol> arr; RowChecker * checker; Symbol * slice; bool keepStrength; public: tabuStatus() { slice = NULL; } tabuStatus( const tabuStatus<RowChecker,Symbol,Tuple> & copy ) : strength( copy.strength ), params( copy.params ), goods( copy.goods ), bads( copy.bads ), arr( copy.arr ), checker( copy.checker ), keepStrength( copy.keepStrength ) { slice = new Symbol[strength]; } tabuStatus( arrays::Array<Symbol> & _arr, int _strength, bool initialize ) : arr(_arr, 1), params( _strength, _arr.getWidth() ), goods( params ), checker( new RowChecker ) { keepStrength = false; strength = _strength; slice = new Symbol[strength]; if ( initialize ) { printf("Constructing tabu status!\n"); init(); } } tabuStatus( arrays::Array<Symbol> & _arr, int _strength, bool initialize, RowChecker * _checker ) : arr(_arr, 1), params( _strength, _arr.getWidth() ), goods( params ), checker( _checker ) { keepStrength = false; strength = _strength; slice = new Symbol[strength]; if ( initialize ) { printf("Constructing tabu status!\n"); init(); } } tabuStatus( arrays::Array<Symbol> & _arr, int _strength, bool initialize, const typename Tuple::initParams & _params ) : arr(_arr, 1), goods( _params ), checker( new RowChecker ), params( _params ) { keepStrength = false; strength = _strength; slice = new Symbol[strength]; if ( initialize ) { printf("Constructing tabu status!\n"); init(); } } tabuStatus( arrays::Array<Symbol> & _arr, int _strength, bool initialize, const typename Tuple::initParams & _params, RowChecker * _checker ) : arr(_arr, 1), goods( _params ), checker( _checker ), params( _params ) { keepStrength = false; strength = _strength; slice = new Symbol[strength]; if ( initialize ) { printf("Constructing tabu status!\n"); init(); } } ~tabuStatus() { if ( slice != NULL ) { delete[] slice; slice = NULL; } } void reInit( arrays::Array<Symbol> & _arr, int _strength ) { printf("Re-constructing tabu status!\n"); _arr.copyInto( arr ); if ( ! keepStrength ) { strength = _strength; if ( slice != NULL ) delete[] slice; slice = new Symbol[_strength]; } init(); } void memorizeStrength() { keepStrength = true; } void init() { int v = arr.getSymbolCount(); int k = arr.getWidth(); int N = arr.getHeight(); Tuple t(params); int i; bool found; long inc = 0; do { // FIRST CHECK THE CURRENT T-TUPLE found = false; for ( i = 0; i < N; i++ ) { arr.sliceInto(i, t, slice); if ( checker->good( slice, strength ) ) { found = true; goods[ t ]->insert( i ); } } if ( ! found ) { bads.insert( t ); } inc++; if ( (inc % 10000) == 0 ) { printf("at inc %ld with %ld bads\n", inc, (long) bads.size() ); } // NOW, INCREMENT THE CURRENT T-TUPLE } while ( ++t ); printf("Finished construction of tabu status!\n"); } tabu::intScore getScore() { return tabu::intScore( (int) bads.size() ); } void getResultInto(arrays::Array<Symbol> & s) { arr.copyInto( s ); } Symbol getArrayValue( int i, int j ) const { return arr.get(i, j); } arrays::SymbolGenerator<Symbol> * getSymbolGenerator() { return arr.gen; } const arrays::Array<Symbol> & getArr() { return arr; } const arrays::Array<Symbol> * getArrayPtr() { return &arr; } void print() const { printf("\nTUPLE MAP: \n"); Tuple t(params); do { const rowset * r = goods[ t ]; t.print(); printf(" ==> "); if ( r->empty() ) { printf("XX"); } else { rowset::const_iterator rsIt = r->begin(); while ( true ) { printf("[%d]", *rsIt); if ( ++rsIt != r->end() ) { printf(" -> "); } else { break; } } } printf("\n"); } while (++t); printf("\n"); printf("\nBAD TUPLES: \n"); std::set<Tuple>::const_iterator it = bads.begin(); for ( ; it != bads.end(); it++ ) { it->print(); printf("\n"); } } int countBadPerColumn( int * counts ) { int total = 0; for ( int i = 0; i < arr.getWidth(); i++ ) { counts[i] = 0; } std::set<Tuple>::const_iterator it = bads.begin(); for ( ; it != bads.end(); it++ ) { int st = it->strength(); for ( i = 0; i < st; i++ ) { counts[ it->get( i ) ]++; total++; } } return total; } int calculateEffectOfChange( int row, int col, Symbol newValue ) { Tuple real( params ); Tuple::lesserTuple iterator( real.createLesserTuple() ); int delta = 0; do { for ( int i = 0; i < strength - 1; i++ ) { int xx = iterator[i]; xx = xx; } real.initViaUpgrade( iterator, col ); for ( int i = 0; i < strength; i++ ) { int xx = real[i]; xx = xx; } int sz = (int) goods[ real ]->size(); if ( sz == 0 ) { // things can get better if this tuple was previously bad arr.sliceInto(row,real,slice); slice[ real.indexOf( col ) ] = newValue; if ( checker->good( slice, strength ) ) delta--; } else if ( sz == 1 ) { // things can get worse if this tuple was previously good, but not covered arr.sliceInto(row,real,slice); if ( checker->good( slice, strength ) ) { slice[ real.indexOf( col ) ] = newValue; if ( ! checker->good( slice, strength ) ) delta++; } } } while ( ++iterator ); return delta; } int change( int row, int col, Symbol newValue ) { arr.set( row, col, newValue ); Tuple real( params ); Tuple::lesserTuple iterator( real.createLesserTuple() ); int delta = 0; do { real.initViaUpgrade( iterator, col ); arr.sliceInto(row,real,slice); bool wasBad = ( goods[ real ]->size() == 0 ); if ( checker->good( slice, strength ) ) { goods[ real ]->insert( row ); if ( wasBad ) { bads.erase( real ); } } else { goods[ real ]->erase( row ); if ( !wasBad && goods[ real ]->size() == 0 ) { bads.insert( real ); } } } while ( ++iterator ); return delta; } int getStrength() { return strength; } int getSymbolCount() { return arr.getSymbolCount(); } }; };
[ [ [ 1, 331 ] ] ]
048295346e9b72d422af2c7d55140b8ed15043b8
da12544e7d7c2a58e4641f1ddb54d6696b6302af
/STM32Port_AQAdjustments/ReceiverSTM32.h
afcea18c2b51cb7aa2aad0f50d95f6d61810abf1
[]
no_license
MorS25/SnorCopter
05e9fb14bcfdd8ee2a80e44f742e37d7c2fcd3b1
a8ebe941b457cfe2a705276fb54d8be034b02757
refs/heads/master
2021-01-19T11:10:22.769579
2011-12-11T18:28:05
2011-12-11T18:28:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,363
h
#if defined(AeroQuadMega_v2STM32) /* Copyright (c) 2011 ala42. All rights reserved. STM32 receiver class by ala42 using time input capture for use with AeroQuad software and Maple library V 1.0 Oct 15 2011 Define the pin numbers used for the receiver in receiverPin[] Timer and timer channels are accessed using the Maple PIN_MAP array. Make sure libmaple and this receiver class are compiled using the same structure alignment mode. When in doubt, change the stm32_pin_info declaration in wirish_types.h to align the size to a multiple of 4 byte by adding a filler byte at the end of the structure declaration. */ #include "wirish.h" //#define STM32_TIMER_DEBUG // enable debug messages /////////////////////////////////////////////////////////////////////////////// // configuration part starts here // definition of pins used for PWM receiver input #ifdef BOARD_aeroquad32 static byte receiverPin[] = { Port2Pin('D', 12), Port2Pin('D', 13), Port2Pin('D', 14), Port2Pin('D', 15), Port2Pin('E', 9), Port2Pin('E', 11), Port2Pin('E', 13), Port2Pin('E', 14) }; #endif #ifdef BOARD_aeroquad32mini static byte receiverPin[] = { 2, // PB7 4, // PB6 5, // PB8 6, // PB9 7, // PA15 JTDI TIM2_CH1 8 // PB3 JTDO SPI3SCK /TIM2_CH2 }; #endif /////////////////////////////////////////////////////////////////////////////// // implementation part starts here. // forward declaration, array is defined at the end of this file extern voidFuncPtr PWM_in_handler[]; // interrupt handler needs access to receiver class class Receiver_AeroQuad_STM32 *STM32_receiver; class Receiver_AeroQuad_STM32 : public Receiver { private: typedef struct { timer_dev *TimerDev; timer_gen_reg_map *TimerRegs; __io uint32 *Timer_ccr; int Low; int High; uint16 HighTime; uint16 RiseTime; int Channel; int TimerChannel; int PolarityMask; int Valid; int Debug; } tFrqData; #define FRQInputs 8 volatile tFrqData FrqData[FRQInputs]; public: void initialize(void) { STM32_receiver = this; // give interrupt handler access to this class InitFrqMeasurement(); this->_initialize(); // load in calibration xmitFactor from EEPROM } /* #define ROLL 0 #define PITCH 1 #define YAW 2 #define THROTTLE 3 #define MODE 4 #define AUX 5 #define AUX2 6 #define AUX3 7 */ uint16_t getReceiverChannel(const byte channel) { //static byte ReceiverChannelMap[] = {3, 2, 0, 1, 4, 6, 5, 7}; // mapping for ala42 static byte ReceiverChannelMap[] = {0, 1, 2, 3, 4, 5, 6, 7}; // default mapping volatile tFrqData *f = &FrqData[ReceiverChannelMap[channel]]; uint16_t PulsLength = f->HighTime; return PulsLength; } // hide the class details from the interupt handler void IrqChangeValue(int chan) { FrqChange(&FrqData[chan]); } private: void FrqInit(int aChannel, int aDefault, volatile tFrqData *f, timer_dev *aTimer, int aTimerChannel) { aTimerChannel--; // transfor timer channel numbering from 1-4 to 0-3 f->Channel = aChannel; f->Valid = false; f->TimerDev = aTimer; timer_gen_reg_map *timer = aTimer->regs.gen; f->TimerRegs = timer; f->Timer_ccr = &timer->CCR1 + aTimerChannel; f->Debug = false; f->HighTime = aDefault; f->TimerChannel = aTimerChannel; int TimerEnable = (1 << (4*aTimerChannel)); f->PolarityMask = TimerEnable << 1; timer->PSC = 72-1; timer->ARR = 0xffff; timer->CR1 = 0; timer->DIER &= ~(1); timer->CCER &= ~TimerEnable; // Disable timer timer->CCER &= ~(f->PolarityMask); #ifdef STM32_TIMER_DEBUG Serial.print(" timer "); Serial.print((int32)timer, 16); Serial.print(" CCMR0 "); Serial.print(timer->CCMR1, 16); #endif volatile uint32 *mr; if(aTimerChannel < 2) { mr = &(timer->CCMR1); } else { mr = &(timer->CCMR2); } *mr &= ~(0xFF << (8*(aTimerChannel&1))); // prescaler 1 *mr |= 0x61<< (8*(aTimerChannel&1));// 6=filter, 1=inputs 1,2,3,4 #ifdef STM32_TIMER_DEBUG Serial.print(" CCER0 "); Serial.print(timer->CCER, 16); Serial.print(" CCMR1 "); Serial.print(timer->CCMR1, 16); #endif timer->CCER |= TimerEnable; // Enable #ifdef STM32_TIMER_DEBUG Serial.print(" CCER2 "); Serial.print(timer->CCER, 16); #endif timer->CR1 = 1; #ifdef STM32_TIMER_DEBUG Serial.print(" CCER3 "); Serial.print(timer->CCER, 16); Serial.print(" CCMR1 "); Serial.print(timer->CCMR1, 16); Serial.println(""); #endif } void InitFrqMeasurement() { #ifdef STM32_TIMER_DEBUG Serial.println("InitFrqMeasurement"); #endif for(int rcLine = 0; rcLine < (int)(sizeof(receiverPin) / sizeof(receiverPin[0])); rcLine++) { int pin = receiverPin[rcLine]; timer_dev *timer_num = PIN_MAP[pin].timer_device; if(timer_num == NULL) { #ifdef STM32_TIMER_DEBUG Serial.print("InitFrqMeasurement: invalid PWM input "); Serial.print(pin); Serial.println(); #endif } else { pinMode(pin, INPUT); #ifdef STM32_TIMER_DEBUG timer_gen_reg_map *timer = PIN_MAP[pin].timer_device->regs.gen; Serial.print("pin "); Serial.print(pin); Serial.print(" timerbase "); Serial.print((int32)timer,16); Serial.println(); #endif FrqInit(rcLine, 1500, &FrqData[rcLine], timer_num, PIN_MAP[pin].timer_channel); timer_attach_interrupt(timer_num, PIN_MAP[pin].timer_channel, PWM_in_handler[rcLine]); } } #ifdef STM32_TIMER_DEBUG Serial.println("InitFrqMeasurement done"); #endif } void PWMInvertPolarity(volatile tFrqData *f) { f->TimerRegs->CCER ^= f->PolarityMask; // invert polarity } void FrqChange(volatile tFrqData *f) { timer_gen_reg_map *timer = f->TimerRegs; uint16_t c = *(f->Timer_ccr); if(f->Debug) { Serial.print(f->Channel); Serial.print(" "); Serial.print((int)c, 16); Serial.println(""); } bool rising = (timer->CCER & f->PolarityMask) == 0; if(f->Valid) { if(rising) { // rising edge, store start time f->RiseTime = c; //Serial.print(" r "); //Serial.println(f->RiseTime, 10); } else { f->HighTime = c - f->RiseTime; //Serial.print(" f "); //Serial.println(f->HighTime, 10); } } else { if(rising) { // rising egde, store start time f->RiseTime = c; f->Valid = true; } } PWMInvertPolarity(f); } }; // class Receiver_AeroQuad_STM32 /////////////////////////////////////////////////////////////////////////////// // definition of interrupt handler funtions, one for each channel void PWM_in_0() { STM32_receiver->IrqChangeValue(0); } void PWM_in_1() { STM32_receiver->IrqChangeValue(1); } void PWM_in_2() { STM32_receiver->IrqChangeValue(2); } void PWM_in_3() { STM32_receiver->IrqChangeValue(3); } void PWM_in_4() { STM32_receiver->IrqChangeValue(4); } void PWM_in_5() { STM32_receiver->IrqChangeValue(5); } void PWM_in_6() { STM32_receiver->IrqChangeValue(6); } void PWM_in_7() { STM32_receiver->IrqChangeValue(7); } voidFuncPtr PWM_in_handler[] = { PWM_in_0, PWM_in_1, PWM_in_2, PWM_in_3, PWM_in_4, PWM_in_5, PWM_in_6, PWM_in_7 }; #endif
[ [ [ 1, 280 ] ] ]
3971e143d2d5de36d9f4923033881e77a905e3c4
92c233548950eb0d8474151a1e9c4b4f7bddd450
/src/Tests/testBiggestValue.cpp
96237a62505035d890be6165e2f9d0a8e59df35a
[]
no_license
alepharchives/quickfast
f989e431d1faaacc4404d26bb1c28f8380dc2e70
53c1834b6a8552fa491d139a41ecf2c91ce44ca6
refs/heads/master
2020-04-11T03:00:09.627113
2011-04-01T13:57:07
2011-04-01T13:57:07
6,812,133
0
1
null
null
null
null
UTF-8
C++
false
false
34,225
cpp
// Copyright (c) 2009, Object Computing, Inc. // All rights reserved. // See the file license.txt for licensing information. #include <Common/QuickFASTPch.h> #define BOOST_TEST_NO_MAIN QuickFASTTest #include <boost/test/unit_test.hpp> #include <boost/filesystem.hpp> #include <Codecs/XMLTemplateParser.h> #include <Codecs/TemplateRegistry.h> #include <Codecs/Encoder.h> #include <Codecs/Decoder.h> #include <Codecs/DataDestination.h> #include <Codecs/DataSourceString.h> #include <Codecs/SingleMessageConsumer.h> #include <Codecs/GenericMessageBuilder.h> #include <Messages/Message.h> #include <Messages/FieldIdentity.h> #include <Messages/FieldInt32.h> #include <Messages/FieldUInt32.h> #include <Messages/FieldInt64.h> #include <Messages/FieldUInt64.h> #include <Messages/FieldAscii.h> #include <Messages/FieldByteVector.h> #include <Messages/FieldDecimal.h> #include <Messages/FieldGroup.h> #include <Messages/FieldSequence.h> #include <Messages/FieldUtf8.h> #include <Messages/Sequence.h> #include <Common/Exceptions.h> using namespace QuickFAST; // test with various combinations: (8*5 + 4 + 3) * 2 = 94 //8 primitive field types: // int32, int64, uint32, uint64, decimal, ascii string, utf8 string, //byte vector //5 general purpose operators // nop, constant, default, copy, delta, //2 special purpose operators: // increment (applies only to 4 integer types), tail (applies only //to 3 types: ascii, utf8, and byte vector) //2 presence values // mandatory, required namespace{ void validateMessage1(Messages::Message & message, const std::string buffer) { BOOST_CHECK_EQUAL(message.getApplicationType(), "unittestdata"); Messages::FieldCPtr value; //<int32 name="int32_nop" id="1"> //msg.addField(identity_int32_nop, Messages::FieldInt32::create(2147483647)); BOOST_CHECK(message.getField("int32_nop", value)); BOOST_CHECK_EQUAL(value->toInt32(), 2147483647); //<uInt32 name="uint32_nop" id="2"> //msg.addField(identity_uint32_nop, Messages::FieldUInt32::create(4294967295)); BOOST_CHECK(message.getField("uint32_nop", value)); BOOST_CHECK_EQUAL(value->toUInt32(), 4294967295UL); //<int64 name="int64_nop" id="3"> //msg.addField(identity_int64_nop, Messages::FieldInt64::create(9223372036854775807)); BOOST_CHECK(message.getField("int64_nop", value)); BOOST_CHECK_EQUAL(value->toInt64(), 9223372036854775807LL); //<uInt64 name="uint64_nop" id="4"> //msg.addField(identity_uint64_nop, Messages::FieldUInt64::create(18446744073709551615)); BOOST_CHECK(message.getField("uint64_nop", value)); BOOST_CHECK_EQUAL(value->toUInt64(), 18446744073709551615ULL); //<decimal name="decimal_nop" id="5"> //msg.addField(identity_decimal_nop, Messages::FieldDecimal::create(Decimal(9223372036854775807, 63))); BOOST_CHECK(message.getField("decimal_nop", value)); BOOST_CHECK_EQUAL(value->toDecimal(), Decimal (9223372036854775807LL, 63)); //<string name="asciistring_nop" charset="ascii" id="6"> //msg.addField(identity_asciistring_nop, Messages::FieldAscii::create(buffer.c_str())); BOOST_CHECK(message.getField("asciistring_nop", value)); BOOST_CHECK_EQUAL(value->toAscii(), buffer.c_str()); //<string name="utf8string_nop" charset="unicode" id="7"> //msg.addField(identity_utf8string_nop, Messages::FieldAscii::create(buffer.c_str())); BOOST_CHECK(message.getField("utf8string_nop", value)); BOOST_CHECK_EQUAL(value->toUtf8(), buffer.c_str()); //<byteVector name="bytevector_nop" id="8"> //msg.addField(identity_bytevector_nop, Messages::FieldByteVector::create("")); BOOST_CHECK(message.getField("bytevector_nop", value)); BOOST_CHECK_EQUAL(value->toByteVector(), buffer.c_str()); // <int32 name="int32_const" id="9"><constant value="2147483647"/> //msg.addField(identity_int32_const, Messages::FieldInt32::create(2147483647)); BOOST_CHECK(message.getField("int32_const", value)); BOOST_CHECK_EQUAL(value->toInt32(), 2147483647L); // <uInt32 name="uint32_const" id="10"><constant value="0"/> //msg.addField(identity_uint32_const, Messages::FieldUInt32::create(4294967295)); BOOST_CHECK(message.getField("uint32_const", value)); BOOST_CHECK_EQUAL(value->toUInt32(), 4294967295UL); // <int64 name="int64_const" id="11"><constant value="9223372036854775807"/> //msg.addField(identity_int64_const, Messages::FieldInt64::create(9223372036854775807)); BOOST_CHECK(message.getField("int64_const", value)); BOOST_CHECK_EQUAL(value->toInt64(), 9223372036854775807LL); #if 0 // Disable this test due to a bug in boost::lexical_cast: https://svn.boost.org/trac/boost/ticket/2295 // <uInt64 name="uint64_const" id="12"><constant value="0"/> //msg.addField(identity_uint64_const, Messages::FieldUInt64::create(18446744073709551615)); BOOST_CHECK(message.getField("uint64_const", value)); BOOST_CHECK_EQUAL(value->toUInt64(), 18446744073709551615ULL); #endif // <decimal name="decimal_const" id="13"><constant value="9223372036854775807000000000000000000000000000000000000000000000000000000000000000"/> //msg.addField(identity_decimal_const, Messages::FieldDecimal::create(Decimal(9223372036854775807, 63))); BOOST_CHECK(message.getField("decimal_const", value)); BOOST_CHECK_EQUAL(value->toDecimal(), Decimal(9223372036854775807LL, 63)); // <string name="asciistring_const" charset="ascii" id="14"><constant value="$buffer"/> //msg.addField(identity_asciistring_const, Messages::FieldAscii::create(buffer.c_str())); BOOST_CHECK(message.getField("asciistring_const", value)); BOOST_CHECK_EQUAL(value->toAscii(), "$buffer"); // <string name="utf8string_const" charset="unicode" id="15"><constant value="$buffer"/> //msg.addField(identity_utf8string_const, Messages::FieldAscii::create(buffer.c_str())); BOOST_CHECK(message.getField("utf8string_const", value)); BOOST_CHECK_EQUAL(value->toUtf8(), "$buffer"); // <byteVector name="bytevector_const" id="16"><constant value="longgest string"/> //msg.addField(identity_bytevector_const, Messages::FieldByteVector::create(buffer.c_str())); BOOST_CHECK(message.getField("bytevector_const", value)); BOOST_CHECK_EQUAL(value->toByteVector(), "$buffer"); // <int32 name="int32_default" id="17"><default value="2147483647"/> //msg.addField(identity_int32_default, Messages::FieldInt32::create(2147483647)); BOOST_CHECK(message.getField("int32_default", value)); BOOST_CHECK_EQUAL(value->toInt32(), 2147483647); // <uInt32 name="uint32_default" id="18"><default value="0"/> //msg.addField(identity_uint32_default, Messages::FieldUInt32::create(4294967295)); BOOST_CHECK(message.getField("uint32_default", value)); BOOST_CHECK_EQUAL(value->toUInt32(), 4294967295UL); // <int64 name="int64_default" id="19"><default value="9223372036854775807"/> //msg.addField(identity_int64_default, Messages::FieldInt64::create(9223372036854775807)); BOOST_CHECK(message.getField("int64_default", value)); BOOST_CHECK_EQUAL(value->toInt64(), 9223372036854775807LL); #if 0 // Disable this test due to a bug in boost::lexical_cast: https://svn.boost.org/trac/boost/ticket/2295 // <uInt64 name="uint64_default" id="20"><default value="0"/> //msg.addField(identity_uint64_default, Messages::FieldUInt64::create(18446744073709551615)); BOOST_CHECK(message.getField("uint64_default", value)); BOOST_CHECK_EQUAL(value->toUInt64(), 18446744073709551615ULL); #endif // <decimal name="decimal_default" id="21"><default value="9223372036854775807000000000000000000000000000000000000000000000000000000000000000"/> //msg.addField(identity_decimal_default, Messages::FieldDecimal::create(Decimal(9223372036854775807, 63))); BOOST_CHECK(message.getField("decimal_default", value)); BOOST_CHECK_EQUAL(value->toDecimal(), Decimal(9223372036854775807LL, 63)); // <string name="asciistring_default" charset="ascii" id="22"><default value="$buffer"/> //msg.addField(identity_asciistring_default, Messages::FieldAscii::create(buffer.c_str())); BOOST_CHECK(message.getField("asciistring_default", value)); BOOST_CHECK_EQUAL(value->toAscii(), buffer.c_str()); // <string name="utf8string_default" charset="unicode" id="23"><default value="$buffer"/> //msg.addField(identity_utf8string_default, Messages::FieldAscii::create(buffer.c_str())); BOOST_CHECK(message.getField("utf8string_default", value)); BOOST_CHECK_EQUAL(value->toUtf8(), buffer.c_str()); // <byteVector name="bytevector_default" id="24"><default value="$buffer"/> //msg.addField(identity_bytevector_default, Messages::FieldByteVector::create(buffer.c_str())); BOOST_CHECK(message.getField("bytevector_default", value)); BOOST_CHECK_EQUAL(value->toByteVector(), buffer.c_str()); // <int32 name="int32_copy" id="25"><copy/> //msg.addField(identity_int32_copy, Messages::FieldInt32::create(2147483647)); BOOST_CHECK(message.getField("int32_copy", value)); BOOST_CHECK_EQUAL(value->toInt32(), 2147483647); // <uInt32 name="uint32_copy" id="26"><copy/> //msg.addField(identity_uint32_copy, Messages::FieldUInt32::create(4294967295)); BOOST_CHECK(message.getField("uint32_copy", value)); BOOST_CHECK_EQUAL(value->toUInt32(), 4294967295UL); // <int64 name="int64_copy" id="27"><copy/> //msg.addField(identity_int64_copy, Messages::FieldInt64::create(9223372036854775807)); BOOST_CHECK(message.getField("int64_copy", value)); BOOST_CHECK_EQUAL(value->toInt64(), 9223372036854775807LL); // <uInt64 name="uint64_copy" id="28"><copy/> // msg.addField(identity_uint64_copy, Messages::FieldUInt64::create(18446744073709551615)); BOOST_CHECK(message.getField("uint64_copy", value)); BOOST_CHECK_EQUAL(value->toUInt64(), 18446744073709551615ULL); // <decimal name="decimal_copy" id="29"><copy value="9223372036854775807000000000000000000000000000000000000000000000000000000000000000"/> //msg.addField(identity_decimal_copy, Messages::FieldDecimal::create(Decimal(9223372036854775807, 63))); BOOST_CHECK(message.getField("decimal_copy", value)); BOOST_CHECK_EQUAL(value->toDecimal(), Decimal(9223372036854775807LL, 63)); // <string name="asciistring_copy" charset="ascii" id="30"><copy/> //msg.addField(identity_asciistring_copy, Messages::FieldAscii::create(buffer.c_str())); BOOST_CHECK(message.getField("asciistring_copy", value)); BOOST_CHECK_EQUAL(value->toAscii(), buffer.c_str()); // <string name="utf8string_copy" charset="unicode" id="31"><copy/> //msg.addField(identity_utf8string_copy, Messages::FieldAscii::create(buffer.c_str())); BOOST_CHECK(message.getField("utf8string_copy", value)); BOOST_CHECK_EQUAL(value->toUtf8(), buffer.c_str()); // <byteVector name="bytevector_copy" id="32"><copy/> //msg.addField(identity_bytevector_copy, Messages::FieldByteVector::create(buffer.c_str())); BOOST_CHECK(message.getField("bytevector_copy", value)); BOOST_CHECK_EQUAL(value->toByteVector(), buffer.c_str()); // <int32 name="int32_delta" id="33"><copy/> //msg.addField(identity_int32_delta, Messages::FieldInt32::create(2147483647)); BOOST_CHECK(message.getField("int32_delta", value)); BOOST_CHECK_EQUAL(value->toInt32(), 2147483647); // <uInt32 name="uint32_delta" id="34"><delta/> //msg.addField(identity_uint32_delta, Messages::FieldUInt32::create(4294967295)); BOOST_CHECK(message.getField("uint32_delta", value)); BOOST_CHECK_EQUAL(value->toUInt32(), 4294967295UL); // <int64 name="int64_delta" id="35"><delta/> //msg.addField(identity_int64_delta, Messages::FieldInt64::create(9223372036854775807)); BOOST_CHECK(message.getField("int64_delta", value)); BOOST_CHECK_EQUAL(value->toInt64(), 9223372036854775807LL); // <uInt64 name="uint64_delta" id="36"><delta/> //msg.addField(identity_uint64_delta, Messages::FieldUInt64::create(18446744073709551615)); BOOST_CHECK(message.getField("uint64_delta", value)); BOOST_CHECK_EQUAL(value->toUInt64(), 18446744073709551615ULL); // <decimal name="decimal_delta" id="37"><delta/> //msg.addField(identity_decimal_delta, Messages::FieldDecimal::create(Decimal(9223372036854775807, 63))); BOOST_CHECK(message.getField("decimal_delta", value)); BOOST_CHECK_EQUAL(value->toDecimal(), Decimal(9223372036854775807LL, 63)); // <string name="asciistring_delta" charset="ascii" id="38"><delta/> //msg.addField(identity_asciistring_delta, Messages::FieldAscii::create(buffer.c_str())); BOOST_CHECK(message.getField("asciistring_delta", value)); BOOST_CHECK_EQUAL(value->toAscii(), buffer.c_str()); // <string name="utf8string_delta" charset="unicode" id="39"><delta/> //msg.addField(identity_utf8string_delta, Messages::FieldAscii::create(buffer.c_str())); BOOST_CHECK(message.getField("utf8string_delta", value)); BOOST_CHECK_EQUAL(value->toUtf8(), buffer.c_str()); // <byteVector name="bytevector_delta" id="40"><delta/> //msg.addField(identity_bytevector_delta, Messages::FieldByteVector::create(buffer.c_str())); BOOST_CHECK(message.getField("bytevector_delta", value)); BOOST_CHECK_EQUAL(value->toByteVector(), buffer.c_str()); // <int32 name="int32_incre" id="41"><increment value="1"/> //msg.addField(identity_int32_incre, Messages::FieldInt32::create(1)); BOOST_CHECK(message.getField("int32_incre", value)); BOOST_CHECK_EQUAL(value->toInt32(), 1); // <uInt32 name="uint32_incre" id="42"><increment value="1"/> //msg.addField(identity_uint32_incre, Messages::FieldUInt32::create(1)); BOOST_CHECK(message.getField("uint32_incre", value)); BOOST_CHECK_EQUAL(value->toUInt32(), 1); // <int64 name="int64_incre" id="43"><increment value="1"/> //msg.addField(identity_int64_incre, Messages::FieldInt64::create(1)); BOOST_CHECK(message.getField("int64_incre", value)); BOOST_CHECK_EQUAL(value->toInt64(), 1); // <uInt64 name="uint64_incre" id="44"><increment value="1"/> //msg.addField(identity_uint64_incre, Messages::FieldUInt64::create(1)); BOOST_CHECK(message.getField("uint64_incre", value)); BOOST_CHECK_EQUAL(value->toUInt64(), 1); // <string name="asciistring_tail" charset="ascii" id="45"><tail/> //msg.addField(identity_asciistring_tail, Messages::FieldAscii::create(buffer.c_str())); BOOST_CHECK(message.getField("asciistring_tail", value)); BOOST_CHECK_EQUAL(value->toAscii(), buffer.c_str ()); // <string name="utf8string_tail" charset="unicode" id="46"><tail/> //msg.addField(identity_utf8string_tail, Messages::FieldAscii::create(buffer.c_str())); BOOST_CHECK(message.getField("utf8string_tail", value)); BOOST_CHECK_EQUAL(value->toUtf8(), buffer.c_str ()); // <byteVector name="bytevector_tail" id="47"><tail/> //msg.addField(identity_bytevector_tail, Messages::FieldByteVector::create(buffer.c_str())); BOOST_CHECK(message.getField("bytevector_tail", value)); BOOST_CHECK_EQUAL(value->toByteVector(), buffer.c_str ()); } void biggest_value_test (const std::string& xml, const std::string& buffer) { std::ifstream templateStream(xml.c_str(), std::ifstream::binary); Codecs::XMLTemplateParser parser; Codecs::TemplateRegistryPtr templateRegistry = parser.parse(templateStream); Messages::Message msg(templateRegistry->maxFieldCount()); //<int32 name="int32_nop" id="1"> Messages::FieldIdentityCPtr identity_int32_nop = new Messages::FieldIdentity("int32_nop"); //<uInt32 name="uint32_nop" id="2"> Messages::FieldIdentityCPtr identity_uint32_nop = new Messages::FieldIdentity("uint32_nop"); //<int64 name="int64_nop" id="3"> Messages::FieldIdentityCPtr identity_int64_nop = new Messages::FieldIdentity("int64_nop"); //<uInt64 name="uint64_nop" id="4"> Messages::FieldIdentityCPtr identity_uint64_nop = new Messages::FieldIdentity("uint64_nop"); //<decimal name="decimal_nop" id="5"> Messages::FieldIdentityCPtr identity_decimal_nop = new Messages::FieldIdentity("decimal_nop"); //<string name="asciistring_nop" charset="ascii" id="6"> Messages::FieldIdentityCPtr identity_asciistring_nop = new Messages::FieldIdentity("asciistring_nop"); //<string name="utf8string_nop" charset="unicode" id="7"> Messages::FieldIdentityCPtr identity_utf8string_nop = new Messages::FieldIdentity("utf8string_nop"); //<byteVector name="bytevector_nop" id="8"> Messages::FieldIdentityCPtr identity_bytevector_nop = new Messages::FieldIdentity("bytevector_nop"); // <int32 name="int32_const" id="9"><constant value="2147483647"/> Messages::FieldIdentityCPtr identity_int32_const = new Messages::FieldIdentity("int32_const"); // <uInt32 name="uint32_const" id="10"><constant value="4294967295"/> Messages::FieldIdentityCPtr identity_uint32_const = new Messages::FieldIdentity("uint32_const"); // <int64 name="int64_const" id="11"><constant value="9223372036854775807"/> Messages::FieldIdentityCPtr identity_int64_const = new Messages::FieldIdentity("int64_const"); #if 0 // Disable this test due to a bug in boost::lexical_cast: https://svn.boost.org/trac/boost/ticket/2295 // <uInt64 name="uint64_const" id="12"><constant value="18446744073709551615"/> Messages::FieldIdentityCPtr identity_uint64_const = new Messages::FieldIdentity("uint64_const"); #endif //<decimal name="decimal_const" id="13"><constant value="9223372036854775807000000000000000000000000000000000000000000000000000000000000000"/> Messages::FieldIdentityCPtr identity_decimal_const = new Messages::FieldIdentity("decimal_const"); // <string name="asciistring_const" charset="ascii" id="14"><constant value="$buffer"/> Messages::FieldIdentityCPtr identity_asciistring_const = new Messages::FieldIdentity("asciistring_const"); // <string name="utf8string_const" charset="unicode" id="15"><constant value="$buffer"/> Messages::FieldIdentityCPtr identity_utf8string_const = new Messages::FieldIdentity("utf8string_const"); // <byteVector name="bytevector_const" id="16"><constant value="$buffer"/> Messages::FieldIdentityCPtr identity_bytevector_const = new Messages::FieldIdentity("bytevector_const"); // <int32 name="int32_default" id="17"><default value="2147483647"/> Messages::FieldIdentityCPtr identity_int32_default = new Messages::FieldIdentity("int32_default"); // <uInt32 name="uint32_default" id="18"><default value="0"/> Messages::FieldIdentityCPtr identity_uint32_default = new Messages::FieldIdentity("uint32_default"); // <uInt64 name="int64_default" id="19"><default value="9223372036854775807"/> Messages::FieldIdentityCPtr identity_int64_default = new Messages::FieldIdentity("int64_default"); #if 0 // Disable this test due to a bug in boost::lexical_cast: https://svn.boost.org/trac/boost/ticket/2295 // <uInt64 name="uint64_default" id="20"><default value="0"/> Messages::FieldIdentityCPtr identity_uint64_default = new Messages::FieldIdentity("uint64_default"); #endif // <decimal name="decimal_default" id="21"><default value="9223372036854775807000000000000000000000000000000000000000000000000000000000000000"/> Messages::FieldIdentityCPtr identity_decimal_default = new Messages::FieldIdentity("decimal_default"); // <string name="asciistring_default" charset="ascii" id="22"><default value="default asciistring"/> Messages::FieldIdentityCPtr identity_asciistring_default = new Messages::FieldIdentity("asciistring_default"); // <string name="utf8string_default" charset="unicode" id="23"><default value="default utf8string"/> Messages::FieldIdentityCPtr identity_utf8string_default = new Messages::FieldIdentity("utf8string_default"); // <byteVector name="bytevector_default" id="24"><default value="$buffer"/> Messages::FieldIdentityCPtr identity_bytevector_default = new Messages::FieldIdentity("bytevector_default"); // <int32 name="int32_copy" id="25"><copy/> Messages::FieldIdentityCPtr identity_int32_copy = new Messages::FieldIdentity("int32_copy"); // <uInt32 name="uint32_copy" id="26"><copy/> Messages::FieldIdentityCPtr identity_uint32_copy = new Messages::FieldIdentity("uint32_copy"); // <int64 name="int64_copy" id="27"><copy/> Messages::FieldIdentityCPtr identity_int64_copy = new Messages::FieldIdentity("int64_copy"); // <uInt64 name="uint64_copy" id="28"><copy/> Messages::FieldIdentityCPtr identity_uint64_copy = new Messages::FieldIdentity("uint64_copy"); // <decimal name="decimal_copy" id="29"><copy value="9223372036854775807000000000000000000000000000000000000000000000000000000000000000"/> Messages::FieldIdentityCPtr identity_decimal_copy = new Messages::FieldIdentity("decimal_copy"); // <string name="asciistring_copy" charset="ascii" id="30"><copy/> Messages::FieldIdentityCPtr identity_asciistring_copy = new Messages::FieldIdentity("asciistring_copy"); // <string name="utf8string_copy" charset="unicode" id="31"><copy/> Messages::FieldIdentityCPtr identity_utf8string_copy = new Messages::FieldIdentity("utf8string_copy"); // <byteVector name="bytevector_copy" id="32"><copy/> Messages::FieldIdentityCPtr identity_bytevector_copy = new Messages::FieldIdentity("bytevector_copy"); // <int32 name="int32_delta" id="33"><copy/> Messages::FieldIdentityCPtr identity_int32_delta = new Messages::FieldIdentity("int32_delta"); // <uInt32 name="uint32_delta" id="34"><delta/> Messages::FieldIdentityCPtr identity_uint32_delta = new Messages::FieldIdentity("uint32_delta"); // <int64 name="int64_delta" id="35"><delta/> Messages::FieldIdentityCPtr identity_int64_delta = new Messages::FieldIdentity("int64_delta"); // <uInt64 name="uint64_delta" id="36"><delta/> Messages::FieldIdentityCPtr identity_uint64_delta = new Messages::FieldIdentity("uint64_delta"); // <decimal name="decimal_delta" id="37"><delta/> Messages::FieldIdentityCPtr identity_decimal_delta = new Messages::FieldIdentity("decimal_delta"); // <string name="asciistring_delta" charset="ascii" id="38"><delta/> Messages::FieldIdentityCPtr identity_asciistring_delta = new Messages::FieldIdentity("asciistring_delta"); // <string name="utf8string_delta" charset="unicode" id="39"><delta/> Messages::FieldIdentityCPtr identity_utf8string_delta = new Messages::FieldIdentity("utf8string_delta"); // <byteVector name="bytevector_delta" id="40"><delta/> Messages::FieldIdentityCPtr identity_bytevector_delta = new Messages::FieldIdentity("bytevector_delta"); // <int32 name="int32_incre" id="41"><increment value="1"/> Messages::FieldIdentityCPtr identity_int32_incre = new Messages::FieldIdentity("int32_incre"); // <uInt32 name="uint32_incre" id="42"><increment value="1"/> Messages::FieldIdentityCPtr identity_uint32_incre = new Messages::FieldIdentity("uint32_incre"); // <int64 name="int64_incre" id="43"><increment value="1"/> Messages::FieldIdentityCPtr identity_int64_incre = new Messages::FieldIdentity("int64_incre"); // <uInt64 name="uint64_incre" id="44"><increment value="1"/> Messages::FieldIdentityCPtr identity_uint64_incre = new Messages::FieldIdentity("uint64_incre"); // <string name="asciistring_tail" charset="ascii" id="45"><tail/> Messages::FieldIdentityCPtr identity_asciistring_tail = new Messages::FieldIdentity("asciistring_tail"); // <string name="utf8string_tail" charset="unicode" id="46"><tail/> Messages::FieldIdentityCPtr identity_utf8string_tail = new Messages::FieldIdentity("utf8string_tail"); // <byteVector name="bytevector_tail" id="47"><tail/> Messages::FieldIdentityCPtr identity_bytevector_tail = new Messages::FieldIdentity("bytevector_tail"); //<int32 name="int32_nop" id="1"> msg.addField(identity_int32_nop, Messages::FieldInt32::create(2147483647)); //<uInt32 name="uint32_nop" id="2"> msg.addField(identity_uint32_nop, Messages::FieldUInt32::create(4294967295UL)); //<int64 name="int64_nop" id="3"> msg.addField(identity_int64_nop, Messages::FieldInt64::create(9223372036854775807LL)); //<uInt64 name="uint64_nop" id="4"> msg.addField(identity_uint64_nop, Messages::FieldUInt64::create(18446744073709551615ULL)); //<decimal name="decimal_nop" id="5"> msg.addField(identity_decimal_nop, Messages::FieldDecimal::create(Decimal(9223372036854775807LL, 63))); //<string name="asciistring_nop" charset="ascii" id="6"> msg.addField(identity_asciistring_nop, Messages::FieldAscii::create(buffer.c_str())); //<string name="utf8string_nop" charset="unicode" id="7"> msg.addField(identity_utf8string_nop, Messages::FieldAscii::create(buffer.c_str())); //<byteVector name="bytevector_nop" id="8"> msg.addField(identity_bytevector_nop, Messages::FieldByteVector::create(buffer.c_str())); // <int32 name="int32_const" id="9"><constant value="2147483647"/> msg.addField(identity_int32_const, Messages::FieldInt32::create(2147483647)); // <uInt32 name="uint32_const" id="10"><constant value="0"/> msg.addField(identity_uint32_const, Messages::FieldUInt32::create(4294967295UL)); // <int64 name="int64_const" id="11"><constant value="9223372036854775807"/> msg.addField(identity_int64_const, Messages::FieldInt64::create(9223372036854775807LL)); #if 0 // Disable this test due to a bug in boost::lexical_cast: https://svn.boost.org/trac/boost/ticket/2295 // <uInt64 name="uint64_const" id="12"><constant value="9223372036854775807"/> msg.addField(identity_uint64_const, Messages::FieldUInt64::create(18446744073709551615ULL)); #endif // <decimal name="decimal_const" id="13"><constant value="9223372036854775807000000000000000000000000000000000000000000000000000000000000000"/> msg.addField(identity_decimal_const, Messages::FieldDecimal::create(Decimal(9223372036854775807LL, 63))); // <string name="asciistring_const" charset="ascii" id="14"><constant value="$buffer"/> msg.addField(identity_asciistring_const, Messages::FieldAscii::create("$buffer")); // <string name="utf8string_const" charset="unicode" id="15"><constant value="$buffer"/> msg.addField(identity_utf8string_const, Messages::FieldAscii::create("$buffer")); // <byteVector name="bytevector_const" id="16"><constant value="$buffer"/> msg.addField(identity_bytevector_const, Messages::FieldByteVector::create("$buffer")); // <int32 name="int32_default" id="17"><default value="2147483647"/> msg.addField(identity_int32_default, Messages::FieldInt32::create(2147483647)); // <uInt32 name="uint32_default" id="18"><default value="0"/> msg.addField(identity_uint32_default, Messages::FieldUInt32::create(4294967295UL)); // <int64 name="int64_default" id="19"><default value="9223372036854775807"/> msg.addField(identity_int64_default, Messages::FieldInt64::create(9223372036854775807LL)); #if 0 // Disable this test due to a bug in boost::lexical_cast: https://svn.boost.org/trac/boost/ticket/2295 // <uInt64 name="uint64_default" id="20"><default value="0"/> msg.addField(identity_uint64_default, Messages::FieldUInt64::create(18446744073709551615ULL)); #endif // <decimal name="decimal_default" id="21"><default value="9223372036854775807000000000000000000000000000000000000000000000000000000000000000"/> msg.addField(identity_decimal_default, Messages::FieldDecimal::create(Decimal(9223372036854775807LL, 63))); // <string name="asciistring_default" charset="ascii" id="22"><default value="$buffer"/> msg.addField(identity_asciistring_default, Messages::FieldAscii::create(buffer.c_str())); // <string name="utf8string_default" charset="unicode" id="23"><default value="$buffer"/> msg.addField(identity_utf8string_default, Messages::FieldAscii::create(buffer.c_str())); // <byteVector name="bytevector_default" id="24"><default value="$buffer"/> msg.addField(identity_bytevector_default, Messages::FieldByteVector::create(buffer.c_str())); // <int32 name="int32_copy" id="25"><copy/> msg.addField(identity_int32_copy, Messages::FieldInt32::create(2147483647)); // <uInt32 name="uint32_copy" id="26"><copy/> msg.addField(identity_uint32_copy, Messages::FieldUInt32::create(4294967295UL)); // <int64 name="int64_copy" id="27"><copy/> msg.addField(identity_int64_copy, Messages::FieldInt64::create(9223372036854775807LL)); // <uInt64 name="uint64_copy" id="28"><copy/> msg.addField(identity_uint64_copy, Messages::FieldUInt64::create(18446744073709551615ULL)); // <decimal name="decimal_copy" id="29"><copy value="9223372036854775807000000000000000000000000000000000000000000000000000000000000000"/> msg.addField(identity_decimal_copy, Messages::FieldDecimal::create(Decimal(9223372036854775807LL, 63))); // <string name="asciistring_copy" charset="ascii" id="30"><copy/> msg.addField(identity_asciistring_copy, Messages::FieldAscii::create(buffer.c_str())); // <string name="utf8string_copy" charset="unicode" id="31"><copy/> msg.addField(identity_utf8string_copy, Messages::FieldAscii::create(buffer.c_str())); // <byteVector name="bytevector_copy" id="32"><copy/> msg.addField(identity_bytevector_copy, Messages::FieldByteVector::create(buffer.c_str())); // <int32 name="int32_delta" id="33"><copy/> msg.addField(identity_int32_delta, Messages::FieldInt32::create(2147483647)); // <uInt32 name="uint32_delta" id="34"><delta/> msg.addField(identity_uint32_delta, Messages::FieldUInt32::create(4294967295UL)); // <int64 name="int64_delta" id="35"><delta/> msg.addField(identity_int64_delta, Messages::FieldInt64::create(9223372036854775807LL)); // <uInt64 name="uint64_delta" id="36"><delta/> msg.addField(identity_uint64_delta, Messages::FieldUInt64::create(18446744073709551615ULL)); // <decimal name="decimal_delta" id="37"><delta/> msg.addField(identity_decimal_delta, Messages::FieldDecimal::create(Decimal(9223372036854775807LL, 63))); // <string name="asciistring_delta" charset="ascii" id="38"><delta/> msg.addField(identity_asciistring_delta, Messages::FieldAscii::create(buffer.c_str())); // <string name="utf8string_delta" charset="unicode" id="39"><delta/> msg.addField(identity_utf8string_delta, Messages::FieldAscii::create(buffer.c_str())); // <byteVector name="bytevector_delta" id="40"><delta/> msg.addField(identity_bytevector_delta, Messages::FieldByteVector::create(buffer.c_str())); // <int32 name="int32_incre" id="41"><increment value="1"/> msg.addField(identity_int32_incre, Messages::FieldInt32::create(1)); // <uInt32 name="uint32_incre" id="42"><increment value="1"/> msg.addField(identity_uint32_incre, Messages::FieldUInt32::create(1)); // <int64 name="int64_incre" id="43"><increment value="1"/> msg.addField(identity_int64_incre, Messages::FieldInt64::create(1)); // <uInt64 name="uint64_incre" id="44"><increment value="1"/> msg.addField(identity_uint64_incre, Messages::FieldUInt64::create(1)); // <string name="asciistring_tail" charset="ascii" id="45"><tail/> msg.addField(identity_asciistring_tail, Messages::FieldAscii::create(buffer.c_str ())); // <string name="utf8string_tail" charset="unicode" id="46"><tail/> msg.addField(identity_utf8string_tail, Messages::FieldAscii::create(buffer.c_str ())); // <byteVector name="bytevector_tail" id="47"><tail/> msg.addField(identity_bytevector_tail, Messages::FieldByteVector::create(buffer.c_str ())); Codecs::Encoder encoder(templateRegistry); //encoder.setVerboseOutput (std::cout); Codecs::DataDestination destination; template_id_t templId = 3; // from the XML file encoder.encodeMessage(destination, templId, msg); std::string fastString; destination.toString(fastString); destination.clear(); Codecs::Decoder decoder(templateRegistry); //decoder.setVerboseOutput (std::cout); Codecs::DataSourceString source(fastString); Codecs::SingleMessageConsumer consumer; Codecs::GenericMessageBuilder builder(consumer); decoder.decodeMessage(source, builder); Messages::Message & msgOut = consumer.message(); validateMessage1(msgOut, buffer); // wanna see it again? encoder.reset(); encoder.encodeMessage(destination, templId, msgOut); std::string reencoded; destination.toString(reencoded); destination.clear(); BOOST_CHECK(fastString == reencoded); } char random_char() { // // n = ( rand() % ( max - min + 1 ) ) + min; // 122 = 'z', 97 = 'a' // n = ( rand() % ( 122 - 97 + 1 ) ) + 97 return ( rand() % ( 26 ) ) + 97; } // // Returns a randomly generated string. // void string_generate(std::string& str, size_t len) { // // Generate 10 random characters. // std::generate_n( std::back_inserter( str ), len, random_char ); } } BOOST_AUTO_TEST_CASE(TestBiggestValue) { // uint64 compilerGenerated = 18446744073709551615ULL; //// std::string biggestUInt64 = "18446744073709551615"; // std::string biggestUInt64 = "9223372036854775808"; // uint64 boostGenerated = boost::lexical_cast<unsigned long long>(biggestUInt64); std::string xml (std::getenv ("QUICKFAST_ROOT")); xml += "/src/Tests/resources/biggest_value.xml"; std::string str; string_generate (str, 1000); biggest_value_test (xml, str); }
[ "[email protected]@d6d8e96c-ed78-11dd-ab07-b19b4dad1b3d", "dale.wilson@d6d8e96c-ed78-11dd-ab07-b19b4dad1b3d" ]
[ [ [ 1, 13 ], [ 15, 15 ], [ 18, 36 ], [ 39, 66 ], [ 68, 70 ], [ 72, 75 ], [ 77, 80 ], [ 82, 100 ], [ 102, 105 ], [ 107, 110 ], [ 112, 112 ], [ 114, 116 ], [ 119, 121 ], [ 123, 146 ], [ 148, 151 ], [ 153, 153 ], [ 155, 157 ], [ 160, 162 ], [ 164, 187 ], [ 189, 192 ], [ 194, 197 ], [ 199, 202 ], [ 204, 227 ], [ 229, 232 ], [ 234, 237 ], [ 239, 242 ], [ 244, 329 ], [ 331, 332 ], [ 334, 347 ], [ 349, 350 ], [ 352, 409 ], [ 411, 411 ], [ 413, 413 ], [ 415, 415 ], [ 417, 425 ], [ 427, 427 ], [ 430, 430 ], [ 433, 433 ], [ 435, 443 ], [ 445, 445 ], [ 448, 448 ], [ 451, 451 ], [ 453, 461 ], [ 463, 463 ], [ 465, 465 ], [ 467, 467 ], [ 469, 477 ], [ 479, 479 ], [ 481, 481 ], [ 483, 483 ], [ 485, 507 ], [ 509, 510 ], [ 515, 519 ], [ 524, 527 ], [ 529, 529 ], [ 534, 562 ], [ 568, 572 ], [ 574, 576 ] ], [ [ 14, 14 ], [ 16, 17 ], [ 37, 38 ], [ 67, 67 ], [ 71, 71 ], [ 76, 76 ], [ 81, 81 ], [ 101, 101 ], [ 106, 106 ], [ 111, 111 ], [ 113, 113 ], [ 117, 118 ], [ 122, 122 ], [ 147, 147 ], [ 152, 152 ], [ 154, 154 ], [ 158, 159 ], [ 163, 163 ], [ 188, 188 ], [ 193, 193 ], [ 198, 198 ], [ 203, 203 ], [ 228, 228 ], [ 233, 233 ], [ 238, 238 ], [ 243, 243 ], [ 330, 330 ], [ 333, 333 ], [ 348, 348 ], [ 351, 351 ], [ 410, 410 ], [ 412, 412 ], [ 414, 414 ], [ 416, 416 ], [ 426, 426 ], [ 428, 429 ], [ 431, 432 ], [ 434, 434 ], [ 444, 444 ], [ 446, 447 ], [ 449, 450 ], [ 452, 452 ], [ 462, 462 ], [ 464, 464 ], [ 466, 466 ], [ 468, 468 ], [ 478, 478 ], [ 480, 480 ], [ 482, 482 ], [ 484, 484 ], [ 508, 508 ], [ 511, 514 ], [ 520, 523 ], [ 528, 528 ], [ 530, 533 ], [ 563, 567 ], [ 573, 573 ] ] ]
d211098593d44e0142c932cdf2b9fff976fc8f88
ce262ae496ab3eeebfcbb337da86d34eb689c07b
/SEFoundation/SESceneGraph/SECameraNode.inl
1fcd98c196b3ca4637294e00b0200c3883853dce
[]
no_license
pizibing/swingengine
d8d9208c00ec2944817e1aab51287a3c38103bea
e7109d7b3e28c4421c173712eaf872771550669e
refs/heads/master
2021-01-16T18:29:10.689858
2011-06-23T04:27:46
2011-06-23T04:27:46
33,969,301
0
0
null
null
null
null
UTF-8
C++
false
false
1,335
inl
// Swing Engine Version 1 Source Code // Most of techniques in the engine are mainly based on David Eberly's // Wild Magic 4 open-source code.The author of Swing Engine learned a lot // from Eberly's experience of architecture and algorithm. // Several sub-systems are totally new,and others are re-implimented or // re-organized based on Wild Magic 4's sub-systems. // Copyright (c) 2007-2010. All Rights Reserved // // Eberly's permission: // Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation; either version 2.1 of the License, or (at // your option) any later version. The license is available for reading at // the location: // http://www.gnu.org/copyleft/lgpl.html //---------------------------------------------------------------------------- inline SECamera* SECameraNode::GetCamera() { return m_spCamera; } //---------------------------------------------------------------------------- inline const SECamera* SECameraNode::GetCamera() const { return m_spCamera; } //----------------------------------------------------------------------------
[ "[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac" ]
[ [ [ 1, 31 ] ] ]
9359325b2e6c0d1378ce50070e5ca29897ce8182
9a6a9d17dde3e8888d8183618a02863e46f072f1
/MyMaxVisualisationView.cpp
6b0c6a3e7ca2a2178aa1b7bb3dcf5e1d964a23b4
[]
no_license
pritykovskaya/max-visualization
34266c449fb2c03bed6fd695e0b54f144d78e123
a3c0879a8030970bb1fee95d2bfc6ccf689972ea
refs/heads/master
2021-01-21T12:23:01.436525
2011-07-06T18:23:38
2011-07-06T18:23:38
2,006,225
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
15,185
cpp
// MyMaxVisualisationView.cpp : implementation of the CMyMaxVisualisationView class // #include "stdafx.h" #include "MyMaxVisualisation.h" #include "MyMaxVisualisationDoc.h" #include "MyMaxVisualisationView.h" #include "DialogFinal.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CMyMaxVisualisationView IMPLEMENT_DYNCREATE(CMyMaxVisualisationView, CView) BEGIN_MESSAGE_MAP(CMyMaxVisualisationView, CView) // Standard printing commands ON_COMMAND(ID_FILE_PRINT, &CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, &CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, &CView::OnFilePrintPreview) ON_WM_LBUTTONDOWN() ON_COMMAND(ID_SETTINGS, &CMyMaxVisualisationView::OnSettings) END_MESSAGE_MAP() // CMyMaxVisualisationView construction/destruction CMyMaxVisualisationView::CMyMaxVisualisationView(): max_value(0), min_value(0), draw_traject(false), draw_point(false) { // TODO: add construction code here } CMyMaxVisualisationView::~CMyMaxVisualisationView() { } BOOL CMyMaxVisualisationView::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs return CView::PreCreateWindow(cs); } // CMyMaxVisualisationView drawing // CMyMaxVisualisationView printing BOOL CMyMaxVisualisationView::OnPreparePrinting(CPrintInfo* pInfo) { // default preparation return DoPreparePrinting(pInfo); } void CMyMaxVisualisationView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add extra initialization before printing } void CMyMaxVisualisationView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add cleanup after printing } // CMyMaxVisualisationView diagnostics #ifdef _DEBUG void CMyMaxVisualisationView::AssertValid() const { CView::AssertValid(); } void CMyMaxVisualisationView::Dump(CDumpContext& dc) const { CView::Dump(dc); } CMyMaxVisualisationDoc* CMyMaxVisualisationView::GetDocument() const // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CMyMaxVisualisationDoc))); return (CMyMaxVisualisationDoc*)m_pDocument; } #endif //_DEBUG void CMyMaxVisualisationView::DrawAxis(CDC* pDC){ CMyMaxVisualisationDoc* pDoc = GetDocument(); CRect rc; GetClientRect(&rc); double x_coord = (pDoc-> p_area -> my_area[1] - pDoc-> p_area -> my_area[0]) / 10; double y_coord = (pDoc-> p_area -> my_area[3] - pDoc-> p_area -> my_area[2]) / 10; CPen pen; CPen * pOldPen; pen.CreatePen(PS_SOLID, 2, RGB(0, 0, 0)); pOldPen = pDC -> SelectObject(&pen); int width = rc.Width() - 150; int height = rc.Height() - 150; pDC->MoveTo(75, 50); pDC->LineTo(75, height + 50); pDC->LineTo(width + 75, height + 50); char axis_legend[100]; for (int i = 0; i <= 10; ++i) { pDC->MoveTo(75 + i*width/10, height + 45); pDC->LineTo(75 + i*width/10, height + 55); sprintf(axis_legend, "%4.2f", pDoc->p_area->my_area[0] + i*x_coord); pDC->TextOut(55 + i*width/10, height + 60, CString(axis_legend)); } for (int i = 0; i <= 10; ++i) { pDC->MoveTo(70, 50 + i*height/10); pDC->LineTo(80, 50 + i*height/10); sprintf(axis_legend, "%4.2f", pDoc->p_area->my_area[2] + (10 - i)*y_coord); pDC->TextOut(35, 40 + i*height/10, CString(axis_legend)); } pDC->SelectObject(pOldPen); pen.DeleteObject(); } vector<int> CMyMaxVisualisationView::TransformToPix(vector<double> v) { CMyMaxVisualisationDoc* pDoc = GetDocument(); CRect rc; GetClientRect(&rc); vector <int> res(2); res[0] = (75 + (v[0] - pDoc->p_area->my_area[0])/(pDoc->p_area->my_area[1] - pDoc->p_area->my_area[0])*(rc.Width() - 150)); res[1] = (rc.Height()-100 - (v[1]-pDoc->p_area->my_area[2])/(pDoc->p_area->my_area[3]-pDoc->p_area->my_area[2])*(rc.Height()-150)); return res; } vector<double> CMyMaxVisualisationView::TransformToPoint(vector<int> v) { CMyMaxVisualisationDoc* pDoc = GetDocument(); CRect rc; GetClientRect(&rc); vector <double> res(2); res[0] = (pDoc->p_area->my_area[0]+(v[0]-75)/(rc.Width() - 150)*(pDoc->p_area->my_area[1] - pDoc->p_area->my_area[0])); res[1] = (pDoc->p_area->my_area[2]+(rc.Height()-100-v[1])/(rc.Height()-150)*(pDoc->p_area->my_area[3] - pDoc->p_area->my_area[2])); return res; } int CMyMaxVisualisationView::TransformToPixX(double x) { CMyMaxVisualisationDoc* pDoc = GetDocument(); CRect rc; GetClientRect(&rc); return 75 + (x - pDoc->p_area->my_area[0])/(pDoc->p_area->my_area[1] - pDoc->p_area->my_area[0])*(rc.Width() - 150); } int CMyMaxVisualisationView::TransformToPixY(double y) { CMyMaxVisualisationDoc* pDoc = GetDocument(); CRect rc; GetClientRect(&rc); return rc.Height()- 100 -(y - pDoc->p_area->my_area[2]) / (pDoc->p_area->my_area[3]-pDoc->p_area->my_area[2])*(rc.Height() - 150); } double CMyMaxVisualisationView::TransformToPointX(double x) { CMyMaxVisualisationDoc* pDoc = GetDocument(); CRect rc; GetClientRect(&rc); return pDoc->p_area->my_area[0]+(double)(x-75)/(rc.Width() - 150)*(pDoc->p_area->my_area[1] - pDoc->p_area->my_area[0]); } double CMyMaxVisualisationView::TransformToPointY(double y) { CMyMaxVisualisationDoc* pDoc = GetDocument(); CRect rc; GetClientRect(&rc); return pDoc->p_area->my_area[2]+(double)(rc.Height()-100-y)/(rc.Height()-150)*(pDoc->p_area->my_area[3] - pDoc->p_area->my_area[2]); } void CMyMaxVisualisationView::DrawMap(CDC* pDC) { CMyMaxVisualisationDoc* pDoc = GetDocument(); CRect rc; GetClientRect(&rc); int width = rc.Width() - 150; int heigth = rc.Height() - 150; double cur_value; cur_value = (*(pDoc->p_func))(TransformToPointX(75), TransformToPointY(heigth + 50)); min_value = cur_value; max_value = cur_value; double x, y, color; for (int i = 76; i < width + 75; i = i + 5) { for(int j = heigth + 50; j > 50; j = j - 5) { x = TransformToPointX(i); y = TransformToPointY(j); cur_value = (*(pDoc->p_func))(x,y); if (cur_value > max_value) max_value = cur_value; if (cur_value < min_value) min_value = cur_value; } } CDC map; CBitmap bit; bit.CreateCompatibleBitmap(pDC, width, heigth); map.CreateCompatibleDC(pDC); map.SelectObject(&bit); for (int i = 0; i < width; ++i) { for(int j = 0; j < heigth; ++j) { x = TransformToPointX(i + 75); y = TransformToPointY(heigth + 50 - j); cur_value = (*(pDoc->p_func))(x,y); color = (cur_value - min_value)/(max_value - min_value) * 150; map.SetPixel(i, heigth - j, RGB(0, color, 100)); } } pDC->BitBlt(75, 50, width, heigth, &map, 0, 0, SRCCOPY); } void CMyMaxVisualisationView::DrawTrajectory(CDC* pDC) { CMyMaxVisualisationDoc* pDoc = GetDocument(); if (draw_traject == 1) { CRect rc; GetClientRect(&rc); CPen pen; CPen * pOldPen; pen.CreatePen(PS_SOLID, 1, RGB(150,150,200)); pOldPen = pDC->SelectObject(&pen); vector <vector<double>> temp = pDoc->method_result.my_trajectory; vector <vector <double>>::iterator iter = temp.begin(); int x = TransformToPixX(temp[0][0]); int y = TransformToPixY(temp[0][1]); pDC->MoveTo(x, y); pDC->Rectangle(x - 3, y - 3, x + 3, y + 3); ++iter; for (int i = 0; i < temp.size(); ++i) { x = TransformToPixX(temp[i][0]); y = TransformToPixY(temp[i][1]); pDC->LineTo(x, y); pDC->Rectangle(x - 2, y - 2, x + 2, y + 2); } pDC->SelectObject(pOldPen); pen.DeleteObject(); CBrush brush; CBrush * pOldBrush; brush.CreateSolidBrush(RGB(255, 255, 0)); pOldBrush = pDC->SelectObject(&brush); pDC->Ellipse(x - 6, y - 6, x + 6, y + 6); pDC->SelectObject(pOldBrush); brush.DeleteObject(); } } // CMyMaxVisualisationView message handlers void CMyMaxVisualisationView::OnLButtonDown(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default CMyMaxVisualisationDoc* pDoc = GetDocument(); CRect rc; GetClientRect(&rc); int width = rc.Width() - 150; int height = rc.Height() - 150; if (point.x >= 75 && point.x <= 75 + width && point.y >= 50 && point.y <= height + 50) { double x = TransformToPointX(point.x); double y = TransformToPointY(point.y); vector<double> current_point; current_point.push_back(x); current_point.push_back(y); clicks.push_back(current_point); if (clicks.size() == pDoc -> p_current_method ->numb_of_start_points()) { MethodResult result = pDoc -> p_current_method -> search_process(pDoc->p_func, pDoc->p_area, clicks); pDoc -> method_result = result; draw_traject = 1; draw_point = 0; clicks.clear(); } else { draw_point = 1; draw_traject = 0; } } Invalidate(); CView::OnLButtonDown(nFlags, point); } void CMyMaxVisualisationView::DrawPoint(CDC* pDC ) { CPen pen; CPen * pOldPen; pen.CreatePen(PS_SOLID, 1, RGB(150,150,200)); pOldPen = pDC->SelectObject(&pen); vector<int> point = TransformToPix(clicks[0]); pDC->Rectangle(point[0] - 3, point[1] - 3, point[0] + 3, point[1] + 3); pDC->SelectObject(pOldPen); pen.DeleteObject(); } void CMyMaxVisualisationView::WriteFuncAndMethodNames(CDC* pDC) { CMyMaxVisualisationDoc* pDoc = GetDocument(); CRect rc; GetClientRect(&rc); CPen pen; CPen * pOldPen; pen.CreatePen(PS_SOLID, 1, RGB(0,0,0)); pOldPen = pDC->SelectObject(&pen); int width = rc.Width() - 150; int height = rc.Height() - 150; char inscr[100]; double start_value; sprintf(inscr, "Function: %s", pDoc->p_func->get_formula().c_str()); pDC->TextOut(400, 25, CString(inscr)); int t = height + 80; sprintf(inscr, "Search Metod: %s", pDoc->p_current_method->get_method_name().c_str()); pDC->TextOut(80, t, CString(inscr)); pDC->SelectObject(pOldPen); pen.DeleteObject(); }; //выводим результат void CMyMaxVisualisationView::WriteResult(CDC* pDC) { if (draw_traject == 1) { CMyMaxVisualisationDoc* pDoc = GetDocument(); CRect rc; GetClientRect(&rc); CPen pen; CPen * pOldPen; pen.CreatePen(PS_SOLID, 1, RGB(0,0,0)); pOldPen = pDC->SelectObject(&pen); int height = rc.Height() - 150; int t = height + 80; char inscr[255]; for (int i = 0; i < pDoc->p_current_method->numb_of_start_points(); ++i) { double start_value = (*(pDoc->p_func))(pDoc->method_result.my_trajectory[i][0], pDoc->method_result.my_trajectory[i][1]); sprintf(inscr, "Start Point %d: (%f, %f) Start Value %d: %f", i+1, pDoc->method_result.my_trajectory[i][0], pDoc->method_result.my_trajectory[i][1], i+1, start_value); pDC->TextOut(80, t + 15 + 15*i,CString(inscr)); } vector <vector<double>> temp = pDoc->method_result.my_trajectory; double final_x = temp[temp.size()-1][0]; double final_y = temp[temp.size()-1][1]; double cur_value = (*(pDoc->p_func))(final_x, final_y); sprintf(inscr, "Final Point: (%f, %f) Final Value: %f", final_x, final_y, cur_value); t = rc.Height() - 25; pDC->TextOut(80, t, CString(inscr)); sprintf(inscr, "Reason of stop: %s", pDoc->method_result.reason_of_stop.c_str()); pDC->TextOut(550, t, CString(inscr)); sprintf(inscr, "Steps made: %d", pDoc->method_result.my_trajectory.size()); pDC->TextOut(550, t - 30, CString(inscr)); pDC->SelectObject(pOldPen); pen.DeleteObject(); } } void CMyMaxVisualisationView::OnDraw(CDC* pDC) { CMyMaxVisualisationDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; DrawAxis(pDC); WriteFuncAndMethodNames(pDC); DrawMap(pDC); if (draw_point) { DrawPoint(pDC); } DrawTrajectory(pDC); WriteResult(pDC); } void CMyMaxVisualisationView::OnSettings() { vector<double> second_point; DialogFinal dial; CMyMaxVisualisationDoc* pDoc = GetDocument(); dial.m_min_x = pDoc -> p_area->my_area[0]; dial.m_max_x = pDoc -> p_area->my_area[1]; dial.m_min_y = pDoc -> p_area->my_area[2]; dial.m_max_y = pDoc -> p_area->my_area[3]; dial.m_func = pDoc-> f_type; dial.m_meth = pDoc -> method_type; dial.m_steps = pDoc -> p_random_method -> get_steps(); // random dial.m_rand_eps = pDoc -> p_random_method -> get_epsilon(); dial.m_p = pDoc-> p_random_method -> get_p(); dial.m_fail_steps = pDoc -> p_random_method -> get_fail_steps(); // gorge dial.m_eps_point_change = pDoc -> p_gorge_method -> get_eps_point_change(); dial.m_start_x = 0; dial.m_start_y = 0; dial.m_x_second_start_point = 0.1; dial.m_y_second_start_point = 0.1; if (draw_traject) { dial.m_start_x = pDoc->method_result.my_trajectory[0][0]; dial.m_start_y = pDoc->method_result.my_trajectory[0][1]; if (pDoc->method_type == 1) { dial.m_x_second_start_point = pDoc->method_result.my_trajectory[1][0]; dial.m_y_second_start_point = pDoc->method_result.my_trajectory[1][1]; } } else { if (clicks.size() == 1) { dial.m_start_x = clicks[0][0]; dial.m_start_y = clicks[0][1]; } } if (dial.DoModal() == IDOK) { pDoc -> p_area->my_area.clear(); pDoc -> p_area->my_area.push_back(dial.m_min_x); pDoc -> p_area->my_area.push_back(dial.m_max_x); pDoc -> p_area->my_area.push_back(dial.m_min_y); pDoc -> p_area->my_area.push_back(dial.m_max_y); pDoc -> f_type = dial.m_func; pDoc -> method_type = dial.m_meth; // Полиморфизм if (pDoc->method_type == 0) { pDoc->p_current_method = pDoc->p_random_method; } else { pDoc->p_current_method = pDoc->p_gorge_method; } // random pDoc -> p_random_method -> set_steps(dial.m_steps); pDoc -> p_random_method -> set_epsilon(dial.m_rand_eps); pDoc -> p_random_method -> set_p(dial.m_p); pDoc -> p_random_method -> set_fail_steps(dial.m_fail_steps); // gorge pDoc -> p_gorge_method -> set_numb_of_steps(dial.m_steps); pDoc -> p_gorge_method -> set_eps_point_change(dial.m_eps_point_change); switch (pDoc -> f_type) { case 0: { delete pDoc -> p_func; pDoc -> p_func = new Function_1(); break; } case 1: { delete pDoc -> p_func; pDoc -> p_func = new Function_2(); break; } case 2: { delete pDoc -> p_func; pDoc -> p_func = new Function_3(); break; } case 3: { delete pDoc -> p_func; pDoc -> p_func = new Function_4(); break; } } vector<double> first_start_point; first_start_point.push_back(dial.m_start_x); first_start_point.push_back(dial.m_start_y); vector<double> second_start_point; second_start_point.push_back(dial.m_x_second_start_point); second_start_point.push_back(dial.m_y_second_start_point); vector<vector<double>> start_points; start_points.push_back(first_start_point); start_points.push_back(second_start_point); pDoc->method_result = pDoc->p_current_method->search_process(pDoc->p_func, pDoc->p_area, start_points); draw_traject = 1; draw_point = 0; clicks.clear(); Invalidate(); } }
[ [ [ 1, 571 ] ] ]
10a4b1f2edb3fffa28b3042d49ace53378a89aea
0bbd7f9f444c4e1e52ab3fbea809a3c96a9034d9
/lib/zchaff-mincost/core/zchaff_solver.cpp
20d8918d00e9c08fb0bde8949cd17e71714ccbe0
[ "MIT" ]
permissive
msakai/kodkod
75ff92b564dbe8d1e8f2e1c94080d429e39b38b2
e8914f533a5416255de760039ad8f8c1445e094f
refs/heads/master
2020-05-19T08:12:08.156968
2011-11-06T23:24:02
2011-11-06T23:24:02
2,720,881
0
0
null
null
null
null
UTF-8
C++
false
false
64,160
cpp
// ********************************************************************* // Copyright 2000-2004, Princeton University. All rights reserved. // By using this software the USER indicates that he or she has read, // understood and will comply with the following: // // --- Princeton University hereby grants USER nonexclusive permission // to use, copy and/or modify this software for internal, noncommercial, // research purposes only. Any distribution, including commercial sale // or license, of this software, copies of the software, its associated // documentation and/or modifications of either is strictly prohibited // without the prior consent of Princeton University. Title to copyright // to this software and its associated documentation shall at all times // remain with Princeton University. Appropriate copyright notice shall // be placed on all software copies, and a complete copy of this notice // shall be included in all copies of the associated documentation. // No right is granted to use in advertising, publicity or otherwise // any trademark, service mark, or the name of Princeton University. // // // --- This software and any associated documentation is provided "as is" // // PRINCETON UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS // OR IMPLIED, INCLUDING THOSE OF MERCHANTABILITY OR FITNESS FOR A // PARTICULAR PURPOSE, OR THAT USE OF THE SOFTWARE, MODIFICATIONS, OR // ASSOCIATED DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, // TRADEMARKS OR OTHER INTELLECTUAL PROPERTY RIGHTS OF A THIRD PARTY. // // Princeton University shall not be liable under any circumstances for // any direct, indirect, special, incidental, or consequential damages // with respect to any claim by USER or any third party on account of // or arising from the use, or inability to use, this software or its // associated documentation, even if Princeton University has been advised // of the possibility of those damages. // ******************************************************************** #include <stdio.h> #include <iostream> #include <algorithm> #include <fstream> #include <vector> #include <map> #include <set> #include <queue> #ifdef HAVE_LIMITS_H #include "limits.h" #endif using namespace std; #include "zchaff_solver.h" // #define VERIFY_ON #ifdef VERIFY_ON ofstream verify_out("resolve_trace"); #endif void MSolver::re_init_stats(void) { _stats.is_mem_out = false; _stats.outcome = UNDETERMINED; _stats.next_restart = _params.restart.first_restart; _stats.restart_incr = _params.restart.backtrack_incr; _stats.next_cls_deletion = _params.cls_deletion.interval; _stats.next_var_score_decay = _params.decision.decay_period; _stats.current_randomness = _params.decision.base_randomness; _stats.total_bubble_move = 0; _stats.num_decisions = 0; _stats.num_decisions_stack_conf = 0; _stats.num_decisions_vsids = 0; _stats.num_decisions_shrinking = 0; _stats.num_backtracks = 0; _stats.max_dlevel = 0; _stats.num_implications = 0; _stats.num_restarts = 0; _stats.num_del_orig_cls = 0; _stats.num_shrinkings = 0; if (_stats.start_cpu_time != 0) _stats.start_cpu_time = get_cpu_time(); _stats.finish_cpu_time = 0; _stats.random_seed = 0; _stats.total_cost = 0; } void MSolver::init_stats(void) { re_init_stats(); _stats.been_reset = true; _stats.num_free_variables = 0; _stats.num_free_branch_vars = 0; } void MSolver::init_parameters(void) { _params.verbosity = 0; _params.time_limit = 3600 * 24; // a day _params.shrinking.size = 95; _params.shrinking.enable = false; _params.shrinking.upper_bound = 800; _params.shrinking.lower_bound = 600; _params.shrinking.upper_delta = -5; _params.shrinking.lower_delta = 10; _params.shrinking.window_width = 20; _params.shrinking.bound_update_frequency = 20; _params.decision.base_randomness = 0; _params.decision.decay_period = 40; _params.decision.bubble_init_step = 0x400; _params.cls_deletion.enable = true ; _params.cls_deletion.head_activity = 100;//500; _params.cls_deletion.tail_activity = 2;//10; _params.cls_deletion.head_num_lits = 20; // 6; _params.cls_deletion.tail_num_lits = 300;//100 45; _params.cls_deletion.tail_vs_head = 32;//16; _params.cls_deletion.interval = 600; _params.restart.enable = true; _params.restart.interval = 700; _params.restart.first_restart = 700; _params.restart.backtrack_incr = 700; } MSolver::MSolver(void) { init_parameters(); init_stats(); _dlevel = 0; _force_terminate = false; _implication_id = 0; _num_marked = 0; _num_in_new_cl = 0; _outside_constraint_hook = NULL; _sat_hook = NULL; _stats.min_cost = INT_MAX; } MSolver::~MSolver(void) { while (!_assignment_stack.empty()) { delete _assignment_stack.back(); _assignment_stack.pop_back(); } } void MSolver::set_time_limit(float t) { _params.time_limit = t; } float MSolver::elapsed_cpu_time(void) { return get_cpu_time() - _stats.start_cpu_time; } float MSolver::cpu_run_time(void) { return (_stats.finish_cpu_time - _stats.start_cpu_time); } void MSolver::set_variable_number(int n) { assert(num_variables() == 0); MDatabase::set_variable_number(n); _stats.num_free_variables = num_variables(); while (_assignment_stack.size() <= num_variables()) _assignment_stack.push_back(new vector<int>); assert(_assignment_stack.size() == num_variables() + 1); } void MSolver::set_variable_cost(int var_idx, int cost) { assert(var_idx > 0 && var_idx <= (int)num_variables()); variable(var_idx).cost() = cost; } int MSolver::add_variable(void) { int num = MDatabase::add_variable(); ++_stats.num_free_variables; while (_assignment_stack.size() <= num_variables()) _assignment_stack.push_back(new vector<int>); assert(_assignment_stack.size() == num_variables() + 1); return num; } void MSolver::set_mem_limit(int s) { MDatabase::set_mem_limit(s); } void MSolver::set_randomness(int n) { _params.decision.base_randomness = n; } void MSolver::set_random_seed(int seed) { srand(seed); } void MSolver::enable_cls_deletion(bool allow) { _params.cls_deletion.enable = allow; } void MSolver::add_hook(HookFunPtrT fun, int interval) { pair<HookFunPtrT, int> a(fun, interval); _hooks.push_back(pair<int, pair<HookFunPtrT, int> > (0, a)); } void MSolver::block_current_assignment(int diff, bool mis) { vector<int>block_cls; bool use_decision = false; for (int i = 1; i <= dlevel() && !use_decision; ++i) { for (unsigned j = 0; j < _assignment_stack[i]->size(); ++j) { assert((*_assignment_stack[i])[j] > 1); if ((*_assignment_stack[i])[j] % 2 == 0 && variable((*_assignment_stack[i])[j] / 2).cost() > 0) { if (i > 0) { /*if ((int)block_cls.size() >= dlevel()) { use_decision = true; break; }*/ block_cls.push_back((*_assignment_stack[i])[j] ^ 0x1); } } } } if (use_decision) { block_cls.clear(); // printf("use decision\n"); for (int i = 1; i <= dlevel(); ++i) block_cls.push_back((*_assignment_stack[i])[0] ^ 0x1); } else { // printf("not use decision\n"); // assert(0); /*if (mis) { vector<int>final; for (unsigned i = 0; i < block_cls.size(); ++i) unique.insert(block_cls[i]); for (unsigned i = 0; i < MIS_fl.size(); ++i) unique.insert(MIS_fl[i]); block_cls.clear(); for (set<int>::iterator si = unique.begin(); si != unique.end(); ++si) block_cls.push_back(*si); }*/ /*if (block_cls.size() == 0) { int cost = 0; for (unsigned j = 0; j < _assignment_stack[0]->size(); ++j) { int lit = (*_assignment_stack[0])[j]; //printf("%d ", lit); if (lit % 2 == 0) cost += variable(lit / 2).cost(); } printf("m %d t %d 0 %d d %d\n", _stats.min_cost, _stats.total_cost, cost, dlevel()); }*/ //assert(block_cls.size()); if (diff > 0) { vector<int>final; multimap<int, int>queue; for (unsigned i = 0; i < block_cls.size(); ++i) { if (MIS_fl.find(block_cls[i]) != MIS_fl.end()) { final.push_back(block_cls[i]); } else { queue.insert(pair<int, int>(variable(block_cls[i] / 2).dlevel(), block_cls[i])); } } unsigned size = block_cls.size() - diff; for (multimap<int, int>::iterator itr = queue.begin(); itr != queue.end(); ++itr) { final.push_back(itr->second); if (final.size() >= size) break; } block_cls = final; } } for (set<int>::iterator itr = MIS_fl.begin(); itr != MIS_fl.end(); ++itr) { if (variable(*itr / 2).cost() == 0) block_cls.push_back(*itr); } if (block_cls.size() == 0) return; /*printf("Add blocking: "); for (unsigned i = 0; i < block_cls.size(); ++i) printf("%d ", block_cls[i]); printf("\n"); */ assert(_conflicts.empty()); assert(_implication_queue.empty()); // printf("block size %d dlevel %d\n", block_cls.size(), dlevel()); // add_conflict_clause(&block_cls[0], block_cls.size()); add_clause_incr(&block_cls[0], block_cls.size()); } int MSolver::current_lower_bound(void) { return 0; } void MSolver::run_periodic_functions(void) { if (!_implication_queue.empty()) return; int cost = 0; if (_assignment_stack[0]->size() > 0) { for (unsigned j = 0; j < _assignment_stack[0]->size(); ++j) { int lit = (*_assignment_stack[0])[j]; //printf("%d ", lit); if (lit % 2 == 0) cost += variable(lit / 2).cost(); } //printf("\n"); } if (_stats.num_decisions % 10000 == 1) { /*cout << "Decision: " << _assignment_stack[0]->size() << "/" <<num_variables() << " Time: " << get_cpu_time() - _stats.start_cpu_time << "/" << _params.time_limit << " Current: " <<_stats.min_cost<<" cost@0: "<<cost<<" mincost: "<< _stats.min_cost<<"\n"<<flush;*/ // dump_assignment_stack(cout); } // printf("cost is %d min is %d\n", cost, _stats.min_cost); int mis = MIS_LB(); if (dlevel() == 0 && cost + mis >= _stats.min_cost) { //printf("Optimal found!\n"); _stats.outcome = UNSATISFIABLE; return; } int diff = _stats.total_cost + mis - _stats.min_cost; if (diff >= 0) { // if (_stats.total_cost + MIS_LB() >= _stats.min_cost) { // if (diff > 0 && _stats.num_decisions % 1000 == 1) // printf("greater by %d\n", diff); block_current_assignment(diff); return; } // a. restart if (_params.restart.enable && _stats.num_backtracks > _stats.next_restart && _shrinking_cls.empty()) { _stats.next_restart = _stats.num_backtracks + _stats.restart_incr; delete_unrelevant_clauses(); restart(); if (_stats.num_restarts % 5 == 1) compact_lit_pool(); /*cout << "\rDecision: " << _assignment_stack[0]->size() << "/" <<num_variables() << "\tTime: " << get_cpu_time() - _stats.start_cpu_time << "/" << _params.time_limit << flush; */ } // b. decay variable score if (_stats.num_backtracks > _stats.next_var_score_decay) { _stats.next_var_score_decay = _stats.num_backtracks + _params.decision.decay_period; decay_variable_score(); } // c. run hook functions for (unsigned i = 0; i< _hooks.size(); ++i) { pair<int, pair<HookFunPtrT, int> > & hook = _hooks[i]; if (_stats.num_decisions >= hook.first) { hook.first += hook.second.second; hook.second.first((void *) this); } } } int MSolver::total_cost(void) { int cost = 0; for (unsigned i = 1; i <= num_variables(); ++i) { if (variable(i).value() == 1) { cost += variable(i).cost(); } } if (cost != _stats.total_cost) printf("%d %d\n", cost, _stats.total_cost); assert(cost == _stats.total_cost); return cost; } void MSolver::init_solve(void) { MDatabase::init_stats(); re_init_stats(); _stats.been_reset = false; assert(_conflicts.empty()); assert(_conflict_lits.empty()); assert(_num_marked == 0); assert(_num_in_new_cl == 0); assert(_dlevel == 0); for (unsigned i = 0, sz = variables()->size(); i < sz; ++i) { variable(i).score(0) = variable(i).lits_count(0); variable(i).score(1) = variable(i).lits_count(1); } _ordered_vars.resize(num_variables()); update_var_score(); set_random_seed(_stats.random_seed); top_unsat_cls_idx = clauses()->size() - 1; _stats.shrinking_benefit = 0; _shrinking_cls.clear(); _stats.shrinking_cls_length = 0; if (MIS.empty()) find_MIS(); } void MSolver::find_MIS(void){ set<int>lits; multimap<double, int>candidates; for (vector<MClause>::iterator mitr = clauses()->begin(); mitr != clauses()->end(); ++mitr) { //DEBUG - 1?> MClause & cl = *mitr; if (cl.status() != ORIGINAL_CL) continue; int mc = 0;//INT_MAX; for (int i = 0, sz = cl.num_lits(); i < sz; ++i) { if (cl.literal(i).var_sign() == 0 && variable(cl.literal(i).var_index()).cost() > 0) { //if (variable(cl.literal(i).var_index()).cost() < mc) // mc = variable(cl.literal(i).var_index()).cost(); mc += variable(cl.literal(i).var_index()).cost(); } } if (mc > 0) { candidates.insert(pair<double,int>(-1000.0*mc/cl.num_lits(), cl.id())); } //if (mc < INT_MAX) { // assert(mc > 0); // candidates.insert(pair<double,int>(-1000.0*mc/cl.num_lits(), cl.id())); //} } for (multimap<double, int>::iterator itr = candidates.begin(); itr != candidates.end(); ++itr) { bool overlap = false; MClause &cl = clause(itr->second); for (int i = 0, sz = cl.num_lits(); i < sz; ++i) { if (lits.find(cl.literal(i).var_index()) != lits.end()) { overlap = true; break; } } if (overlap) continue; MIS.push_back(itr->second); for (int i = 0, sz = cl.num_lits(); i < sz; ++i) lits.insert(cl.literal(i).var_index()); } //printf("Found %d clauses in MIS\n", MIS.size()); mis0 = 0; } int MSolver::MIS_LB(bool debug) { MIS_fl.clear(); if (mis0 > 100) return 0; if (_stats.min_cost == INT_MAX /*|| _stats.num_decisions % 2 != 1*/) { //printf("return 0\n"); return 0; } int total = 0; // return 0; for (unsigned k = 0; k < MIS.size(); ++k) { MClause &cl = clause(MIS[k]); bool cls_useful = true; int min_cost = INT_MAX; vector<int>lits; for (int i = 0, sz = cl.num_lits(); i < sz; ++i) { if (literal_value(cl.literal(i)) == 1) { cls_useful = false; break; } if (literal_value(cl.literal(i)) == 0) { if (variable(cl.literal(i).var_index()).dlevel() > 0 && cl.literal(i).var_sign() == 1) lits.push_back(cl.literal(i).s_var()); continue; } assert(variable(cl.literal(i).var_index()).value() == UNKNOWN); if (variable(cl.literal(i).var_index()).cost() <= 0 || cl.literal(i).var_sign() == 1) { cls_useful = false; break; } if (variable(cl.literal(i).var_index()).cost() < min_cost && cl.literal(i).var_sign() == 0) min_cost = variable(cl.literal(i).var_index()).cost(); } if (!cls_useful || min_cost == INT_MAX) continue; for (unsigned i = 0; i < lits.size(); ++i) { //MIS_fl.push_back(lits[i] ^ 0x1); MIS_fl.insert(lits[i] ^ 0x1); } // assert(min_cost == 1); total += min_cost; if (debug) { printf("Total %d Clause: ", total); for (int i = 0, sz = cl.num_lits(); i < sz; ++i) { printf("%d:%d ", cl.literal(i).s_var(), variable(cl.literal(i).var_index()).value()); if (cl.literal(i).var_sign() == 0 && fu[cl.literal(i).var_index()] == 1) printf("SAT by +%d ", cl.literal(i).var_index() * 2); if (cl.literal(i).var_sign() == 1 && fu[cl.literal(i).var_index()] == 0) printf("SAT by -%d ", cl.literal(i).var_index() * 2 + 1); } printf("\n"); } } // if (total > 0) // printf("MIS returns %d\n", total); if (total <= 0) { ++mis0; //if (mis0 > 100) //printf("Permanent disable MIS_LB\n"); } else mis0 = 0; return total; } void MSolver::set_var_value(int v, int value, MClauseIdx ante, int dl) { /*if (dl == 0) { printf("set var %d value %d at d0 cos %d\n", v, value, ante); for (unsigned i = 0; i < clause(ante).num_lits(); ++i) printf("%d ", clause(ante).literal(i).s_var()); printf("\n"); }*/ assert(value == 0 || value == 1); MVariable & var = variable(v); assert(var.value() == UNKNOWN); assert(dl == dlevel()); var.set_dlevel(dl); var.set_value(value); var.antecedent() = ante; var.assgn_stack_pos() = _assignment_stack[dl]->size(); if (value == 1) _stats.total_cost += var.cost(); _assignment_stack[dl]->push_back(v * 2 + !value); set_var_value_BCP(v, value); ++_stats.num_implications ; if (var.is_branchable()) --num_free_variables(); } void MSolver::set_var_value_BCP(int v, int value) { vector<MLitPoolElement *> & watchs = variable(v).watched(value); for (vector <MLitPoolElement *>::iterator itr = watchs.begin(); itr != watchs.end(); ++itr) { MClauseIdx cl_idx; MLitPoolElement * other_watched = *itr; MLitPoolElement * watched = *itr; int dir = watched->direction(); MLitPoolElement * ptr = watched; while (true) { ptr += dir; if (ptr->val() <= 0) { // reached one end of the clause if (dir == 1) // reached the right end, i.e. spacing element is cl_id cl_idx = ptr->get_clause_index(); if (dir == watched->direction()) { // we haven't go both directions. ptr = watched; dir = -dir; // change direction, go the other way continue; } // otherwise, we have already go through the whole clause int the_value = literal_value(*other_watched); if (the_value == 0) // a conflict _conflicts.push_back(cl_idx); else if (the_value != 1) // i.e. unknown queue_implication(other_watched->s_var(), cl_idx); break; } if (ptr->is_watched()) { // literal is the other watched lit, skip it. other_watched = ptr; continue; } if (literal_value(*ptr) == 0) // literal value is 0, keep going continue; // now the literal's value is either 1 or unknown, watch it instead int v1 = ptr->var_index(); int sign = ptr->var_sign(); variable(v1).watched(sign).push_back(ptr); ptr->set_watch(dir); // remove the original watched literal from watched list watched->unwatch(); *itr = watchs.back(); // copy the last element in it's place watchs.pop_back(); // remove the last element --itr; // do this so with don't skip one during traversal break; } } } void MSolver::unset_var_value(int v) { if (v == 0) return; MVariable & var = variable(v); if (var.value() == 1) _stats.total_cost -= var.cost(); var.set_value(UNKNOWN); var.set_antecedent(NULL_CLAUSE); var.set_dlevel(-1); var.assgn_stack_pos() = -1; if (var.is_branchable()) { ++num_free_variables(); if (var.var_score_pos() < _max_score_pos) _max_score_pos = var.var_score_pos(); } } void MSolver::dump_assignment_stack(ostream & os ) { os << "Assignment Stack: "; for (int i = 0; i <= dlevel(); ++i) { os << "(" <<i << ":"; for (unsigned j = 0; j < (*_assignment_stack[i]).size(); ++j) { os << ((*_assignment_stack[i])[j]&0x1?"-":"+") << ((*_assignment_stack[i])[j] >> 1) << " "; } os << ") " << endl; } os << endl; } void MSolver::dump_implication_queue(ostream & os) { _implication_queue.dump(os); } void MSolver::delete_clause_group(int gid) { assert(is_gid_allocated(gid)); if (_stats.been_reset == false) reset(); // if delete some clause, then implication queue are invalidated for (vector<MClause>::iterator itr = clauses()->begin(); itr != clauses()->end(); ++itr) { MClause & cl = *itr; if (cl.status() != DELETED_CL) { if (cl.gid(gid) == true) { mark_clause_deleted(cl); } } } // delete the index from variables for (vector<MVariable>::iterator itr = variables()->begin(); itr != variables()->end(); ++itr) { for (unsigned i = 0; i < 2; ++i) { // for each phase // delete the lit index from the vars #ifdef KEEP_LIT_CLAUSES vector<MClauseIdx> & lit_clauses = (*itr).lit_clause(i); for (vector<MClauseIdx>::iterator itr1 = lit_clauses.begin(); itr1 != lit_clauses.end(); ++itr1) { if (clause(*itr1).status() == DELETED_CL) { *itr1 = lit_clauses.back(); lit_clauses.pop_back(); --itr1; } } #endif // delete the watched index from the vars vector<MLitPoolElement *> & watched = (*itr).watched(i); for (vector<MLitPoolElement *>::iterator itr1 = watched.begin(); itr1 != watched.end(); ++itr1) { if ((*itr1)->val() <= 0) { *itr1 = watched.back(); watched.pop_back(); --itr1; } } } } free_gid(gid); } void MSolver::reset(void) { if (_stats.been_reset) return; if (num_variables() == 0) return; back_track(0); _conflicts.clear(); while (!_implication_queue.empty()) _implication_queue.pop(); _stats.outcome = UNDETERMINED; _stats.been_reset = true; } void MSolver::delete_unrelevant_clauses(void) { unsigned original_del_cls = num_deleted_clauses(); int num_conf_cls = num_clauses() - init_num_clauses() + num_del_orig_cls(); if (num_conf_cls < 50000) { //printf("Total %d conflict clauses, no deletion.\n", num_conf_cls); return; } int head_count = num_conf_cls / _params.cls_deletion.tail_vs_head; int count = 0; int deleted = 0; for (vector<MClause>::iterator mitr = clauses()->begin(); mitr != clauses()->end() - 1; ++mitr) { // cout<<"count "<<ci++<<" "<<clauses()->size()<<endl<<flush; MClause & cl = *mitr; if (cl.status() != CONFLICT_CL) { continue; } bool cls_sat_at_dl_0 = false; for (int i = 0, sz = cl.num_lits(); i < sz; ++i) { if (literal_value(cl.literal(i)) == 1 && variable(cl.literal(i).var_index()).dlevel() == 0) { cls_sat_at_dl_0 = true; break; } } if (cls_sat_at_dl_0) { int val_0_lits = 0, val_1_lits = 0, unknown_lits = 0; for (unsigned i = 0; i < cl.num_lits(); ++i) { int lit_value = literal_value(cl.literal(i)); if (lit_value == 0) ++val_0_lits; if (lit_value == 1) ++val_1_lits; if (lit_value == UNKNOWN) ++unknown_lits; if (unknown_lits + val_1_lits > 1) { mark_clause_deleted(cl); ++deleted; break; } } continue; } count++; int max_activity = _params.cls_deletion.head_activity - (_params.cls_deletion.head_activity - _params.cls_deletion.tail_activity) * count/num_conf_cls; int max_conf_cls_size; if (head_count > 0) { max_conf_cls_size = _params.cls_deletion.head_num_lits; --head_count; } else { max_conf_cls_size = _params.cls_deletion.tail_num_lits; } if (cl.activity() > max_activity) continue; int val_0_lits = 0, val_1_lits = 0, unknown_lits = 0, lit_value; for (unsigned i = 0; i < cl.num_lits(); ++i) { lit_value = literal_value(cl.literal(i)); if (lit_value == 0) ++val_0_lits; else if (lit_value == 1) ++val_1_lits; else ++unknown_lits; if ((unknown_lits > max_conf_cls_size)) { mark_clause_deleted(cl); ++deleted; break; } } } printf("Total %d conflict clauses. delete %d\n", num_conf_cls, deleted); // if none were recently marked for deletion... if (original_del_cls == num_deleted_clauses()) { return; } // delete the index from variables for (vector<MVariable>::iterator itr = variables()->begin(); itr != variables()->end(); ++itr) { for (unsigned i = 0; i < 2; ++i) { // for each phase // delete the lit index from the vars #ifdef KEEP_LIT_CLAUSES vector<MClauseIdx> & lit_clauses = (*itr).lit_clause(i); for (vector<MClauseIdx>::iterator itr1 = lit_clauses.begin(); itr1 != lit_clauses.end(); ++itr1) { if (clause(*itr1).status() == DELETED_CL) { *itr1 = lit_clauses.back(); lit_clauses.pop_back(); --itr1; } } #endif // delete the watched index from the vars vector<MLitPoolElement *> & watched = (*itr).watched(i); for (vector<MLitPoolElement *>::iterator itr1 = watched.begin(); itr1 != watched.end(); ++itr1) { if ((*itr1)->val() <= 0) { *itr1 = watched.back(); watched.pop_back(); --itr1; } } } } for (unsigned i = 1, sz = variables()->size(); i < sz; ++i) { if (variable(i).dlevel() != 0) { variable(i).score(0) = variable(i).lits_count(0); variable(i).score(1) = variable(i).lits_count(1); /*if (variable(i).lits_count(0) == 0 && variable(i).value() == UNKNOWN) { queue_implication(i * 2 + 1, NULL_CLAUSE); } //else if (variable(i).lits_count(1) == 0 && // variable(i).value() == UNKNOWN) { // queue_implication(i * 2, NULL_CLAUSE); //} */ } else { variable(i).score(0) = 0; variable(i).score(1) = 0; } } update_var_score(); } bool MSolver::time_out(void) { return (get_cpu_time() - _stats.start_cpu_time> _params.time_limit); } void MSolver::adjust_variable_order(int * lits, int n_lits) { // note lits are signed vars, not MLitPoolElements for (int i = 0; i < n_lits; ++i) { int var_idx = lits[i] >> 1; MVariable & var = variable(var_idx); assert(var.value() != UNKNOWN); int orig_score = var.score(); ++variable(var_idx).score(lits[i] & 0x1); int new_score = var.score(); if (orig_score == new_score) continue; int pos = var.var_score_pos(); int orig_pos = pos; assert(_ordered_vars[pos].first == & var); assert(_ordered_vars[pos].second == orig_score); int bubble_step = _params.decision.bubble_init_step; for (pos = orig_pos ; pos >= 0; pos -= bubble_step) { if (_ordered_vars[pos].second >= new_score) break; } pos += bubble_step; for (bubble_step = bubble_step >> 1; bubble_step > 0; bubble_step = bubble_step >> 1) { if (pos - bubble_step >= 0 && _ordered_vars[pos - bubble_step].second < new_score) pos -= bubble_step; } // now found the position, do a swap _ordered_vars[orig_pos] = _ordered_vars[pos]; _ordered_vars[orig_pos].first->set_var_score_pos(orig_pos); _ordered_vars[pos].first = & var; _ordered_vars[pos].second = new_score; _ordered_vars[pos].first->set_var_score_pos(pos); _stats.total_bubble_move += orig_pos - pos; } } void MSolver::decay_variable_score(void) { unsigned i, sz; for (i = 1, sz = variables()->size(); i < sz; ++i) { MVariable & var = variable(i); var.score(0) /= 2; var.score(1) /= 2; } for (i = 0, sz = _ordered_vars.size(); i < sz; ++i) { _ordered_vars[i].second = _ordered_vars[i].first->score(); } } bool MSolver::decide_next_branch(void) { //cout<<"decide... "<<dlevel()<<endl<<flush; if (dlevel() > 0) assert(_assignment_stack[dlevel()]->size() > 0); if (!_implication_queue.empty()) { // some hook function did a decision, so skip my own decision making. // if the front of implication queue is 0, that means it's finished // because var index start from 1, so 2 *vid + sign won't be 0. // else it's a valid decision. return (_implication_queue.front().lit != 0); } int s_var = 0; if (_params.shrinking.enable) { assert(0); while (!_shrinking_cls.empty()) { s_var = _shrinking_cls.begin()->second; _shrinking_cls.erase(_shrinking_cls.begin()); if (variable(s_var >> 1).value() == UNKNOWN) { _stats.num_decisions++; _stats.num_decisions_shrinking++; ++dlevel(); queue_implication(s_var ^ 0x1, NULL_CLAUSE); return true; } } } if (_outside_constraint_hook != NULL) _outside_constraint_hook(this); ++_stats.num_decisions; if (num_free_variables() == 0) // no more free vars return false; /* bool cls_sat = true; int i, sz, var_idx, score, max_score = -1; for (; top_unsat_cls_idx >= 0; --top_unsat_cls_idx) { MClause &cl = clause(top_unsat_cls_idx); if (cl.status() != CONFLICT_CL) continue; cls_sat = false; if (cl.sat_lit_idx() < (int)cl.num_lits() && literal_value(cl.literal(cl.sat_lit_idx())) == 1) cls_sat = true; if (!cls_sat) { max_score = -1; for (i = 0, sz = cl.num_lits(); i < sz; ++i) { var_idx = cl.literal(i).var_index(); if (literal_value(cl.literal(i)) == 1) { cls_sat = true; cl.sat_lit_idx() = i; break; } else if (variable(var_idx).value() == UNKNOWN) { score = variable(var_idx).score(); if (score > max_score) { max_score = score; s_var = var_idx * 2; } } } } if (!cls_sat) break; } if (!cls_sat && max_score != -1) { ++dlevel(); if (dlevel() > _stats.max_dlevel) _stats.max_dlevel = dlevel(); MVariable& v = variable(s_var >> 1); if (v.score(0) < v.score(1)) s_var += 1; else if (v.score(0) == v.score(1)) { if (v.two_lits_count(0) > v.two_lits_count(1)) s_var+=1; else if (v.two_lits_count(0) == v.two_lits_count(1)) s_var+=rand()%2; } assert(s_var >= 2); if (variable(s_var / 2).cost() > 0) queue_implication(s_var | 0x1, NULL_CLAUSE); else queue_implication(s_var, NULL_CLAUSE); ++_stats.num_decisions_stack_conf; return true; } */ for (unsigned i = _max_score_pos; i < _ordered_vars.size(); ++i) { MVariable & var = *_ordered_vars[i].first; if (var.value() == UNKNOWN && var.is_branchable()) { // move th max score position pointer _max_score_pos = i; // make some randomness happen if (--_stats.current_randomness < _params.decision.base_randomness) _stats.current_randomness = _params.decision.base_randomness; int randomness = _stats.current_randomness; if (randomness >= num_free_variables()) randomness = num_free_variables() - 1; int skip = rand() % (1 + randomness); int index = i; while (skip > 0) { ++index; if (_ordered_vars[index].first->value() == UNKNOWN && _ordered_vars[index].first->is_branchable()) --skip; } MVariable * ptr = _ordered_vars[index].first; assert(ptr->value() == UNKNOWN && ptr->is_branchable()); int sign = 0; if (ptr->score(0) < ptr->score(1)) sign += 1; else if (ptr->score(0) == ptr->score(1)) { if (ptr->two_lits_count(0) > ptr->two_lits_count(1)) sign += 1; else if (ptr->two_lits_count(0) == ptr->two_lits_count(1)) sign += rand() % 2; } int var_idx = ptr - &(*variables()->begin()); s_var = var_idx + var_idx + sign; break; } } assert(s_var >= 2); // there must be a free var somewhere ++dlevel(); if (dlevel() > _stats.max_dlevel) _stats.max_dlevel = dlevel(); ++_stats.num_decisions_vsids; _implication_id = 0; // queue_implication(s_var, NULL_CLAUSE); if (variable(s_var / 2).cost() > 0) queue_implication(s_var | 0x1, NULL_CLAUSE); else queue_implication(s_var, NULL_CLAUSE); return true; } int MSolver::preprocess(void) { assert(dlevel() == 0); // 1. detect all the unused variables vector<int> un_used; for (unsigned i = 1, sz = variables()->size(); i < sz; ++i) { MVariable & v = variable(i); if (v.lits_count(0) == 0 && v.lits_count(1) == 0) { un_used.push_back(i); queue_implication(i+i+1, NULL_CLAUSE); int r = deduce(); assert(r == NO_CONFLICT); } } if (_params.verbosity > 1 && un_used.size() > 0) { cout << un_used.size() << " Variables are defined but not used " << endl; if (_params.verbosity > 2) { for (unsigned i = 0; i< un_used.size(); ++i) cout << un_used[i] << " "; cout << endl; } } // 2. detect all variables with only one phase occuring (i.e. pure literals) /* vector<int> uni_phased; for (unsigned i = 1, sz = variables()->size(); i < sz; ++i) { MVariable & v = variable(i); if (v.value() != UNKNOWN) continue; if (v.lits_count(0) == 0) { // no positive phased lits. queue_implication(i+i+1, NULL_CLAUSE); uni_phased.push_back(-i); } else if (v.lits_count(1) == 0) { // no negative phased lits. queue_implication(i+i, NULL_CLAUSE); uni_phased.push_back(i); } } if (_params.verbosity > 1 && uni_phased.size() > 0) { cout << uni_phased.size() << " Variables only appear in one phase." <<endl; if (_params.verbosity > 2) { for (unsigned i = 0; i< uni_phased.size(); ++i) cout << uni_phased[i] << " "; cout <<endl; } }*/ // 3. Unit clauses for (unsigned i = 0, sz = clauses()->size(); i < sz; ++i) { if (clause(i).status() != DELETED_CL && clause(i).num_lits() == 1 && variable(clause(i).literal(0).var_index()).value() == UNKNOWN) queue_implication(clause(i).literal(0).s_var(), i); } if (deduce() == CONFLICT) { //cout << " CONFLICT during preprocess " <<endl; #ifdef VERIFY_ON for (unsigned i = 1; i < variables()->size(); ++i) { if (variable(i).value() != UNKNOWN) { assert(variable(i).dlevel() <= 0); int ante = variable(i).antecedent(); int ante_id = 0; if (ante >= 0) { ante_id = clause(ante).id(); verify_out << "VAR: " << i << " L: " << variable(i).assgn_stack_pos() << " V: " << variable(i).value() << " A: " << ante_id << " Lits:"; for (unsigned j = 0; j < clause(ante).num_lits(); ++j) verify_out <<" " << clause(ante).literal(j).s_var(); verify_out << endl; } } } verify_out << "CONF: " << clause(_conflicts[0]).id() << " =="; for (unsigned i = 0; i < clause(_conflicts[0]).num_lits(); ++i) { int svar = clause(_conflicts[0]).literal(i).s_var(); verify_out << " " << svar; } verify_out << endl; #endif return CONFLICT; } if (_params.verbosity > 1) { cout << _assignment_stack[0]->size() << " vars set during preprocess; " << endl; } return NO_CONFLICT; } void MSolver::mark_var_unbranchable(int vid) { if (variable(vid).is_branchable()) { variable(vid).disable_branch(); if (variable(vid).value() == UNKNOWN) --num_free_variables(); } } void MSolver::mark_var_branchable(int vid) { MVariable & var = variable(vid); if (!var.is_branchable()) { var.enable_branch(); if (var.value() == UNKNOWN) { ++num_free_variables(); if (var.var_score_pos() < _max_score_pos) _max_score_pos = var.var_score_pos(); } } } MClauseIdx MSolver::add_orig_clause(int * lits, int n_lits, int gid) { int cid = add_clause_with_gid(lits, n_lits, gid); if (cid >= 0) { clause(cid).set_status(ORIGINAL_CL); clause(cid).activity() = 0; } return cid; } MClauseIdx MSolver::add_clause_with_gid(int * lits, int n_lits, int gid) { unsigned gflag; if (gid == PERMANENT_GID ) gflag = 0; else if (gid == VOLATILE_GID) { gflag = (~0x0); } else { assert(gid <= WORD_WIDTH && gid > 0); gflag = (1 << (gid- 1)); } MClauseIdx cid = add_clause(lits, n_lits, gflag); if (cid < 0) { _stats.is_mem_out = true; _stats.outcome = MEM_OUT; } return cid; } MClauseIdx MSolver::add_conflict_clause(int * lits, int n_lits, int gflag) { // printf("add cf of size %d\n", n_lits); MClauseIdx cid = add_clause(lits, n_lits, gflag); if (cid >= 0) { clause(cid).set_status(CONFLICT_CL); clause(cid).activity() = 0; } else { _stats.is_mem_out = true; _stats.outcome = MEM_OUT; } return cid; } bool MSolver::find_another_sat(void) { // assert(_stats.outcome == SATISFIABLE); /*if (dlevel() == 0) { assert(0); return true; }*/ assert(0); vector<int>block_cls; for (int i = 1; i <= dlevel(); ++i) block_cls.push_back((*_assignment_stack[i])[0] ^ 0x1); //reset(); // add_orig_clause(block_cls, assns); _stats.outcome = UNDETERMINED; add_clause_incr(&block_cls[0], block_cls.size()); reset(); // verify_integrity(); return false; } void MSolver::real_solve(void) { // while (_stats.outcome == UNDETERMINED) { while (_stats.outcome != UNSATISFIABLE) { run_periodic_functions(); if (_stats.outcome == UNSATISFIABLE) { //printf("UNSAT\n"); return; } if (decide_next_branch()) { while (deduce() == CONFLICT) { int blevel; blevel = analyze_conflicts(); if (blevel < 0) { _stats.outcome = UNSATISFIABLE; //printf("UNSAT\n"); return; } } } else { if (_sat_hook != NULL && _sat_hook(this)) continue; if (_stats.total_cost < _stats.min_cost) { _stats.min_cost = _stats.total_cost; true_lits.clear(); //FILE *log = fopen("assgn.txt", "w"); _mincost_assign.resize(num_variables()); for (unsigned i = 1; i <= num_variables(); ++i) { _mincost_assign[i - 1] = variable(i).value(); //fprintf(log, "%d\n", i * (variable(i).value() == 1 ? 1 : -1)); if (variable(i).value() == 1 && variable(i).cost()) true_lits.push_back(i); } //fclose(log); for (unsigned i = 0; i < clauses()->size(); ++i) { if (clause(i).status() != ORIGINAL_CL) continue; bool sat = false; for (unsigned j = 0; j < clause(i).num_lits(); ++j) { if (literal_value(clause(i).literal(j)) == 1) { sat = true; break; } } if (!sat) { printf("Solution can't be verified\n"); exit(1); } } //printf("\nNew solution found with cost %d\n", _stats.min_cost); //printf("Solution verified\n\n"); } block_current_assignment(0, false); while (!_implication_queue.empty()) _implication_queue.pop(); restart(); //reset(); continue; _stats.outcome = SATISFIABLE; //printf("SAT\n"); return; } if (time_out()) { _stats.outcome = TIME_OUT; printf("TIME_OUT\n"); return; } if (_force_terminate) { _stats.outcome = ABORTED; printf("ABORTED\n"); return; } if (_stats.is_mem_out) { _stats.outcome = MEM_OUT; printf("MEM_OUT\n"); return; } } } int MSolver::solve(void) { if (_stats.outcome == UNDETERMINED) { init_solve(); if (preprocess() == CONFLICT) _stats.outcome = UNSATISFIABLE; else // the real search real_solve(); // cout << endl; _stats.finish_cpu_time = get_cpu_time(); } if (!_mincost_assign.empty() && _stats.outcome == UNSATISFIABLE) { for (unsigned i = 0; i < _mincost_assign.size(); ++i) { variable(i + 1).set_value(_mincost_assign[i]); } _stats.outcome = SATISFIABLE; } return _stats.outcome; } void MSolver::back_track(int blevel) { assert(blevel <= dlevel()); for (int i = dlevel(); i >= blevel; --i) { vector<int> & assignments = *_assignment_stack[i]; for (int j = assignments.size() - 1 ; j >= 0; --j) unset_var_value(assignments[j]>>1); assignments.clear(); } dlevel() = blevel - 1; if (dlevel() < 0 ) dlevel() = 0; ++_stats.num_backtracks; } int MSolver::deduce(void) { while (!_implication_queue.empty()) { const MImplication & imp = _implication_queue.front(); int lit = imp.lit; int vid = lit>>1; MClauseIdx cl = imp.antecedent; _implication_queue.pop(); MVariable & var = variable(vid); if (var.value() == UNKNOWN) { // an implication set_var_value(vid, !(lit & 0x1), cl, dlevel()); } else if (var.value() == (unsigned)(lit & 0x1)) { // a conflict // note: literal & 0x1 == 1 means the literal is in negative phase // when a conflict occure at not current dlevel, we need to backtrack // to resolve the problem. // conflict analysis will only work if the conflict occure at // the top level (current dlevel) _conflicts.push_back(cl); break; } else { // so the variable have been assigned before // update its antecedent with a shorter one if (var.antecedent() != NULL_CLAUSE && clause(cl).num_lits() < clause(var.antecedent()).num_lits()) var.antecedent() = cl; assert(var.dlevel() <= dlevel()); } } // if loop exited because of a conflict, we need to clean implication queue while (!_implication_queue.empty()) _implication_queue.pop(); return (_conflicts.size() ? CONFLICT : NO_CONFLICT); } void MSolver::verify_integrity(void) { for (unsigned i = 1; i < variables()->size(); ++i) { if (variable(i).value() != UNKNOWN) { int pos = variable(i).assgn_stack_pos(); int value = variable(i).value(); int dlevel = variable(i).dlevel(); assert((*_assignment_stack[dlevel])[pos] == (int) (i+i+1-value)); } } for (unsigned i = 0; i < clauses()->size(); ++i) { if (clause(i).status() == DELETED_CL) continue; MClause & cl = clause(i); int num_0 = 0; int num_1 = 0; int num_unknown = 0; int watched[2]; int watch_index = 0; watched[1] = watched[0] = 0; for (unsigned j = 0; j < cl.num_lits(); ++j) { MLitPoolElement lit = cl.literal(j); int vid = lit.var_index(); if (variable(vid).value() == UNKNOWN) { ++num_unknown; } else { if (literal_value(lit) == 0) ++num_0; else ++num_1; } if (lit.is_watched()) { watched[watch_index] = lit.s_var(); ++watch_index; } } if (watch_index == 0) { assert(cl.num_lits() == 1); continue; } assert(watch_index == 2); for (unsigned j = 0; j < cl.num_lits(); ++j) { MLitPoolElement lit = cl.literal(j); int vid1 = (watched[0]>>1); if (variable(vid1).value() == (unsigned)(watched[0] & 0x1)) { if (!lit.is_watched()) { assert(literal_value(lit) == 0); assert(variable(lit.var_index()).dlevel() <= variable(vid1).dlevel()); } } int vid2 = (watched[1]>>1); if (variable(vid2).value() == (unsigned)(watched[1] & 0x1)) { if (!lit.is_watched()) { assert(literal_value(lit) == 0); assert(variable(lit.var_index()).dlevel() <= variable(vid1).dlevel()); } } } } } void MSolver::mark_vars(MClauseIdx cl, int var_idx) { assert(_resolvents.empty() || var_idx != -1); #ifdef VERIFY_ON _resolvents.push_back(clause(cl).id()); #endif for (MLitPoolElement* itr = clause(cl).literals(); (*itr).val() > 0; ++itr) { int v = (*itr).var_index(); if (v == var_idx) continue; else if (variable(v).dlevel() == dlevel()) { if (!variable(v).is_marked()) { variable(v).set_marked(); ++_num_marked; if (_mark_increase_score) { int tmp = itr->s_var(); adjust_variable_order(&tmp, 1); } } } else { assert(variable(v).dlevel() < dlevel()); if (variable(v).new_cl_phase() == UNKNOWN) { // it's not in the new cl // We can remove the variable assigned at dlevel 0 if // we are nog going to use incremental SAT. // if(variable(v).dlevel()){ ++_num_in_new_cl; variable(v).set_new_cl_phase((*itr).var_sign()); _conflict_lits.push_back((*itr).s_var()); // } } else { // if this variable is already in the new clause, it must // have the same phase assert(variable(v).new_cl_phase() == (*itr).var_sign()); } } } } int MSolver::analyze_conflicts(void) { assert(!_conflicts.empty()); assert(_conflict_lits.size() == 0); assert(_implication_queue.empty()); assert(_num_marked == 0); if (dlevel() == 0) { // already at level 0. Conflict means unsat. #ifdef VERIFY_ON for (unsigned i = 1; i < variables()->size(); ++i) { if (variable(i).value() != UNKNOWN) { assert(variable(i).dlevel() <= 0); int ante = variable(i).antecedent(); int ante_id = 0; if (ante >= 0) { ante_id = clause(ante).id(); assert(clause(ante).status() != DELETED_CL); verify_out << "VAR: " << i << " L: " << variable(i).assgn_stack_pos() << " V: " << variable(i).value() << " A: " << ante_id << " Lits:"; for (unsigned j = 0; j < clause(ante).num_lits(); ++j) verify_out << " " << clause(ante).literal(j).s_var(); verify_out << endl; } } } MClauseIdx shortest; shortest = _conflicts.back(); unsigned len = clause(_conflicts.back()).num_lits(); while (!_conflicts.empty()) { if (clause(_conflicts.back()).num_lits() < len) { shortest = _conflicts.back(); len = clause(_conflicts.back()).num_lits(); } _conflicts.pop_back(); } verify_out << "CONF: " << clause(shortest).id() << " =="; for (unsigned i = 0; i < clause(shortest).num_lits(); ++i) { int svar = clause(shortest).literal(i).s_var(); verify_out << " " << svar; } verify_out << endl; #endif _conflicts.clear(); back_track(0); return -1; } return conflict_analysis_firstUIP(); } // when all the literals involved are in _conflict_lits // call this function to finish the adding clause and backtrack int MSolver::finish_add_conf_clause(int gflag) { MClauseIdx added_cl = add_conflict_clause(&(*_conflict_lits.begin()), _conflict_lits.size(), gflag); if (added_cl < 0) { // memory out. _stats.is_mem_out = true; _conflicts.clear(); assert(_implication_queue.empty()); return 1; } top_unsat_cls_idx = clauses()->size() - 1; #ifdef VERIFY_ON verify_out << "CL: " << clause(added_cl).id() << " <="; for (unsigned i = 0; i< _resolvents.size(); ++i) verify_out << " " << _resolvents[i]; verify_out << endl; _resolvents.clear(); #endif adjust_variable_order(&(*_conflict_lits.begin()), _conflict_lits.size()); if (_params.shrinking.enable) { _shrinking_cls.clear(); if (_stats.shrinking_cls_length != 0) { int benefit = _stats.shrinking_cls_length - _conflict_lits.size(); _stats.shrinking_benefit += benefit; _stats.shrinking_cls_length = 0; _recent_shrinkings.push(benefit); if (_recent_shrinkings.size() > _params.shrinking.window_width) { _stats.shrinking_benefit -= _recent_shrinkings.front(); _recent_shrinkings.pop(); } } if (_conflict_lits.size() > _params.shrinking.size) { _shrinking_cls.clear(); for (unsigned i = 0, sz = _conflict_lits.size(); i < sz; ++i) { _shrinking_cls.insert(pair<int, int> (variable(_conflict_lits[i]>>1).dlevel(), _conflict_lits[i])); } int prev_dl = _shrinking_cls.begin()->first; multimap<int, int>::iterator itr, itr_del; int last_dl = _shrinking_cls.rbegin()->first; bool found_gap = false; for (itr = _shrinking_cls.begin(); itr->first != last_dl;) { if (itr->first - prev_dl > 2) { found_gap = true; break; } prev_dl = itr->first; itr_del = itr; ++itr; _shrinking_cls.erase(itr_del); } if (found_gap && _shrinking_cls.size() > 0 && prev_dl < dlevel() - 1) { _stats.shrinking_cls_length = _conflict_lits.size(); ++_stats.num_shrinkings; back_track(prev_dl + 1); _conflicts.clear(); #ifdef VERIFY_ON _resolvents.clear(); #endif _num_in_new_cl = 0; for (unsigned i = 0, sz = _conflict_lits.size(); i < sz; ++i) variable(_conflict_lits[i]>>1).set_new_cl_phase(UNKNOWN); _conflict_lits.clear(); if (_stats.num_shrinkings % _params.shrinking.bound_update_frequency == 0 && _recent_shrinkings.size() == _params.shrinking.window_width) { if (_stats.shrinking_benefit > _params.shrinking.upper_bound) _params.shrinking.size += _params.shrinking.upper_delta; else if (_stats.shrinking_benefit < _params.shrinking.lower_bound) _params.shrinking.size += _params.shrinking.lower_delta; } return prev_dl; } } } int back_dl = 0; int unit_lit = -1; for (unsigned i = 0; i < clause(added_cl).num_lits(); ++i) { int vid = clause(added_cl).literal(i).var_index(); int sign =clause(added_cl).literal(i).var_sign(); assert(variable(vid).value() != UNKNOWN); assert(literal_value(clause(added_cl).literal(i)) == 0); int dl = variable(vid).dlevel(); if (dl < dlevel()) { if (dl > back_dl) back_dl = dl; } else { assert(unit_lit == -1); unit_lit = vid + vid + sign; } } if (back_dl == 0) { _stats.next_restart = _stats.num_backtracks + _stats.restart_incr; _stats.next_cls_deletion = _stats.num_backtracks + _params.cls_deletion.interval; } back_track(back_dl + 1); queue_implication(unit_lit, added_cl); // after resolve the first conflict, others must also be resolved // for (unsigned i = 1; i < _conflicts.size(); ++i) // assert(!is_conflicting(_conflicts[i])); _conflicts.clear(); while (!_conflict_lits.empty()) { int svar = _conflict_lits.back(); _conflict_lits.pop_back(); MVariable & var = variable(svar >> 1); assert(var.new_cl_phase() == (unsigned)(svar & 0x1)); --_num_in_new_cl; var.set_new_cl_phase(UNKNOWN); } assert(_num_in_new_cl == 0); return back_dl; } int MSolver::conflict_analysis_firstUIP(void) { int min_conf_id = _conflicts[0]; int min_conf_length = -1; MClauseIdx cl; unsigned gflag; _mark_increase_score = false; if (_conflicts.size() > 1) { for (vector<MClauseIdx>::iterator ci = _conflicts.begin(); ci != _conflicts.end(); ci++) { assert(_num_in_new_cl == 0); assert(dlevel() > 0); cl = *ci; mark_vars(cl, -1); // current dl must be the conflict cl. vector <int> & assignments = *_assignment_stack[dlevel()]; // now add conflict lits, and unassign vars for (int i = assignments.size() - 1; i >= 0; --i) { int assigned = assignments[i]; if (variable(assigned >> 1).is_marked()) { // this variable is involved in the conflict clause or its antecedent variable(assigned>>1).clear_marked(); --_num_marked; MClauseIdx ante_cl = variable(assigned>>1).get_antecedent(); if ( _num_marked == 0 ) { // the first UIP encountered, conclude add clause assert(variable(assigned>>1).new_cl_phase() == UNKNOWN); // add this assignment's reverse, e.g. UIP _conflict_lits.push_back(assigned ^ 0x1); ++_num_in_new_cl; variable(assigned>>1).set_new_cl_phase((assigned^0x1)&0x1); break; } else { assert(ante_cl != NULL_CLAUSE); mark_vars(ante_cl, assigned >> 1); } } } if (min_conf_length == -1 || (int)_conflict_lits.size() < min_conf_length) { min_conf_length = _conflict_lits.size(); min_conf_id = cl; } for (vector<int>::iterator vi = _conflict_lits.begin(); vi != _conflict_lits.end(); ++vi) { int s_var = *vi; MVariable & var = variable(s_var >> 1); assert(var.new_cl_phase() == (unsigned)(s_var & 0x1)); var.set_new_cl_phase(UNKNOWN); } _num_in_new_cl = 0; _conflict_lits.clear(); #ifdef VERIFY_ON _resolvents.clear(); #endif } } assert(_num_marked == 0); cl = min_conf_id; clause(cl).activity() += 5; _mark_increase_score = true; mark_vars(cl, -1); gflag = clause(cl).gflag(); vector <int> & assignments = *_assignment_stack[dlevel()]; for (int i = assignments.size() - 1; i >= 0; --i) { int assigned = assignments[i]; if (variable(assigned >> 1).is_marked()) { variable(assigned>>1).clear_marked(); --_num_marked; MClauseIdx ante_cl = variable(assigned>>1).get_antecedent(); if ( _num_marked == 0 ) { _conflict_lits.push_back(assigned ^ 0x1); ++_num_in_new_cl; variable(assigned >> 1).set_new_cl_phase((assigned ^ 0x1) & 0x1); break; } else { gflag |= clause(ante_cl).gflag(); mark_vars(ante_cl, assigned >> 1); clause(ante_cl).activity() += 5; } } } return finish_add_conf_clause(gflag); } void MSolver::print_cls(ostream & os) { for (unsigned i = 0; i < clauses()->size(); ++i) { MClause & cl = clause(i); if (cl.status() == DELETED_CL) continue; if (cl.status() == ORIGINAL_CL) { os <<"0 "; } else { assert(cl.status() == CONFLICT_CL); os << "A "; } for (unsigned j = 1; j < 33; ++j) os << (cl.gid(j) ? 1 : 0); os << "\t"; for (unsigned j = 0; j < cl.num_lits(); ++j) { os << (cl.literal(j).var_sign() ? "-":"") << cl.literal(j).var_index() << " "; } os <<"0" << endl; } } int MSolver::mem_usage(void) { int mem_dbase = MDatabase::mem_usage(); int mem_assignment = 0; for (int i = 0; i < _stats.max_dlevel; ++i) mem_assignment += _assignment_stack[i]->capacity() * sizeof(int); mem_assignment += sizeof(vector<int>)* _assignment_stack.size(); return mem_dbase + mem_assignment; } void MSolver::clean_up_dbase(void) { assert(dlevel() == 0); int mem_before = mem_usage(); // 1. remove all the learned clauses for (vector<MClause>::iterator itr = clauses()->begin(); itr != clauses()->end() - 1; ++itr) { MClause & cl = * itr; if (cl.status() != ORIGINAL_CL) mark_clause_deleted(cl); } // delete_unrelevant_clauses() is specialized using berkmin deletion strategy // 2. free up the mem for the vectors if possible for (unsigned i = 0; i < variables()->size(); ++i) { for (unsigned j = 0; j < 2; ++j) { // both phase vector<MLitPoolElement *> watched; vector<MLitPoolElement *> & old_watched = variable(i).watched(j); watched.reserve(old_watched.size()); for (vector<MLitPoolElement *>::iterator itr = old_watched.begin(); itr != old_watched.end(); ++itr) watched.push_back(*itr); // because watched is a temp mem allocation, it will get deleted // out of the scope, but by swap it with the old_watched, the // contents are reserved. old_watched.swap(watched); #ifdef KEEP_LIT_CLAUSES vector<int> lits_cls; vector<int> & old_lits_cls = variable(i).lit_clause(j); lits_cls.reserve(old_lits_cls.size()); for (vector<int>::iterator itr1 = old_lits_cls.begin(); itr1 != old_lits_cls.end(); ++itr1) lits_cls.push_back(*itr1); old_lits_cls.swap(lits_cls); #endif } } int mem_after = mem_usage(); if (_params.verbosity > 0) { cout << "Database Cleaned, releasing (approximately) " << mem_before - mem_after << " Bytes" << endl; } } void MSolver::update_var_score(void) { for (unsigned i = 1, sz = variables()->size(); i < sz; ++i) { _ordered_vars[i-1].first = & variable(i); _ordered_vars[i-1].second = variable(i).score(); } ::stable_sort(_ordered_vars.begin(), _ordered_vars.end(), cmp_var_stat); for (unsigned i = 0, sz = _ordered_vars.size(); i < sz; ++i) _ordered_vars[i].first->set_var_score_pos(i); _max_score_pos = 0; } void MSolver::restart(void) { _stats.num_restarts += 1; if (_params.verbosity > 1 ) cout << "Restarting ... " << endl; if (dlevel() > 0) back_track(1); assert(dlevel() == 0); } // this function can be called within a solving process. i.e. not after // solve() terminate int MSolver::add_clause_incr(int * lits, int num_lits, int gid) { // Do not mess up with shrinking. /*bool sat = false; for (int i = 0; i < num_lits; ++i) { if (lits[i] % 2 == 0 && fu[lits[i] / 2] == 1) { sat = true; break; } if (lits[i] % 2 == 1 && fu[lits[i] / 2] == 0) { sat = true; break; } } if (!sat) { int total = 0; for (unsigned j = 0; j < MIS.size(); ++j) { MClause &ccc = clause(MIS[j]); bool cs = false; for (unsigned k = 0; k < ccc.num_lits(); ++k) { if (literal_value(ccc.literal(k)) == 1) { cs = true; break; } } if (!cs) { for (unsigned k = 0; k < ccc.num_lits(); ++k) { if (ccc.literal(k).var_sign() == 0) { cs = true; break; } } if (cs) ++total; } } printf("dlevel %d cost %d lits %d NMIS %d\n", dlevel(), total_cost(), num_lits, total); int ones = 0; for (unsigned i = 0; i < fu.size(); ++i) { if (variable(i).value() != UNKNOWN) { if (variable(i).value() != fu[i]) { assert(0); printf("var %d diff %d %d\n", i, variable(i).value(), fu[i]); } } else { if (fu[i]) printf("%d %d\n", ++ones, i * 2); } } //MIS_LB(true); } assert(sat); */ assert(!_params.shrinking.enable || _shrinking_cls.empty()); unsigned gflag; if (gid == PERMANENT_GID) gflag = 0; else if (gid == VOLATILE_GID) { gflag = ~0x0; } else { assert(gid <= WORD_WIDTH && gid > 0); gflag = (1 << (gid - 1)); } int cl = add_clause(lits, num_lits, gflag); if (cl < 0) return -1; //clause(cl).set_status(ORIGINAL_CL); clause(cl).set_status(CONFLICT_CL); if (clause(cl).num_lits() == 1) { int var_idx = clause(cl).literal(0).var_index(); if (literal_value(clause(cl).literal(0)) == 0 && variable(var_idx).dlevel() == 0) { back_track(0); printf("backtrack to 0\n"); if (preprocess() == CONFLICT) _stats.outcome = UNSATISFIABLE; } else { if (dlevel() > 0) back_track(1); queue_implication(clause(cl).literal(0).s_var(), cl); } return cl; } for (unsigned i = 0, sz = clause(cl).num_lits(); i < sz; ++i) { int var_idx = lits[i] >> 1; int value = variable(var_idx).value(); if (value == UNKNOWN) continue; if (variable(var_idx).dlevel() == 0 && variable(var_idx).antecedent() == -1 && literal_value(clause(cl).literal(i)) == 0) { back_track(0); if (preprocess() == CONFLICT) _stats.outcome = UNSATISFIABLE; return cl; } } int max_level = 0; int max_level2 = 0; int unit_lit = 0; int unknown_count = 0; int num_sat = 0; int sat_dlevel = -1, max_lit = 0; bool already_sat = false; for (unsigned i = 0, sz = clause(cl).num_lits(); unknown_count < 2 && i < sz; ++i) { int var_idx = lits[i] / 2; int value = variable(var_idx).value(); if (value == UNKNOWN) { unit_lit = clause(cl).literal(i).s_var(); ++unknown_count; } else { int dl = variable(var_idx).dlevel(); if (dl >= max_level) { max_level2 = max_level; max_level = dl; max_lit = clause(cl).literal(i).s_var(); } else if (dl > max_level2) max_level2 = dl; if (literal_value(clause(cl).literal(i)) == 1) { already_sat = true; ++num_sat; sat_dlevel = dl; } } } if (unknown_count == 0) { if (already_sat) { assert(sat_dlevel > -1); if (num_sat == 1 && sat_dlevel == max_level && max_level > max_level2) { back_track(max_level2 + 1); assert(max_lit > 1); queue_implication(max_lit, cl); } } else { assert(is_conflicting(cl)); if (max_level > max_level2) { back_track(max_level2 + 1); assert(max_lit > 1); queue_implication(max_lit, cl); } else { back_track(max_level); if (max_level == 0 && preprocess() == CONFLICT) _stats.outcome = UNSATISFIABLE; } } } else if (unknown_count == 1) { if (!already_sat) { if (max_level < dlevel()) back_track(max_level + 1); queue_implication(unit_lit, cl); } } return cl; }
[ [ [ 1, 1948 ] ] ]
d7f021b6e4d9efe8a60e6c03236b141fcdd1d501
0f457762985248f4f6f06e29429955b3fd2c969a
/physics/trunk/src/prologue/TutApp5.h
8193a178d19e31c7be4b201d87941c2bda4c8059
[]
no_license
tk8812/ukgtut
f19e14449c7e75a0aca89d194caedb9a6769bb2e
3146ac405794777e779c2bbb0b735b0acd9a3f1e
refs/heads/master
2021-01-01T16:55:07.417628
2010-11-15T16:02:53
2010-11-15T16:02:53
37,515,002
0
0
null
null
null
null
UTF-8
C++
false
false
844
h
#pragma once //#include "tutapp1.h" namespace irr { namespace scene { class CBulletAnimatorManager; class CBulletObjectAnimator; class CBulletWorldAnimator; }; }; class CTutApp5 :public ggf::irr_base::IBaseApp, public ggf::oop::Singleton<CTutApp5>,public irr::IEventReceiver { public: CTutApp5(void); ~CTutApp5(void); irr::scene::CBulletAnimatorManager* m_pBulletPhysicsFactory; irr::scene::ISceneNode* m_pWorldNode; irr::scene::CBulletWorldAnimator* m_pWorldAnimator; virtual int Init(LPCWSTR lpclassName); virtual bool Apply(float fElapsedTime); virtual void Render(float fElapsedTime); bool OnEvent(const irr::SEvent& event); void Close() { m_pDevice->closeDevice(); m_pDevice->drop(); UnregisterClass( _bstr_t(m_strClassName.c_str()),m_hInstance ); } };
[ "gbox3d@58f0f68e-7603-11de-abb5-1d1887d8974b" ]
[ [ [ 1, 43 ] ] ]
a2ef6ab5425deac5c5078cf511e5547269cf80d2
814b49df11675ac3664ac0198048961b5306e1c5
/Code/Game/BioGame/Sniper.cpp
3b9963281df1bfa4e81d939abe850eff1fe6f627
[]
no_license
Atridas/biogame
f6cb24d0c0b208316990e5bb0b52ef3fb8e83042
3b8e95b215da4d51ab856b4701c12e077cbd2587
refs/heads/master
2021-01-13T00:55:50.502395
2011-10-31T12:58:53
2011-10-31T12:58:53
43,897,729
0
0
null
null
null
null
UTF-8
C++
false
false
90
cpp
#include "Sniper.h" CSniper::CSniper(void) { } CSniper::~CSniper(void) { }
[ [ [ 1, 11 ] ] ]
fba720ce8f5659ff77f567026f66c12131ecf28c
ef8e875dbd9e81d84edb53b502b495e25163725c
/testbench/src/application/console.cpp
f92534ed9a84040a37ddeb24d20e875a51507bd0
[]
no_license
panone/litewiz
22b9d549097727754c9a1e6286c50c5ad8e94f2d
e80ed9f9d845b08c55b687117acb1ed9b6e9a444
refs/heads/master
2021-01-10T19:54:31.146153
2010-10-01T13:29:38
2010-10-01T13:29:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,443
cpp
/******************************************************************************* *******************************************************************************/ #include <QTextStream> #include "console.h" /******************************************************************************/ Console * Console::instance = 0; /******************************************************************************* *******************************************************************************/ QTextStream & Console::output ( void ) { return instance->outputStream; } /******************************************************************************* *******************************************************************************/ QTextStream & Console::input ( void ) { return instance->inputStream; } /******************************************************************************* *******************************************************************************/ Console::Console ( void ) : outputStream( stdout ), inputStream( stdin ) { instance = this; } /******************************************************************************* *******************************************************************************/ Console::~Console ( void ) { outputStream.flush(); } /******************************************************************************/
[ [ [ 1, 53 ] ] ]
307579d96ad20195e30c715b2ca3d33b610f85a7
ef23e388061a637f82b815d32f7af8cb60c5bb1f
/src/mame/includes/xexex.h
6da8bd36083ee1a6a42bba5a8250cc0909aec9f6
[]
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,520
h
/************************************************************************* Xexex *************************************************************************/ class xexex_state : public driver_device { public: xexex_state(running_machine &machine, const driver_device_config_base &config) : driver_device(machine, config) { } /* memory pointers */ UINT16 * m_workram; UINT16 * m_spriteram; // UINT16 * m_paletteram; // currently this uses generic palette handling /* video-related */ int m_layer_colorbase[4]; int m_sprite_colorbase; int m_layerpri[4]; int m_cur_alpha; /* misc */ UINT16 m_cur_control2; INT32 m_cur_sound_region; INT32 m_strip_0x1a; int m_suspension_active; int m_resume_trigger; emu_timer *m_dmadelay_timer; int m_frame; /* devices */ device_t *m_maincpu; device_t *m_audiocpu; device_t *m_k054539; device_t *m_filter1l; device_t *m_filter1r; device_t *m_filter2l; device_t *m_filter2r; device_t *m_k056832; device_t *m_k053246; device_t *m_k053250; device_t *m_k053251; device_t *m_k053252; device_t *m_k054338; }; /*----------- defined in video/xexex.c -----------*/ extern void xexex_sprite_callback(running_machine &machine, int *code, int *color, int *priority_mask); extern void xexex_tile_callback(running_machine &machine, int layer, int *code, int *color, int *flags); VIDEO_START( xexex ); SCREEN_UPDATE( xexex );
[ "Mike@localhost" ]
[ [ [ 1, 56 ] ] ]
91901733908f2f16770fa8ec5d8282f0a52e6821
fbe2cbeb947664ba278ba30ce713810676a2c412
/iptv_root/iptv_media3/Demuxer.cpp
54587b7787fb51a2393a5b95d6af0de93bd24349
[]
no_license
abhipr1/multitv
0b3b863bfb61b83c30053b15688b070d4149ca0b
6a93bf9122ddbcc1971dead3ab3be8faea5e53d8
refs/heads/master
2020-12-24T15:13:44.511555
2009-06-04T17:11:02
2009-06-04T17:11:02
41,107,043
0
0
null
null
null
null
UTF-8
C++
false
false
6,470
cpp
#include "Demuxer.h" #include "DemuxedMediaType.h" #include "global_error.h" #include "media_utilities.h" #include "mediapkt.h" #include "VideoDecoder.h" #include "AudioDecoder.h" IDemuxer::IDemuxer() : m_uCurSeq(0), m_bInit(false), m_bHeaderSet(false) { memset( &m_urlProtocol, 0, sizeof (URLProtocol) ); memset( &m_urlCtx, 0, sizeof (URLContext) ); } ULONG IDemuxer::SetHeader(BYTE *_pHeader, ULONG _uHeaderLen) { ULONG cbWrite; CHECK_ERROR(m_StreamBuf.WriteData(_pHeader, _uHeaderLen, cbWrite), RET_OK) CHECK_ERROR(m_StreamHeader.SetData(_pHeader, _uHeaderLen), RET_OK) m_bHeaderSet = TRUE; return RET_OK; } ULONG IDemuxer::GetHeader(BYTE **_ppHeader, ULONG & _uHeaderLen) { if (!_ppHeader) return RET_INVALID_ARG; if (!m_bHeaderSet) return RET_ERROR; *_ppHeader = m_StreamHeader.GetDataPtr(); _uHeaderLen = m_StreamHeader.Size(); return RET_OK; } ULONG IDemuxer::GetNextFrame(ULONG _id, BYTE **_ppData, ULONG & _uDatalen, MediaSpec & _mediaSpec) { _mediaSpec = NONE; if (!m_bInit) { return RET_INIT_ERROR; } if (!_ppData) { return RET_INVALID_ARG; } *_ppData = NULL; AVPacket pkt; if ( av_read_frame(m_pFmtCtx, &pkt) != 0) { return RET_ERROR; } _uDatalen = pkt.size + sizeof(MediaPktExt); m_DemuxedFrame.SetSize(_uDatalen); if (m_DemuxedFrame.Size() != _uDatalen) { _uDatalen = 0; return RET_ERROR; } BYTE *pData = m_DemuxedFrame.GetDataPtr(); MediaPktExt *pMediaPktExt = (MediaPktExt *) pData; memset(pMediaPktExt, 0, sizeof(MediaPktExt)); BYTE *pPayload = &pData[sizeof(MediaPktExt)]; memcpy(pPayload, pkt.data, pkt.size); pMediaPktExt->id = _id; pMediaPktExt->seq = m_uCurSeq++; pMediaPktExt->datalen = sizeof(MediaPktExt) - sizeof(MediaPkt) + pkt.size; pMediaPktExt->dwMsTimestamp = pkt.pts; AVCodecContext *pCodecCtx = m_pFmtCtx->streams[pkt.stream_index]->codec; if (pCodecCtx->codec_type == CODEC_TYPE_AUDIO) { pMediaPktExt->flags = PKT_AUDIO; pMediaPktExt->type = ASF_DEMUXED_AUDIO; _mediaSpec = AUDIO; } else if (pCodecCtx->codec_type == CODEC_TYPE_VIDEO) { pMediaPktExt->flags = PKT_VIDEO | PKT_KEYFRAME; pMediaPktExt->type = ASF_DEMUXED_VIDEO; _mediaSpec = VIDEO; } else { return RET_ERROR; } bool bIndexFound = false; for (unsigned index=0; index<m_DemuxedPktInfoList.size(); index++) { if (m_DemuxedPktInfoList[index].m_iStreamIndex == pkt.stream_index) { bIndexFound = true; pMediaPktExt->ulSubSeq = ++m_DemuxedPktInfoList[index].m_uSubSeq; break; } } if (!bIndexFound) { DemuxedPktInfo pktInfo(pkt.stream_index, 0, _mediaSpec); m_DemuxedPktInfoList.push_back(pktInfo); pMediaPktExt->ulSubSeq = pktInfo.m_uSubSeq; } *_ppData = pData; return RET_OK; } ULONG IDemuxer::SetPacket(BYTE *_pPkt, ULONG _uPktLen, ULONG _uHeaderLen) { if (!_pPkt || !_uPktLen) return RET_INVALID_ARG; BYTE *pData = &_pPkt[_uHeaderLen]; ULONG cbWrite, cbToWrite; cbToWrite = _uPktLen - _uHeaderLen; CHECK_ERROR(m_StreamBuf.WriteData(pData, cbToWrite, cbWrite), RET_OK) return RET_OK; } //--------------------------------ASFDemuxer methods definition--------------------------------// ULONG ASFDemuxer::Init() { unsigned ret = RET_OK; av_register_all(); m_urlProtocol.url_open = OpenASF; m_urlProtocol.url_read = ReadASF; m_urlProtocol.url_close = CloseASF; m_urlCtx.flags = URL_RDONLY; m_urlCtx.is_streamed = 1; m_urlCtx.prot = &m_urlProtocol; m_urlCtx.max_packet_size = 0; m_urlCtx.priv_data = this; memset(&m_byteCtx, 0, sizeof(m_byteCtx)); url_fdopen(&m_byteCtx, &m_urlCtx); BYTE *pBufTmp = new BYTE[m_byteCtx.buffer_size]; if (pBufTmp) { get_buffer(&m_byteCtx, pBufTmp, 2048); delete pBufTmp; m_byteCtx.buf_ptr = m_byteCtx.buffer; AVFormatParameters fmtParam; memset(&fmtParam, 0, sizeof(AVFormatParameters)); fmtParam.initial_pause = 1; /* we force a pause when starting an RTSP stream */ fmtParam.width = 0; fmtParam.height = 0; fmtParam.time_base.num = 1; fmtParam.time_base.den = 25; fmtParam.pix_fmt = PIX_FMT_NONE; AVInputFormat* pInputFmt = av_find_input_format("asf"); if (pInputFmt) { if (av_open_input_stream(&m_pFmtCtx, &m_byteCtx, "", pInputFmt, &fmtParam) == 0) { m_bInit = true; } else { ret = RET_ERROR; } } else { ret = RET_ERROR; } } else { ret = RET_LOW_MEMORY; } return ret; } Decoder *ASFDemuxer::GetDecoder(MediaSpec _mediaSpec) { if (!m_bInit) return NULL; AVCodecContext *pCodecCtx; Decoder *pASFDecoder = NULL; for (int index=0; index < m_DemuxedPktInfoList.size(); index++) { if (m_DemuxedPktInfoList[index].m_mediaSpec == _mediaSpec) { int iStreamIndex = m_DemuxedPktInfoList[index].m_iStreamIndex; AVCodecContext *pCodecCtx = m_pFmtCtx->streams[iStreamIndex]->codec; if (_mediaSpec == VIDEO) { pASFDecoder = new ASFVideoDecoder(pCodecCtx); } else if (_mediaSpec == AUDIO) { pASFDecoder = new ASFAudioDecoder(pCodecCtx); } break; } } if (!pASFDecoder) { return NULL; } if (pASFDecoder->Init() != RET_OK) { delete pASFDecoder; return NULL; } return pASFDecoder; } int ASFDemuxer::OpenASF(URLContext *h, const char *_pUrlPath, int flags) { return 0; } int ASFDemuxer::CloseASF(URLContext *h) { return 0; } int ASFDemuxer::ReadASF(URLContext *h, unsigned char *buf, int size) { ASFDemuxer * pDemuxer = (ASFDemuxer *) h->priv_data; int ret = -1; ULONG cbRead; pDemuxer->m_StreamBuf.ReadData(buf, size, cbRead); if (cbRead) { ret = cbRead; } return ret; }
[ "heineck@c016ff2c-3db2-11de-a81c-fde7d73ceb89" ]
[ [ [ 1, 287 ] ] ]
89c8af36176b2339b6aacf5ce9dc462cbac35455
b2fa537cef03244de283e231932f22ee41aec051
/src/agg/graphics.cpp
896c48d326473d603358b55c49bbcb71f7c548b9
[]
no_license
rebolsource/r3-hostkit
2e0037119cde8a161e2f7994fd3842cc3891e9d5
f331c6a46947e6e5afedc90f3d375bcd3f7ad8a1
refs/heads/master
2021-01-10T18:34:50.420402
2010-09-09T18:38:59
2010-09-10T11:59:58
813,301
0
0
null
null
null
null
UTF-8
C++
false
false
12,143
cpp
//exported functions #include "agg_graphics.h" #undef IS_ERROR //extern "C" void Reb_Print(char *fmt, ...);//output just for testing extern "C" void* Rich_Text; extern "C" REBINT Draw_Gob(void *graphics, REBSER *block, REBSER *args); namespace agg { extern "C" RL_LIB *RL; extern "C" void agg_add_vertex (void* gr, REBXYF p) { ((agg_graphics*)gr)->agg_add_vertex(p.x, p.y); } extern "C" void agg_anti_alias(void* gr, REBINT mode) { ((agg_graphics*)gr)->agg_anti_alias(mode!=0); } extern "C" void agg_arc(void* gr, REBXYF c, REBXYF r, REBDEC ang1, REBDEC ang2, REBINT closed) { ((agg_graphics*)gr)->agg_arc(c.x, c.y, r.x, r.y, ang1, ang2, closed); } extern "C" void agg_arrow(void* gr, REBXYF mode, REBYTE* col) { ((agg_graphics*)gr)->agg_arrows(col, (REBINT)mode.x, (REBINT)mode.y); } extern "C" void agg_begin_poly (void* gr, REBXYF p) { ((agg_graphics*)gr)->agg_begin_poly(p.x, p.y); } extern "C" void agg_box(void* gr, REBXYF p1, REBXYF p2, REBDEC r) { if (r) { ((agg_graphics*)gr)->agg_rounded_rect(p1.x, p1.y, p2.x, p2.y, r); } else { ((agg_graphics*)gr)->agg_box(p1.x, p1.y, p2.x, p2.y); } } extern "C" void agg_circle(void* gr, REBXYF p, REBXYF r) { ((agg_graphics*)gr)->agg_ellipse(p.x, p.y, r.x, r.y); } extern "C" void agg_clip(void* gr, REBXYF p1, REBXYF p2) { ((agg_graphics*)gr)->agg_set_clip(p1.x, p1.y, p2.x, p2.y); } extern "C" void agg_curve3(void* gr, REBXYF p1, REBXYF p2, REBXYF p3) { ((agg_graphics*)gr)->agg_curve3(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y); } extern "C" void agg_curve4(void* gr, REBXYF p1, REBXYF p2, REBXYF p3, REBXYF p4) { ((agg_graphics*)gr)->agg_curve4(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y); } extern "C" void agg_ellipse(void* gr, REBXYF p1, REBXYF p2) { REBDEC rx = p2.x / 2; REBDEC ry = p2.y / 2; ((agg_graphics*)gr)->agg_ellipse(p1.x + rx, p1.y + ry, rx, ry); } extern "C" void agg_end_poly (void* gr) { ((agg_graphics*)gr)->agg_end_poly(); } extern "C" void agg_end_spline (void* gr, REBINT step, REBINT closed) { ((agg_graphics*)gr)->agg_end_bspline(step, closed); } extern "C" void agg_fill_pen(void* gr, REBYTE* col) { if (col) ((agg_graphics*)gr)->agg_fill_pen(col[0], col[1], col[2], 255 - col[3]); else ((agg_graphics*)gr)->agg_fill_pen(0, 0, 0, 0); } extern "C" void agg_fill_pen_image(void* gr, REBYTE* img, REBINT w, REBINT h) { ((agg_graphics*)gr)->agg_fill_pen(0, 0, 0, 255, img, w, h); } extern "C" void agg_fill_rule(void* gr, REBINT mode) { if (mode >= W_DRAW_EVEN_ODD && mode <= W_DRAW_NON_ZERO) ((agg_graphics*)gr)->agg_fill_rule((agg::filling_rule_e)mode); } extern "C" void agg_gamma(void* gr, REBDEC gamma) { ((agg_graphics*)gr)->agg_set_gamma(gamma); } extern "C" void agg_gradient_pen(void* gr, REBINT gradtype, REBINT mode, REBXYF oft, REBXYF range, REBDEC angle, REBXYF scale, REBSER* colors){ unsigned char colorTuples[256*4+1] = {2, 0,0,0,0, 0,0,0,0, 255,255,255,0}; //max number of color tuples is 256 + one length information char REBDEC offsets[256] = {0.0 , 0.0, 1.0}; //gradient fill RXIARG val; REBCNT type,i,j,k; REBDEC* matrix = new REBDEC[6]; for (i = 0, j = 1, k = 5; type = RL_GET_VALUE(colors, i, &val); i++) { if (type == RXT_DECIMAL || type == RXT_INTEGER) { offsets[j] = (type == RXT_DECIMAL) ? val.dec64 : val.int64; //do some validation offsets[j] = MIN(MAX(offsets[j], 0.0), 1.0); if (j != 1 && offsets[j] < offsets[j-1]) offsets[j] = offsets[j-1]; if (j != 1 && offsets[j] == offsets[j-1]) offsets[j-1]-= 0.0000000001; j++; } else if (type == RXT_TUPLE) { memcpy(&colorTuples[k], val.bytes + 1, 4); k+=4; } } //sanity checks if (j == 1) offsets[0] = -1; colorTuples[0] = MAX(2, (k - 5) / 4); ((agg_graphics*)gr)->agg_gradient_pen(gradtype, oft.x, oft.y, range.x, range.y, angle, scale.x, scale.y, colorTuples, offsets, mode); } extern "C" void agg_invert_matrix(void* gr) { ((agg_graphics*)gr)->agg_invert_mtx(); } extern "C" void agg_image(void* gr, REBYTE* img, REBINT w, REBINT h,REBXYF offset) { ((agg_graphics*)gr)->agg_image(img, offset.x, offset.y, w, h); } extern "C" void agg_image_filter(void* gr, REBINT type, REBINT mode, REBDEC blur) { ((agg_graphics*)gr)->agg_image_filter(type, mode, blur); } extern "C" void agg_image_options(void* gr, REBYTE* keyCol, REBINT border) { if (keyCol) ((agg_graphics*)gr)->agg_image_options(keyCol[0], keyCol[1], keyCol[2], 255 - keyCol[3], border); else ((agg_graphics*)gr)->agg_image_options(0,0,0,0, border); } extern "C" void agg_image_pattern(void* gr, REBINT mode, REBXYF offset, REBXYF size){ if (mode) ((agg_graphics*)gr)->agg_image_pattern(mode,offset.x,offset.y,size.x,size.y); else ((agg_graphics*)gr)->agg_image_pattern(0,0,0,0,0); } extern "C" void agg_image_scale(void* gr, REBYTE* img, REBINT w, REBINT h, REBSER* points) { RXIARG p[4]; REBCNT type; REBCNT n, len = 0; for (n = 0; type = RL_GET_VALUE(points, n, &p[len]); n++) { if (type == RXT_PAIR) if (++len == 4) break; } if (!len) return; if (len == 1) ((agg_graphics*)gr)->agg_image(img, p[0].pair.x, p[0].pair.y, w, h); ((agg_graphics*)gr)->agg_begin_poly(p[0].pair.x, p[0].pair.y); switch (len) { case 2: ((agg_graphics*)gr)->agg_add_vertex(p[1].pair.x, p[0].pair.y); ((agg_graphics*)gr)->agg_add_vertex(p[1].pair.x, p[1].pair.y); ((agg_graphics*)gr)->agg_add_vertex(p[0].pair.x, p[1].pair.y); break; case 3: ((agg_graphics*)gr)->agg_add_vertex(p[1].pair.x, p[1].pair.y); ((agg_graphics*)gr)->agg_add_vertex(p[2].pair.x, p[2].pair.y); ((agg_graphics*)gr)->agg_add_vertex(p[0].pair.x, p[2].pair.y); break; case 4: ((agg_graphics*)gr)->agg_add_vertex(p[1].pair.x, p[1].pair.y); ((agg_graphics*)gr)->agg_add_vertex(p[2].pair.x, p[2].pair.y); ((agg_graphics*)gr)->agg_add_vertex(p[3].pair.x, p[3].pair.y); break; } ((agg_graphics*)gr)->agg_end_poly_img(img, w, h); } extern "C" void agg_line(void* gr, REBXYF p1, REBXYF p2) { ((agg_graphics*)gr)->agg_line(p1.x, p1.y, p2.x, p2.y); } extern "C" void agg_line_cap(void* gr, REBINT mode) { ((agg_graphics*)gr)->agg_stroke_cap((line_cap_e)mode); } extern "C" void agg_line_join(void* gr, REBINT mode) { ((agg_graphics*)gr)->agg_stroke_join((line_join_e)mode); ((agg_graphics*)gr)->agg_dash_join((line_join_e)mode); } extern "C" void agg_line_pattern(void* gr, REBYTE* col, REBDEC* patterns) { ((agg_graphics*)gr)->agg_line_pattern(col, patterns); } extern "C" void agg_line_width(void* gr, REBDEC width, REBINT mode) { ((agg_graphics*)gr)->agg_line_width(width, mode); } extern "C" void agg_matrix(void* gr, REBSER* mtx) { RXIARG val; REBCNT type; REBCNT n; REBDEC* matrix = new REBDEC[6]; for (n = 0; type = RL_GET_VALUE(mtx, n, &val),n < 6; n++) { if (type == RXT_DECIMAL) matrix[n] = val.dec64; else if (type == RXT_INTEGER) matrix[n] = val.int64; else return; } if (n != 6) return; ((agg_graphics*)gr)->agg_set_mtx(matrix); delete[] matrix; } extern "C" void agg_pen(void* gr, REBYTE* col) { if (col) ((agg_graphics*)gr)->agg_pen(col[0], col[1], col[2], 255 - col[3]); else ((agg_graphics*)gr)->agg_pen(0,0,0,0); } extern "C" void agg_pen_image(void* gr, REBYTE* img, REBINT w, REBINT h) { ((agg_graphics*)gr)->agg_pen(0, 0, 0, 255, img, w, h); } extern "C" void agg_pop_matrix(void* gr) { ((agg_graphics*)gr)->agg_pop_mtx(); } extern "C" void agg_push_matrix(void* gr) { ((agg_graphics*)gr)->agg_push_mtx(); } extern "C" void agg_reset_gradient_pen(void* gr) { ((agg_graphics*)gr)->agg_reset_gradient_pen(); } extern "C" void agg_reset_matrix(void* gr) { ((agg_graphics*)gr)->agg_reset_mtx(); } extern "C" void agg_rotate(void* gr, REBDEC ang) { ((agg_graphics*)gr)->agg_rotate(ang); } extern "C" void agg_scale(void* gr, REBXYF sc) { ((agg_graphics*)gr)->agg_scale(sc.x, sc.y); } extern "C" void agg_skew(void* gr, REBXYF angle) { ((agg_graphics*)gr)->agg_skew(angle.x, angle.y); } extern "C" REBINT agg_text(void* gr, REBINT mode, REBXYF p1, REBXYF p2, REBSER* block) { return ((agg_graphics*)gr)->agg_text(mode, &p1, &p2, block); } extern "C" void agg_transform(void* gr, REBDEC ang, REBXYF ctr, REBXYF sc, REBXYF oft) { ((agg_graphics*)gr)->agg_transform(ang, ctr.x, ctr.y, sc.x, sc.y, oft.x, oft.y); } extern "C" void agg_translate(void* gr, REBXYF p) { ((agg_graphics*)gr)->agg_translate(p.x, p.y); } extern "C" void agg_triangle(void* gr, REBXYF p1, REBXYF p2, REBXYF p3, REBYTE* c1, REBYTE* c2, REBYTE* c3, REBDEC dilation) { ((agg_graphics*)gr)->agg_gtriangle(p1, p2, p3, c1, c2, c3, dilation); } //SHAPE functions extern "C" void agg_path_arc(void* gr, REBINT rel, REBXYF p, REBXYF r, REBDEC ang, REBINT sweep, REBINT large) { ((agg_graphics*)gr)->agg_path_arc(rel, r.x, r.y, ang, large, sweep, p.x, p.y); } extern "C" void agg_path_close(void* gr) { ((agg_graphics*)gr)->agg_path_close(); } extern "C" void agg_path_curv(void* gr, REBINT rel, REBXYF p1, REBXYF p2) { ((agg_graphics*)gr)->agg_path_cubic_curve_to(rel, p1.x, p1.y, p2.x, p2.y); } extern "C" void agg_path_curve(void* gr, REBINT rel, REBXYF p1,REBXYF p2, REBXYF p3) { ((agg_graphics*)gr)->agg_path_cubic_curve(rel, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y); } extern "C" void agg_path_hline(void* gr, REBCNT rel, REBDEC x) { ((agg_graphics*)gr)->agg_path_hline(rel, x); } extern "C" void agg_path_line(void* gr, REBCNT rel, REBXYF p) { ((agg_graphics*)gr)->agg_path_line(rel, p.x, p.y); } extern "C" void agg_path_move(void* gr, REBCNT rel, REBXYF p) { ((agg_graphics*)gr)->agg_path_move(rel, p.x, p.y); } extern "C" void agg_path_open(void* gr) { ((agg_graphics*)gr)->agg_begin_path(); } extern "C" void agg_path_vline(void* gr, REBCNT rel, REBDEC y) { ((agg_graphics*)gr)->agg_path_vline(rel, y); } extern "C" void agg_path_qcurv(void* gr, REBINT rel, REBXYF p) { ((agg_graphics*)gr)->agg_path_quadratic_curve_to(rel, p.x, p.y); } extern "C" void agg_path_qcurve(void* gr, REBINT rel, REBXYF p1, REBXYF p2) { ((agg_graphics*)gr)->agg_path_quadratic_curve(rel, p1.x, p1.y, p2.x, p2.y); } extern "C" REBINT Draw_Image(REBYTE *image, REBINT w, REBINT h, REBSER *block) { agg_graphics::ren_buf renbuf(image, w, h, w * 4); agg_graphics::pixfmt pixf(renbuf); agg_graphics::ren_base rb_win(pixf); agg_graphics* graphics = new agg_graphics(&renbuf, w, h, 0, 0); REBSER *args = 0; REBINT result = Draw_Gob(graphics, block, args); if (result < 0) goto do_cleanup; result = graphics->agg_render(rb_win); do_cleanup: delete graphics; return result; } #ifdef ndef extern "C" void agg_get_size(void* gr, REBPAR* p) { ((agg_graphics*)gr)->agg_size(p); } extern "C" void agg_effect(void* gr, REBPAR* p1, REBPAR* p2, REBSER* block) { ((agg_graphics*)gr)->agg_effect(p1, p2, block); } #endif }
[ [ [ 1, 422 ] ] ]
0e03e11c0fc29979b253ce46758d03362decfd82
2fd3cf69d422c2e62db908a5f6ec85890cc12f80
/__OBSOLETE__/auxWindow.h
c0af9858bd43b325c7e92d27404509c19dc5f1ec
[]
no_license
ksherlock/BShisen
24ec5fb05c8bda250a1090ec32f7dc6f3df7c036
f5f9db386d847ea3f26a1116ff465676290b3aa9
refs/heads/master
2016-09-06T01:37:57.086749
2010-06-10T02:18:14
2010-06-10T02:18:14
18,947,831
2
0
null
null
null
null
UTF-8
C++
false
false
214
h
#ifndef __AUXWINDOW_H__ #define __AUXWINDOW_H__ #include <Window.h> class GetGame: public BWindow { public: GetGame(); ~GetGame(); unsigned PromptGame(unsigned gameno); private: }; #endif
[ "(no author)@5590a31f-7b70-45f8-8c82-aa3a8e5f4507" ]
[ [ [ 1, 18 ] ] ]
03b475ca5fcb08d93a20634b696cba22c8ded211
c70941413b8f7bf90173533115c148411c868bad
/core/include/vtxDynLib.h
f205e8c6359c5ab4437710fd081d67995cf9a9df
[]
no_license
cnsuhao/vektrix
ac6e028dca066aad4f942b8d9eb73665853fbbbe
9b8c5fa7119ff7f3dc80fb05b7cdba335cf02c1a
refs/heads/master
2021-06-23T11:28:34.907098
2011-03-27T17:39:37
2011-03-27T17:39:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,985
h
/* ----------------------------------------------------------------------------- This source file is part of "vektrix" (the rich media and vector graphics rendering library) For the latest info, see http://www.fuse-software.com/ Copyright (c) 2009-2010 Fuse-Software (tm) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #ifndef __vtxDynLib_H__ #define __vtxDynLib_H__ #include "vtxPrerequisites.h" namespace vtx { //----------------------------------------------------------------------- #if VTX_OS == VTX_WIN32 # define DYNLIB_HANDLE hInstance # define DYNLIB_LOAD(a) LoadLibrary(a) # define DYNLIB_GETSYM(a, b) GetProcAddress(a, b) # define DYNLIB_UNLOAD(a) !FreeLibrary(a) struct HINSTANCE__; typedef struct HINSTANCE__* hInstance; #elif VTX_OS == VTX_LINUX # define DYNLIB_HANDLE void* # define DYNLIB_LOAD(a) dlopen(a, RTLD_LAZY | RTLD_GLOBAL) # define DYNLIB_GETSYM(a, b) dlsym(a, b) # define DYNLIB_UNLOAD(a) dlclose(a) #elif VTX_OS == VTX_APPLE # define DYNLIB_HANDLE CFBundleRef # define DYNLIB_LOAD(a) mac_loadExeBundle(a) # define DYNLIB_GETSYM(a, b) mac_getBundleSym(a, b) # define DYNLIB_UNLOAD(a) mac_unloadExeBundle(a) #endif //----------------------------------------------------------------------- /** A class for loading external program libraries */ class DynLib { public: DynLib(const String& name); ~DynLib(); /** Load the library */ void load(); /** Unload the library */ void unload(); /** Get the name of the program library */ const String& getName() const; /** Get a symbol (method, attribute, ...) by name */ void* getSymbol(const String& name) const throw(); /** Get an eventual error formatted as String */ String getError(); protected: String mName; DYNLIB_HANDLE mInstance; }; //----------------------------------------------------------------------- } #endif
[ "stonecold_@9773a11d-1121-4470-82d2-da89bd4a628a", "fixxxeruk@9773a11d-1121-4470-82d2-da89bd4a628a" ]
[ [ [ 1, 31 ], [ 33, 86 ] ], [ [ 32, 32 ] ] ]
586771edea15afdba966e7f7ec205e1cf74fedb1
1092bd6dc9b728f3789ba96e37e51cdfb9e19301
/loci/video/renderers/drawer.h
e972a85cc4c790b2dd9a05fb6eacc6b83c4cb45c
[]
no_license
dtbinh/loci-extended
772239e63b4e3e94746db82d0e23a56d860b6f0d
f4b5ad6c4412e75324d19b71559a66dd20f4f23f
refs/heads/master
2021-01-10T12:23:52.467480
2011-03-15T22:03:06
2011-03-15T22:03:06
36,032,427
0
0
null
null
null
null
UTF-8
C++
false
false
870
h
#ifndef LOCI_VIDEO_RENDERERS_DRAWER_H_ #define LOCI_VIDEO_RENDERERS_DRAWER_H_ /** * An interface for scene renderers * An interface for scene renderers that simply render something without * per-frame parameters. * * @file drawer.h * @author David Gill * @date 24/04/2010 */ namespace loci { namespace video { class scene_renderer { public: scene_renderer(bool reflective = false) : reflective_(reflective) { } void draw() { render(); } bool reflective() { return reflective_; } protected: void reflections(bool flag) { reflective_ = flag; } private: virtual void render() = 0; bool reflective_; }; } // namespace video } // namespace loci #endif // LOCI_VIDEO_RENDERERS_DRAWER_H_
[ "[email protected]@0e8bac56-0901-9d1a-f0c4-3841fc69e132" ]
[ [ [ 1, 43 ] ] ]
34370ad8e45ca317722a042b6161f8e407e4ddb8
81488d2175ab16c6c942054fa3dcdc7cdce8d8df
/ofxMagnetic/docs/video/ofVideoGrabber.h
c503a168b9bc518b5b87de6a882e832c0962ee6e
[]
no_license
devert/ofxmagnetic
fbaabd0389c9ac4c23683d353b47bfda25c6f33f
b6f1d9ccf744b6c45009ddafa9aa0af02ddddd9c
refs/heads/master
2020-04-04T05:00:16.008427
2010-11-03T23:42:57
2010-11-03T23:42:57
32,811,146
1
0
null
null
null
null
UTF-8
C++
false
false
3,302
h
#ifndef _OF_VIDEO_GRABBER #define _OF_VIDEO_GRABBER #include "ofConstants.h" #include "ofTexture.h" #include "ofGraphics.h" #include "ofTypes.h" #ifdef OF_VIDEO_CAPTURE_QUICKTIME #include "ofQtUtils.h" #endif #ifdef OF_VIDEO_CAPTURE_DIRECTSHOW #include "videoInput.h" #endif #ifdef OF_VIDEO_CAPTURE_UNICAP #include "ofUCUtils.h" #endif #ifdef OF_VIDEO_CAPTURE_GSTREAMER #include "ofGstUtils.h" #endif // todo: // QT - callback, via SGSetDataProc - couldn't get this to work yet // image decompress options ala mung... class ofVideoGrabber : public ofBaseVideo{ public : ofVideoGrabber(); virtual ~ofVideoGrabber(); void listDevices(); bool isFrameNew(); void grabFrame(); void close(); bool initGrabber(int w, int h, bool bTexture = true); void videoSettings(); unsigned char * getPixels(); int getDeviceCount(); ofTexture & getTextureReference(); void setVerbose(bool bTalkToMe); void setDeviceID(int _deviceID); void setDesiredFrameRate(int framerate); void setUseTexture(bool bUse); void draw(float x, float y, float w, float h); void draw(float x, float y); void update(); //the anchor is the point the image is drawn around. //this can be useful if you want to rotate an image around a particular point. void setAnchorPercent(float xPct, float yPct); //set the anchor as a percentage of the image width/height ( 0.0-1.0 range ) void setAnchorPoint(int x, int y); //set the anchor point in pixels void resetAnchor(); //resets the anchor to (0, 0) float getHeight(); float getWidth(); int height; int width; protected: bool bChooseDevice; int deviceID; int deviceCount; bool bUseTexture; ofTexture tex; bool bVerbose; bool bGrabberInited; unsigned char * pixels; int attemptFramerate; bool bIsFrameNew; //--------------------------------- quicktime #ifdef OF_VIDEO_CAPTURE_QUICKTIME unsigned char * offscreenGWorldPixels; // 32 bit: argb (qt k32ARGBPixelFormat) int w,h; bool bHavePixelsChanged; GWorldPtr videogworld; SeqGrabComponent gSeqGrabber; SGChannel gVideoChannel; Rect videoRect; bool bSgInited; string deviceName; SGGrabCompleteBottleUPP myGrabCompleteProc; bool qtInitSeqGrabber(); bool qtCloseSeqGrabber(); bool qtSelectDevice(int deviceNumber, bool didWeChooseADevice); //-------------------------------------------------------------------- #ifdef TARGET_OSX //-------------------------------------------------------------------- bool saveSettings(); bool loadSettings(); //-------------------------------------------------------------------- #endif //-------------------------------------------------------------------- #endif //--------------------------------- directshow #ifdef OF_VIDEO_CAPTURE_DIRECTSHOW int device; videoInput VI; bool bDoWeNeedToResize; #endif //--------------------------------- linux unicap #ifdef OF_VIDEO_CAPTURE_UNICAP ofUCUtils ucGrabber; #endif #ifdef OF_VIDEO_CAPTURE_GSTREAMER ofGstUtils gstUtils; #endif }; #endif
[ "[email protected]@70826fe1-adc8-3e30-cfb8-25ad2d9f667f" ]
[ [ [ 1, 137 ] ] ]
8a0545cb87d4ce2d78e3885d0a5e27a8921fda89
4f04b6f376acb98e41ac16659f9e9eee99163bc8
/sequential-v2/Stack.h
ab712b312122c8641a58ee7e8ed8e9c125963e46
[]
no_license
jskvara/PAR-KGM
d4689971b88565067f1cb3369b5f7d4425646107
407874a0b0a417cff28448ddcfc622a67b96cdd0
refs/heads/master
2020-04-09T10:28:17.442416
2011-12-15T22:55:34
2011-12-15T22:55:34
2,991,233
0
0
null
null
null
null
UTF-8
C++
false
false
832
h
#include "Graph.h" #pragma once //pomocna struktura pro reprezentaci prvku v zasobniku -> spojovy seznam struct StackNode { Graph *graph; StackNode* next; }; class Stack { private: //odkaz na prvni prvek StackNode* m_top; //velikost zasobniku int size; public: //konstruktor Stack(); //destruktor ~Stack(); //prida prvek na zasobnik void push(Graph* graph); //odebere prvek ze zasobniku Graph* pop(); //kontrola zda je zasobnik prazdny bool is_empty() const; //vyprazdni zasobnik void clear(); //vrati pocet prvku v zasobniku int count() const; };
[ [ [ 1, 35 ] ] ]
2fb3683f7fae88dd358c911cd5966c0fac759d62
7b7a3f9e0cac33661b19bdfcb99283f64a455a13
/Engine/dll/Assimp/include/aiMatrix3x3.inl
7706f1f2a3dda73b95dcb1e2592d273c0905f7d8
[]
no_license
grimtraveller/fluxengine
62bc0169d90bfe656d70e68615186bd60ab561b0
8c967eca99c2ce92ca4186a9ca00c2a9b70033cd
refs/heads/master
2021-01-10T10:58:56.217357
2009-09-01T15:07:05
2009-09-01T15:07:05
55,775,414
0
0
null
null
null
null
UTF-8
C++
false
false
2,433
inl
/** @file Inline implementation of the 3x3 matrix operators */ #ifndef AI_MATRIX3x3_INL_INC #define AI_MATRIX3x3_INL_INC #include "aiMatrix3x3.h" #ifdef __cplusplus #include "aiMatrix4x4.h" #include <algorithm> // ------------------------------------------------------------------------------------------------ // Construction from a 4x4 matrix. The remaining parts of the matrix are ignored. inline aiMatrix3x3::aiMatrix3x3( const aiMatrix4x4& pMatrix) { a1 = pMatrix.a1; a2 = pMatrix.a2; a3 = pMatrix.a3; b1 = pMatrix.b1; b2 = pMatrix.b2; b3 = pMatrix.b3; c1 = pMatrix.c1; c2 = pMatrix.c2; c3 = pMatrix.c3; } // ------------------------------------------------------------------------------------------------ inline aiMatrix3x3& aiMatrix3x3::operator *= (const aiMatrix3x3& m) { *this = aiMatrix3x3( m.a1 * a1 + m.b1 * a2 + m.c1 * a3, m.a2 * a1 + m.b2 * a2 + m.c2 * a3, m.a3 * a1 + m.b3 * a2 + m.c3 * a3, m.a1 * b1 + m.b1 * b2 + m.c1 * b3, m.a2 * b1 + m.b2 * b2 + m.c2 * b3, m.a3 * b1 + m.b3 * b2 + m.c3 * b3, m.a1 * c1 + m.b1 * c2 + m.c1 * c3, m.a2 * c1 + m.b2 * c2 + m.c2 * c3, m.a3 * c1 + m.b3 * c2 + m.c3 * c3); return *this; } // ------------------------------------------------------------------------------------------------ inline aiMatrix3x3 aiMatrix3x3::operator* (const aiMatrix3x3& m) const { aiMatrix3x3 temp( *this); temp *= m; return temp; } // ------------------------------------------------------------------------------------------------ inline aiMatrix3x3& aiMatrix3x3::Transpose() { // (float&) don't remove, GCC complains cause of packed fields std::swap( (float&)a2, (float&)b1); std::swap( (float&)a3, (float&)c1); std::swap( (float&)b3, (float&)c2); return *this; } // ------------------------------------------------------------------------------------------------ inline aiMatrix3x3& aiMatrix3x3::Rotation(float a, aiMatrix3x3& out) { out.a1 = out.b2 = ::cos(a); out.b1 = ::sin(a); out.a2 = - out.b1; out.a3 = out.b3 = out.c1 = out.c2 = 0.f; out.c3 = 1.f; return out; } // ------------------------------------------------------------------------------------------------ inline aiMatrix3x3& aiMatrix3x3::Translation( const aiVector2D& v, aiMatrix3x3& out) { out = aiMatrix3x3(); out.a3 = v.x; out.b3 = v.y; return out; } #endif // __cplusplus #endif // AI_MATRIX3x3_INL_INC
[ "marvin.kicha@e13029a8-578f-11de-8abc-d1c337b90d21" ]
[ [ [ 1, 78 ] ] ]
21f8afc371040361ea7afc6fe8a76700ced1c5c6
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/contrib/nspatialdb/src/spatialdb/nscriptablesector_cmds.cc
f84cde7ec36013cf553470ea83e7222bb8b164b8
[]
no_license
moltenguy1/minimangalore
9f2edf7901e7392490cc22486a7cf13c1790008d
4d849672a6f25d8e441245d374b6bde4b59cbd48
refs/heads/master
2020-04-23T08:57:16.492734
2009-08-01T09:13:33
2009-08-01T09:13:33
35,933,330
0
0
null
null
null
null
UTF-8
C++
false
false
7,301
cc
//------------------------------------------------------------------- // nscriptablesector_cmds.cc // (C) 2004 Gary Haussmann //------------------------------------------------------------------- #include "spatialdb/nscriptablesector.h" #include "kernel/npersistserver.h" static void n_addvisibleobject(void *slf, nCmd *cmd); static void n_addoccludingobject(void *slf, nCmd *cmd); static void n_addportalobject(void *slf, nCmd *cmd); static void n_remobject(void *slf, nCmd *cmd); static void n_clearobjects(void *slf, nCmd *cmd); //------------------------------------------------------------------------------ /** @scriptclass nscriptablesector @superclass nroot @classinfo */ void n_initcmds(nClass *cl) { cl->BeginCmds(); cl->AddCmd("v_addvisibleobject_ssffff", 'AVOB', n_addvisibleobject); cl->AddCmd("v_addoccludingobject_sffffff", 'AOOB', n_addoccludingobject); cl->AddCmd("v_addportalobject_ssffff", 'APOB', n_addportalobject); cl->AddCmd("v_remobject_s", 'RMOB', n_remobject); cl->AddCmd("v_clearobjects_v", 'CLOb', n_clearobjects); cl->EndCmds(); } //------------------------------------------------------------------------------ /** @cmd addvisibleobject @input s(object name), s(scenenode path), f(xcoord), f(ycoord), f(zcoord), f(radius) @output v @info Add a visible object into the sector, using the specified path as the root scene node. */ static void n_addvisibleobject(void* slf, nCmd* cmd) { nScriptableSector *self = (nScriptableSector *)slf; const char* s0 = cmd->In()->GetS(); const char* s1 = cmd->In()->GetS(); float x = cmd->In()->GetF(); float y = cmd->In()->GetF(); float z = cmd->In()->GetF(); float r = cmd->In()->GetF(); self->AddVisibleObject(s0, s1, vector3(x,y,z), r); } //------------------------------------------------------------------------------ /** @cmd addoccludingobject @input s(object name), f(min xcoord), f(min ycoord), f(min zcoord), f(max xcoord), f(max ycoord), f(max zcoord) @output v @info Add an occluding object to the sector, using the specific bounding box as the occluder. Note that this doesn't actually render anything except in debug visualization mode; if you want to actually see the occluder you'll have to add a visible object with the same size, shape and position. */ static void n_addoccludingobject(void* slf, nCmd* cmd) { nScriptableSector *self = (nScriptableSector *)slf; const char* s0 = cmd->In()->GetS(); float x1 = cmd->In()->GetF(); float y1 = cmd->In()->GetF(); float z1 = cmd->In()->GetF(); float x2 = cmd->In()->GetF(); float y2 = cmd->In()->GetF(); float z2 = cmd->In()->GetF(); self->AddOccludingObject( s0, vector3(x1,y1,z1), vector3(x2,y2,z2) ); } //------------------------------------------------------------------------------ /** @cmd addportalobject @input s(object name), s(NOH path to sector on other side of portal), f(xcoord), f(ycoord), f(zcoord), f(radius) @output v @info Add an occluding object to the sector, using the specific bounding box as the occluder. Note that this doesn't actually render anything except in debug visualization mode; if you want to actually see the occluder you'll have to add a visible object with the same size, shape and position. */ static void n_addportalobject(void* slf, nCmd* cmd) { nScriptableSector *self = (nScriptableSector *)slf; const char* s0 = cmd->In()->GetS(); const char* s1 = cmd->In()->GetS(); float x = cmd->In()->GetF(); float y = cmd->In()->GetF(); float z = cmd->In()->GetF(); float r = cmd->In()->GetF(); self->AddPortalObject( s0, s1, vector3(x,y,z), r ); } //------------------------------------------------------------------------------ /** @cmd remobject @input s(object name) @output v @info Remove the named object from the sector */ static void n_remobject(void* slf, nCmd* cmd) { nScriptableSector *self = (nScriptableSector *)slf; const char* s0 = cmd->In()->GetS(); self->RemObject( s0 ); } //------------------------------------------------------------------------------ /** @cmd clearobjects @input v @output v @info Remove all objects from the sector */ static void n_clearobjects(void* slf, nCmd* cmd) { nScriptableSector *self = (nScriptableSector *)slf; self->ClearObjects(); } bool nScriptableSector::SaveCmds(nPersistServer* ps) { if (nRoot::SaveCmds(ps)) { // walk our objects and add them to the persistserver // find the element in here somewhere... nCmd* cmd; for (int i=0; i < m_scriptobject_array.Size(); i++) { nScriptableSectorObject *object = m_scriptobject_array[i]; // dump this object out--what type is it? nSpatialElement *se = object->spatialinfo; if (se->GetSpatialType() & nSpatialElement::N_SPATIAL_OCCLUDER) { // write out an occluder n_assert(se->HasAABB()); bbox3 box = se->GetAABB(); cmd = ps->GetCmd(this, 'AOOB'); cmd->In()->SetS(object->objectname.Get()); cmd->In()->SetF(box.vmin.x); cmd->In()->SetF(box.vmin.y); cmd->In()->SetF(box.vmin.z); cmd->In()->SetF(box.vmax.x); cmd->In()->SetF(box.vmax.y); cmd->In()->SetF(box.vmax.z); ps->PutCmd(cmd); } else if (se->GetSpatialType() & nSpatialElement::N_SPATIAL_PORTAL) { // write out a portal object n_assert(se->HasAABB()); bbox3 box = se->GetAABB(); cmd = ps->GetCmd(this, 'APOB'); cmd->In()->SetS(object->objectname.Get()); cmd->In()->SetS("argh"); cmd->In()->SetF(box.center().x); cmd->In()->SetF(box.center().y); cmd->In()->SetF(box.center().z); cmd->In()->SetF(box.extents().x); ps->PutCmd(cmd); } else { // write out a visible object n_assert(se->HasAABB()); bbox3 box = se->GetAABB(); cmd = ps->GetCmd(this, 'AVOB'); cmd->In()->SetS(object->objectname.Get()); cmd->In()->SetS(object->rendernode.getname()); cmd->In()->SetF(box.center().x); cmd->In()->SetF(box.center().y); cmd->In()->SetF(box.center().z); cmd->In()->SetF(box.extents().x); ps->PutCmd(cmd); } } return true; } return false; } //------------------------------------------------------------------- // EOF //-------------------------------------------------------------------
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 220 ] ] ]
86b7bfdec28da836d18be2992f79300d83fa0ed0
21da454a8f032d6ad63ca9460656c1e04440310e
/src/wcpp/lang/wsiString.h
3fcf92f6fc179e448186f24aeb6b0fccf11b1861
[]
no_license
merezhang/wcpp
d9879ffb103513a6b58560102ec565b9dc5855dd
e22eb48ea2dd9eda5cd437960dd95074774b70b0
refs/heads/master
2021-01-10T06:29:42.908096
2009-08-31T09:20:31
2009-08-31T09:20:31
46,339,619
0
0
null
null
null
null
GB18030
C++
false
false
10,779
h
#pragma once #include "wsiObject.h" #include "wsiArray.h" class wsiCharSequence; class wsiStringBuffer; // class wsiByteArray; class wsiCharset; // class wsiCharArray; class wsiLocale; typedef wsiArray<wsiString> wsiStringArray; #define WS_IID_OF_wsiString \ { 0x5e93f255, 0x1df4, 0x4257, { 0xab, 0x63, 0xb2, 0x97, 0xd0, 0xa0, 0x86, 0x78 } } // {5E93F255-1DF4-4257-AB63-B297D0A08678} #define WS_IID_OF_wsiStringRW \ { 0x7d62e29c, 0xed7f, 0x41cd, { 0x96, 0x60, 0x80, 0xe1, 0xea, 0x95, 0x8, 0x77 } } // {7D62E29C-ED7F-41cd-9660-80E1EA950877} class wsiString : public wsiObject { public: static const ws_iid sIID; public: WS_METHOD( ws_char , CharAt )(ws_int index) const = 0; // 返回指定索引处的 ws_char 值。 WS_METHOD( ws_int , CodePointAt )(ws_int index) const = 0; // 返回指定索引处的字符(Unicode 代码点)。 WS_METHOD( ws_int , CodePointBefore )(ws_int index) const = 0; // 返回指定索引之前的字符(Unicode 代码点)。 WS_METHOD( ws_int , CodePointCount )(ws_int beginIndex, ws_int endIndex) const = 0; // 返回此 String 的指定文本范围中的 Unicode 代码点数。 WS_METHOD( ws_int , CompareTo )(wsiString * anotherString) const = 0; // 按字典顺序比较两个字符串。 WS_METHOD( ws_int , CompareToIgnoreCase )(wsiString * str) const = 0; // 按字典顺序比较两个字符串,不考虑大小写。 WS_METHOD( ws_result , Concat )(wsiString ** ret, wsiString * str) const = 0; // 将指定字符串连接到此字符串的结尾。 WS_METHOD( ws_boolean , Contains )(wsiCharSequence * s) const = 0; // 当且仅当此字符串包含指定的 ws_char 值序列时,返回 true。 WS_METHOD( ws_boolean , ContentEquals )(wsiCharSequence * cs) const = 0; // 将此字符串与指定的 CharSequence 比较。 WS_METHOD( ws_boolean , ContentEquals )(wsiStringBuffer * sb) const = 0; // 将此字符串与指定的 StringBuffer 比较。 WS_METHOD( ws_boolean , EndsWith )(wsiString * suffix) const = 0; // 测试此字符串是否以指定的后缀结束。 WS_METHOD( ws_boolean , Equals )(wsiObject * anObject) const = 0; // 将此字符串与指定的对象比较。 WS_METHOD( ws_boolean , EqualsIgnoreCase )(wsiString * anotherString) const = 0; // 将此 wsiString * 与另一个 wsiString * 比较,不考虑大小写。 WS_METHOD( ws_result , GetBytes )(wsiByteArray ** ret) const = 0; // 使用平台的默认字符集将此 wsiString * 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。 WS_METHOD( ws_result , GetBytes )(wsiByteArray ** ret, wsiCharset * charset) const = 0; // 使用给定的 charset 将此 wsiString * 编码到 byte 序列,并将结果存储到新的 byte 数组。 WS_METHOD( ws_result , GetBytes )(wsiByteArray ** ret, wsiString * charsetName) const = 0; // 使用指定的字符集将此 wsiString * 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。 WS_METHOD( ws_result , GetChars )(ws_int srcBegin, ws_int srcEnd, ws_char * dst, ws_int dstSize) const = 0; // 将字符从此字符串复制到目标字符数组。 WS_METHOD( ws_int , HashCode )(void) const = 0; // 返回此字符串的哈希码。 WS_METHOD( ws_int , IndexOf )(ws_int ch) const = 0; // 返回指定字符在此字符串中第一次出现处的索引。 WS_METHOD( ws_int , IndexOf )(ws_int ch, ws_int fromIndex) const = 0; // 返回在此字符串中第一次出现指定字符处的索引,从指定的索引开始搜索。 WS_METHOD( ws_int , IndexOf )(wsiString * str) const = 0; // 返回指定子字符串在此字符串中第一次出现处的索引。 WS_METHOD( ws_int , IndexOf )(wsiString * str, ws_int fromIndex) const = 0; // 返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始。 WS_METHOD( ws_result , Intern )(wsiString ** ret) const = 0; // 返回字符串对象的规范化表示形式。 WS_METHOD( ws_boolean , IsEmpty )(void) const = 0; // 当且仅当 length() 为 0 时返回 true。 WS_METHOD( ws_int , LastIndexOf )(ws_int ch) const = 0; // 返回指定字符在此字符串中最后一次出现处的索引。 WS_METHOD( ws_int , LastIndexOf )(ws_int ch, ws_int fromIndex) const = 0; // 返回指定字符在此字符串中最后一次出现处的索引,从指定的索引处开始进行反向搜索。 WS_METHOD( ws_int , LastIndexOf )(wsiString * str) const = 0; // 返回指定子字符串在此字符串中最右边出现处的索引。 WS_METHOD( ws_int , LastIndexOf )(wsiString * str, ws_int fromIndex) const = 0; // 返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索。 WS_METHOD( ws_int , Length )(void) const = 0; // 返回此字符串的长度。 WS_METHOD( ws_boolean , Matches )(wsiString * regex) const = 0; // 告知此字符串是否匹配给定的正则表达式。 WS_METHOD( ws_int , OffsetByCodePoints )(ws_int index, ws_int codePointOffset) const = 0; // 返回此 wsiString * 中从给定的 index 处偏移 codePointOffset 个代码点的索引。 WS_METHOD( ws_boolean , RegionMatches )(ws_boolean ignoreCase, ws_int toffset, wsiString * other, ws_int ooffset, ws_int len) const = 0; // 测试两个字符串区域是否相等。 WS_METHOD( ws_boolean , RegionMatches )(ws_int toffset, wsiString * other, ws_int ooffset, ws_int len) const = 0; // 测试两个字符串区域是否相等。 WS_METHOD( ws_result , Replace )(wsiString ** ret, ws_char oldChar, ws_char newChar) const = 0; // 返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。 WS_METHOD( ws_result , Replace )(wsiString ** ret, wsiCharSequence * target, wsiCharSequence * replacement) const = 0; // 使用指定的字面值替换序列替换此字符串所有匹配字面值目标序列的子字符串。 WS_METHOD( ws_result , ReplaceAll )(wsiString ** ret, wsiString * regex, wsiString * replacement) const = 0; // 使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。 WS_METHOD( ws_result , ReplaceFirst )(wsiString ** ret, wsiString * regex, wsiString * replacement) const = 0; // 使用给定的 replacement 替换此字符串匹配给定的正则表达式的第一个子字符串。 WS_METHOD( ws_result , Split )(wsiStringArray ** ret, wsiString * regex) const = 0; // 根据给定正则表达式的匹配拆分此字符串。 WS_METHOD( ws_result , Split )(wsiStringArray ** ret, wsiString * regex, ws_int limit) const = 0; // 根据匹配给定的正则表达式来拆分此字符串。 WS_METHOD( ws_boolean , StartsWith )(wsiString * prefix) const = 0; // 测试此字符串是否以指定的前缀开始。 WS_METHOD( ws_boolean , StartsWith )(wsiString * prefix, ws_int toffset) const = 0; // 测试此字符串从指定索引开始的子字符串是否以指定前缀开始。 WS_METHOD( ws_result , SubSequence )(wsiCharSequence ** ret, ws_int beginIndex, ws_int endIndex) const = 0; // 返回一个新的字符序列,它是此序列的一个子序列。 WS_METHOD( ws_result , Substring )(wsiString ** ret, ws_int beginIndex) const = 0; // 返回一个新的字符串,它是此字符串的一个子字符串。 WS_METHOD( ws_result , Substring )(wsiString ** ret, ws_int beginIndex, ws_int endIndex) const = 0; // 返回一个新字符串,它是此字符串的一个子字符串。 WS_METHOD( ws_result , ToCharArray )(wsiCharArray ** ret) const = 0; // 将此字符串转换为一个新的字符数组。 WS_METHOD( ws_result , ToLowerCase )(wsiString ** ret) const = 0; // 使用默认语言环境的规则将此 wsiString * 中的所有字符都转换为小写。 WS_METHOD( ws_result , ToLowerCase )(wsiString ** ret, wsiLocale * locale) const = 0; // 使用给定 Locale 的规则将此 wsiString * 中的所有字符都转换为小写。 WS_METHOD( ws_result , ToString )(wsiString ** ret) const = 0; // 返回此对象本身(它已经是一个字符串!)。 WS_METHOD( ws_result , ToUpperCase )(wsiString ** ret) const = 0; // 使用默认语言环境的规则将此 wsiString * 中的所有字符都转换为大写。 WS_METHOD( ws_result , ToUpperCase )(wsiString ** ret, wsiLocale * locale) const = 0; // 使用给定 Locale 的规则将此 wsiString * 中的所有字符都转换为大写。 WS_METHOD( ws_result , Trim )(wsiString ** ret) const = 0; // 返回字符串的副本,忽略前导空白和尾部空白。 public: // extends wsiString WS_METHOD( const ws_char * const , GetBuffer )(void) const = 0; WS_METHOD( ws_int , GetLength )(void) const = 0; }; class wsiStringRW : public wsiString { public: static const ws_iid sIID; public: WS_METHOD( ws_char * , GetBufferRW )(void) = 0; WS_METHOD( ws_int , GetBufferSize )(void) const = 0; WS_METHOD( ws_int , SetLength )(ws_int newLength) = 0; WS_METHOD( ws_int , SetString )(const ws_char * const buf, ws_int len) = 0; };
[ "xukun0217@98f29a9a-77f1-11de-91f8-ab615253d9e8" ]
[ [ [ 1, 108 ] ] ]
1472d8cc6194e848821b3b7a91651fb6725d196c
cf98fd401c09dffdd1e7b1aaa91615e9fe64961f
/tags/0.0.1/src/sc/bytebuffer.cpp
6c6d9b79372cbe4219ba81d7e88d9447efe5b3bd
[]
no_license
BackupTheBerlios/bvr20983-svn
77f4fcc640bd092c3aa85311fecfbea1a3b7677e
4d177c13f6ec110626d26d9a2c2db8af7cb1869d
refs/heads/master
2021-01-21T13:36:43.379562
2009-10-22T00:25:39
2009-10-22T00:25:39
40,663,412
0
0
null
null
null
null
UTF-8
C++
false
false
5,549
cpp
/* * $Id$ * * A Byte String class used in smartcard implementation. * * Copyright (C) 2008 Dorothea Wachmann * * 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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ #include "os.h" #include "sc/bytebuffer.h" #include "exception/bvr20983exception.h" #include "exception/lasterrorexception.h" #include "util/logstream.h" namespace bvr20983 { /* * ByteBuffer::ByteBuffer * * Constructor Parameters: * None */ ByteBuffer::ByteBuffer(const TString& buffer) { m_buffer.clear(); if( buffer.size()>0 ) { int bufLen = 0; #ifdef _UNICODE // cp=28591 --> ISO 8859-1 Latin I bufLen = ::WideCharToMultiByte( 28591, 0, buffer.data(), buffer.size(),NULL, 0, NULL, NULL ); THROW_LASTERROREXCEPTION1( bufLen ); auto_ptr<BYTE> buf = auto_ptr<BYTE>(new BYTE[bufLen]); ::memset(buf.get(),bufLen,sizeof(BYTE)); THROW_LASTERROREXCEPTION1( ::WideCharToMultiByte( 28591, 0, buffer.data(), buffer.size(),(LPSTR)buf.get(), bufLen, NULL, NULL ) ); m_buffer = BString(buf.get(),bufLen); #else BYTE* buf = (BYTE*)buffer.data(); bufLen = buffer.size(); m_buffer = BString(buf,bufLen); #endif } // of if } /** * */ ByteBuffer::ByteBuffer(const ByteBuffer& buffer) { m_buffer = buffer.m_buffer; } /** * */ ByteBuffer::ByteBuffer(const BYTE* buffer,DWORD bufferLen) { m_buffer = BString(buffer,bufferLen); } /** * */ ByteBuffer::operator TString() { TString result; if( m_buffer.size()>0 ) { #ifdef _UNICODE auto_ptr<TCHAR> buffer = auto_ptr<TCHAR>(new TCHAR[m_buffer.size()]); ::memset(buffer.get(),m_buffer.size(),sizeof(TCHAR)); THROW_LASTERROREXCEPTION1( ::MultiByteToWideChar(28591, MB_ERR_INVALID_CHARS, (LPCSTR)m_buffer.data(),m_buffer.size(),buffer.get(),m_buffer.size()) ); result = TString(buffer.get(),m_buffer.size()); #else LPTSTR buffer = (LPTSTR)m_buffer.data(); result = TString(buffer,m_buffer.size()); #endif } // of if return result; } /** * */ void ByteBuffer::GetBSTR(BSTR* result) { *result = NULL; if( m_buffer.size()>0 ) { #ifdef _UNICODE auto_ptr<TCHAR> buffer = auto_ptr<TCHAR>(new TCHAR[m_buffer.size()]); ::memset(buffer.get(),m_buffer.size(),sizeof(TCHAR)); THROW_LASTERROREXCEPTION1( ::MultiByteToWideChar(28591, MB_ERR_INVALID_CHARS, (LPCSTR)m_buffer.data(),m_buffer.size(),buffer.get(),m_buffer.size()) ); *result = ::SysAllocString(buffer.get()); #else BSTR buffer = (BSTR)m_buffer.data(); *result = ::SysAllocString(buffer); #endif } // of if } #ifdef _UNICODE wostream& ByteBuffer::Dump(wostream& os) const #else ostream& ByteBuffer::Dump(ostream& os) const #endif { ios_base::iostate err = 0; #ifdef _UNICODE wostream::sentry opfx(os); #else ostream::sentry opfx(os); #endif try { if( opfx && !m_buffer.empty() ) { os<<setfill(_T('0')); DWORD lines = m_buffer.size()/16 + (m_buffer.size()%16!=0 ? 1 : 0); for( DWORD l=0;l<lines;l++ ) { DWORD c=0; os<<setw(4)<<l*16<<_T(":"); for( c=0;c<16;c++ ) { if( l*16+c<m_buffer.size() ) { const BYTE& b = m_buffer[l*16+c]; os<<_T(" ")<<setw(2)<<hex<<b; } // of if else os<<_T("___"); } // of for os<<_T("|"); for( c=0;c<16;c++ ) { if( l*16+c<m_buffer.size() ) { const BYTE& b = m_buffer[l*16+c]; if( b>=0x20 && b<=0x7a ) { TCHAR ch = (TCHAR)b; os<<ch; } // of if else os<<_T("."); } // of if else os<<_T("_"); } // of for os<<_T("|")<<endl; } // of for os.width(0); os.fill(_T(' ')); } // of if } catch(...) { bool flag = false; try { os.setstate(ios_base::failbit); } catch(...) { flag = true; } if( flag ) throw; } if( err ) os.setstate(err); return os; } template<class charT, class Traits> basic_ostream<charT, Traits>& operator <<(basic_ostream<charT, Traits >& os,const ByteBuffer& e) { return e.Dump(os); } } // of namespace bvr20983 template basic_ostream<TCHAR,char_traits<TCHAR>>& bvr20983::operator << <TCHAR,char_traits<TCHAR>>( basic_ostream<TCHAR,char_traits<TCHAR>>&,const ByteBuffer&); /*==========================END-OF-FILE===================================*/
[ "dwachmann@01137330-e44e-0410-aa50-acf51430b3d2" ]
[ [ [ 1, 213 ] ] ]
03f225307d5d413b4366d97a3ee792e36ea12e3e
bd89d3607e32d7ebb8898f5e2d3445d524010850
/adaptationlayer/tsy/simatktsy_dll/src/satdatadownload.cpp
67c16984158c3cebe06a9fa86fb2d9e4cc557a32
[]
no_license
wannaphong/symbian-incubation-projects.fcl-modemadaptation
9b9c61ba714ca8a786db01afda8f5a066420c0db
0e6894da14b3b096cffe0182cedecc9b6dac7b8d
refs/heads/master
2021-05-30T05:09:10.980036
2010-10-19T10:16:20
2010-10-19T10:16:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
27,793
cpp
/* * Copyright (c) 2007-2010 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of the License "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ // INCLUDE FILES #include "satdatadownload.h" // sat datadownload class #include "satmesshandler.h" // sat message handler class #include "satmessaging.h" // sat messaging class #include "ber_tlv.h" // sat ber-tlv classes #include "satutil.h" // sat utility class #include <pn_const.h> // server id constants #include <tisi.h> // isi message #include <smsisi.h> // sms server #include <etelmm.h> // etel multimode api #include <uiccisi.h> // UICC server #include "OstTraceDefinitions.h" #ifdef OST_TRACE_COMPILER_IN_USE #include "satdatadownloadTraces.h" #endif // CONSTANTS // Temporary TPDU data store buffer const TUint8 KTtpduMaxSize = 255; // Cell Broadcast isi msg length const TUint8 KCbsMsgMaxLength = 92; // Max address length const TUint8 KAddrMaxLength = 255; // ParamIndicator value const TUint8 KParamIndicators = 7; // ParamIndicator length const TUint8 KParamIndicatorsLength = 1; // Max Info Length const TUint8 KMaxInfoLength = 82; // SMS Delivery report buffer size const TUint8 KDeliveryReportSize = 248; // Length of sw1 and sw2 const TUint8 KSw1Sw2Length = 2; // ==================== MEMBER FUNCTIONS ==================================== // ----------------------------------------------------------------------------- // CSatDataDownload::CSatDataDownload // C++ default constructor can NOT contain any code, that // might leave. // ----------------------------------------------------------------------------- // CSatDataDownload::CSatDataDownload ( CSatMessHandler* aSatMessHandler, CTsySatMessaging* aSatMessaging ) : iSatMessHandler( aSatMessHandler ), iSatMessaging( aSatMessaging ), iSmsPpProtocolId( KZero ), iSmsPpDcs( KZero ), iSmsPpTransactionId( KZero ), iSmsPpDdOngoing( EFalse ), // No SMS PP DD on going during construction iSmsPpDdSupported( ETrue ) // Most likely SIM supports SMS PP DD { OstTrace0( TRACE_NORMAL, CSATDATADOWNLOAD_CSATDATADOWNLOAD_TD, "CSatDataDownload::CSatDataDownload" ); } // ----------------------------------------------------------------------------- // CSatDataDownload::ConstructL // Symbian 2nd phase constructor can leave. // ----------------------------------------------------------------------------- // void CSatDataDownload::ConstructL() { OstTrace0( TRACE_NORMAL, CSATDATADOWNLOAD_CONSTRUCTL_TD, "CSatDataDownload::ConstructL" ); } // ----------------------------------------------------------------------------- // CSatDataDownload::NewL // Two-phased constructor. // ----------------------------------------------------------------------------- // CSatDataDownload* CSatDataDownload::NewL ( CSatMessHandler* aSatMessHandler, CTsySatMessaging* aSatMessaging ) { OstTrace0( TRACE_NORMAL, CSATDATADOWNLOAD_NEWL_TD, "CSatDataDownload::NewL" ); TFLOGSTRING("TSY: CSatDataDownload::NewL"); CSatDataDownload* self = new ( ELeave ) CSatDataDownload( aSatMessHandler, aSatMessaging ); CleanupStack::PushL( self ); self->ConstructL(); CleanupStack::Pop( self ); return self; } // ----------------------------------------------------------------------------- // CSatDataDownload::~CSatDataDownload // C++ destructor // ----------------------------------------------------------------------------- // CSatDataDownload::~CSatDataDownload() { OstTrace0( TRACE_NORMAL, DUP1_CSATDATADOWNLOAD_CSATDATADOWNLOAD_TD, "CSatDataDownload::~CSatDataDownload" ); TFLOGSTRING("TSY: CSatDataDownload::~CSatDataDownload"); } // ----------------------------------------------------------------------------- // CSatDataDownload::UiccCatRespEnvelopeReceived // Breaks a ISI message data notification from Sim server // ----------------------------------------------------------------------------- // void CSatDataDownload::UiccCatRespEnvelopeReceived( const TIsiReceiveC& aIsiMessage ) { OstTrace0( TRACE_NORMAL, CSATDATADOWNLOAD_UICCCATRESPENVELOPERECEIVED_TD, "CSatDataDownload::UiccCatRespEnvelopeReceived" ); TFLOGSTRING("TSY:CSatDataDownload::UiccCatRespEnvelopeReceived"); TUint8 status( aIsiMessage.Get8bit( ISI_HEADER_SIZE + UICC_CAT_RESP_OFFSET_STATUS ) ); TUint8 sw1( 0 ); TUint8 sw2( 0 ); TPtrC8 apduData; if ( UICC_STATUS_OK == status ) { TUint uiccSbApduOffset( 0 ); if ( KErrNone == aIsiMessage.FindSubBlockOffsetById( ISI_HEADER_SIZE + SIZE_UICC_CAT_RESP, UICC_SB_APDU, EIsiSubBlockTypeId16Len16, uiccSbApduOffset ) ) { TUint16 apduLength( aIsiMessage.Get16bit( uiccSbApduOffset + UICC_SB_APDU_OFFSET_APDULENGTH ) ); apduData.Set( aIsiMessage.GetData( uiccSbApduOffset + UICC_SB_APDU_OFFSET_APDU, apduLength ) ); if( KSw1Sw2Length <= apduLength ) { // Status bytes are two last bytes in APDU sw1 = apduData[apduLength - 2]; sw2 = apduData[apduLength - 1]; } } else // Subblock is mandatory { TFLOGSTRING("TSY: CSatMessHandler::UiccCatRespEnvelopeReceived - Mandatory subblock UICC_SB_APDU not found"); OstTrace0( TRACE_NORMAL, DUP1_CSATDATADOWNLOAD_UICCCATRESPENVELOPERECEIVED_TD, "CSatDataDownload::UiccCatRespEnvelopeReceived- Mandatory subblock UICC_SB_APDU not found" ); } } TTpFailure result; // Create delivery report according to SW result if ( KError != TSatUtility::Sw1Sw2Check( sw1, sw2 ) ) { TFLOGSTRING("TSY: CSatDataDownload::UiccCatRespEnvelopeReceived, OK"); OstTrace0( TRACE_NORMAL, DUP2_CSATDATADOWNLOAD_UICCCATRESPENVELOPERECEIVED_TD, "CSatDataDownload::UiccCatRespEnvelopeReceived" ); result = ENone; } else if ( KAtkSwDataNtfSw1busy == sw1 ) { TFLOGSTRING("TSY:CSatDataDownload::UiccCatRespEnvelopeReceived, SIM Busy"); OstTrace0( TRACE_NORMAL, DUP3_CSATDATADOWNLOAD_UICCCATRESPENVELOPERECEIVED_TD, "CSatDataDownload::UiccCatRespEnvelopeReceived" ); result = ESatBusy; } else { TFLOGSTRING("TSY:CSatDataDownload::UiccCatRespEnvelopeReceived, Data Download Error"); OstTrace0( TRACE_NORMAL, DUP4_CSATDATADOWNLOAD_UICCCATRESPENVELOPERECEIVED_TD, "CSatDataDownload::UiccCatRespEnvelopeReceived" ); result = ESatDlError; } if( KSw1Sw2Length <= apduData.Length() ) { BuildSimMsgReport( result, apduData.Mid( 0, apduData.Length() - KSw1Sw2Length ) ); } else { BuildSimMsgReport( result, KNullDesC8 ); } } // ----------------------------------------------------------------------------- // CSatDataDownload::BuildSmsSimReport // Creates a SMS PP DD delivery report // ----------------------------------------------------------------------------- // void CSatDataDownload::BuildSimMsgReport ( const TTpFailure aTpFailure, const TDesC8& aUserData ) { OstTraceExt2( TRACE_NORMAL, CSATDATADOWNLOAD_BUILDSIMMSGREPORT_TD, "CSatDataDownload::BuildSimMsgReport TpFailure: %{TTpFailure}, UserDataLen: %d", aTpFailure, aUserData.Length() ); TFLOGSTRING3("TSY:CSatDataDownload::BuildSimMsgReport TpFailure: %x, UserDataLen: %d", aTpFailure, aUserData.Length() ); // Select Cause and CauseType according to routing result TUint8 causeType( ENone == aTpFailure ? SMS_CAUSE_TYPE_COMMON : SMS_CAUSE_TYPE_EXT ); TUint8 smsCause( ENone == aTpFailure ? SMS_OK : SMS_EXT_ERR_PROTOCOL_ERROR ); TUint16 dataLen( aUserData.Length() ); // SMS_RECEIVED_MSG_REPORT_REQ- first subblock is needed when: // 1) Delivery of SMS PP failed // second and third subblock is added when // 2) SIM provided data in AtkSwDataNtf // Create SMS_RECEIVED_MSG_REPORT_REQ message TBuf8<KDeliveryReportSize> msgBuffer; TIsiSend reportReq( msgBuffer ); // Report has following structure: // SMS_RECEIVED_MSG_REPORT_REQ (Minimum, OK case AND no SIM Data) // + SMS_SB_DELIVER_REPORT (optional Added when reception is not OK) // + SMS_SB_PARAM_INDICATOR (optional, Added when user data is not empty ) // + SMS_SB_USER_DATA (optional, Response user data is put here) // SMS_RECEIVED_MSG_REPORT_REQ header msgBuffer.Append( causeType ); msgBuffer.Append( smsCause ); msgBuffer.AppendFill( KPadding, 3 ); msgBuffer.Append( 0 ); // no of sublocks // Add SMS_SB_DELIVER_REPORT subblock if any failure is there if( ENone != aTpFailure || 0 < dataLen ) { TFLOGSTRING("TSY:CSatDataDownload::BuildSimMsgReport \ Adding SMS_SB_DELIVER_REPORT" ); OstTrace0( TRACE_NORMAL, DUP1_CSATDATADOWNLOAD_BUILDSIMMSGREPORT_TD, "CSatDataDownload::BuildSimMsgReport Adding SMS_SB_DELIVER_REPORT" ); TIsiSubBlock deliverReport( msgBuffer, SMS_SB_DELIVER_REPORT,EIsiSubBlockTypeId16Len16 ); // set message parameters zero as in S40 ATK server also // First octet of SMS-Deliver-Report TPDU. Contains TP-UDHI and TP-MTI // elements. See 3GPP TS 23.040 chapter 9.2.2.1a (i) and (ii) // SMS-DELIVER-REPORT for RP-ACK and RP-ERROR. msgBuffer.Append( 0x00 ); // SMS_MTI_DELIVER_REPORT msgBuffer.Append( aTpFailure ); // GSM-TP Failure cause // Increment number of subblock msgBuffer[5]++; deliverReport.CompleteSubBlock(); } // Add SMS_SB_PRSM_INDICATOR and SMS_SB_USER_DATA subblock if ( dataLen ) { TFLOGSTRING("TSY:CSatDataDownload::BuildSimMsgReport \ Adding SMS_SB_PARAM_INDICATOR & SMS_SB_USER_DATA" ); OstTrace0( TRACE_NORMAL, DUP2_CSATDATADOWNLOAD_BUILDSIMMSGREPORT_TD, "CSatDataDownload::BuildSimMsgReport Adding SMS_SB_PARAM_INDICATOR AND SMS_SB_USER_DATA" ); // Add two more Sublock: // SMS_SB_PARAM_INDICATOR ///////////////////////// TIsiSubBlock paramInd( msgBuffer, SMS_SB_PARAM_INDICATOR, EIsiSubBlockTypeId16Len16 ); msgBuffer.Append( iSmsPpProtocolId ); msgBuffer.Append( iSmsPpDcs ); msgBuffer.Append( KParamIndicatorsLength ); // = 1 msgBuffer.Append( KParamIndicators ); // All selected (=7) // Increment number of subblock msgBuffer[5]++; paramInd.CompleteSubBlock(); // SMS_SB_USER_DATA (subblock for TPDU data) ////////////////// TIsiSubBlock userData( msgBuffer, SMS_SB_USER_DATA, EIsiSubBlockTypeId16Len16 ); TUint16 maxDataLen( SMS_DELIVER_ACK_UD_MAX_LEN ); if( ENone != aTpFailure ) { maxDataLen = SMS_DELIVER_ERR_UD_MAX_LEN; } dataLen = Min( dataLen, maxDataLen ); // data length // to append MSB byte msgBuffer.Append( dataLen >> 8 ); msgBuffer.Append( dataLen ); // Append for character count on basis of DCS used TUint16 dataLengthInOctets = 0; TUint8 aDefaultAlphabet = ( iSmsPpDcs && 0x0C) ; if( !aDefaultAlphabet ) { dataLengthInOctets = ( ( dataLen + 1 ) * 7 ) / 8 ; } else { dataLengthInOctets = dataLen; } // To append MSB byte msgBuffer.Append( dataLengthInOctets >> 8 ); msgBuffer.Append( dataLengthInOctets ); // Append whole msg or max data len bytes msgBuffer.Append( aUserData.Left( dataLen ) ); // Increment number of subblock msgBuffer[5]++; userData.CompleteSubBlock(); } iSatMessHandler->SendSmsReportReq( iSatMessaging->GetTransactionId(), msgBuffer ); } // ----------------------------------------------------------------------------- // CSatDataDownload::CellBroadcastReceived // Breaks a cell broadcast isi message coming from network. // Calls SendEnvelopeForCellBroadcast in order to send the envelope to // SIM server // ----------------------------------------------------------------------------- // void CSatDataDownload::CellBroadcastReceived ( const TIsiReceiveC& aIsiMessage // SMS_GSM(_TEMP)_CB_ROUTING_NTF ) { OstTrace0( TRACE_NORMAL, CSATDATADOWNLOAD_CELLBROADCASTRECEIVED_TD, "CSatDataDownload::CellBroadcastReceived" ); TFLOGSTRING( "TSY:CSatDataDownload::CellBroadcastReceived" ); TBuf8<KCbsMsgMaxLength> cbsMsg; // For each subblock i // Check whether the CB message id of this subblock is allowed: // if allowed, // - Retrieve the infoLenght byte B // - if B==0xFF, then this is a GSM CB DDL message // - otherwise this is a WCDMA CD DDL message (0<B<83) // and the content of message must be truncated to B bytes, // the unused bytes (B+1 to 82) must be filled with zeros. // - send envelope containing Page data // End TInt sbNumber( aIsiMessage.Get8bit( ISI_HEADER_SIZE + SMS_CB_SIM_ROUTING_IND_OFFSET_SUBBLOCKCOUNT ) ); TUint startsbOffset( 0 ); if ( KErrNone == aIsiMessage.FindSubBlockOffsetById( ISI_HEADER_SIZE + SIZE_SMS_CB_SIM_ROUTING_IND , SMS_SB_CB_MESSAGE, EIsiSubBlockTypeId16Len16, startsbOffset ) ) { TUint sbOffset( 0 ); for ( TInt sb( 1 ); sb < sbNumber; sb++ ) { // fill cbsMsg block with 0 cbsMsg.Zero(); if ( KErrNone == aIsiMessage.FindSubBlockOffsetByIndex( startsbOffset , sb, EIsiSubBlockTypeId16Len16, sbOffset ) ) { //Append Serial number cbsMsg.Append( ( aIsiMessage.Get16bit( sbOffset + SMS_SB_CB_MESSAGE_OFFSET_SERIALNUMBER )>> 8) ); cbsMsg.Append( aIsiMessage.Get16bit( sbOffset + SMS_SB_CB_MESSAGE_OFFSET_SERIALNUMBER ) ); // Append CB Message id cbsMsg.Append( aIsiMessage.Get16bit( sbOffset + SMS_SB_CB_MESSAGE_OFFSET_CBMESSAGEID )>> 8 ); cbsMsg.Append( aIsiMessage.Get16bit( sbOffset + SMS_SB_CB_MESSAGE_OFFSET_CBMESSAGEID ) ); // Append Data Coding scheme cbsMsg.Append( aIsiMessage.Get8bit( sbOffset + SMS_SB_CB_MESSAGE_OFFSET_DATACODINGSCHEME ) ); // Append Page cbsMsg.Append( aIsiMessage.Get8bit( sbOffset + SMS_SB_CB_MESSAGE_OFFSET_PAGE ) ); // Append data length TUint8 infoLength( aIsiMessage.Get8bit( sbOffset + SMS_SB_CB_MESSAGE_OFFSET_INFOLENGTH ) ); if ( KMaxInfoLength < infoLength ) { // CB message max length is 82. Info length may contain // value 0xFF, which means that length should be ignored. // Inthis case maximum is used. infoLength = SMS_CB_MESSAGE_CONTENT_SIZE; // 82 } // Append the message content and fill with zeroes if necessary cbsMsg.AppendJustify( aIsiMessage.GetData( sbOffset + SMS_SB_CB_MESSAGE_OFFSET_CONTENTOFMESSAGE, infoLength ), SMS_CB_MESSAGE_CONTENT_SIZE, ELeft, KPadding ); SendCellBroadcastDdlEnvelope( iSatMessaging->GetTransactionId(), cbsMsg ); } } } } // ----------------------------------------------------------------------------- // CSatDataDownload::SmsSimMsgIndReceivedL // Breaks a sms point to point isi message // Sends envelope // ----------------------------------------------------------------------------- // void CSatDataDownload::SmsSimMsgIndReceivedL ( const TIsiReceiveC& aIsiMessage ) { OstTrace0( TRACE_NORMAL, CSATDATADOWNLOAD_SMSSIMMSGINDRECEIVEDL_TD, "CSatDataDownload::SmsSimMsgIndReceivedL" ); TFLOGSTRING( "TSY:CSatDataDownload::SmsSimMsgIndReceivedL" ); TBuf8<KAddrMaxLength> bcdSmscAddress; // to store Service centre number TBuf8<KTtpduMaxSize> smsTpdu; // Temporary buffer to store TPDU data TUint sbDeliver( 0 ); // Check for correct subblock SMS_SB_ADDRESS if( KErrNone == aIsiMessage.FindSubBlockOffsetById( ISI_HEADER_SIZE + SIZE_SMS_RECEIVED_SIM_MSG_IND, SMS_SB_ADDRESS, EIsiSubBlockTypeId16Len16, sbDeliver ) ) { TUint8 addressLen( aIsiMessage.Get8bit( sbDeliver + SMS_SB_ADDRESS_OFFSET_ADDRESSDATALENGTH ) ); // Service centre Address append in bcdSmscAddress buffer // If address type is SMS_SMSC_ADDRESS, addtional length is // included in addres data. Let's omit that. TUint8 addressType( aIsiMessage.Get8bit( sbDeliver + SMS_SB_ADDRESS_OFFSET_ADDRESSTYPE ) ); if ( SMS_SMSC_ADDRESS == addressType ) { bcdSmscAddress.Append( aIsiMessage.GetData( sbDeliver + SMS_SB_ADDRESS_OFFSET_ADDRESSDATA + 1, addressLen - 1 ) ); } } // Check for correct Subblock SMS_SB_TPDU if ( KErrNone == aIsiMessage.FindSubBlockOffsetById( ISI_HEADER_SIZE + SIZE_SMS_RECEIVED_SIM_MSG_IND, SMS_SB_TPDU, EIsiSubBlockTypeId16Len16, sbDeliver ) ) { // Read user data length TUint8 userDataLen( aIsiMessage.Get8bit( sbDeliver + SMS_SB_TPDU_OFFSET_DATALENGTH ) ); // SMS_SB_TPDU subblock, // which contain the message payload data. smsTpdu.Append( aIsiMessage.GetData( sbDeliver + SMS_SB_TPDU_OFFSET_DATABYTES, userDataLen )); // Destination Address Length // 1st Byte of destination address contains no os semioctets //in address bytes // +1 to calculate correct nos of bytes in address // divide by 2 to convert semioctets to no of octets // +2 to add type of address byte and no of TUint8 tpduIndexCalc( ( ( smsTpdu[1] + 1 )/2 ) + 2 ); // Storing protocol id and datacoding scheme from TPDU data buffer iSmsPpProtocolId = smsTpdu[ tpduIndexCalc + 1 ]; iSmsPpDcs = smsTpdu[ tpduIndexCalc + 2 ]; } // Either Envelope sending or SMS storing is going on iSmsPpDdOngoing = ETrue; if( iSmsPpDdSupported ) // Check for SMS PP-DATA Download supported { TFLOGSTRING( "TSY:CSatDataDownload::SmsSimMsgIndReceivedL SMS SIM Supported, sending Envelope..." ); OstTrace0( TRACE_NORMAL, DUP1_CSATDATADOWNLOAD_SMSSIMMSGINDRECEIVEDL_TD, "CSatDataDownload::SmsSimMsgIndReceivedL SMS Sim Supported, sending Envelope..." ); iSmsPpTransactionId = iSatMessaging->GetTransactionId(); // Data Download supported, send envelope SendSmsPpDdlEnvelope( iSmsPpTransactionId, bcdSmscAddress, smsTpdu ); } else { TFLOGSTRING( "TSY:CSatDataDownload::SmsSimMsgIndReceivedL SMS SIM not supported, storing SMS..." ); OstTrace0( TRACE_NORMAL, DUP2_CSATDATADOWNLOAD_SMSSIMMSGINDRECEIVEDL_TD, "CSatDataDownload::SmsSimMsgIndReceivedL SMS SIM not supported, storing SMS..." ); // Save the SMS instead. RMobileSmsStore::TMobileGsmSmsEntryV1 smsEntry; // if SMSC present if ( bcdSmscAddress.Length() ) { // TON & NPI, stored in first index TSatUtility::GetTonAndNpi( bcdSmscAddress[0], smsEntry.iServiceCentre.iTypeOfNumber, smsEntry.iServiceCentre.iNumberPlan ); // SMSC Address, exclude TON/NPI TBuf8<KAddrMaxLength> scAscii; TSatUtility::BCDToAscii( bcdSmscAddress.Mid( 1 ), scAscii ); smsEntry.iServiceCentre.iTelNumber.Copy( scAscii ); } // TPDU data smsEntry.iMsgData.Copy( smsTpdu ); // Store SMS if ( KErrNone != iSatMessaging->StoreSmsL( smsEntry ) ) { // Clear the flag iSmsPpDdOngoing = EFalse; BuildSimMsgReport( ESatDlError, KNullDesC8 ); } } } // ----------------------------------------------------------------------------- // CSatDataDownload::SendCellBroadcastDdlEnvelope // Prepare the envelope to be sent to SIM server after a Cell Broadcast message // has been received, without request, by the mobile equipment. // ----------------------------------------------------------------------------- // void CSatDataDownload::SendCellBroadcastDdlEnvelope ( TUint8 aTransId, TDesC8& aPdu ) { OstTrace0( TRACE_NORMAL, CSATDATADOWNLOAD_SENDCELLBROADCASTDDLENVELOPE_TD, "CSatDataDownload::SendCellBroadcastDdlEnvelope" ); TFLOGSTRING( "TSY:CSatDataDownload::SendEnvelopeForCellBroadcast" ); TTlv envelope; //Tag envelope.Begin( KBerTlvCellBroadcastTag ); //device identities envelope.AddTag( KTlvDeviceIdentityTag ); envelope.AddByte( KNetwork ); envelope.AddByte( KSim ); // cell broadcast page envelope.AddTag( KTlvCellBroadcastPageTag ); envelope.AddData( aPdu ); iSatMessHandler->UiccCatReqEnvelope( aTransId, envelope.End() ); } // ----------------------------------------------------------------------------- // CSatDataDownload::SendSmsPpDdlEnvelope // Prepare the envelope to be sent to SIM server after a SMS-PP message has // has been received, without request, by the mobile equipment. // ----------------------------------------------------------------------------- // void CSatDataDownload::SendSmsPpDdlEnvelope ( TUint8 aTransId, TDesC8& aSmsScAddress, TDesC8& aPdu ) { OstTrace0( TRACE_NORMAL, CSATDATADOWNLOAD_SENDSMSPPDDLENVELOPE_TD, "CSatDataDownload::SendSmsPpDdlEnvelope" ); TFLOGSTRING( "TSY:CSatDataDownload::SendEnvelopeForSmsPpDownload" ); TTlv envelope; envelope.Begin( KBerTlvSmsPpDownloadTag ); //device identities envelope.AddTag( KTlvDeviceIdentityTag ); envelope.AddByte( KNetwork ); envelope.AddByte( KSim ); envelope.AddTag( KTlvAddressTag ); envelope.AddData( aSmsScAddress ); envelope.AddTag( KTlvSmsTpduTag ); envelope.AddData( aPdu ); iSatMessHandler->UiccCatReqEnvelope( aTransId, envelope.End() ); } // ----------------------------------------------------------------------------- // CSatDataDownload::SmsPpDlSupported // Setter for SMP PP DD support status // ----------------------------------------------------------------------------- // void CSatDataDownload::SmsPpDlSupported ( TBool aStatus ) { OstTrace1( TRACE_NORMAL, CSATDATADOWNLOAD_SMSPPDLSUPPORTED_TD, "CSatDataDownload::SmsPpDlSupported: %d", aStatus ); TFLOGSTRING2( "TSY: CSatDataDownload::SmsPpDlSupported: %d", aStatus ); iSmsPpDdSupported = aStatus; } // ----------------------------------------------------------------------------- // CSatDataDownload::MessageReceivedL // Handle received messages related to event download // Called by CSatMessHandler::MessageReceivedL, when a new ISI message arrives. // ----------------------------------------------------------------------------- // void CSatDataDownload::MessageReceivedL ( const TIsiReceiveC& aIsiMessage ) { OstTrace0( TRACE_NORMAL, CSATDATADOWNLOAD_MESSAGERECEIVEDL_TD, "CSatDataDownload::MessageReceivedL" ); TFLOGSTRING( "TSY:CSatDataDownload::MessageReceivedL" ); TInt resource( aIsiMessage.Get8bit( ISI_HEADER_OFFSET_RESOURCEID ) ); TInt messageId( aIsiMessage.Get8bit( ISI_HEADER_OFFSET_MESSAGEID ) ); // handle SIM Data Download related isi messages if ( PN_SMS == resource ) { switch ( messageId ) { case SMS_CB_SIM_ROUTING_IND: { // A Cell Broadcast message was sent by the // network, without having been requested by the phone. // Process received message CellBroadcastReceived( aIsiMessage ); break; } case SMS_RECEIVED_SIM_MSG_IND: { // Receive SMS PP Data Download Indication , Send by SMS Server // on reception of message on network SmsSimMsgIndReceivedL(aIsiMessage); break; } default: { // none break; } } } else if ( PN_UICC == resource ) { switch( messageId ) { case UICC_CAT_RESP: { // In case of envelope response handle the data TUint8 serviceType( aIsiMessage.Get8bit( ISI_HEADER_SIZE + UICC_CAT_RESP_OFFSET_SERVICETYPE ) ); if ( UICC_CAT_ENVELOPE == serviceType ) { if ( iSmsPpDdOngoing && iSmsPpTransactionId == aIsiMessage.Get8bit( ISI_HEADER_OFFSET_TRANSID ) ) { // Set flag iSmsPpDdOngoing false // since a response is received for the envelope // that was sent for a received sms-pp message iSmsPpDdOngoing = EFalse; // Process received message UiccCatRespEnvelopeReceived( aIsiMessage ); } } break; } default: { // none break; } } } else { // None } } // End of File
[ "dalarub@localhost", "mikaruus@localhost", "[email protected]" ]
[ [ [ 1, 1 ], [ 3, 31 ], [ 33, 33 ], [ 35, 52 ], [ 55, 78 ], [ 80, 89 ], [ 91, 103 ], [ 105, 124 ], [ 126, 138 ], [ 140, 162 ], [ 169, 172 ], [ 174, 176 ], [ 179, 182 ], [ 185, 188 ], [ 191, 194 ], [ 206, 222 ], [ 224, 229 ], [ 231, 255 ], [ 258, 260 ], [ 262, 282 ], [ 284, 305 ], [ 313, 332 ], [ 335, 357 ], [ 359, 441 ], [ 443, 447 ], [ 449, 452 ], [ 455, 496 ], [ 498, 502 ], [ 504, 514 ], [ 517, 526 ], [ 529, 571 ], [ 573, 601 ], [ 603, 630 ], [ 632, 648 ], [ 650, 671 ], [ 673, 722 ] ], [ [ 2, 2 ], [ 53, 54 ], [ 79, 79 ], [ 90, 90 ], [ 104, 104 ], [ 125, 125 ], [ 139, 139 ], [ 163, 168 ], [ 173, 173 ], [ 177, 178 ], [ 183, 184 ], [ 189, 190 ], [ 195, 205 ], [ 223, 223 ], [ 256, 256 ], [ 261, 261 ], [ 283, 283 ], [ 358, 358 ], [ 442, 442 ], [ 448, 448 ], [ 453, 454 ], [ 497, 497 ], [ 503, 503 ], [ 515, 516 ], [ 527, 528 ], [ 572, 572 ], [ 602, 602 ], [ 631, 631 ], [ 649, 649 ], [ 672, 672 ] ], [ [ 32, 32 ], [ 34, 34 ], [ 230, 230 ], [ 257, 257 ], [ 306, 312 ], [ 333, 334 ] ] ]
332ee1ce792074cc019345c0734700409db5158a
4f913cc1a50e8e649fd40313631a161234e3c59d
/CAuLoopedDecoder.h
ab7083182ddfa18b78598fc747b47d52d8b45bdd
[]
no_license
autch/kpiadx.kpi
abb1f084163478796e202196a7411a049a76116c
f482c3871d948e71a3b3839e9066f845ecdb5915
refs/heads/master
2021-12-16T01:22:32.824315
2010-12-15T06:34:48
2010-12-15T06:34:48
1,170,398
1
0
null
null
null
null
SHIFT_JIS
C++
false
false
3,348
h
#pragma once #include "stdafx.h" // PCM レベルでループを実現する template<class CSrcDecoder> class CAuLoopedDecoder { private: // 本当に使いたいデコーダ CSrcDecoder m_Decoder; SOUNDINFO m_Info; DWORD m_dwLoopStart; DWORD m_dwLoopEnd; DWORD m_dwSamplesRendered; // ファイル先頭からの通算サンプル数 DWORD m_dwBufferLeft; // m_pbyBuffer に実際に入っている PCM のバイト数 DWORD m_dwBufferCapacity; // m_pbyBuffer のサイズ PBYTE m_pbyBuffer; // ブロックサイズ以下の中途半端なサイズで転送するためのバッファ void Reset() { m_dwBufferLeft = 0; m_dwSamplesRendered = 0; } public: CAuLoopedDecoder() { m_pbyBuffer = NULL; } ~CAuLoopedDecoder() { Close(); } VOID Close() { m_Decoder.Close(); delete[] m_pbyBuffer; m_pbyBuffer = NULL; } BOOL Open(LPSTR szFileName, SOUNDINFO* pInfo) { BOOL r = m_Decoder.Open(szFileName, pInfo); if(r) { m_Info = *pInfo; m_dwLoopStart = m_Decoder.GetLoopStart(); m_dwLoopEnd = m_Decoder.GetLoopEnd(); m_dwBufferCapacity = m_Info.dwUnitRender * 2; m_pbyBuffer = new BYTE[m_dwBufferCapacity]; Reset(); } return r; } DWORD SetPosition(DWORD dwPos) { Reset(); DWORD r = m_Decoder.SetPosition(dwPos); m_dwSamplesRendered = m_Decoder.GetCurrentSamplesRendered(); return r; } DWORD BytesToSamples(DWORD dwBytes) { return dwBytes / (m_Info.dwBitsPerSample >> 3) / m_Info.dwChannels; } DWORD SamplesToBytes(DWORD dwSamples) { return dwSamples * (m_Info.dwBitsPerSample >> 3) * m_Info.dwChannels; } VOID SeekToLoopStart() { m_Decoder.SeekToLoopStartBlock(); } DWORD Render(BYTE* pBuffer, DWORD dwSize) { if(m_Info.dwLoopFlag) { DWORD dwBytesToRender = dwSize; while(dwBytesToRender > 0) { if(m_dwBufferLeft > 0) { // バッファから吐き出し専門 DWORD dwBytesToCopy = m_dwBufferLeft > dwBytesToRender ? dwBytesToRender : m_dwBufferLeft; CopyMemory(pBuffer, m_pbyBuffer, dwBytesToCopy); MoveMemory(m_pbyBuffer, m_pbyBuffer + dwBytesToCopy, m_dwBufferCapacity - dwBytesToCopy); pBuffer += dwBytesToCopy; m_dwBufferLeft -= dwBytesToCopy; dwBytesToRender -= dwBytesToCopy; } if(dwBytesToRender > 0) { // バッファへ書き込み専門 DWORD dwBytesRendered = m_Decoder.Render(m_pbyBuffer + m_dwBufferLeft, dwSize); if(m_dwSamplesRendered + BytesToSamples(dwBytesRendered) >= m_dwLoopEnd) { DWORD dwBytesToSave = SamplesToBytes(m_dwLoopEnd - m_dwSamplesRendered); SeekToLoopStart(); m_dwSamplesRendered = m_dwLoopStart; m_dwBufferLeft += dwBytesToSave; } else { m_dwSamplesRendered += BytesToSamples(dwBytesRendered); m_dwBufferLeft += dwBytesRendered; } } } return dwSize; } else return m_Decoder.Render(pBuffer, dwSize); } VOID SetConfigPath(LPSTR szPath) { m_Decoder.SetConfigPath(szPath); } };
[ "autch@f88602a7-bc0e-0410-bfba-c07ee007e53c" ]
[ [ [ 1, 116 ] ] ]
a3332f38017801a583b55c096eacd9ef939fd2fa
0b66a94448cb545504692eafa3a32f435cdf92fa
/tags/0.8/cbear.berlios.de/meta/identity.hpp
88828693f1789ad5ca8743d7171d913cacc66240
[ "MIT" ]
permissive
BackupTheBerlios/cbear-svn
e6629dfa5175776fbc41510e2f46ff4ff4280f08
0109296039b505d71dc215a0b256f73b1a60b3af
refs/heads/master
2021-03-12T22:51:43.491728
2007-09-28T01:13:48
2007-09-28T01:13:48
40,608,034
0
0
null
null
null
null
UTF-8
C++
false
false
247
hpp
#ifndef CBEAR_BERLIOS_DE_META_IDENTITY_HPP_INCLUDED #define CBEAR_BERLIOS_DE_META_IDENTITY_HPP_INCLUDED namespace cbear_berlios_de { namespace meta { template<class T> class identity { public: typedef T type; }; } } #endif
[ "sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838" ]
[ [ [ 1, 19 ] ] ]
9dca6308f5efe201dbc4fd6e0021dc8941cb6e88
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/3rdParty/boost/libs/serialization/test/test_xml_load.cpp
195407c80502eb7fd2950e079636db57a1bd66d7
[]
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
471
cpp
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // test_demo_xml_load.cpp // (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) #include <boost/test/test_tools.hpp> #define main test_main #include "../example/demo_xml_load.cpp"
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 13 ] ] ]
95de164c3bd57416d4f6384d6f66884e8574d68d
a352572bc22d863f72020118d8f5b94c69521f3f
/cs4620/src/Frustum.h
870b9c487aa1df83d8b2819cf598d68fb0d8a87c
[]
no_license
mjs513/cs4620-1
63345a9a7774279d8d6ab63b1af64d65b14b0ae3
419da5df73c5a9c34387b3cd2f7f3c542e0a3c3e
refs/heads/master
2021-01-10T06:45:47.809907
2010-12-10T20:59:46
2010-12-10T20:59:46
46,994,144
0
0
null
null
null
null
UTF-8
C++
false
false
439
h
/* * Frustum.h * * Created on: Sep 25, 2010 * Author: Roberto */ #ifndef FRUSTUM_H_ #define FRUSTUM_H_ #include "Plane.h" #include "BoundingSphere.h" #include <vector> class Frustum { public: Frustum(); float pctVisible() const; bool includes(const BoundingSphere &sphere) const; private: double _frustum[6][4]; mutable int _totalTests,_passedTests; }; #endif /* FRUSTUM_H_ */
[ "robertorfischer@ebbd4279-5267-bd07-7df5-4dafc36418f6" ]
[ [ [ 1, 33 ] ] ]
6b5604f5a8a5b3fbc506467d83e7ecf1edfafa4c
4a266d6931aa06a2343154cab99d8d5cfdac6684
/csci3081/project-phase2/ModelTest.h
6d69e6385f6a5ef0bf78ecae73c87965a4f195c6
[]
no_license
Magneticmagnum/robotikdude-school
f0185feb6839ad5c5324756fc86f984fce7abdc1
cb39138b500c8bbc533e796225588439dcfa6555
refs/heads/master
2021-01-10T19:01:39.479621
2011-05-17T04:44:47
2011-05-17T04:44:47
35,382,573
0
0
null
null
null
null
UTF-8
C++
false
false
2,429
h
#ifndef MODELTEST_H_ #define MODELTEST_H_ #include "Model.h" #include <cxxtest/TestSuite.h> class ModelTest: public CxxTest::TestSuite { public: void test_getInstance() { log4cxx::LoggerPtr log(log4cxx::Logger::getLogger("ModelTest")); LOG4CXX_DEBUG(log, "--> Entering ModelTest::test_getInstance()"); Model* model1 = Model::getInstance(MODEL_DISHWASHER); // TS_ASSERT(model1); Model* model2 = Model::getInstance(MODEL_DISHWASHER); // TS_ASSERT(model2); // TS_ASSERT_EQUALS(model1, model2); model1 = Model::getInstance(MODEL_MICROWAVE); // TS_ASSERT(model1); model2 = Model::getInstance(MODEL_MICROWAVE); // TS_ASSERT(model2); // TS_ASSERT_EQUALS(model1, model2); model1 = Model::getInstance(MODEL_OVEN); TS_ASSERT(model1); model2 = Model::getInstance(MODEL_OVEN); TS_ASSERT(model2); TS_ASSERT_EQUALS(model1, model2); model1 = Model::getInstance(MODEL_PERSON); // TS_ASSERT(model1); model2 = Model::getInstance(MODEL_PERSON); // TS_ASSERT(model2); // TS_ASSERT_EQUALS(model1, model2); model1 = Model::getInstance(MODEL_REFRIGERATOR); TS_ASSERT(model1); model2 = Model::getInstance(MODEL_REFRIGERATOR); TS_ASSERT(model2); TS_ASSERT_EQUALS(model1, model2); model1 = Model::getInstance(MODEL_STOVE); TS_ASSERT(model1); model2 = Model::getInstance(MODEL_STOVE); TS_ASSERT(model2); TS_ASSERT_EQUALS(model1, model2); model1 = Model::getInstance(MODEL_TELEVISION); TS_ASSERT(model1); model2 = Model::getInstance(MODEL_TELEVISION); TS_ASSERT(model2); TS_ASSERT_EQUALS(model1, model2); model1 = Model::getInstance(MODEL_TOASTER); TS_ASSERT(model1); model2 = Model::getInstance(MODEL_TOASTER); TS_ASSERT(model2); TS_ASSERT_EQUALS(model1, model2); model1 = Model::getInstance(MODEL_WATERHEATER); TS_ASSERT(model1); model2 = Model::getInstance(MODEL_WATERHEATER); TS_ASSERT(model2); TS_ASSERT_EQUALS(model1, model2); model1 = Model::getInstance("blah"); TS_ASSERT(!model1); LOG4CXX_DEBUG(log, "<-- Exiting ModelTest::test_getInstance()"); } }; #endif /* MODELTEST_H_ */
[ "robotikdude@e80761d0-8fc2-79d0-c9d0-3546e327c268" ]
[ [ [ 1, 78 ] ] ]
cd77fdc6284df082a438c3dd18406f601c60cf6f
58ef4939342d5253f6fcb372c56513055d589eb8
/ThemeChanger/ThemeChange/inc/OKCModel.h
610852c8e672670f80397d5567ad4404824c4837
[]
no_license
flaithbheartaigh/lemonplayer
2d77869e4cf787acb0aef51341dc784b3cf626ba
ea22bc8679d4431460f714cd3476a32927c7080e
refs/heads/master
2021-01-10T11:29:49.953139
2011-04-25T03:15:18
2011-04-25T03:15:18
50,263,327
0
0
null
null
null
null
UTF-8
C++
false
false
980
h
/* ============================================================================ Name : OKCModel.h Author : zengcity Version : 1.0 Copyright : Your copyright notice Description : COKCModel declaration ============================================================================ */ #ifndef OKCMODEL_H #define OKCMODEL_H // INCLUDES #include <e32std.h> #include <e32base.h> #include <badesca.h> // CLASS DECLARATION /** * COKCModel * */ class COKCModel : public CBase { public: // Constructors and destructor /** * Destructor. */ ~COKCModel(); /** * Two-phased constructor. */ static COKCModel* NewL(); /** * Two-phased constructor. */ static COKCModel* NewLC(); private: /** * Constructor for performing 1st stage construction */ COKCModel(); /** * EPOC default constructor for performing 2nd stage construction */ void ConstructL(); }; #endif // OKCMODEL_H
[ "zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494" ]
[ [ [ 1, 59 ] ] ]
5fb843085a1b2cda98e6923cbdde8050ce143c8b
879b481e3d2af7de070d8da986cfea2507adfb6f
/Source/MainComponent.h
03bd269873b69afd17f21696fbec21275fd4a24a
[]
no_license
grimtraveller/Granular-Audio-Destroyer
f1b4861417d5a7d44957bdcc2e9e608228dda881
2d9fb44f89f5914befb0a9e663248e5432598d29
refs/heads/master
2021-01-21T01:33:57.446402
2010-12-09T05:29:16
2010-12-09T05:29:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,985
h
/* ============================================================================== This is an automatically generated file created by the Jucer! Creation date: 1 Dec 2010 11:30:39pm Be careful when adding custom code to these files, as only the code within the "//[xyz]" and "//[/xyz]" sections will be retained when the file is loaded and re-saved. Jucer version: 1.12 ------------------------------------------------------------------------------ The Jucer is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-6 by Raw Material Software ltd. ============================================================================== */ #ifndef __JUCER_HEADER_MAINCOMPONENT_MAINCOMPONENT_9FE0D261__ #define __JUCER_HEADER_MAINCOMPONENT_MAINCOMPONENT_9FE0D261__ //[Headers] -- You can add your own extra header files here -- #include "../JuceLibraryCode/JuceHeader.h" #include "GranularSlice.h" //[/Headers] #define NUM_GRAINS 8 //============================================================================== /** //[Comments] An auto-generated component, created by the Jucer. Describe your class and how it works here! //[/Comments] */ class MainComponent : public Component, public ButtonListener, public AudioIODeviceCallback { public: //============================================================================== MainComponent (); ~MainComponent(); //============================================================================== //[UserMethods] -- You can add your own custom methods in this section. void playAudioFile(File &audioFile); void memStoreAudioFile(File &audioFile); void saveAudioFile(File &saveFile); void playPressed(); void resetAudioRenderer(); void setupGranularSlices(); bool renderAudioToBuffer(float** outputChannelData, int numOutputChannels, int numSamples); //[/UserMethods] void paint (Graphics& g); void resized(); void buttonClicked (Button* buttonThatWasClicked); void audioDeviceAboutToStart (AudioIODevice* device); void audioDeviceStopped(); void audioDeviceIOCallback (const float** inputChannelData, int numInputChannels, float** outputChannelData, int numOutputChannels, int numSamples); //============================================================================== juce_UseDebuggingNewOperator private: //[UserVariables] -- You can add your own custom variables in this section. AudioDeviceManager mDeviceManager; AudioSourcePlayer mAudioSourcePlayer; AudioTransportSource mTransportSource; AudioFormatReaderSource* mCurrentAudioFileSource; File mCurrentFile; float samples [1024]; float *mInterleavedBuffer; float *mLeftBuffer; float *mRightBuffer; int nextSample, subSample; int64 mBufferLength; float accumulator; int mNumChannels; int64 mGrainStartPositionAbsolute; int64 mGrainLength; int64 mGrainCurrentPositionRelativeLeft; int64 mGrainCurrentPositionRelativeRight; int64 mSampleCounter; float mVelocityFactor; int64 mGrainAdvanceAmount; bool mPlaying; GranularSlice *mGranularSlices[NUM_GRAINS]; //[/UserVariables] //============================================================================== TextButton* mOpenFileButton; TextButton* mSaveFileButton; TextButton* mPlayButton; //============================================================================== // (prevent copy constructor and operator= being generated..) MainComponent (const MainComponent&); const MainComponent& operator= (const MainComponent&); }; #endif // __JUCER_HEADER_MAINCOMPONENT_MAINCOMPONENT_9FE0D261__
[ [ [ 1, 122 ] ] ]
adff35a9fe64d24c24493247744411f3e78b6a5c
021e8c48a44a56571c07dd9830d8bf86d68507cb
/build/vtk/vtkMesaRenderer.h
6c9fc36bd3af2c34680c4ba20ae69f282baf24e7
[ "BSD-3-Clause" ]
permissive
Electrofire/QdevelopVset
c67ae1b30b0115d5c2045e3ca82199394081b733
f88344d0d89beeec46f5dc72c20c0fdd9ef4c0b5
refs/heads/master
2021-01-18T10:44:01.451029
2011-05-01T23:52:15
2011-05-01T23:52:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,584
h
/*========================================================================= Program: Visualization Toolkit Module: vtkMesaRenderer.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkMesaRenderer - OpenGL renderer // .SECTION Description // vtkMesaRenderer is a concrete implementation of the abstract class // vtkRenderer. vtkMesaRenderer interfaces to the mesa graphics library. // This file is created, by a copy of vtkOpenGLRenderer #ifndef __vtkMesaRenderer_h #define __vtkMesaRenderer_h #include "vtkRenderer.h" class VTK_RENDERING_EXPORT vtkMesaRenderer : public vtkRenderer { protected: int NumberOfLightsBound; public: static vtkMesaRenderer *New(); vtkTypeMacro(vtkMesaRenderer,vtkRenderer); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Concrete open gl render method. void DeviceRender(void); // Description: // Internal method temporarily removes lights before reloading them // into graphics pipeline. void ClearLights(void); void Clear(void); // Description: // Ask lights to load themselves into graphics pipeline. int UpdateLights(void); // Create a vtkMesaCamera, will be used by the super class // to create the correct camera object. virtual vtkCamera* MakeCamera(); // Create a vtkMesaLight, will be used by the super class // to create the correct light object. virtual vtkLight* MakeLight(); protected: vtkMesaRenderer(); ~vtkMesaRenderer(); //BTX // Picking functions to be implemented by sub-classes virtual void DevicePickRender(); virtual void StartPick(unsigned int pickFromSize); virtual void UpdatePickId(); virtual void DonePick(); virtual unsigned int GetPickedId(); virtual unsigned int GetNumPickedIds(); virtual int GetPickedIds(unsigned int atMost, unsigned int *callerBuffer); virtual double GetPickedZ(); // Ivars used in picking class vtkGLPickInfo* PickInfo; //ETX double PickedZ; private: vtkMesaRenderer(const vtkMesaRenderer&); // Not implemented. void operator=(const vtkMesaRenderer&); // Not implemented. }; #endif
[ "ganondorf@ganondorf-VirtualBox.(none)" ]
[ [ [ 1, 84 ] ] ]
f88d37f9fe5424602a003adc2fed7f1db59957a8
59166d9d1eea9b034ac331d9c5590362ab942a8f
/XMLTree2Geom/main.cpp
5b2d6bfd314f7dd32c873ea20869df3beaa787c1
[]
no_license
seafengl/osgtraining
5915f7b3a3c78334b9029ee58e6c1cb54de5c220
fbfb29e5ae8cab6fa13900e417b6cba3a8c559df
refs/heads/master
2020-04-09T07:32:31.981473
2010-09-03T15:10:30
2010-09-03T15:10:30
40,032,354
0
3
null
null
null
null
WINDOWS-1251
C++
false
false
990
cpp
#include "xmlTree.h" #include "osgNodeBranch.h" #include "osgNodeFronds.h" #include "osgNodeLeaf.h" #include <osgViewer/Viewer> #include <osgViewer/ViewerEventHandlers> #include "ticpp.h" int main() { xmlTree::Instance().Init( "tree.xml" ); ////////////////////////////////////////////////////////////////////////// /* //загрузка и сохранение ствола osgNodeBranch branch; branch.LODSave(); //загрузка и сохранение веток osgNodeFronds fronds; fronds.LODSave(); */ //загрузка и сохранение листвы osgNodeLeaf leaf; leaf.LODSave(); // Create a Viewer. osgViewer::Viewer viewer; // add the stats handler viewer.addEventHandler( new osgViewer::StatsHandler ); //viewer.setSceneData( tree->getRootNode().get() ); viewer.getCamera()->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR); // Display, and main loop. return viewer.run(); }
[ "asmzx79@3290fc28-3049-11de-8daa-cfecb5f7ff5b" ]
[ [ [ 1, 43 ] ] ]
11d5d8ff1a69c3b29b7e4d37dbc1032635a4b16e
45901972d53b88c968dc09e88d8241bf18fcba7a
/tools/rospack/rosstack.cpp
ce9c0884b514904efc33dcf688b7a9ca883f1776
[]
no_license
lubosz/rosstacks
d5a99b7794b265cb981a6873074dabdbf4de5ff8
67ca37234eaba02ca05d1d0136d7023711d16e34
refs/heads/master
2021-01-19T12:58:32.411499
2011-11-07T20:43:00
2011-11-07T20:43:00
2,735,039
0
0
null
null
null
null
UTF-8
C++
false
false
40,353
cpp
/* * Copyright (C) 2009, Morgan Quigley and Brian Gerkey * * 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 names of Stanford University 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. */ /* Author: Morgan Quigley, Brian Gerkey */ #include <cstdlib> #include <algorithm> #include <cstdio> #include <cstring> #include <cerrno> #include <string> #include <vector> #include <map> #include <stack> #include <queue> #include <cassert> #if !defined(WIN32) #include <unistd.h> #include <dirent.h> #include <sys/time.h> #include <sys/file.h> #include <stdint.h> #endif #include <stdexcept> #include <time.h> #include <sstream> #include <iterator> #if defined(_MSC_VER) // msvc only #define F_OK 0x00 #define W_OK 0x02 #define R_OK 0x04 #else // non msvc only #include <libgen.h> #endif #if defined(WIN32) // both msvc and mingw #include <direct.h> #include <time.h> #include <windows.h> #include <io.h> #include <fcntl.h> #define PATH_MAX MAX_PATH #define snprintf _snprintf #define getcwd _getcwd #define fdopen _fdopen #define access _access #define mkdir(a,b) _mkdir(a) #endif #include "tinyxml-2.5.3/tinyxml.h" #include "rospack/rosstack.h" #include "rospack/rospack.h" using namespace std; //#define VERBOSE_DEBUG const double DEFAULT_MAX_CACHE_AGE = 60.0; // rebuild cache every minute #include <sys/stat.h> #ifndef S_ISDIR #define S_ISDIR(x) (((x) & S_IFMT) == S_IFDIR) #endif using namespace rosstack; #ifdef __APPLE__ const string g_ros_os("osx"); #else #if defined(WIN32) const string g_ros_os("win32"); #else const string g_ros_os("linux"); #endif #endif #if defined(_MSVC_VER) // The MS compiler complains bitterly about undefined symbols due to the // static members of the TiXmlBase class. They need to exist in every // compilation unit (i.e. DLL or EXE), but they don't get exported // properly across DLL boundaries (for reasons I've tried to investigate, // before deciding it was a waste of my time). So they're defined here as well // to keep rosstack happy (rospack's lib links directly to tinyxml.cpp, // rosstack's lib does not). // I'll fix this later. Thanks, MS, for creating yet another broken system. const int rospack_tinyxml::TiXmlBase::utf8ByteTable[256] = { // 0 1 2 3 4 5 6 7 8 9 a b c d e f 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x00 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x10 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x20 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x30 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x40 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x50 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x60 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x70 End of ASCII range 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x80 0x80 to 0xc1 invalid 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x90 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xa0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xb0 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xc0 0xc2 to 0xdf 2 byte 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xd0 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xe0 0xe0 to 0xef 3 byte 4, 4, 4, 4, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // 0xf0 0xf0 to 0xf4 4 byte, 0xf5 and higher invalid }; bool rospack_tinyxml::TiXmlBase::condenseWhiteSpace = true; #endif ////////////////////////////////////////////////////////////////////////////// // Global storage for --foo options // --deps-only bool g_deps_only; // --length= string g_length; // The stack name string g_stack; // the number of entries to list in the profile table unsigned int g_profile_length = 0; // global singleton rosstack pointer... yeah, I know. ROSStack *g_rosstack = NULL; ////////////////////////////////////////////////////////////////////////////// #if defined(WIN32) // This isn't entirely necessary - the Win32 API functions handle / just as // well as \ for paths, and CMake chokes if we output paths with \ in them // anyway. const char *rosstack::fs_delim = "\\"; const char *rosstack::path_delim = ";"; #else const char *rosstack::fs_delim = "/"; const char *rosstack::path_delim = ":"; #endif Stack::Stack(string _path) : path(_path), deps_calculated(false), direct_deps_calculated(false), descendants_calculated(false), manifest_loaded(false) { vector<string> path_tokens; string_split(path, path_tokens, fs_delim); name = path_tokens.back(); // Don't load the manifest here, because it causes spurious errors to be // printed if the stack has been moved (#1785). Presumably the manifest // will be loaded later, prior to being needed. //load_manifest(); } bool Stack::is_stack(const string &path) { return file_exists(path + string(fs_delim) + "stack.xml"); } bool Stack::is_package(const string &path) { return file_exists(path + string(fs_delim) + "manifest.xml"); } bool Stack::is_no_subdirs(const string &path) { return file_exists(path + string(fs_delim) + "rosstack_nosubdirs"); } const VecStack &Stack::deps1() { return direct_deps(); } const VecStack &Stack::deps(traversal_order_t order, int depth) { if (depth > 1000) { fprintf(stderr,"[rosstack] woah! expanding the dependency tree made it blow " "up.\n There must be a circular dependency somewhere.\n"); throw runtime_error(string("circular dependency")); } if (deps_calculated) return _deps; // postorder traversal of the dependency tree VecStack my_dd = direct_deps(); for (VecStack::iterator i = my_dd.begin(); i != my_dd.end(); ++i) { VecStack d = (*i)->deps(order, depth+1); // recurse on direct dependencies if (order == PREORDER) _deps.push_back(*i); for (VecStack::iterator j = d.begin(); j != d.end(); ++j) { // don't add things twice, but if you have something already // and we're doing a quasi-preorder traversal, bump it to the back bool have = false; VecStack::iterator prior_loc; for (VecStack::iterator k = _deps.begin(); k != _deps.end() && !have; ++k) if ((*k) == (*j)) { prior_loc = k; have = true; } if (have && order == PREORDER) { _deps.erase(prior_loc); _deps.push_back(*j); } else if (!have) _deps.push_back(*j); } if (order == POSTORDER) { // only stuff it to the end if it isn't there already bool have = false; for (VecStack::iterator k = _deps.begin(); k != _deps.end() && !have; ++k) if ((*k) == (*i)) have = true; if (!have) _deps.push_back(*i); } } deps_calculated = true; return _deps; } string Stack::manifest_path() { return path + string(fs_delim) + "stack.xml"; } VecStack Stack::descendants1() { VecStack children; for (VecStack::iterator p = stacks.begin(); p != stacks.end(); ++p) { // We catch exceptions here, because we don't care if some // unrelated packages in the system have invalid manifests try { if ((*p)->has_parent(name)) children.push_back(*p); } catch (runtime_error &e) { } } return children; } const VecStack &Stack::descendants(int depth) { if (depth > 100) { fprintf(stderr, "[rosstack] woah! circular dependency! aaaaaa!\n"); throw runtime_error(string("circular dependency")); } if (descendants_calculated) return _descendants; VecStack desc_with_dups; for (VecStack::iterator p = stacks.begin(); p != stacks.end(); ++p) { // We catch exceptions here, because we don't care if some // unrelated packages in the system have invalid manifests try { if ((*p)->has_parent(name)) { desc_with_dups.push_back(*p); const VecStack &p_desc = (*p)->descendants(depth+1); for (VecStack::const_iterator q = p_desc.begin(); q != p_desc.end(); ++q) desc_with_dups.push_back(*q); } } catch (runtime_error &e) { } } assert(_descendants.size() == 0); for (VecStack::iterator p = desc_with_dups.begin(); p != desc_with_dups.end(); ++p) { bool found = false; for (VecStack::iterator q = _descendants.begin(); q != _descendants.end() && !found; ++q) if ((*q)->name == (*p)->name) found = true; if (!found) _descendants.push_back(*p); } descendants_calculated = true; return _descendants; } bool Stack::has_parent(string pkg) { VecStack parents = direct_deps(true); for (VecStack::iterator i = parents.begin(); i != parents.end(); ++i) if ((*i)->name == pkg) return true; return false; } const VecStack &Stack::direct_deps(bool missing_stack_as_warning) { if (direct_deps_calculated) return _direct_deps; #ifdef VERBOSE_DEBUG printf("calculating direct deps for package [%s]\n", name.c_str()); #endif rospack_tinyxml::TiXmlElement *mroot = manifest_root(); rospack_tinyxml::TiXmlNode *dep_node = 0; while ((dep_node = mroot->IterateChildren(string("depend"), dep_node))) { rospack_tinyxml::TiXmlElement *dep_ele = dep_node->ToElement(); assert(dep_ele); const char *dep_stackname = dep_ele->Attribute("stack"); if (!dep_stackname) { fprintf(stderr,"[rosstack] bad depend syntax (no 'stack' attribute) in " "[%s]\n", manifest_path().c_str()); throw runtime_error(string("invalid manifest")); } // Must make a copy here, because the call to g_get_stack() below might // cause a recrawl, which blows aways the accumulated data structure. string dep_stackname_copy = string(dep_stackname); string name_copy = name; #ifdef VERBOSE_DEBUG printf("direct_deps: stk %s has dep %s\n", name.c_str(), dep_stackname_copy.c_str()); #endif try { _direct_deps.push_back(g_get_stack(dep_stackname_copy)); } catch (runtime_error &e) { if (missing_stack_as_warning) fprintf(stderr, "[rosstack] warning: couldn't find dependency " "[%s] of [%s]\n", dep_stackname_copy.c_str(), name_copy.c_str()); else { fprintf(stderr, "[rosstack] couldn't find dependency [%s] of [%s]\n", dep_stackname_copy.c_str(), name_copy.c_str()); throw runtime_error(string("missing dependency")); } } } direct_deps_calculated = true; return _direct_deps; } void Stack::load_manifest() { if (manifest_loaded) return; if (!manifest.LoadFile(manifest_path())) { string errmsg = string("error parsing manifest file at [") + manifest_path().c_str() + string("]"); fprintf(stderr, "[rosstack] warning: error parsing manifest file at [%s]. Blowing away the cache...\n", manifest_path().c_str()); g_rosstack->deleteCache(); // Only want this warning printed once. manifest_loaded = true; throw runtime_error(errmsg); } rospack_tinyxml::TiXmlElement *mroot = manifest.RootElement(); } rospack_tinyxml::TiXmlElement *Stack::manifest_root() { load_manifest(); rospack_tinyxml::TiXmlElement *ele = manifest.RootElement(); if (!ele) { string errmsg = string("error parsing manifest file at [") + manifest_path().c_str() + string("]"); throw runtime_error(errmsg); } return ele; } VecStack Stack::stacks; ////////////////////////////////////////////////////////////////////////////// ROSStack::ROSStack() : ros_root(NULL), crawled(false) { g_rosstack = this; Stack::stacks.reserve(500); // get some space to avoid early recopying... ros_root = getenv("ROS_ROOT"); if (!ros_root) { fprintf(stderr,"[rosstack] ROS_ROOT is not defined in the environment.\n"); throw runtime_error(string("no ROS_ROOT")); } if (!file_exists(ros_root)) { fprintf(stderr,"[rosstack] the path specified as ROS_ROOT is not " "accessible. Please ensure that this environment variable " "is set and is writeable by your user account.\n"); throw runtime_error(string("no ROS_ROOT")); } createROSHomeDirectory(); crawl_for_stacks(); } ROSStack::~ROSStack() { for (VecStack::iterator p = Stack::stacks.begin(); p != Stack::stacks.end(); ++p) delete (*p); Stack::stacks.clear(); } const char* ROSStack::usage() { return "USAGE: rosstack [options] <command> [stack]\n" " Allowed commands:\n" " help\n" " find [stack]\n" " contents [stack]\n" " list\n" " list-names\n" " depends [stack] (alias: deps)\n" " depends-manifests [stack] (alias: deps-manifests)\n" " depends1 [stack] (alias: deps1)\n" " depends-indent [stack] (alias: deps-indent)\n" " depends-on [stack]\n" " depends-on1 [stack]\n" " contains [package]\n" " contains-path [package]\n" " profile [--length=<length>] \n\n" " If [stack] is omitted, the current working directory\n" " is used (if it contains a stack.xml).\n\n"; } Stack *ROSStack::get_stack(const string &stack_name) { #ifdef VERBOSE_DEBUG printf("searching for stack %s\n", stack_name.c_str()); #endif for (VecStack::iterator p = Stack::stacks.begin(); p != Stack::stacks.end(); ++p) { if ((*p)->name == stack_name) { if(!crawled) { // Answer come from the cache; check that the path is valid, and // contains a manifest (related to #1115). std::string manifest_path = (*p)->path + fs_delim + "stack.xml"; struct stat s; int ret; while((ret = stat(manifest_path.c_str(), &s)) != 0 && errno == EINTR); if(ret == 0) { // Answer looks good return (*p); } else { // Bad cache. Warn and fall through to the recrawl below. fprintf(stderr, "[rosstack] warning: invalid cached location %s for package %s; forcing recrawl\n", (*p)->path.c_str(), (*p)->name.c_str()); break; } } else { // Answer came from a fresh crawl; no further checking needed. return (*p); } } } if (!crawled) // maybe it's a brand-new stack. force a crawl. { crawl_for_stacks(true); // will set the crawled flag; recursion is safe return get_stack(stack_name); } throw runtime_error(string("couldn't find stack ") + stack_name); return NULL; // or not } int ROSStack::cmd_depends_on(bool include_indirect) { // We can't proceed if the argument-parsing logic wasn't able to provide // any package name. Note that we need to check for an empty opt_package // here, but not in other places (e.g., cmd_deps()), because here we're // catching the exception that get_pkg() throws when it can't find the // package. Elsewhere, we let that exception propagate up. if(g_stack.size() == 0) { string errmsg = string("no stack name given, and current directory is not a stack root"); throw runtime_error(errmsg); } // Explicitly crawl for stacks, to ensure that we get newly added // dependent stacks. We also avoid the possibility of a recrawl // happening within the loop below, which could invalidate the stacks // vector as we loop over it. crawl_for_stacks(true); Stack* s; try { s = get_stack(g_stack); } catch(runtime_error) { fprintf(stderr, "[rosstack] warning: stack %s doesn't exist\n", g_stack.c_str()); //s = new Stack(g_stack); //Stack::stacks.push_back(s); s = add_stack(g_stack); } assert(s); const VecStack descendants = include_indirect ? s->descendants() : s->descendants1(); for (VecStack::const_iterator sit = descendants.begin(); sit != descendants.end(); ++sit) printf("%s\n", (*sit)->name.c_str()); return 0; } int ROSStack::cmd_find() { // todo: obey the search order Stack *p = get_stack(g_stack); printf("%s\n", p->path.c_str()); return 0; } string ROSStack::lookup_owner(string pkg_name, bool just_owner_name) { // hack... we'll treat g_stack as the name of the package to look up. rospack::Package *pkg = rp.get_pkg(pkg_name); #ifdef VERBOSE_DEBUG printf("package path: [%s]\n", pkg->path.c_str()); #endif map<string, string> bases; // all the places the search can bottom out for (VecStack::iterator p = Stack::stacks.begin(); // first, add stacks p != Stack::stacks.end(); ++p) bases[(*p)->path] = (*p)->name; /* char *rr = getenv("ROS_ROOT"); // add ROS_ROOT if (rr) { bases } */ char *rpp = getenv("ROS_PACKAGE_PATH"); // add ROS_PACKAGE_PATH entries if (rpp) { vector<string> rppvec; string_split(rpp, rppvec, path_delim); sanitize_rppvec(rppvec); for (vector<string>::iterator i = rppvec.begin(); i != rppvec.end(); ++i) bases[*i] = string(""); } #ifdef VERBOSE_DEBUG printf("bases:\n"); for (map<string, string>::iterator i = bases.begin(); i != bases.end(); ++i) printf("%s -> %s\n", i->first.c_str(), i->second.c_str()); #endif // now, chop the package path until we hit one of the bases string pkg_path_fragment = pkg->path; while (pkg_path_fragment.length() > 1) { // chop off everything to the right of the last slash size_t last_slash_pos = pkg_path_fragment.find_last_of('/'); if (last_slash_pos == string::npos) break; // shouldn't happen, but might as well catch it pkg_path_fragment = pkg_path_fragment.substr(0, last_slash_pos); #ifdef VERBOSE_DEBUG printf("frag = %s\n", pkg_path_fragment.c_str()); #endif map<string, string>::iterator i = bases.find(pkg_path_fragment); if (i != bases.end()) { if (just_owner_name) return bases[pkg_path_fragment]; else return pkg_path_fragment; break; } } return string(""); } int ROSStack::cmd_contains() { printf("%s\n", lookup_owner(g_stack, true).c_str()); return 0; } int ROSStack::cmd_contains_path() { printf("%s\n", lookup_owner(g_stack, false).c_str()); return 0; } int ROSStack::cmd_deps() { VecStack d = get_stack(g_stack)->deps(Stack::POSTORDER); for (VecStack::iterator i = d.begin(); i != d.end(); ++i) printf("%s\n", (*i)->name.c_str()); return 0; } int ROSStack::cmd_deps_manifests() { VecStack d = get_stack(g_stack)->deps(Stack::POSTORDER); for (VecStack::iterator i = d.begin(); i != d.end(); ++i) printf("%s/stack.xml ", (*i)->path.c_str()); puts(""); return 0; } int ROSStack::cmd_deps1() { VecStack d = get_stack(g_stack)->deps1(); for (VecStack::iterator i = d.begin(); i != d.end(); ++i) printf("%s\n", (*i)->name.c_str()); return 0; } int ROSStack::cmd_depsindent(Stack *stack, int indent) { VecStack d = stack->deps1(); for (VecStack::iterator i = d.begin(); i != d.end(); ++i) { for(int s=0; s<indent; s++) printf(" "); printf("%s\n", (*i)->name.c_str()); cmd_depsindent(*i, indent+2); } return 0; } static bool space(char c) { return isspace(c); } static bool not_space(char c) { return !isspace(c); } static vector<string> split_space(const string& str) { typedef string::const_iterator iter; vector<string> ret; iter i = str.begin(); while (i != str.end()) { i = find_if(i, str.end(), not_space); iter j = find_if(i, str.end(), space); if (i != str.end()) ret.push_back(string(i, j)); i = j; } return ret; } int ROSStack::run(int argc, char **argv) { assert(argc >= 2); int i; const char* opt_length = "--length="; string errmsg = string(usage()); i=1; const char* cmd = argv[i++]; for(;i<argc;i++) { if(!strncmp(argv[i], opt_length, strlen(opt_length))) { if(strlen(argv[i]) > strlen(opt_length)) g_length = string(argv[i]+strlen(opt_length)); else throw runtime_error(errmsg); } else break; } if(strcmp(cmd, "profile") && g_length.size()) throw runtime_error(errmsg); if(i < argc) { if(!strcmp(cmd, "help") || !strcmp(cmd, "list") || !strcmp(cmd, "list-names") || !strcmp(cmd, "profile")) throw runtime_error(errmsg); g_stack = string(argv[i++]); } // Are we sitting in a stack? else if(Stack::is_stack(".")) { char buf[1024]; if(!getcwd(buf,sizeof(buf))) throw runtime_error(errmsg); #if defined(_MSC_VER) // No basename on Windows; use _splitpath_s instead char drive[_MAX_DRIVE], dir[_MAX_DIR], fname[_MAX_FNAME], ext[_MAX_EXT]; _splitpath_s(buf, drive, _MAX_DRIVE, dir, _MAX_DIR, fname, _MAX_FNAME, ext, _MAX_EXT); char filename[_MAX_FNAME + _MAX_EXT]; if (ext[0] != '\0') { _makepath_s(filename, _MAX_FNAME + _MAX_EXT, NULL, NULL, fname, ext); g_stack = string(filename); } else g_stack = string(fname); #else g_stack = string(basename(buf)); #endif } if (i != argc) throw runtime_error(errmsg); if (!strcmp(cmd, "profile")) { if (g_length.size()) g_profile_length = atoi(g_length.c_str()); else g_profile_length = 20; // default is about a screenful or so #ifdef VERBOSE_DEBUG printf("profile_length = %d\n", g_profile_length); #endif // re-crawl with profiling enabled crawl_for_stacks(true); return 0; } else if (!strcmp(cmd, "find")) return cmd_find(); else if (!strcmp(cmd, "contains")) return cmd_contains(); else if (!strcmp(cmd, "contains-path")) return cmd_contains_path(); else if (!strcmp(cmd, "list")) return cmd_print_stack_list(true); else if (!strcmp(cmd, "list-names")) return cmd_print_stack_list(false); else if (!strcmp(cmd, "contents")) return cmd_print_packages(); else if (!strcmp(cmd, "depends") || !strcmp(cmd, "deps")) return cmd_deps(); else if (!strcmp(cmd, "depends-manifests") || !strcmp(cmd, "deps-manifests")) return cmd_deps_manifests(); else if (!strcmp(cmd, "depends1") || !strcmp(cmd, "deps1")) return cmd_deps1(); else if (!strcmp(cmd, "depends-indent") || !strcmp(cmd, "deps-indent")) return cmd_depsindent(get_stack(g_stack), 0); else if (!strcmp(cmd, "depends-on")) return cmd_depends_on(true); else if (!strcmp(cmd, "depends-on1")) return cmd_depends_on(false); else if (!strcmp(cmd, "help")) fputs(usage(), stderr); else throw runtime_error(errmsg); return 0; } int ROSStack::cmd_print_stack_list(bool print_path) { for (VecStack::iterator i = Stack::stacks.begin(); i != Stack::stacks.end(); ++i) if (print_path) printf("%s %s\n", (*i)->name.c_str(), (*i)->path.c_str()); else printf("%s\n", (*i)->name.c_str()); return 0; } int ROSStack::cmd_print_packages() { rospack::ROSPack rp; string path = get_stack(g_stack)->path; //printf("partial crawl of %s\n", path.c_str()); rospack::VecPkg pkgs = rp.partial_crawl(path); //printf("found %d pkgs\n", pkgs.size()); for (rospack::VecPkg::iterator i = pkgs.begin(); i != pkgs.end(); ++i) { printf("%s\n", (*i)->name.c_str()); delete *i; } return 0; } void ROSStack::createROSHomeDirectory() { char *homedir = getenv("HOME"); if (!homedir) { //fprintf(stderr, "[rospack] WARNING: cannot create ~/.ros directory.\n"); } else { string path = string(homedir) + "/.ros"; if (access(path.c_str(), R_OK) && !mkdir(path.c_str(), 0700)) fprintf(stderr,"[rosstack] WARNING: cannot create ~/.ros directory.\n"); } } string ROSStack::getCachePath() { string path; path = string(ros_root) + fs_delim + ".rosstack_cache"; if (access(ros_root, W_OK) == 0) return path; // if we cannot write into the ros_root, then let's try to // write into the user's .ros directory. createROSHomeDirectory(); path = string(getenv("HOME")) + fs_delim + ".ros" + fs_delim + "rosstack_cache"; return path; } void ROSStack::deleteCache() { string cache_path = g_rosstack->getCachePath(); if (file_exists(cache_path)) remove(cache_path.c_str()); } bool ROSStack::cache_is_good() { string cache_path = getCachePath(); // first see if it's new enough double cache_max_age = DEFAULT_MAX_CACHE_AGE; const char *user_cache_time_str = getenv("ROS_CACHE_TIMEOUT"); if(user_cache_time_str) cache_max_age = atof(user_cache_time_str); if(cache_max_age == 0.0) return false; struct stat s; if (stat(cache_path.c_str(), &s) == 0) { double dt = difftime(time(NULL), s.st_mtime); #ifdef VERBOSE_DEBUG printf("cache age: %f\n", dt); #endif // Negative cache_max_age means it's always new enough. It's dangerous // for the user to set this, but rosbash uses it. if ((cache_max_age > 0.0) && (dt > cache_max_age)) return false; } // try to open it FILE *cache = fopen(cache_path.c_str(), "r"); if (!cache) return false; // it's not readable by us. sad. // see if ROS_ROOT and ROS_PACKAGE_PATH are identical char linebuf[30000]; bool ros_root_ok = false, ros_package_path_ok = false; const char *ros_package_path = getenv("ROS_PACKAGE_PATH"); while (!feof(cache)) { linebuf[0] = 0; if (!fgets(linebuf, sizeof(linebuf), cache)) break; if (!linebuf[0]) continue; linebuf[strlen(linebuf)-1] = 0; // get rid of trailing newline if (linebuf[0] == '#') { if (!strncmp("#ROS_ROOT=", linebuf, 10)) { if (!strcmp(linebuf+10, ros_root)) ros_root_ok = true; } else if (!strncmp("#ROS_PACKAGE_PATH=", linebuf, 18)) { if (!ros_package_path) { if (!strlen(linebuf+18)) ros_package_path_ok = true; } else if (!strcmp(linebuf+18, getenv("ROS_PACKAGE_PATH"))) ros_package_path_ok = true; } } else break; // we're out of the header. nothing more matters to this check. } fclose(cache); return ros_root_ok && ros_package_path_ok; } class CrawlQueueEntry { public: string path; double start_time, elapsed_time; CrawlQueueEntry(string _path) : path(_path), start_time(0), elapsed_time(0) { } bool operator>(const CrawlQueueEntry &rhs) const { return elapsed_time > rhs.elapsed_time; } }; double ROSStack::time_since_epoch() { #if defined(WIN32) #if defined(_MSC_VER) || defined(_MSC_EXTENSIONS) #define DELTA_EPOCH_IN_MICROSECS 11644473600000000Ui64 #else #define DELTA_EPOCH_IN_MICROSECS 11644473600000000ULL #endif FILETIME ft; unsigned __int64 tmpres = 0; GetSystemTimeAsFileTime(&ft); tmpres |= ft.dwHighDateTime; tmpres <<= 32; tmpres |= ft.dwLowDateTime; tmpres /= 10; tmpres -= DELTA_EPOCH_IN_MICROSECS; return static_cast<double>(tmpres) / 1e6; #else struct timeval tod; gettimeofday(&tod, NULL); return tod.tv_sec + 1e-6 * tod.tv_usec; #endif } // Add stack, filtering out duplicates. Stack* ROSStack::add_stack(string path) { // Filter out duplicates; first encountered takes precedence Stack* newp = new Stack(path); Stack* return_p = newp; // TODO: make this check more efficient bool dup = false; for(std::vector<Stack *>::const_iterator it = Stack::stacks.begin(); it != Stack::stacks.end(); it++) { if((*it)->name == newp->name) { dup=true; return_p = *it; break; } } if(dup) delete newp; else Stack::stacks.push_back(newp); return return_p; } void ROSStack::crawl_for_stacks(bool force_crawl) { for (VecStack::iterator p = Stack::stacks.begin(); p != Stack::stacks.end(); ++p) delete *p; Stack::stacks.clear(); if(!force_crawl && cache_is_good()) { string cache_path = getCachePath(); FILE *cache = fopen(cache_path.c_str(), "r"); if (cache) // one last check just in case nutty stuff happened in between { #ifdef VERBOSE_DEBUG printf("trying to use cache...\n"); #endif char linebuf[30000]; while (!feof(cache)) { linebuf[0] = 0; if (!fgets(linebuf, sizeof(linebuf), cache)) break; // error in read operation if (!linebuf[0] || linebuf[0] == '#') continue; char *newline_pos = strchr(linebuf, '\n'); if (newline_pos) *newline_pos = 0; //Stack::stacks.push_back(new Stack(linebuf)); add_stack(linebuf); } fclose(cache); return; // cache load went OK; we're done here. } } // if we get here, this means the cache either bogus or we've been // instructed to rebuild it. #ifdef VERBOSE_DEBUG printf("building cache\n"); #endif deque<CrawlQueueEntry> q; q.push_back(CrawlQueueEntry(ros_root)); vector<string> rspvec; // seed the crawler with ROS_ROOT and ROS_PACKAGE_PATH char *rr = getenv("ROS_ROOT"); if (!rr) { fprintf(stderr, "[rosstack] ERROR: ROS_ROOT not set.\n"); exit(1); } // Add the ROS stack //Stack::stacks.push_back(new Stack(string(rr))); add_stack(string(rr)); string rsp; char *rpp = getenv("ROS_PACKAGE_PATH"); if (rpp) rsp = string(rpp); string_split(rsp, rspvec, path_delim); sanitize_rppvec(rspvec); #ifdef VERBOSE_DEBUG printf("seeding crawler with [%s], which has %lu entries\n", rsp.c_str(), rspvec.size()); #endif for (vector<string>::iterator i = rspvec.begin(); i != rspvec.end(); ++i) { if (Stack::is_no_subdirs(*i)) fprintf(stderr, "[rosstack] WARNING: non-stack directory in " "ROS_PACKAGE_PATH marked " "rosstack_nosubdirs:\n\t%s\n", i->c_str()); else q.push_back(CrawlQueueEntry(*i)); } const double crawl_start_time = time_since_epoch(); priority_queue<CrawlQueueEntry, vector<CrawlQueueEntry>, greater<CrawlQueueEntry> > profile; while (!q.empty()) { CrawlQueueEntry cqe = q.front(); q.pop_front(); // Check whether this part of ROS_PACKAGE_PATH is itself a package/stack if (Stack::is_stack(cqe.path)) { //Stack::stacks.push_back(new Stack(*i)); add_stack(cqe.path); continue; } else if (Stack::is_package(cqe.path)) continue; // ignore it. //printf("crawling %s\n", cqe.path.c_str()); if (g_profile_length > 0) { if (cqe.start_time != 0) { // this stack symbol means we've already crawled its children, and it's // just here for timing purposes. save the traversal time and bail. cqe.elapsed_time = time_since_epoch() - cqe.start_time; profile.push(cqe); if (profile.size() > g_profile_length) // only save the worst guys profile.pop(); continue; } cqe.start_time = time_since_epoch(); q.push_front(cqe); } #if defined(WIN32) // And again... WIN32_FIND_DATA find_file_data; HANDLE hfind = INVALID_HANDLE_VALUE; if ((hfind = FindFirstFile((cqe.path + "\\*").c_str(), &find_file_data)) == INVALID_HANDLE_VALUE) { fprintf(stderr, "[rosstack] FindFirstFile error %u while crawling %s\n", GetLastError(), cqe.path.c_str()); continue; } do { if (!S_ISDIR(find_file_data.dwFileAttributes)) continue; // Ignore non-directories if (find_file_data.cFileName[0] == '.') continue; // Ignore hidden directories string child_path = cqe.path + fs_delim + string(find_file_data.cFileName); if (Stack::is_stack(child_path)) continue; // Ignore leaves. if (Stack::is_stack(child_path)) { // Filter out duplicates; first encountered takes precedence Stack *newp = new Stack(child_path); //printf("found stack %s\n", child_path.c_str()); // TODO: make this check more efficient bool dup = false; for(std::vector<Stack *>::const_iterator it = Stack::stacks.begin(); it != Stack::stacks.end(); it++) { if((*it)->name == newp->name) { dup=true; break; } } if(dup) delete newp; else Stack::stacks.push_back(newp); } //check to make sure we're allowed to descend else if (!Stack::is_no_subdirs(child_path)) q.push_front(CrawlQueueEntry(child_path)); } while (FindNextFile(hfind, &find_file_data) != 0); DWORD last_error = GetLastError(); FindClose(hfind); if (last_error != ERROR_NO_MORE_FILES) { fprintf(stderr, "[rosstack] FindNextFile error %u while crawling %s\n", GetLastError(), cqe.path.c_str()); continue; } #else DIR *d = opendir(cqe.path.c_str()); if (!d) { fprintf(stderr, "[rosstack] opendir error [%s] while crawling %s\n", strerror(errno), cqe.path.c_str()); continue; } struct dirent *ent; while ((ent = readdir(d)) != NULL) { struct stat s; string child_path = cqe.path + fs_delim + string(ent->d_name); if (stat(child_path.c_str(), &s) != 0) continue; if (!S_ISDIR(s.st_mode)) continue; if (ent->d_name[0] == '.') continue; // ignore hidden dirs else if (Stack::is_stack(child_path)) { add_stack(child_path); /* // Filter out duplicates; first encountered takes precedence Stack *newp = new Stack(child_path); //printf("found stack %s\n", child_path.c_str()); // TODO: make this check more efficient bool dup = false; for(std::vector<Stack *>::const_iterator it = Stack::stacks.begin(); it != Stack::stacks.end(); it++) { if((*it)->name == newp->name) { dup=true; break; } } if(dup) delete newp; else Stack::stacks.push_back(newp); */ } else if (Stack::is_package(child_path)) continue; // ignore this guy, he's a leaf. //check to make sure we're allowed to descend else if (!Stack::is_no_subdirs(child_path)) q.push_front(CrawlQueueEntry(child_path)); } closedir(d); #endif } crawled = true; // don't try to re-crawl if we can't find something const double crawl_elapsed_time = time_since_epoch() - crawl_start_time; // write the results of this crawl to the cache file string cache_path = getCachePath(); char tmp_cache_dir[PATH_MAX]; char tmp_cache_path[PATH_MAX]; strncpy(tmp_cache_dir, cache_path.c_str(), sizeof(tmp_cache_dir)); #if defined(_MSC_VER) // No dirname on Windows; use _splitpath_s instead char drive[_MAX_DRIVE], dir[_MAX_DIR], fname[_MAX_FNAME], ext[_MAX_EXT]; _splitpath_s(tmp_cache_dir, drive, _MAX_DRIVE, dir, _MAX_DIR, fname, _MAX_FNAME, ext, _MAX_EXT); char full_dir[_MAX_DRIVE + _MAX_DIR]; _makepath_s(full_dir, _MAX_DRIVE + _MAX_DIR, drive, dir, NULL, NULL); snprintf(tmp_cache_path, sizeof(tmp_cache_path), "%s\\.rosstack_cache.XXXXXX", full_dir); #else snprintf(tmp_cache_path, sizeof(tmp_cache_path), "%s/.rosstack_cache.XXXXXX", dirname(tmp_cache_dir)); #endif #if defined(__MINGW32__) // There is no equivalent of mkstemp or _mktemp_s on mingw, so we resort to a slightly less secure // method. Could use mktemp, but as we're just redirecting to FILE anyway, tmpfile() works // for us. FILE *cache = tmpfile(); if ( cache == NULL ) { fprintf(stderr, "[rospack] Unable to generate temporary cache file name: %u", errno); } #elif defined(WIN32) // This one is particularly nasty: on Windows, there is no equivalent of // mkstemp, so we're stuck with the security risks of mktemp. Hopefully not a // problem in our use cases. if (_mktemp_s(tmp_cache_path, PATH_MAX) != 0) { fprintf(stderr, "[rosstack] Unable to generate temporary cache file name: %u", GetLastError()); throw runtime_error(string("Failed to create tmp cache file name")); } FILE *cache = fopen(tmp_cache_path, "w"); #else int fd = mkstemp(tmp_cache_path); if (fd < 0) { fprintf(stderr, "Unable to create temporary cache file: %s\n", tmp_cache_path); throw runtime_error(string("failed to create tmp cache file")); } FILE *cache = fdopen(fd, "w"); #endif if (!cache) { fprintf(stderr, "woah! couldn't create the cache file. Please check " "ROS_ROOT to make sure it's a writeable directory.\n"); throw runtime_error(string("failed to create tmp cache file")); } fprintf(cache, "#ROS_ROOT=%s\n#ROS_PACKAGE_PATH=%s\n", ros_root, rsp.c_str()); for (VecStack::iterator s = Stack::stacks.begin(); s != Stack::stacks.end(); ++s) fprintf(cache, "%s\n", (*s)->path.c_str()); fclose(cache); if(file_exists(cache_path.c_str())) remove(cache_path.c_str()); if(rename(tmp_cache_path, cache_path.c_str()) < 0) { fprintf(stderr, "[rospack] Error: failed rename cache file %s to %s\n", tmp_cache_path, cache_path.c_str()); perror("rename"); throw runtime_error(string("failed to rename cache file")); } if (g_profile_length) { // dump it into a stack to reverse it (so slowest guys are first) stack<CrawlQueueEntry> reverse_profile; while (!profile.empty()) { reverse_profile.push(profile.top()); profile.pop(); } printf("\nFull tree crawl took %.6f seconds.\n", crawl_elapsed_time); printf("-------------------------------------------------------------\n"); while (!reverse_profile.empty()) { CrawlQueueEntry cqe = reverse_profile.top(); reverse_profile.pop(); printf("%.6f %s\n", cqe.elapsed_time, cqe.path.c_str()); } printf("\n"); } } ////////////////////////////////////////////////////////////////////////////// void rosstack::string_split(const string &s, vector<string> &t, const string &d) { t.clear(); size_t start = 0, end; while ((end = s.find_first_of(d, start)) != string::npos) { t.push_back(s.substr(start, end-start)); start = end + 1; } if (start != s.length()) t.push_back(s.substr(start)); } bool rosstack::file_exists(const string &fname) { return (access(fname.c_str(), F_OK) == 0); // will be different in windows } Stack *rosstack::g_get_stack(const string &name) { return g_rosstack->get_stack(name); } void ROSStack::sanitize_rppvec(std::vector<std::string> &rppvec) { // drop any trailing slashes for (size_t i = 0; i < rppvec.size(); i++) { size_t last_slash_pos = rppvec[i].find_last_of("/"); if (last_slash_pos != string::npos && last_slash_pos == rppvec[i].length()-1) { fprintf(stderr, "[rosstack] warning: trailing slash found in " "ROS_PACKAGE_PATH\n"); rppvec[i].erase(last_slash_pos); } } }
[ "kwc@61973afe-1cd6-434e-a0a9-934cb0052259", "gerkey@61973afe-1cd6-434e-a0a9-934cb0052259", "mquigley@61973afe-1cd6-434e-a0a9-934cb0052259" ]
[ [ [ 1, 40 ], [ 48, 52 ], [ 74, 92 ], [ 98, 99 ], [ 132, 140 ], [ 142, 146 ], [ 158, 163 ], [ 165, 165 ], [ 170, 190 ], [ 192, 323 ], [ 326, 327 ], [ 329, 380 ], [ 382, 383 ], [ 385, 386 ], [ 388, 460 ], [ 462, 462 ], [ 494, 504 ], [ 516, 530 ], [ 534, 573 ], [ 576, 718 ], [ 733, 733 ], [ 735, 806 ], [ 808, 826 ], [ 828, 832 ], [ 834, 922 ], [ 940, 942 ], [ 944, 945 ], [ 973, 999 ], [ 1002, 1021 ], [ 1025, 1028 ], [ 1031, 1031 ], [ 1033, 1033 ], [ 1035, 1036 ], [ 1038, 1051 ], [ 1063, 1078 ], [ 1137, 1156 ], [ 1159, 1177 ], [ 1179, 1186 ], [ 1188, 1195 ], [ 1205, 1205 ], [ 1230, 1237 ], [ 1239, 1249 ], [ 1251, 1251 ], [ 1254, 1255 ], [ 1260, 1294 ], [ 1297, 1308 ] ], [ [ 41, 47 ], [ 53, 73 ], [ 93, 97 ], [ 100, 131 ], [ 141, 141 ], [ 147, 157 ], [ 164, 164 ], [ 166, 169 ], [ 191, 191 ], [ 324, 325 ], [ 328, 328 ], [ 381, 381 ], [ 384, 384 ], [ 387, 387 ], [ 461, 461 ], [ 463, 493 ], [ 505, 515 ], [ 531, 533 ], [ 574, 574 ], [ 719, 732 ], [ 734, 734 ], [ 807, 807 ], [ 827, 827 ], [ 833, 833 ], [ 923, 939 ], [ 943, 943 ], [ 946, 972 ], [ 1000, 1001 ], [ 1022, 1024 ], [ 1029, 1029 ], [ 1037, 1037 ], [ 1052, 1062 ], [ 1079, 1136 ], [ 1157, 1158 ], [ 1178, 1178 ], [ 1187, 1187 ], [ 1196, 1204 ], [ 1206, 1229 ], [ 1238, 1238 ], [ 1250, 1250 ], [ 1252, 1253 ], [ 1256, 1259 ] ], [ [ 575, 575 ], [ 1030, 1030 ], [ 1032, 1032 ], [ 1034, 1034 ], [ 1295, 1296 ], [ 1309, 1324 ] ] ]
8156b7361f5aecbf41bd62e4d62ab3fa9b511b10
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/tags/techdemo2/engine/multimedia/src/null/NullListener.cpp
3286f43934b04b57614714506dfaf438bd769f5b
[ "ClArtistic", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
jacmoe/dsa-hl-svn
55b05b6f28b0b8b216eac7b0f9eedf650d116f85
97798e1f54df9d5785fb206c7165cd011c611560
refs/heads/master
2021-04-22T12:07:43.389214
2009-11-27T22:01:03
2009-11-27T22:01:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,276
cpp
/* This source file is part of Rastullahs Lockenpracht. * Copyright (C) 2003-2005 Team Pantheon. http://www.team-pantheon.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the Clarified Artistic License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not you can get it here * http://www.jpaulmorrison.com/fbp/artistic2.htm. */ #include "NullListener.h" using namespace Ogre; Ogre::String rl::NullListener::msMovableType = "NullListener"; namespace rl { /** * @param name Der Name des Zuhoerers. * @author JoSch * @date 03-12-2005 */ NullListener::NullListener(const String &name): ListenerMovable(name) { } /** * @author JoSch * @date 03-12-2005 */ NullListener::~NullListener() { } /** * @author JoSch * @date 03-11-2005 * @return Den Objekttypen */ const String& NullListener::getMovableType() const { return msMovableType; } }
[ "tanis@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 56 ] ] ]
bef04f608f1a486d4bf78f4f85c58ebda38077fd
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Framework/Camera.h
27fcaf568a6d40897f66155feb5ac59627f405aa
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
1,081
h
#ifndef CAMERA_H #define CAMERA_H #include <D3DX10.h> class Camera { public: Camera(); void Reset(); void Update(float dt); ~Camera(void){}; D3DXMATRIX View(){return view;} D3DXMATRIX Projection(){return projection;} D3DXMATRIX ViewProjection(){return viewProjection;} D3DXMATRIX InvView(){return invView;} D3DXVECTOR3 Position(){return position;} D3DXVECTOR3 Forward(){return forward;} float FOV(){return fov;} float FOVDivBy2(){return fov*0.5f;} float NearHeight(){return nearHeight;} float NearWidth(){return nearWidth;} float ViewPortWidth(){return viewPortWidth;} float ViewPortHeight(){return viewPortHeight;} float FarPlane(){return far_plane;} float NearPlane(){return near_plane;} private: D3DXMATRIX view, projection, invView, viewProjection; D3DXVECTOR3 position, lookAt, right, forward, initialForward, initialRight, up; float deltaMovement, deltaRotation, yaw, pitch; float fov; float near_plane; float far_plane; float nearHeight, nearWidth, viewPortWidth, viewPortHeight; }; #endif
[ [ [ 1, 45 ] ] ]
2b5e38895f29b7cf0b6657f962c589a8ada66c8b
2e5fd1fc05c0d3b28f64abc99f358145c3ddd658
/deps/quickfix/src/C++/SocketConnection.cpp
41aa8b504efca35c2e64bb05c068827ef3a779f4
[ "BSD-2-Clause" ]
permissive
indraj/fixfeed
9365c51e2b622eaff4ce5fac5b86bea86415c1e4
5ea71aab502c459da61862eaea2b78859b0c3ab3
refs/heads/master
2020-12-25T10:41:39.427032
2011-02-15T13:38:34
2011-02-15T20:50:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,952
cpp
/**************************************************************************** ** Copyright (c) quickfixengine.org All rights reserved. ** ** This file is part of the QuickFIX FIX Engine ** ** This file may be distributed under the terms of the quickfixengine.org ** license as defined by quickfixengine.org and appearing in the file ** LICENSE included in the packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.quickfixengine.org/LICENSE for licensing information. ** ** Contact [email protected] if any conditions of this licensing are ** not clear to you. ** ****************************************************************************/ #ifdef _MSC_VER #include "stdafx.h" #else #include "config.h" #endif #include "CallStack.h" #include "SocketConnection.h" #include "SocketAcceptor.h" #include "SocketConnector.h" #include "SocketInitiator.h" #include "Session.h" #include "Utility.h" namespace FIX { SocketConnection::SocketConnection( int s, Sessions sessions, SocketMonitor* pMonitor ) : m_socket( s ), m_sendLength( 0 ), m_sessions(sessions), m_pSession( 0 ), m_pMonitor( pMonitor ) { FD_ZERO( &m_fds ); FD_SET( m_socket, &m_fds ); } SocketConnection::SocketConnection( SocketInitiator& i, const SessionID& sessionID, int s, SocketMonitor* pMonitor ) : m_socket( s ), m_sendLength( 0 ), m_pSession( i.getSession( sessionID, *this ) ), m_pMonitor( pMonitor ) { FD_ZERO( &m_fds ); FD_SET( m_socket, &m_fds ); m_sessions.insert( sessionID ); } SocketConnection::~SocketConnection() { if ( m_pSession ) Session::unregisterSession( m_pSession->getSessionID() ); } bool SocketConnection::send( const std::string& msg ) { QF_STACK_PUSH(SocketConnection::send) Locker l( m_mutex ); m_sendQueue.push_back( msg ); processQueue(); signal(); return true; QF_STACK_POP } bool SocketConnection::processQueue() { QF_STACK_PUSH(SocketConnection::processQueue) Locker l( m_mutex ); if( !m_sendQueue.size() ) return true; struct timeval timeout = { 0, 0 }; fd_set writeset = m_fds; if( select( 1 + m_socket, 0, &writeset, 0, &timeout ) <= 0 ) return false; const std::string& msg = m_sendQueue.front(); int result = socket_send ( m_socket, msg.c_str() + m_sendLength, msg.length() - m_sendLength ); if( result > 0 ) m_sendLength += result; if( m_sendLength == msg.length() ) { m_sendLength = 0; m_sendQueue.pop_front(); } return !m_sendQueue.size(); QF_STACK_POP } void SocketConnection::disconnect() { QF_STACK_PUSH(SocketConnection::disconnect) if ( m_pMonitor ) m_pMonitor->drop( m_socket ); QF_STACK_POP } bool SocketConnection::read( SocketConnector& s ) { QF_STACK_PUSH(SocketConnection::read) if ( !m_pSession ) return false; try { readFromSocket(); readMessages( s.getMonitor() ); } catch( SocketRecvFailed& e ) { m_pSession->getLog()->onEvent( e.what() ); return false; } return true; QF_STACK_POP } bool SocketConnection::read( SocketAcceptor& a, SocketServer& s ) { QF_STACK_PUSH(SocketConnection::read) std::string msg; try { readFromSocket(); if ( !m_pSession ) { if ( !readMessage( msg ) ) return false; m_pSession = Session::lookupSession( msg, true ); if( !isValidSession() ) { m_pSession = 0; if( a.getLog() ) { a.getLog()->onEvent( "Session not found for incoming message: " + msg ); a.getLog()->onIncoming( msg ); } } if( m_pSession ) m_pSession = a.getSession( msg, *this ); if( m_pSession ) m_pSession->next( msg, UtcTimeStamp() ); if( !m_pSession ) { s.getMonitor().drop( m_socket ); return false; } Session::registerSession( m_pSession->getSessionID() ); } readMessages( s.getMonitor() ); return true; } catch ( SocketRecvFailed& e ) { if( m_pSession ) m_pSession->getLog()->onEvent( e.what() ); s.getMonitor().drop( m_socket ); } catch ( InvalidMessage& ) { s.getMonitor().drop( m_socket ); } return false; QF_STACK_POP } bool SocketConnection::isValidSession() { QF_STACK_PUSH(SocketConnection::isValidSession) if( m_pSession == 0 ) return false; SessionID sessionID = m_pSession->getSessionID(); if( Session::isSessionRegistered(sessionID) ) return false; return !( m_sessions.find(sessionID) == m_sessions.end() ); QF_STACK_POP } void SocketConnection::readFromSocket() throw( SocketRecvFailed ) { QF_STACK_PUSH(SocketConnection::readFromSocket) int size = recv( m_socket, m_buffer, sizeof(m_buffer), 0 ); if( size <= 0 ) throw SocketRecvFailed( size ); m_parser.addToStream( m_buffer, size ); QF_STACK_POP } bool SocketConnection::readMessage( std::string& msg ) { QF_STACK_PUSH(SocketConnection::readMessage) try { return m_parser.readFixMessage( msg ); } catch ( MessageParseError& ) {} return true; QF_STACK_POP } void SocketConnection::readMessages( SocketMonitor& s ) { if( !m_pSession ) return; std::string msg; while( readMessage( msg ) ) { try { m_pSession->next( msg, UtcTimeStamp() ); } catch ( InvalidMessage& ) { if( !m_pSession->isLoggedOn() ) s.drop( m_socket ); } } } void SocketConnection::onTimeout() { QF_STACK_PUSH(SocketConnection::onTimeout) if ( m_pSession ) m_pSession->next(); QF_STACK_POP } } // namespace FIX
[ [ [ 1, 249 ] ] ]
59b715fb37a8c3498ec995888a477fffaf1e6a1c
d0e3e591986c27ea73575a5b88f8326ab319816b
/fset.h
7266b3fe267596f0f3c36205a451d27f9606e1ec
[]
no_license
codegooglecom/wtfu
f8851940908ddad141dffd471b66552583f48728
3eaaa969588799a5fb4d6a66851e00193fc1c6af
refs/heads/master
2016-08-11T16:10:59.543826
2010-11-24T07:51:14
2010-11-24T07:51:14
43,666,270
0
0
null
null
null
null
UTF-8
C++
false
false
1,522
h
#ifndef wtfFILES_SET_H #define wtfFILES_SET_H #include "wx/wxprec.h" #ifdef __BORLANDC__ # pragma hdrstop #endif #ifndef WX_PRECOMP # include "wx/wx.h" # include "wx/xml/xml.h" #endif //precompiled headers #include "nset.h" WX_DECLARE_HASH_MAP( int, NamesSet*, wxIntegerHash, wxIntegerEqual, NamesSetsH ); class FilesSet : public wxObject { DECLARE_ABSTRACT_CLASS(FilesSet) private: NamesSetsH nsets; int Id; int MainId; int NextNSId; wxString Title; public: FilesSet(); ~FilesSet(); // methods for iterating names sets NamesSet* GetFirstNS(int *id); NamesSet* GetNextNS(int *id); NamesSet* GetLastNS(int *id); NamesSet* GetPrevNS(int *id); // getting properties int GetId(); wxString GetTitle(); int GetMainId(); int GetNextNSId(); // setting properties bool SetId(int id); bool SetTitle(const wxString& title); bool SetMainId(int mid); // manipulating with names sets NamesSet *GetNamesSet(int nsid); bool AddNamesSet(NamesSet* nset); bool DeleteNamesSet(int nsid); bool DeleteAllNamesSets(); bool AddName(int nsid, int nid, const wxString& name); bool DeleteName(int nsid, int nid); // accessing to main names set NamesSet *GetFilesSet(); wxString GetSourceDir(); bool SetSourceDir(const wxString& dir); bool AddFile(int fid, const wxString& name); bool DeleteFile(int fid); }; #endif // #ifndef wtfFILES_SET_H
[ "JupMoon.Io@b849ae62-46ad-11de-9b56-810ca157e297" ]
[ [ [ 1, 67 ] ] ]
8b7c380c395e049d1b2a8ab492a65ba93107929f
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Animation/Animation/Animation/WaveletCompressed/hkaWaveletCompressedAnimation.h
6a2d64f29c86b01b04c123c92f62ba43cf40bd7b
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
10,208
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HKANIMATION_ANIMATION_WAVELETCOMPRESSED_HKWAVELETCOMPRESSEDANIMATION_XML_H #define HKANIMATION_ANIMATION_WAVELETCOMPRESSED_HKWAVELETCOMPRESSEDANIMATION_XML_H #include <Animation/Animation/Animation/hkaAnimation.h> /// hkaWaveletCompressedAnimation meta information extern const class hkClass hkaWaveletCompressedAnimationClass; class hkaInterleavedUncompressedAnimation; /// Compresses animation data using a wavelet transform. /// See Animation Compression section of the Userguide for details. class hkaWaveletCompressedAnimation : public hkaAnimation { public: HK_DECLARE_CLASS_ALLOCATOR( HK_MEMORY_CLASS_ANIM_COMPRESSED ); HK_DECLARE_REFLECTION(); /// Compression parameters struct CompressionParams { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_ANIM_COMPRESSED, hkaWaveletCompressedAnimation::CompressionParams ); HK_DECLARE_REFLECTION(); /// Bits used for float quantization - default 8, range [2,16] hkUint16 m_quantizationBits; /// Block size - default 65535 hkUint16 m_blockSize; /// (INTERNAL) Allows exact preservation (full 4-bytes floats) of the first 'n' floats during the quantization process - default 'false' hkUint16 m_preserve; /// If m_useOldStyleTruncation (deprecated) is set to 'true', this is the fraction of wavelet coefficients discarded (set to zero) - default 0.1 hkReal m_truncProp; /// Allows backwards compatability (see m_truncProp) - default 'false' hkBool m_useOldStyleTruncation; /// TrackAnalysis absolute position tolerance. See the "Compression Overview" section of the Userguide for details - default 0.0 hkReal m_absolutePositionTolerance; // Set to 0 to use only relative tolerance /// TrackAnalysis relative position tolerance. See the "Compression Overview" section of the Userguide for details - default 0.01 hkReal m_relativePositionTolerance; // Set to 0 to use only abs tolerance /// TrackAnalysis rotation position tolerance. See the "Compression Overview" section of the Userguide for details - default 0.001 hkReal m_rotationTolerance; /// TrackAnalysis scale position tolerance. See the "Compression Overview" section of the Userguide for details - default 0.01 hkReal m_scaleTolerance; /// TrackAnalysis float tolerance. See the "Compression Overview" section of the Userguide for details - default 0.001 hkReal m_absoluteFloatTolerance; CompressionParams(); }; /// This structure is used when specifying per track compression settings struct PerTrackCompressionParams { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_ANIM_COMPRESSED, hkaWaveletCompressedAnimation::PerTrackCompressionParams ); /// List of CompressionParams to enable per-bone compression settings /// On initialisation only a single element is allocated. hkArray<struct hkaWaveletCompressedAnimation::CompressionParams> m_parameterPalette; /// An array of indices into the palette above for transform tracks hkArray<int> m_trackIndexToPaletteIndex; /// An array of indices into the palette above for float tracks hkArray<int> m_floatTrackIndexToPaletteIndex; }; /// Constructor compresses data hkaWaveletCompressedAnimation(const hkaInterleavedUncompressedAnimation& raw, const CompressionParams& params, hkBool useThreeComponentQuaternions = true ); /// Constructor allowing different compression settings for each track in the animation hkaWaveletCompressedAnimation(const hkaInterleavedUncompressedAnimation& raw, const PerTrackCompressionParams& params, hkBool useThreeComponentQuaternions = true ); /// Get the tracks at a given time /// Note: If you are calling this method directly you may find some quantization error present in the rotations. /// The blending done in hkaAnimatedSkeleton is not sensitive to rotation error so rather than renormalize here /// we defer it until blending has been completed. If you are using this method directly you may want to call /// hkaSkeletonUtils::normalizeRotations() on the results. virtual void sampleTracks(hkReal time, hkQsTransform* transformTracksOut, hkReal* floatTracksOut, hkaChunkCache* cache) const; /// Get a subset of the the first 'maxNumTracks' tracks of a pose at a given time (all tracks from 0 to maxNumTracks-1 inclusive). virtual void samplePartialTracks(hkReal time, hkUint32 maxNumTransformTracks, hkQsTransform* transformTracksOut, hkUint32 maxNumFloatTracks, hkReal* floatTracksOut, hkaChunkCache* cache) const; /// Sample individual animation tracks virtual void sampleIndividualTransformTracks( hkReal time, const hkInt16* tracks, hkUint32 numTracks, hkQsTransform* transformOut ) const; /// Sample a individual floating tracks virtual void sampleIndividualFloatTracks( hkReal time, const hkInt16* tracks, hkUint32 numTracks, hkReal* out ) const; /// Returns the number of original samples / frames of animation virtual int getNumOriginalFrames() const; /// Get a key for use with the cache virtual hkUint32 getFullCacheKey( hkUint32 poseIdx ) const; /// Clear the cache of all keys associated with this animation - use to 'unload' an animation from the cache virtual void clearAllCacheKeys(hkaChunkCache* cache) const; /* * Block decompression */ /// Return the number of chunks of data required to sample the tracks at time t virtual int getNumDataChunks(hkUint32 frame, hkReal delta) const; /// Return the chunks of data required to sample the tracks at time t virtual void getDataChunks(hkUint32 frame, hkReal delta, DataChunk* dataChunks, int numDataChunks) const; /// Return the maximum total size of all chunk data which could be returned by getDataChunks for this animation. virtual int getMaxSizeOfCombinedDataChunks() const; /// Get a subset of the tracks a given time using data chunks. Sample is calculated using pose[frameIndex] * (1 - frameDelta) + pose[frameIndex+1] * frameDelta. static void HK_CALL samplePartialWithDataChunks(hkUint32 frameIndex, hkReal frameDelta, hkUint32 maxNumTransformTracks, hkQsTransform* transformTracksOut, hkUint32 maxNumFloatTracks, hkReal* floatTracksOut, const DataChunk* dataChunks, int numDataChunks); void getBlockDataAndSize(int blockNum, DataChunk& dataChunkOut) const; public: /// The number of samples encoded in the animation. int m_numberOfPoses; /// The number of tracks in each encoded block int m_blockSize; /// struct QuantizationFormat { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_ANIMATION, hkaWaveletCompressedAnimation::QuantizationFormat ); HK_DECLARE_REFLECTION(); QuantizationFormat( ) { } QuantizationFormat( hkFinishLoadedObjectFlag flag ) {} // Backwards compatibility only - pre-per-track compression. hkUint8 m_maxBitWidth; // Always 0 for wavelet since all coefficients are quantized (none preserved). hkUint8 m_preserved; // Number of dynamic tracks that are quantized and stored hkUint32 m_numD; // Index into the data buffer for the quantization offsets hkUint32 m_offsetIdx; // Index into the data buffer for the quantization scales hkUint32 m_scaleIdx; // Index into the data buffer for the quantization bidwidths hkUint32 m_bitWidthIdx; }; /// Quantization Description struct QuantizationFormat m_qFormat; /// Index into the data buffer for the Track Mask hkUint32 m_staticMaskIdx; /// Index into the data buffer for the Static DOF Data hkUint32 m_staticDOFsIdx; /// Number Static Transform DOFs hkUint32 m_numStaticTransformDOFs; /// Number Dynamic Transform DOFs hkUint32 m_numDynamicTransformDOFs; /// Index into the data buffer for the block indices hkUint32 m_blockIndexIdx; /// Size of the block indices (stored as hkUint32) hkUint32 m_blockIndexSize; /// Index into the data buffer for the Quantization Data hkUint32 m_quantizedDataIdx; /// Size of the Quantization Data (stored as hkUint8) hkUint32 m_quantizedDataSize; /// The data buffer where compressed and static data is kept hkArray< hkUint8 > m_dataBuffer; public: // Constructor for initialisation of vtable fixup HK_FORCE_INLINE hkaWaveletCompressedAnimation( hkFinishLoadedObjectFlag flag ) : hkaAnimation(flag), m_qFormat(flag), m_dataBuffer(flag) { if (flag.m_finishing) handleEndian(); } private: /// Initialize the animation with construction info void initialize(const hkaInterleavedUncompressedAnimation& raw, const PerTrackCompressionParams& params, hkBool useThreeComponentQuaternions); /// Swap the endianness in the data buffer as appropriate void handleEndian(); }; #endif // HKANIMATION_ANIMATION_WAVELETCOMPRESSED_HKWAVELETCOMPRESSEDANIMATION_XML_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ [ [ 1, 228 ] ] ]
03cfdfd03515d91ff16185492d243d125a582160
65fe6f7017f90fa55acf45773470f8f039724748
/antbuster/include/entity/ant.h
c8d0b548ee5a357a042ea1085f4bcb076c3299e7
[]
no_license
ashivers/antbusterhge
bd37276c29d1bb5b3da8d0058d2a3e8421dfa3ab
575a21c56fa6c8633913b7e2df729767ac8a7850
refs/heads/master
2021-01-20T22:40:19.612909
2007-10-03T10:56:44
2007-10-03T10:56:44
40,769,210
0
0
null
null
null
null
GB18030
C++
false
false
1,968
h
#ifndef ANT_H #define ANT_H #include <hgevector.h> #include <hgeCurvedAni.h> #include "common/aimentity.h" /* @class Ant * @note ant */ class Ant : public AimEntity { public: enum DamageType { DT_Normal, // 普通攻击 DT_Impact, // 冲击 DT_Frozen, // 冰冻 DT_Fire, // 火焰 DT_Poison, // 中毒 NumDamageType, }; Ant(cAni::iAnimResManager &arm); virtual ~Ant(); virtual void render(int time); virtual void step(float deltaTime); virtual AimType getAimType() const { return AT_Ant; } void initAnt(const hgeVector &spawnPos, int level); int getHp() const { return hp; } int getMaxHp() const { return int(4 * pow(1.1, level) - 1); } int getLevel() const { return level; } float getSpeed() const; void applyDamage(DamageType damageType, int damage); int refCount; // do not delete the ant if refCount is not 0, this is used by missile like bullets bool hasCake() const { return carryCake; } protected: void applyDamageEffect(); int hp; int level; cAni::iAnimation *anim; cAni::iAnimation *hpAnim; cAni::iAnimation *cakeAnim; float angle; hgeVector dest; int damageEffect[NumDamageType]; float moveMeter; // 移动路程 bool carryCake; // 是否携带蛋糕 }; /* 1、蚂蚁的速度是1.2,负重后速度降为1.0,冰冻后最低速度0.3左右。 2、第一个蚂蚁的血量为4,设蚂蚁的血量为Y,则蚂蚁的血量计算公式为“Yx=4*1.1x-1”。 3、杀死蚂蚁后获得的积分和金钱与蚂蚁的级别相同。 4、屏幕上最多同时会有6只蚂蚁。 5、蚂蚁的AI比看起来的低,经常无视蛋糕四处乱跑。 6、蚂蚁抗上蛋糕的时候会恢复一半的血。 */ #endif//ANT_H
[ "zikaizhang@b4c9a983-0535-0410-ac72-75bbccfdc641" ]
[ [ [ 1, 88 ] ] ]
93e6ff6d047843375b272f98e41687ffa15499f1
6c8c4728e608a4badd88de181910a294be56953a
/UiModule/Ether/View/EtherScene.cpp
1724f14b3620319821dbabab0ecf6586efddbc34
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
caocao/naali
29c544e121703221fe9c90b5c20b3480442875ef
67c5aa85fa357f7aae9869215f840af4b0e58897
refs/heads/master
2021-01-21T00:25:27.447991
2010-03-22T15:04:19
2010-03-22T15:04:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,436
cpp
// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "EtherScene.h" #include "Ether/View/InfoCard.h" #include <QKeyEvent> #include <QGraphicsSceneMouseEvent> #include <QGraphicsItem> #include <QList> #include <QBrush> #include <QDebug> #include "MemoryLeakCheck.h" namespace Ether { namespace View { EtherScene::EtherScene(QObject *parent, const QRectF &scene_rect) : QGraphicsScene(scene_rect, parent), supress_key_events_(false), connected_(false) { #ifdef DYNAMIC_LOGIN_SCENE bg_image_disconnected_ = QPixmap("./data/ui/images/ether/main_background_disconnected.png"); bg_image_connected_ = QPixmap("./data/ui/images/ether/main_background_connected.png"); QBrush bg_brush(bg_image_disconnected_); setBackgroundBrush(bg_brush); connect(this, SIGNAL( sceneRectChanged(const QRectF &) ), SLOT( RectChanged(const QRectF &) )); #endif } EtherScene::~EtherScene() { } void EtherScene::keyPressEvent(QKeyEvent *ke) { QGraphicsScene::keyPressEvent(ke); if (ke->isAutoRepeat() || supress_key_events_) return; switch (ke->key()) { case Qt::Key_W: case Qt::Key_Up: emit UpPressed(); break; case Qt::Key_S: case Qt::Key_Down: emit DownPressed(); break; case Qt::Key_A: case Qt::Key_Left: emit LeftPressed(); break; case Qt::Key_D: case Qt::Key_Right: emit RightPressed(); break; case Qt::Key_Return: case Qt::Key_Enter: emit EnterPressed(); break; default: break; } } void EtherScene::mousePressEvent(QGraphicsSceneMouseEvent *mouse_event) { if (mouse_event->button() == Qt::LeftButton) { QPointF click_pos = mouse_event->buttonDownScenePos(Qt::LeftButton); View::InfoCard *clicked_item = dynamic_cast<View::InfoCard *>(itemAt(click_pos)); if (clicked_item) emit ItemClicked(clicked_item); } QGraphicsScene::mousePressEvent(mouse_event); } void EtherScene::SetConnectionStatus(bool connected) { connected_ = connected; #ifdef DYNAMIC_LOGIN_SCENE RectChanged(sceneRect()); #endif } void EtherScene::RectChanged(const QRectF &new_rect) { QPixmap bg; if (connected_) bg = bg_image_connected_.scaled(new_rect.size().toSize()); else bg = bg_image_disconnected_.scaled(new_rect.size().toSize()); setBackgroundBrush(QBrush(bg)); } void EtherScene::EmitSwitchSignal() { emit EtherSceneReadyForSwitch(); } } }
[ "[email protected]@5b2332b8-efa3-11de-8684-7d64432d61a3", "jujjyl@5b2332b8-efa3-11de-8684-7d64432d61a3" ]
[ [ [ 1, 3 ], [ 5, 6 ], [ 9, 16 ], [ 19, 116 ] ], [ [ 4, 4 ], [ 7, 8 ], [ 17, 18 ] ] ]
a8f230594b19af091e1e120b49503926d4a0ea8e
76ea17bc9bc52ae653bd203dd6716fd1e965a8c9
/libnge0.2/src/IDriver_ogl.h
a45ef6ea2ca8bf371c7485188d94c887ba51fb63
[]
no_license
eickegao/avgscript
1e78cc09b8c52e5ee9b3be48b81ef5b128fef269
75e75b8c5597b673855b91e6e1bd87c5c60b8c04
refs/heads/master
2016-09-08T00:32:29.508547
2009-01-12T08:40:08
2009-01-12T08:40:08
33,953,223
0
0
null
null
null
null
GB18030
C++
false
false
9,117
h
#ifndef _IDRIVER_OGL_H_ #define _IDRIVER_OGL_H_ #include <gl/glut.h> #include <GL/gl.h> #include <GL/glu.h> #include <GL/glaux.h> #include "math_compatible.h" #include "datatype.h" #include "SDL.h" /** * 图象显示接口,有2个实现分别对应2个平台。此处不用派生为了避免虚函数的开销。 */ class IVideoDriver { public: IVideoDriver(); /** * 显示开始函数,所有的显示函数都必须在BeginScene()和EndScene()之间。 * 作用是清屏和一些初始化工作。默认是用黑色0xff000000清屏。可以用 * SetClearColor()改变默认清屏颜色。 * @param flag int,是否清屏的标致,默认为true。 * @return 无返回值. */ void BeginScene(int flag = 1); /** * 显示结束函数,所有的显示函数都必须在BeginScene()和EndScene()之间。 * 作用是提交显示并刷新显示。 * @return 无返回值. */ void EndScene(); /** * 2d图象显示函数,提供了旋转,缩放,混色功能。用于显示2d图片。 * @param texture CTexture*, 由图象加载函数LoadTexture()得到的CTexture*. * @param sx float,x(left) 需要显示图片部分的x坐标.默认是原图(下同)。这4个参数是 * 为了只显示图片上的某一部分而设置的。 * @param sy float,y(top) 需要显示图片部分的y坐标. * @param sw float,w(right) 需要显示图片部分的宽. * @param sh float,h(bottom) 需要显示图片部分的高. * @param dx float,将显示在屏幕的x坐标. * @param dy float,将显示在屏幕的y坐标. * @param xscale float,x(水平)方向上缩放比例.默认为参数1.0,不做缩放。 * @param yscale float,y(垂直)方向上缩放比例.默认为参数1.0,不做缩放。 * @param angle float,旋转角度正代表逆时针,负代表顺时针方向,旋转中心由CTexture的rcentrex和rcentrey指定, * 绕旋转中心旋转这个角度,默认旋转中心是图片的中心,可以通过设置rcentrex和rcentrey * 来改变这个旋转中心。默认参数是0。 * @param color int,混色的颜色,用来做图片的alpha混合。用宏RGBA(r,g,b,a)来生成这个颜色 * 如果RGBA(r,g,b,a)中的a值为0那么图片为透明.默认参数是显示原图。 * 例如要将图片半透明显示可以设置RGBA(0xff,0xff,0xff,0x7f)。显示原图就是RGBA(0xff,0xff,0xff,0xff)。 * @return 无返回值. * @see 用RenderQuadFast()来快速显示原图,如果不需要缩放和旋转的话,会有一定的速度提升。 */ void RenderQuad(CTexture* texture,float sx,float sy,float sw,float sh,float dx,float dy, float xscale = 1.0,float yscale = 1.0,float angle = 0.0,int color=0xffffffff); /** * 2d图象显示函数,提供了混色功能。用于显示2d图片。 * 这个是RenderQuad()的简化版. * @param texture CTexture*, 由图象加载函数LoadTexture()得到的CTexture*. * @param dx float,将显示在屏幕的x坐标. * @param dy float,将显示在屏幕的y坐标. * @see 如果需要旋转,缩放,混色采用RenderQuad(). * @return 无返回值. */ void RenderQuadFast(CTexture* texture,float dx,float dy); /** * 设置清屏的颜色值,用宏RGBA(r,g,b,a)生成这个颜色值。 * @param color int,清屏的颜色值。 */ void SetClearColor(int color); /** * 获取清屏的颜色值。 * @return 颜色值. */ int GetClearColor(); /** * 调试函数,初始化fps记数器 * @return 无返回值. */ void FpsInit() ; /** * 调试函数,用于显示当前的fps,需要先用FpsInit()初始化,不然会得到错误结果. * @return 无返回值. */ void ShowFps() ; /** * 画直线的函数,传入参数是4个float值。 * @param x1 float,直线第一个点的x坐标。 * @param y1 float,直线第一个点的y坐标。 * @param x2 float,直线第二个点的x坐标。 * @param y2 float,直线第二个点的y坐标。 * @param color int,直线的颜色,用宏RGBA生成这个颜色。 * @return 无返回值。 */ void DrawLine(float x1, float y1, float x2, float y2, int color) ; /** * 画直线的函数,传入参数是2个CPointf坐标值。 * @param p1 CPointf,直线第一个点的坐标。 * @param p2 Cpointf,直线第二个点的坐标。 * @param color int,直线的颜色,用宏RGBA生成这个颜色。 * @return 无返回值。 */ void DrawLine(CPointf p1, CPointf p2, int color) ; /** * 画矩形线框的函数,传入参数是4个float值。 * @param x float,画到屏幕上的x坐标。 * @param y float,画到屏幕上的y坐标。 * @param width float,矩形线框的宽。 * @param height float,矩形线框的高。 * @param color int,线框颜色。 * @return 无返回值。 */ void DrawRect(float x, float y, float width, float height,int color) ; /** * 画矩形线框的函数,传入参数是CRectf值。 * @param rect CRectf,矩形线框的参数。 * @param color int,线框颜色。 * @return 无返回值。 */ void DrawRect(CRectf rect,int color) ; /** * 画实心矩形的函数,传入参数是4个float值。 * @param x float,画到屏幕上的x坐标。 * @param y float,画到屏幕上的y坐标。 * @param width float,矩形的宽。 * @param height float,矩形的高。 * @param color int,实心矩形颜色。 * @return 无返回值。 */ void FillRect(float x, float y, float width, float height,int color) ; /** * 画实心矩形的函数,传入参数是CRectf值。 * @param rect CRectf,矩形的参数。 * @param color int,实心矩形颜色。 * @return 无返回值。 */ void FillRect(CRectf rect,int color) ; /** * 画圆形线框的函数。 * @param x float,圆心的顶点的x坐标。 * @param y float,圆心的顶点的y坐标。 * @param radius float ,圆的半径。 * @param color int,圆形线框的颜色。 * @return 无返回值。 */ void DrawCircle(float x, float y, float radius, int color); /** * 画实心圆形的函数。 * @param x float,圆心的顶点的x坐标。 * @param y float,圆心的顶点的y坐标。 * @param radius float ,圆的半径。 * @param color int,实心圆形的颜色。 * @return 无返回值。 */ void FillCircle(float x, float y, float radius, int color); /** * 画椭圆线框的函数。 * @param x float,圆心的顶点的x坐标。 * @param y float,圆心的顶点的y坐标。 * @param xradius float ,椭圆x的半径。 * @param yradius float ,椭圆y的半径。 * @param color int,椭圆线框的颜色。 * @return 无返回值。 */ void DrawEllipse(float x,float y ,float xradius, float yradius , int color) ; /** * 画实心椭圆的函数。 * @param x float,圆心的顶点的x坐标。 * @param y float,圆心的顶点的y坐标。 * @param xradius float ,椭圆x的半径。 * @param yradius float ,椭圆y的半径。 * @param color int,实心椭圆的颜色。 * @return 无返回值。 */ void FillEllipse(float x,float y ,float xradius, float yradius , int color) ; void FillPie(float x, float y, float radius,float theta, int color); /** * 画实心凸多边形的函数。 * @param array CPointf*,凸多边形的顶点数组。 * @param color int,凸多边形的颜色。 * @return 无返回值。 */ void FillPolygon(CPointf* array, int count, int color); /** * 画凸多边形线框的函数。 * @param CPointf* array,凸多边形的顶点数组。 * @param color int,凸多边形线框的颜色。 * @return 无返回值。 */ void DrawPolygon(CPointf* array, int count, int color); void FillRoundRect(float x, float y, float w, float h, float radius, int color); private: int m_colorint; color4f m_clrcolor; float m_sintable[360]; float m_costable[360]; int m_update; int m_frame; int m_t0; }; #endif
[ "pspbter@7305fedb-903f-0410-a37f-9f94d3351015" ]
[ [ [ 1, 215 ] ] ]
dc81c8b5d88a7c2fd58b236cfe18c8bd672d4b1f
741b36f4ddf392c4459d777930bc55b966c2111a
/incubator/deeppurple/lwplugins/lwwrapper/Panel/ControlCheckBox.h
38ba50d97ec2fc0cab292700b8e3598a1467b44c
[]
no_license
BackupTheBerlios/lwpp-svn
d2e905641f60a7c9ca296d29169c70762f5a9281
fd6f80cbba14209d4ca639f291b1a28a0ed5404d
refs/heads/master
2021-01-17T17:01:31.802187
2005-10-16T22:12:52
2005-10-16T22:12:52
40,805,554
0
0
null
null
null
null
UTF-8
C++
false
false
471
h
#pragma once #include "control.h" //##ModelId=3E16FCD6034E class ControlCheckBox : public Control { public: //##ModelId=3E16FCD60362 ControlCheckBox(void); //##ModelId=3E16FCD60364 virtual ~ControlCheckBox(void); //##ModelId=3E16FCD6036E virtual bool RegisterWithPanel(LWPanelID pan); //##ModelId=3E16FCD60378 bool SetValue(bool onoff); //##ModelId=3E16FCD60381 bool GetValue(void); //##ModelId=3E16FCD6038B int Width; };
[ "deeppurple@dac1304f-7ce9-0310-a59f-f2d444f72a61" ]
[ [ [ 1, 21 ] ] ]
3d5e53bb5e24d61dd4c24813a8ae282940d03301
22fb52fc26ab1da21ab837a507524f111df5b694
/v2/src/nifti.cpp
fb410fa25128535bf3b7a90feef2f9fd386b6b91
[]
no_license
yangguang-ecnu/voxelbrain
b343cec00e7b76bc46cc12723f750185fa84e6d2
82e1912ff69998077a5d7ecca9b5b1f9d7c1b948
refs/heads/master
2021-01-10T01:21:59.902255
2009-02-10T05:24:40
2009-02-10T05:24:40
52,189,505
0
0
null
null
null
null
UTF-8
C++
false
false
11,355
cpp
/* Voxelbrain Project. MRI editing software. This file is (c) 2007,2008 Nanyang Technological University author: Konstantin Levinski description: */ /********************************************************************* * * Very simple code snippets to read/write nifti1 files * This code is placed in the public domain. * * If you are the type who doesn't want to use a file format unless * you can write your own i/o code in less than 30minutes, this * example is for you. * * This code does not deal with wrong-endian data, compressed data, * the new qform/sform orientation codes, parsing filenames, volume- * wise or timecourse-wise data access or any of a million other very useful * things that are in the niftilib i/o reference libraries. * We encourage people to use the niftilib reference library and send * feedback/suggestions, see http://niftilib.sourceforge.net/ * But, if that is too much to tackle and you just want to jump in, this * code is a starting point. * This code was written for maximum readability, not for the greatest * coding style. * * * If you are already a little familiar with reading/writing Analyze * files of some flavor, and maybe even have some of your own code, here * are the most important things to be aware of in transitioning to nifti1: * * 1. nii vs .hdr/.img * nifti1 datasets can be stored either in .hdr/.img pairs of files * or in 1 .nii file. In a .nii file the data will start at the byte * specified by the vox_offset field, which will be 352 if no extensions * have been added. And, nifti1 really does like that magic field set * to "n+1" for .nii and "ni1" for .img/.hdr * * 2. scaling * nifti1 datasets can contain a scaling factor. You need to check the * scl_slope field and if that isn't 0, scale your data by * Y * scl_slope + scl_inter * * 3. extensions * nifti1 datasets can have some "extension data" stuffed after the * regular header. You can just ignore it, but, be aware that a * .hdr file may be longer than 348 bytes, and, in a .nii file * you can't just jump to byte 352, you need to use the vox_offset * field to get the start of the image data. * * 4. new datatypes * nifti1 added a few new datatypes that were not in the Analyze 7.5 * format from which nifti1 is derived. If you're just working with * your own data this is not an issue but if you get a foreign nifti1 * file, be aware of exotic datatypes like DT_COMPLEX256 and mundane * things like DT_UINT16. * * 5. other stuff * nifti1 really does like the dim[0] field set to the number of * dimensions of the dataset. Other Analyze flavors might not * have been so scrupulous about that. * nifti1 has a bunch of other new fields such as intent codes, * qform/sform, etc. but, if you just want to get your hands on * the data blob you can ignore these. Example use of these fields * is in the niftilib reference libraries. * * * * To compile: * You need to put a copy of the nifti1.h header file in this directory. * It can be obtained from the NIFTI homepage http://nifti.nimh.nih.gov/ * or from the niftilib SourceForge site http://niftilib.sourceforge.net/ * * cc -o nifti1_read_write nifti1_read_write.c * * * To run: * nifti1_read_write -w abc.nii abc.nii * nifti1_read_write -r abc.nii abc.nii * * * The read method is hardcoded to read float32 data. To change * to your datatype, just change the line: * typedef float MY_DATATYPE; * * The write method is hardcoded to write float32 data. To change * to your datatype, change the line: * typedef float MY_DATATYPE; * and change the lines: * hdr.datatype = NIFTI_TYPE_FLOAT32; * hdr.bitpix = 32; * * * Written by Kate Fissell, University of Pittsburgh, May 2005. * *********************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "nifti.h" #include "volio.h" typedef short int MY_DATATYPE; #define MIN_HEADER_SIZE 348 #define NII_HEADER_SIZE 352 /********************************************************************** * * read_nifti_file * **********************************************************************/ int raw_volume::read_nifti_file(const char * hdr_file, const char * data_file) { FILE *fp; size_t ret,i; double total; /********** open and read header */ fp = fopen(hdr_file,"rb"); if (fp == NULL) { fprintf(stderr, "\nError opening header file %s\n",hdr_file); exit(1); } ret = fread(&hdr, MIN_HEADER_SIZE, 1, fp); if (ret != 1) { fprintf(stderr, "\nError reading header file %s\n",hdr_file); exit(1); } fclose(fp); /********** print a little header information */ fprintf(stderr, "\n%s header information:",hdr_file); fprintf(stderr, "\nXYZT dimensions: %d %d %d %d",hdr.dim[1],hdr.dim[2],hdr.dim[3],hdr.dim[4]); fprintf(stderr, "\nDatatype code and bits/pixel: %d %d",hdr.datatype,hdr.bitpix); fprintf(stderr, "\nScaling slope and intercept: %.6f %.6f",hdr.scl_slope,hdr.scl_inter); fprintf(stderr, "\nByte offset to data in datafile: %ld",(long)(hdr.vox_offset)); fprintf(stderr, "\n"); /* copying */ dim[0] = hdr.dim[1]; dim[1] = hdr.dim[2]; dim[2] = hdr.dim[3]; /********** open the datafile, jump to data offset */ fp = fopen(data_file,"rb"); if (fp == NULL) { fprintf(stderr, "\nError opening data file %s\n",data_file); exit(1); } ret = fseek(fp, (long)(hdr.vox_offset), SEEK_SET); if (ret != 0) { fprintf(stderr, "\nError doing fseek() to %ld in data file %s\n",(long)(hdr.vox_offset), data_file); exit(1); } /********** allocate buffer and read first 3D volume from data file */ int bpv = hdr.bitpix / 8; //bytes per voxel //raw buffer void * raw_data = malloc(bpv * hdr.dim[1]*hdr.dim[2]*hdr.dim[3]); //allocating the data to be used data = (MY_DATATYPE *) malloc(sizeof(MY_DATATYPE) * hdr.dim[1]*hdr.dim[2]*hdr.dim[3]); if (data == NULL) { fprintf(stderr, "\nError allocating data buffer for %s\n",data_file); exit(1); } ret = fread(raw_data, bpv, hdr.dim[1]*hdr.dim[2]*hdr.dim[3], fp); printf("Read %d out of %d items", ret, hdr.dim[1]*hdr.dim[2]*hdr.dim[3]); if(ret == hdr.dim[1]*hdr.dim[2]*hdr.dim[3]) { for (i=0; i<(unsigned int)hdr.dim[1]*hdr.dim[2]*hdr.dim[3]; i++){ //once again, lousy. switch(bpv){ case 1: data[i] = ((unsigned char *)raw_data)[i]; break; case 2: data[i] = ((unsigned short *)raw_data)[i]; break; case 4: data[i] = ((unsigned int *)raw_data)[i]; break; }; }; } else { fprintf(stderr, "\nError reading volume 1 from %s (%d)\n",data_file,ret); exit(1); } free(raw_data); fclose(fp); /********** scale the data buffer */ if (hdr.scl_slope != 0) { for (i=0; i<(unsigned int)hdr.dim[1]*hdr.dim[2]*hdr.dim[3]; i++) data[i] = (data[i] * hdr.scl_slope) + hdr.scl_inter; } /********** print mean of data */ min = 10000; max = 0; int voxel_count = 0; total = 0; for (i=0; i<(unsigned int)hdr.dim[1]*hdr.dim[2]*hdr.dim[3]; i++){ if(data[i]>0){ total += data[i]; voxel_count++; }; if(data[i] > max)max = data[i]; if(data[i] < min)min = data[i]; }; total /= voxel_count;//(hdr.dim[1]*hdr.dim[2]*hdr.dim[3]); fprintf(stderr, "\nMean of volume 1 in %s is %.3f; max/min %d/%d\n",data_file,total, max , min); return(0); } /********************************************************************** * * write_nifti_file * * write a sample nifti1 (.nii) data file * datatype is float32 * XYZT size is 64x64x16x10 * XYZ voxel size is 1mm * TR is 1500ms * **********************************************************************/ int raw_volume::write_nifti_file(const char * hdr_file, const char * data_file) { //nifti_1_header hdr; //nifti1_extender pad={0,0,0,0}; FILE *fp; int ret,i; //MY_DATATYPE *data=NULL; short do_nii; /********** make sure user specified .hdr/.img or .nii/.nii */ if ( (strlen(hdr_file) < 4) || (strlen(data_file) < 4) ) { fprintf(stderr, "\nError: write files must end with .hdr/.img or .nii/.nii extension\n"); exit(1); } if ( (!strncmp(hdr_file+(strlen(hdr_file)-4), ".hdr",4)) && (!strncmp(data_file+(strlen(data_file)-4), ".img",4)) ) { do_nii = 0; } else if ( (!strncmp(hdr_file+(strlen(hdr_file)-4), ".nii",4)) && (!strncmp(data_file+(strlen(data_file)-4), ".nii",4)) ) { do_nii = 1; } else { fprintf(stderr, "\nError: file(s) to be written must end with .hdr/.img or .nii/.nii extension\n"); exit(1); } /********** fill in the minimal default header fields */ //memset((void *)&hdr, 0, sizeof(hdr)); //zerowing /*hdr.sizeof_hdr = MIN_HEADER_SIZE; hdr.dim[0] = 4; hdr.dim[1] = 64; hdr.dim[2] = 64; hdr.dim[3] = 16; hdr.dim[4] = 10; hdr.datatype = NIFTI_TYPE_FLOAT32; hdr.bitpix = 32; hdr.pixdim[1] = 1.0; hdr.pixdim[2] = 1.0; hdr.pixdim[3] = 1.0; hdr.pixdim[4] = 1.5; if (do_nii) hdr.vox_offset = (float) NII_HEADER_SIZE; else hdr.vox_offset = (float)0; hdr.scl_slope = 100.0; hdr.xyzt_units = NIFTI_UNITS_MM | NIFTI_UNITS_SEC; if (do_nii) strncpy(hdr.magic, "n+1\0", 4); else strncpy(hdr.magic, "ni1\0", 4); data = (MY_DATATYPE *) malloc(sizeof(MY_DATATYPE) * hdr.dim[1]*hdr.dim[2]*hdr.dim[3]*hdr.dim[4]); if (data == NULL) { fprintf(stderr, "\nError allocating data buffer for %s\n",data_file); exit(1); } for (i=0; i<hdr.dim[1]*hdr.dim[2]*hdr.dim[3]*hdr.dim[4]; i++) data[i] = (raw_volume::MY_DATA)(i / hdr.scl_slope); */ /********** write first 348 bytes of header */ fp = fopen(hdr_file,"w"); if (fp == NULL) { fprintf(stderr, "\nError opening header file %s for write\n",hdr_file); exit(1); } ret = fwrite(&hdr, MIN_HEADER_SIZE, 1, fp); if (ret != 1) { fprintf(stderr, "\nError writing header file %s\n",hdr_file); exit(1); } fclose(fp); /* close .hdr file */ int bpv = hdr.bitpix / 8; //bytes per voxel // printf("Trying to do %d bpv\n", bpv); //raw buffer void * raw_data = malloc(bpv * hdr.dim[1]*hdr.dim[2]*hdr.dim[3]); for (i=0; i<(unsigned int)hdr.dim[1]*hdr.dim[2]*hdr.dim[3]; i++){ //once again, lousy. switch(bpv){ case 1: ((unsigned char *)raw_data)[i] = data[i]; break; case 2: ((unsigned short *)raw_data)[i] = data[i]; break; case 4: ((unsigned int *)raw_data)[i] = data[i]; break; }; }; fp = fopen(data_file,"wb"); if (fp == NULL) { fprintf(stderr, "\nError opening data file %s for write\n",data_file); exit(1); } ret = fwrite(raw_data, bpv, hdr.dim[1]*hdr.dim[2]*hdr.dim[3]*hdr.dim[4], fp); printf("written %d itens\n", ret); // if (ret != hdr.dim[1]*hdr.dim[2]*hdr.dim[3]*hdr.dim[4]) { // fprintf(stderr, "\nError writing data to %s\n",data_file); // exit(1); // } free(raw_data); fclose(fp); return(0); };
[ "konstantin.levinski@04f5dad0-e037-0410-8c28-d9c1d3725aa7" ]
[ [ [ 1, 353 ] ] ]
433e45894ae3c56eec2f0127371419fe5fecd97a
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/zombie/nscene/src/nscene/nlodnode_main.cc
f4be959180eb1cd155ce10a713ea3d96a9e8b31f
[]
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
3,576
cc
#include "precompiled/pchnscene.h" //------------------------------------------------------------------------------ // nlodnode_main.cc // (C) 2004 RadonLabs GmbH //------------------------------------------------------------------------------ #include "nscene/nlodnode.h" #include "nscene/nscenegraph.h" #include "gfx2/ngfxserver2.h" nNebulaScriptClass(nLodNode, "ntransformnode"); //------------------------------------------------------------------------------ /** */ nLodNode::nLodNode() : minDistance(-100.0f), maxDistance(100.0f) { this->transformNodeClass = kernelServer->FindClass("ntransformnode"); } //------------------------------------------------------------------------------ /** */ nLodNode::~nLodNode() { // empty } //------------------------------------------------------------------------------ /** Attach to the scene server. FIXME FLOH: NOTE, this method will only be correct if this node and its parent nodes are not animated. */ void nLodNode::Attach(nSceneGraph* sceneGraph, nEntityObject* entityObject) { n_assert(sceneGraph); n_assert(entityObject); if (this->CheckFlags(Active)) { // get camera distance const matrix44& viewer = nGfxServer2::Instance()->GetTransform(nGfxServer2::InvView); // get global render context position const matrix44& transform = sceneGraph->GetModelTransform(); // compute position by stepping up node hierarchy (Argh) /* nTransformNode* tNode = this; while ((tNode = (nTransformNode*) tNode->GetParent()) && tNode->IsA(this->transformNodeClass)) { transform = transform * tNode->GetTransform(); } */ vector3 lodViewer = viewer.pos_component() - transform.pos_component(); float distance = lodViewer.len(); if ((distance > this->minDistance) && (distance < this->maxDistance)) { // get number of child nodes int num = 0; nSceneNode* curChild; for (curChild = (nSceneNode*) this->GetHead(); curChild; curChild = (nSceneNode*) curChild->GetSucc()) { if (curChild->IsA(this->transformNodeClass)) { num++; } } // if there are not enough thresholds, set some default values if (!this->thresholds.Size()) { thresholds.Append(100.0f); } while (this->thresholds.Size() < (num - 1)) { this->thresholds.Append(thresholds[this->thresholds.Size()-1] * 2.0f); } // find the proper child to attach int index = 0; if (this->GetHead()) { nSceneNode* childToAttach = (nSceneNode*) this->GetHead(); for (curChild = (nSceneNode*) childToAttach->GetSucc(); curChild; curChild = (nSceneNode*) curChild->GetSucc(), index++) { if (curChild->IsA(this->transformNodeClass)) { if (distance >= this->thresholds[index]) { childToAttach = curChild; } } } childToAttach->Attach(sceneGraph, entityObject); } } } }
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 107 ] ] ]
5075e11ec2132968d7633c9bcae71cd36c648fcc
12203ea9fe0801d613bbb2159d4f69cab3c84816
/Export/cpp/windows/obj/include/nme/errors/EOFError.h
72130090b5aad6df587caf37a8d4daea9e04b0db
[]
no_license
alecmce/haxe_game_of_life
91b5557132043c6e9526254d17fdd9bcea9c5086
35ceb1565e06d12c89481451a7bedbbce20fa871
refs/heads/master
2016-09-16T00:47:24.032302
2011-10-10T12:38:14
2011-10-10T12:38:14
2,547,793
0
0
null
null
null
null
UTF-8
C++
false
false
895
h
#ifndef INCLUDED_nme_errors_EOFError #define INCLUDED_nme_errors_EOFError #ifndef HXCPP_H #include <hxcpp.h> #endif #include <nme/errors/Error.h> HX_DECLARE_CLASS2(nme,errors,EOFError) HX_DECLARE_CLASS2(nme,errors,Error) namespace nme{ namespace errors{ class EOFError_obj : public ::nme::errors::Error_obj{ public: typedef ::nme::errors::Error_obj super; typedef EOFError_obj OBJ_; EOFError_obj(); Void __construct(); public: static hx::ObjectPtr< EOFError_obj > __new(); static Dynamic __CreateEmpty(); static Dynamic __Create(hx::DynamicArray inArgs); ~EOFError_obj(); HX_DO_RTTI; static void __boot(); static void __register(); void __Mark(HX_MARK_PARAMS); ::String __ToString() const { return HX_CSTRING("EOFError"); } }; } // end namespace nme } // end namespace errors #endif /* INCLUDED_nme_errors_EOFError */
[ [ [ 1, 39 ] ] ]
bcdbbfef528caa0ed59c5dcd9db1574accf87d30
30a1e1c0c95239e5fa248fbb1b4ed41c6fe825ff
/jmail/queue.cpp
8ac2e9be7ec1b2fc9ab433a2d7487ac69f4a4160
[]
no_license
inspirer/history
ed158ef5c04cdf95270821663820cf613b5c8de0
6df0145cd28477b23748b1b50e4264a67441daae
refs/heads/master
2021-01-01T17:22:46.101365
2011-06-12T00:58:37
2011-06-12T00:58:37
1,882,931
1
0
null
null
null
null
UTF-8
C++
false
false
206
cpp
// queue.cpp (CQueue, CCMainFrame) #include "StdAfx.h" CQueue::operator CString() { CString y = node.addr; return y; } context::printqueue() { } context::buildqueue() { }
[ [ [ 1, 21 ] ] ]
b207c5d7e514108bd35e0f878f2ee2b19528fcc2
b08e948c33317a0a67487e497a9afbaf17b0fc4c
/LuaPlus/Tools/RemoteLuaDebugger/FindDlg.cpp
e1a5e50439ff0a3f6ff8d7800e9cdbba61a559c2
[ "MIT" ]
permissive
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
1,600
cpp
// FindDlg.cpp : implementation file // #include "stdafx.h" #include "remoteluadebugger.h" #include "FindDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CFindDlg dialog CFindDlg::CFindDlg(CWnd* pParent /*=NULL*/) : CDialog(CFindDlg::IDD, pParent) { //{{AFX_DATA_INIT(CFindDlg) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT } void CFindDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CFindDlg) DDX_Control(pDX, IDC_FI_STRING, m_findString); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CFindDlg, CDialog) //{{AFX_MSG_MAP(CFindDlg) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CFindDlg message handlers BOOL CFindDlg::OnInitDialog() { CDialog::OnInitDialog(); CDebuggerView* view = theApp.GetDocument()->GetDebuggerView(); m_findString.SetWindowText(view->GetEditor().GetWord()); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CFindDlg::OnOK() { CString findText; m_findString.GetWindowText(findText); CDebuggerView* view = theApp.GetDocument()->GetDebuggerView(); view->SetFindText(findText); view->FindNext(); // CDialog::OnOK(); } void CFindDlg::OnCancel() { // TODO: Add extra cleanup here CDialog::OnCancel(); }
[ "voodoohaust@97c0069c-804f-11de-81da-11cc53ed4329" ]
[ [ [ 1, 72 ] ] ]
29ae6eb99310a933672109ef094a9f4a00c8f89f
4ecb7e18f351ee920a6847c7ebd9010b6a5d34ce
/HD/trunk/HuntingDragon/gametutor/header/CGLPipelineDriver.h
81ac8f0140585bd8c286da87439da9934eafb5d3
[]
no_license
dogtwelve/bkiter08-gameloft-internship-2011
505141ea314c234d99652600db5165a22cf041c3
0efc9f009bf12fe4ed36e1abfeb34f346a8c4198
refs/heads/master
2021-01-10T12:16:51.540936
2011-10-27T13:30:50
2011-10-27T13:30:50
46,549,117
0
0
null
null
null
null
UTF-8
C++
false
false
8,510
h
#ifndef __CGLPIPELINEDRIVER_H__ #define __CGLPIPELINEDRIVER_H__ #include "Header.h" #include "CSingleton.h" #include "SGraphics.h" #include "LoadShader.h" #define EGLPD_DEFAUL_MAX_INDICES 100000 namespace GameTutor { enum EGLPipelineDriverPrimaryType { EGLPD_PRIYTPE_FLOAT = GL_FLOAT, EGLPD_PRIYTPE_UINT = GL_UNSIGNED_INT, }; enum EGLPipelineDriverRenderMode { EGLPD_RENDERMODE_TRIANGLE = GL_TRIANGLES, EGLPD_RENDERMODE_TRIANGLESTRIP = GL_TRIANGLE_STRIP, }; enum EGLPipelineDriverAttribType { EGLPD_ATTRIB_VERTEX, EGLPD_ATTRIB_NORMAL, EGLPD_ATTRIB_COLOR, EGLPD_ATTRIB_TEXCOOR, }; enum EGLPipelineDriverMatrixMode { EGLPD_MATRIXMODE_PROJECTION, EGLPD_ATTRIB_MODELVIEW, }; enum EGLPipelineDriverPixelFormat { EGLPD_PIXFMT_R8G8B8 = GL_RGB, EGLPD_PIXFMT_R8G8B8A8 = GL_RGBA, }; class CGLPipelineDriver:public CSingleton<CGLPipelineDriver> { friend class CSingleton<CGLPipelineDriver>; protected: CGLPipelineDriver(): m_isUseAlpha(false), m_isUse2DTexture(false) { glDisable(GL_BLEND | GL_TEXTURE_2D); //glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); for (int i = 0; i < EGLPD_ATTRIB_TEXCOOR - EGLPD_ATTRIB_VERTEX + 1; i++) { m_isUseAttribPointer[i] = false; } for (int i = 0; i < EGLPD_DEFAUL_MAX_INDICES; i++) { m_iAutoIndices[i] = i; } char* strColorVertexShader = ReadFile("../resources/shader/vColorShader.glsl"); char* strColorFragShader = ReadFile("../resources/shader/fColorShader.glsl"); uShaderProgram = createProgram(strColorVertexShader, strColorFragShader); uVertexHandle = glGetAttribLocation(uShaderProgram, "a_vertices"); uColorHandle = glGetAttribLocation(uShaderProgram, "a_colors"); uTexHandle = glGetAttribLocation(uShaderProgram, "a_uv"); uMVPMatHandle = glGetUniformLocation(uShaderProgram, "u_mvpMatrix"); } public: //----------------------------------------------- // Set Color //----------------------------------------------- template <class T> void SetColor(T alpha, T red, T green, T blue) { if (sizeof(T) == 1) { SetColor<__UINT8>(__UINT8(alpha), __UINT8(red), __UINT8(green), __UINT8(blue)); } else { BREAK("Invalid type"); } } template <> void SetColor<float>(float alpha, float red, float green, float blue) { //glColor4f(red, green, blue, alpha); } template <> void SetColor<__UINT8>(__UINT8 alpha, __UINT8 red, __UINT8 green, __UINT8 blue) { //glColor4f(red/255.0f, green/255.0f, blue/255.0f, alpha/255.0f); } //----------------------------------------------- // Set Blending //----------------------------------------------- void EnableBlending(bool val) { if (val != m_isUseAlpha) { m_isUseAlpha = val; if (m_isUseAlpha) { glEnable (GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } else { glDisable(GL_BLEND); } } } //----------------------------------------------- // Attribute Pointer //----------------------------------------------- void AttributePointer(enum EGLPipelineDriverAttribType attribType, int size, enum EGLPipelineDriverPrimaryType primType, __UINT32 stride, void* pointer) { float *xx = (float*)pointer; switch (attribType) { case EGLPD_ATTRIB_VERTEX: glVertexAttribPointer(uVertexHandle, size, __INT32(primType), GL_FALSE, stride, pointer); break; case EGLPD_ATTRIB_NORMAL: //[TODO]: implement normal attribute pointer break; case EGLPD_ATTRIB_COLOR: glVertexAttribPointer(uColorHandle, size, __INT32(primType), GL_FALSE, stride, pointer); break; case EGLPD_ATTRIB_TEXCOOR: glVertexAttribPointer(uTexHandle, size, __INT32(primType), GL_FALSE, stride, pointer); break; } } void UniformMatrix(float* matrix) { glUniformMatrix4fv(uMVPMatHandle, 1, GL_FALSE, matrix); } //----------------------------------------------- // Enable client state (enable/disable attrib pointer) //----------------------------------------------- void EnableAttribPointer(enum EGLPipelineDriverAttribType attribType, bool isUse) { if (isUse) { if (!m_isUseAttribPointer[attribType]) { m_isUseAttribPointer[attribType] = true; switch(attribType) { case EGLPD_ATTRIB_VERTEX: glEnableVertexAttribArray(uVertexHandle); break; case EGLPD_ATTRIB_COLOR: glEnableVertexAttribArray(uColorHandle); break; case EGLPD_ATTRIB_TEXCOOR: glEnableVertexAttribArray(uTexHandle); break; } } } else { if (m_isUseAttribPointer[attribType]) { m_isUseAttribPointer[attribType] = false; switch(attribType) { case EGLPD_ATTRIB_VERTEX: glDisableVertexAttribArray(uVertexHandle); break; case EGLPD_ATTRIB_COLOR: glDisableVertexAttribArray(uColorHandle); break; case EGLPD_ATTRIB_TEXCOOR: glDisableVertexAttribArray(uTexHandle); break; } } } } //----------------------------------------------- // Draw Array //----------------------------------------------- void DrawElements(enum EGLPipelineDriverRenderMode mode, __UINT32 numOfIndices, enum EGLPipelineDriverPrimaryType primType, void *indices) { glUseProgram(uShaderProgram); if (!indices) { indices = m_iAutoIndices; primType = EGLPD_PRIYTPE_UINT; } BREAK_IF(numOfIndices > EGLPD_DEFAUL_MAX_INDICES, "numOfIndices is bigger than EGLPD_DEFAUL_MAX_INDICES"); glDrawElements(mode, numOfIndices, primType, indices); } void DrawElements(enum EGLPipelineDriverRenderMode mode, __UINT32 numOfIndices) { DrawElements(mode, numOfIndices, EGLPD_PRIYTPE_UINT, 0); }; //----------------------------------------------- // Clear Screen //----------------------------------------------- void Clear(SColor<float> c) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClearColor(c.Red, c.Green, c.Blue, c.Alpha); } //----------------------------------------------- // Set view port //----------------------------------------------- void Viewport(SRect<__INT32> rect) { glViewport(rect.X, rect.Y, rect.W, rect.H); } //----------------------------------------------- // Othor //----------------------------------------------- void Ortho(float left, float right, float top, float bottom, float znear, float zfar) { //glOrtho(left, right, bottom, top, znear, zfar); } void LoadIdentity(enum EGLPipelineDriverMatrixMode mode) { /*EnableMatrixMode(mode); glLoadIdentity();*/ } //----------------------------------------------- // Texture //----------------------------------------------- void EnableTexture2D(bool val) { if (val != m_isUse2DTexture) { m_isUse2DTexture = val; if (m_isUse2DTexture) { glEnable (GL_TEXTURE_2D); } else { glDisable(GL_TEXTURE_2D); } } } __UINT32 AddTexure2D(int level, EGLPipelineDriverPixelFormat format, int width, int height, int border, __UINT8 *pixel) { EnableTexture2D(true); __UINT32 texname = 0; glGenTextures(1, &texname); glBindTexture(GL_TEXTURE_2D, texname); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);//GL_LINEAR glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);//GL_LINEAR glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexImage2D(GL_TEXTURE_2D, level, format, width, height, border, format, GL_UNSIGNED_BYTE, pixel); return texname; } void BindTexture2D(__UINT32 texname) { glBindTexture(GL_TEXTURE_2D, texname); } void FreeTexture2D(__UINT32 texname) { glDeleteTextures(1, &texname ); } private: bool m_isUseAttribPointer[EGLPD_ATTRIB_TEXCOOR - EGLPD_ATTRIB_VERTEX + 1]; __UINT32 m_iAttribMapping[EGLPD_ATTRIB_TEXCOOR - EGLPD_ATTRIB_VERTEX + 1]; __UINT32 m_iAutoIndices[EGLPD_DEFAUL_MAX_INDICES]; bool m_isUseAlpha; bool m_isUse2DTexture; // shader programs GLuint uShaderProgram; GLuint uVertexHandle; GLuint uColorHandle; GLuint uTexHandle; GLuint uMVPMatHandle; }; } #endif
[ [ [ 1, 312 ] ] ]
948b0d122ca9b443d50f101d5fe172a1fbe1fafa
6c8c4728e608a4badd88de181910a294be56953a
/Core/MemoryLeakCheck.h
d01caabbe852607b52afd7414270eb1ef3ad3765
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
caocao/naali
29c544e121703221fe9c90b5c20b3480442875ef
67c5aa85fa357f7aae9869215f840af4b0e58897
refs/heads/master
2021-01-21T00:25:27.447991
2010-03-22T15:04:19
2010-03-22T15:04:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,814
h
/** @file MemoryLeakCheck.h For conditions of distribution and use, see copyright notice in license.txt @brief Debug functionality for tracking memory leaks on the Win32 platform. Include this file in a .cpp file to enable C++ operator new to route to log-enabled debug version of malloc. The best method is to include this after all other includes in a .cpp file (or preferably right before including any template/allocating .inl's in the file) Do not include this in any .h files. The reason why this is not included globally is that it wouldn't compile. It relies on a really dirty hack of redefining operator new. Know that it cannot necessarily track all the invokations of new, due to scope issues. After getting the list of leaks when you close the application, look for entries saying "client block" */ #ifndef incl_Core_MemoryLeakCheck_h #define incl_Core_MemoryLeakCheck_h #if defined(_MSC_VER) && defined(_DEBUG) && defined(MEMORY_LEAK_CHECK) #include <new> #define _CRTDBG_MAP_ALLOC #ifdef new #undef new #endif // For the difference between _NORMAL_BLOCK and _CLIENT_BLOCK, see DebugOperatorNew.h __forceinline void *operator new(std::size_t size, const char *file, int line) { return _malloc_dbg(size, _NORMAL_BLOCK, file, line); } __forceinline void *operator new[](std::size_t size, const char *file, int line) { return _malloc_dbg(size, _NORMAL_BLOCK, file, line); } __forceinline void operator delete(void *ptr, const char *, int) { _free_dbg(ptr, _NORMAL_BLOCK); } __forceinline void operator delete[](void *ptr, const char *, int) { _free_dbg(ptr, _NORMAL_BLOCK); } #define new new (__FILE__, __LINE__) #endif // ~_MSC_VER #endif // ~incl_Core_MemoryLeakCheck_h
[ "jjj@5b2332b8-efa3-11de-8684-7d64432d61a3", "jujjyl@5b2332b8-efa3-11de-8684-7d64432d61a3" ]
[ [ [ 1, 18 ], [ 20, 28 ], [ 31, 32 ], [ 34, 37 ], [ 39, 42 ], [ 44, 47 ], [ 49, 55 ] ], [ [ 19, 19 ], [ 29, 30 ], [ 33, 33 ], [ 38, 38 ], [ 43, 43 ], [ 48, 48 ] ] ]
88c0c3b0d1425c20607be130d4be526846eadd33
93176e72508a8b04769ee55bece71095d814ec38
/Utilities/BGL/boost/random/ranlux.hpp
7334551d0b11dd85bde395d354a0a717628b958e
[]
no_license
inglada/OTB
a0171a19be1428c0f3654c48fe5c35442934cf13
8b6d8a7df9d54c2b13189e00ba8fcb070e78e916
refs/heads/master
2021-01-19T09:23:47.919676
2011-06-29T17:29:21
2011-06-29T17:29:21
1,982,100
4
5
null
null
null
null
UTF-8
C++
false
false
1,813
hpp
/* boost random/ranlux.hpp header file * * Copyright Jens Maurer 2002 * 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) * * See http://www.boost.org for most recent version including documentation. * * $Id: ranlux.hpp 24096 2004-07-27 03:43:34Z dgregor $ * * Revision history * 2001-02-18 created */ #ifndef BOOST_RANDOM_RANLUX_HPP #define BOOST_RANDOM_RANLUX_HPP #include <boost/config.hpp> #include <boost/random/subtract_with_carry.hpp> #include <boost/random/discard_block.hpp> namespace boost { namespace random { typedef subtract_with_carry<int, (1<<24), 10, 24, 0> ranlux_base; typedef subtract_with_carry_01<float, 24, 10, 24> ranlux_base_01; typedef subtract_with_carry_01<double, 48, 10, 24> ranlux64_base_01; } typedef random::discard_block<random::ranlux_base, 223, 24> ranlux3; typedef random::discard_block<random::ranlux_base, 389, 24> ranlux4; typedef random::discard_block<random::ranlux_base_01, 223, 24> ranlux3_01; typedef random::discard_block<random::ranlux_base_01, 389, 24> ranlux4_01; typedef random::discard_block<random::ranlux64_base_01, 223, 24> ranlux64_3_01; typedef random::discard_block<random::ranlux64_base_01, 389, 24> ranlux64_4_01; #if !defined(BOOST_NO_INT64_T) && !defined(BOOST_NO_INTEGRAL_INT64_T) namespace random { typedef random::subtract_with_carry<int64_t, (int64_t(1)<<48), 10, 24, 0> ranlux64_base; } typedef random::discard_block<random::ranlux64_base, 223, 24> ranlux64_3; typedef random::discard_block<random::ranlux64_base, 389, 24> ranlux64_4; #endif /* !BOOST_NO_INT64_T && !BOOST_NO_INTEGRAL_INT64_T */ } // namespace boost #endif // BOOST_RANDOM_LINEAR_CONGRUENTIAL_HPP
[ [ [ 1, 50 ] ] ]
433ad1546de42e7d0eadebcde72366f338be32e6
6dac9369d44799e368d866638433fbd17873dcf7
/src/branches/26042005/sound/fmod/FMODModuleBuffer.cpp
b14c74271ad5a5fa10ea90211501054991732f78
[]
no_license
christhomas/fusionengine
286b33f2c6a7df785398ffbe7eea1c367e512b8d
95422685027bb19986ba64c612049faa5899690e
refs/heads/master
2020-04-05T22:52:07.491706
2006-10-24T11:21:28
2006-10-24T11:21:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,861
cpp
#include <FMODModuleBuffer.h> /** FMOD ModuleBuffer Constructor */ FMODModuleBuffer::FMODModuleBuffer() { m_module = NULL; } /** FMOD ModuleBuffer Deconstructor * * Operation: * -# Stop the module playing * -# Close the module */ FMODModuleBuffer::~FMODModuleBuffer() { Stop(); Close(); } /** Load a Tracker Module * * @param filename The name of the tracker module file * * @returns boolean true or false, depending on whether the module loaded or not */ bool FMODModuleBuffer::Load(char *filename) { if((m_module = FMUSIC_LoadSong(filename)) != NULL) { return true; }else{ return false; } } /** Closes a Tracker Module * * @returns boolean true or false, in this case, true only since you ignore any error condition */ bool FMODModuleBuffer::Close(void) { FMUSIC_FreeSong(m_module); return true; } /** Plays a Tracker Module * * @returns The channel id that the tracker module is playing on */ int FMODModuleBuffer::Play(void) { m_channel = FMUSIC_PlaySong(m_module); return m_channel; } /** Pauses a tracker module * * @param pause Whether to pause the module or not * * @returns If the module paused, return true, otherwise false */ bool FMODModuleBuffer::Pause(bool pause) { if(FMUSIC_SetPaused(m_module,pause) == 1) return true; return false; } /** Stop the tracker module * * @returns boolean true or false, depending on whether the module stopped successfully or not */ bool FMODModuleBuffer::Stop(void) { if(FMUSIC_StopSong(m_module) == 1) return true; return false; } /** Sets the play position of the module * * @param position The position to set the module to start at * * @returns boolean true or false, depending on whether it was set successfully or not * * NOTE: This method is not implemented yet, as Fusion has no need to set the position of a track as yet * So it is impossible to know whether this method will set the start position in bytes or seconds, or minutes, or hours, or whatever */ bool FMODModuleBuffer::SetPosition(int position) { return false; } /** Sets the Volume of the module to play at * * @param volume The volume to set the tracker module to play at * * @returns boolean true or false, depending on whether setting the volume was successful or not * * The valid range of values for the volume is 0 to 255, silent, to max volume respectively */ bool FMODModuleBuffer::Volume(unsigned char volume) { if(FSOUND_SetVolume(m_channel,volume) == 1) return true; return false; } /** Tests whether the module is playing or not * * @returns boolean true or false, depending on whether the module is playing or not */ bool FMODModuleBuffer::IsPlaying(void) { if(FMUSIC_IsPlaying(m_module) == 1) return true; return false; }
[ "chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7" ]
[ [ [ 1, 121 ] ] ]
4f9bf66f5f23b03978d65e15e7b9b74f54e3a263
3da0b0276bc8c3d7d1bcdbabfb0e763a38d3a24c
/zju.finished/1285.cpp
a5abf84659633f38042308d52e69bddd6e4a02f4
[]
no_license
usherfu/zoj
4af6de9798bcb0ffa9dbb7f773b903f630e06617
8bb41d209b54292d6f596c5be55babd781610a52
refs/heads/master
2021-05-28T11:21:55.965737
2009-12-15T07:58:33
2009-12-15T07:58:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,695
cpp
#include<iostream> #include<string> #include<map> using namespace std; enum { SIZ = 32, }; int num, con, req; unsigned dis[SIZ][SIZ]; map<string, int> ship; char buf[10]; string s; void fun(){ int cnt,a,b,i; for(i=0; i<num; i++){ for(a=0; a<num; a++){ if(dis[a][i]==-1u) continue; for(b=0; b<num; b++){ if(b==a||dis[i][b]==-1u) continue; if(dis[a][b] > dis[a][i] + dis[i][b]){ dis[a][b] = dis[a][i] + dis[i][b]; } } } } printf("\n"); while(req--){ scanf("%d",&cnt); scanf("%s", buf); s = buf; a = ship[s]; scanf("%s", buf); s = buf; b = ship[s]; if(dis[a][b] == -1u){ printf("NO SHIPMENT POSSIBLE\n"); } else { cnt *= dis[a][b]; cnt *= 100; printf("$%d\n", cnt); } } } void readIn(){ int i,a,b; scanf("%d%d%d",&num, &con, &req); ship.clear(); memset(dis, -1, sizeof(dis)); for(i=0; i<num; i++){ scanf("%s", buf); s = buf; ship.insert(make_pair(s, i)); } for(i=0; i<con; i++){ scanf("%s", buf); s = buf; a = ship[s]; scanf("%s", buf); s = buf; b = ship[s]; dis[a][b] = dis[b][a] = 1; } } int main(){ int tst = 1, tstnum; printf("SHIPPING ROUTES OUTPUT\n\n"); scanf("%d", &tstnum); while(tstnum--){ readIn(); printf("DATA SET %d\n", tst++); fun(); printf("\n"); } printf("END OF OUTPUT\n"); return 0; }
[ [ [ 1, 75 ] ] ]
ab321d272325f25bc62b8df9adfde5cacac178a9
8ddac2310fb59dfbfb9b19963e3e2f54e063c1a8
/Logiciel_PC/WishBoneMonitor/wbwriteregisterview.h
8ea0638d4bf58b13a27ae2c2c9a6950ed7bd9072
[]
no_license
Julien1138/WishBoneMonitor
75efb53585acf4fd63e75fb1ea967004e6caa870
3062132ecd32cd0ffdd89e8a56711ae9a93a3c48
refs/heads/master
2021-01-12T08:25:34.115470
2011-05-02T16:35:54
2011-05-02T16:35:54
76,573,671
0
0
null
null
null
null
UTF-8
C++
false
false
724
h
#ifndef WBWRITEREGISTERVIEW_H #define WBWRITEREGISTERVIEW_H #include "WishBoneWidgetView.h" #include "WBWriteRegisterDoc.h" #include "WBWriteRegisterDlg.h" #include <QLineEdit> #include <QLabel> #include <QPushButton> class WBWriteRegisterView : public WishBoneWidgetView { Q_OBJECT public: WBWriteRegisterView(WBWriteRegisterDoc* pDoc, WBWriteRegisterDlg* pDlg, QWidget *parent = 0); signals: public slots: void ModeChanged(); void WriteRegister(); void Refresh(); private: QLineEdit m_EditValue; QLabel m_LabelUnit; QPushButton* m_pSetButton; void UpdateWidget(); }; #endif // WBWRITEREGISTERVIEW_H
[ [ [ 1, 34 ] ] ]
44f88bcf3bfda8c68790388ede1dd023c010ef43
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/nGENE Proj/AutoPointer.h
3e39da1c19bb9d2061457fed276299c44c968014
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
5,742
h
/* --------------------------------------------------------------------------- This source file is part of nGENE Tech. Copyright (c) 2006- Wojciech Toman This program is free software. File: AutoPointer.h Version: 0.53 --------------------------------------------------------------------------- */ #pragma once #ifndef __INC_AUTOPOINTER_H_ #define __INC_AUTOPOINTER_H_ #include "HashTable.h" #include "Prerequisities.h" namespace nGENE { /** AutoPointer is implementation of a smart pointer with reference counting. @remarks Try to use this class instead of regular pointers as often as possible as it offers safer pointer usage - you do not need to worry about releasing memory as it will be automatically freed on destuction. It is possible due to the fact AutoPointer is created on the stack, whereas regular pointers are created on the heap. */ template <typename T> class AutoPointer { private: T* m_pPtr; static HashTable <T*, uint> s_RefCounter; /// Releases pointer. void finalizePointer(); /// Initializes pointer void initPointer(T* ptr); public: AutoPointer(T* ptr); AutoPointer(); AutoPointer(const AutoPointer<T>& src); AutoPointer<T>& operator=(const AutoPointer<T>& rhs); AutoPointer<T>& operator=(T* rhs); virtual ~AutoPointer(); operator T*() const; const T& operator*() const; const T* operator->() const; bool operator==(const AutoPointer<T>& rhs); bool operator!=(const AutoPointer<T>& rhs); bool operator==(T* rhs); bool operator!=(T* rhs); T& operator*(); T* operator->(); void setPointer(T* ptr); T* getPointer() const {return m_pPtr;} T& getRef() const {return *m_pPtr;} }; template <typename T> HashTable <T*, uint> AutoPointer <T>::s_RefCounter; template <typename T> AutoPointer <T>::AutoPointer(): m_pPtr(NULL) { } //---------------------------------------------------------------------- template <typename T> AutoPointer <T>::AutoPointer(T* ptr) { initPointer(ptr); } //---------------------------------------------------------------------- template <typename T> AutoPointer <T>::AutoPointer(const AutoPointer<T>& src) { initPointer(src.m_pPtr); } //---------------------------------------------------------------------- template <typename T> AutoPointer <T>& AutoPointer <T>::operator=(const AutoPointer <T>& rhs) { if(this == &rhs) return (*this); finalizePointer(); initPointer(rhs.m_pPtr); return (*this); } //---------------------------------------------------------------------- template <typename T> AutoPointer<T>& AutoPointer <T>::operator=(T* rhs) { if(m_pPtr == rhs) return (*this); if(rhs) { if(m_pPtr) finalizePointer(); initPointer(rhs); } else finalizePointer(); return (*this); } //---------------------------------------------------------------------- template <typename T> AutoPointer <T>::~AutoPointer() { finalizePointer(); } //---------------------------------------------------------------------- template <typename T> void AutoPointer <T>::setPointer(T* ptr) { if(m_pPtr == ptr) return; if(ptr) { if(m_pPtr) finalizePointer(); initPointer(ptr); } else finalizePointer(); } //---------------------------------------------------------------------- template <typename T> void AutoPointer <T>::initPointer(T* ptr) { m_pPtr = ptr; if(s_RefCounter.find(m_pPtr) == s_RefCounter.end()) s_RefCounter[m_pPtr] = 1; else ++s_RefCounter[m_pPtr]; } //---------------------------------------------------------------------- template <typename T> void AutoPointer <T>::finalizePointer() { if(s_RefCounter.find(m_pPtr) == s_RefCounter.end()) return; --s_RefCounter[m_pPtr]; if(!s_RefCounter[m_pPtr]) { // No more references, so pointer can be safely deleted s_RefCounter.erase(m_pPtr); NGENE_DELETE(m_pPtr); } } //---------------------------------------------------------------------- template <typename T> const T* AutoPointer <T>::operator->() const { return (m_pPtr); } //---------------------------------------------------------------------- template <typename T> AutoPointer <T>::operator T*() const { return (m_pPtr); } //---------------------------------------------------------------------- template <typename T> const T& AutoPointer <T>::operator*() const { return (*m_pPtr); } //---------------------------------------------------------------------- template <typename T> T* AutoPointer <T>::operator->() { return (m_pPtr); } //---------------------------------------------------------------------- template <typename T> T& AutoPointer <T>::operator*() { return (*m_pPtr); } //---------------------------------------------------------------------- template <typename T> bool AutoPointer <T>::operator==(T* rhs) { return (m_pPtr == rhs); } //---------------------------------------------------------------------- template <typename T> bool AutoPointer <T>::operator!=(T* rhs) { return (m_pPtr != rhs); } //---------------------------------------------------------------------- template <typename T> bool AutoPointer <T>::operator==(const AutoPointer<T>& rhs) { return (m_pPtr == rhs.m_pPtr); } //---------------------------------------------------------------------- template <typename T> bool AutoPointer <T>::operator!=(const AutoPointer<T>& rhs) { return (m_pPtr != rhs.m_pPtr); } //---------------------------------------------------------------------- } #endif
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 229 ] ] ]
703c945f168105dd8962d53e6c15661e36c9bfb1
eb8a27a2cc7307f0bc9596faa4aa4a716676c5c5
/WinEditionWithJRE/browser-lcc/jscc/src/v8/v8/src/x64/cpu-x64.cc
69d2734f369eb2f19f8a980d618de4eca92340c0
[ "BSD-3-Clause", "bzip2-1.0.6", "Artistic-1.0", "LicenseRef-scancode-public-domain", "Artistic-2.0" ]
permissive
baxtree/OKBuzzer
c46c7f271a26be13adcf874d77a7a6762a8dc6be
a16e2baad145f5c65052cdc7c767e78cdfee1181
refs/heads/master
2021-01-02T22:17:34.168564
2011-06-15T02:29:56
2011-06-15T02:29:56
1,790,181
0
0
null
null
null
null
UTF-8
C++
false
false
3,312
cc
// Copyright 2011 the V8 project authors. 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 Google 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. // CPU specific code for x64 independent of OS goes here. #ifdef __GNUC__ #include "third_party/valgrind/valgrind.h" #endif #include "v8.h" #if defined(V8_TARGET_ARCH_X64) #include "cpu.h" #include "macro-assembler.h" namespace v8 { namespace internal { void CPU::Setup() { CpuFeatures::Probe(); } bool CPU::SupportsCrankshaft() { return true; // Yay! } void CPU::FlushICache(void* start, size_t size) { // No need to flush the instruction cache on Intel. On Intel instruction // cache flushing is only necessary when multiple cores running the same // code simultaneously. V8 (and JavaScript) is single threaded and when code // is patched on an intel CPU the core performing the patching will have its // own instruction cache updated automatically. // If flushing of the instruction cache becomes necessary Windows has the // API function FlushInstructionCache. // By default, valgrind only checks the stack for writes that might need to // invalidate already cached translated code. This leads to random // instability when code patches or moves are sometimes unnoticed. One // solution is to run valgrind with --smc-check=all, but this comes at a big // performance cost. We can notify valgrind to invalidate its cache. #ifdef VALGRIND_DISCARD_TRANSLATIONS VALGRIND_DISCARD_TRANSLATIONS(start, size); #endif } void CPU::DebugBreak() { #ifdef _MSC_VER // To avoid Visual Studio runtime support the following code can be used // instead // __asm { int 3 } __debugbreak(); #else asm("int $3"); #endif } } } // namespace v8::internal #endif // V8_TARGET_ARCH_X64
[ [ [ 1, 88 ] ] ]
c758ee518ea25f6fc171af22018f5923498245fa
733e2fcb8d0ed5be1217f67ce6d39ce53d134b58
/yelpcurl.cpp
5fb810225708a0d892649babafa627f6ea43ad15
[]
no_license
swatkat/yelpcurl
2126f9cf4d95dc8ae9e745349455d2a511cf998c
aa2b4824eab1ee8d5230919531431020506c3253
refs/heads/master
2016-08-05T03:08:20.420918
2010-04-04T12:47:17
2010-04-04T12:47:17
32,263,047
0
0
null
null
null
null
UTF-8
C++
false
false
24,312
cpp
#include "yelpcurl.h" /*++ * @method: yelpCurl::yelpCurl * * @description: constructor * * @input: none * * @output: none * *--*/ yelpCurl::yelpCurl(): m_curlHandle( NULL ), m_curlProxyParamsSet( false ), m_curlCallbackParamsSet( false ), m_proxyServerIp( "" ), m_proxyServerPort( "" ), m_proxyUserName( "" ), m_proxyPassword( "" ), m_yelpWebSvcId( "" ) { /* Clear error buffer */ clearCurlCallbackBuffers(); /* Initialize cURL */ m_curlHandle = curl_easy_init(); if( !isCurlInit() ) { std::string dummyStr( "" ); getLastCurlError( dummyStr ); } } /*++ * @method: yelpCurl::~yelpCurl * * @description: destructor * * @input: none * * @output: none * *--*/ yelpCurl::~yelpCurl() { /* Cleanup cURL */ if( isCurlInit() ) { curl_easy_cleanup( m_curlHandle ); m_curlHandle = NULL; } } /*++ * @method: yelpCurl::isCurlInit * * @description: method to check if cURL is initialized properly * * @input: none * * @output: true if cURL is intialized, otherwise false * *--*/ bool yelpCurl::isCurlInit() { return ( NULL != m_curlHandle ) ? true : false; } /*++ * @method: yelpCurl::clearCurlCallbackBuffers * * @description: method to clear callback buffers used by cURL. this is an * internal method and yelpCurl users need not use this. * * @input: none * * @output: none * * @remarks: internal method * *--*/ void yelpCurl::clearCurlCallbackBuffers() { m_callbackData = ""; memset( m_errorBuffer, 0, yelpCurlDefaults::YELPCURL_DEFAULT_BUFFSIZE ); } /*++ * @method: yelpCurl::getLastCurlError * * @description: method to get cURL error response for most recent http request. * yelpCurl users can call this method if any of the Yelp API methods * return false. * * @input: outErrResp - string in which cURL's response is supplied back to caller * * @output: none * *--*/ void yelpCurl::getLastCurlError( std::string& outErrResp ) { m_errorBuffer[yelpCurlDefaults::YELPCURL_DEFAULT_BUFFSIZE-1] = yelpCurlDefaults::YELPCURL_EOS; outErrResp.assign( m_errorBuffer ); } /*++ * @method: yelpCurl::getLastWebResponse * * @description: method to get Yelp's http response for the most recent request. * yelpCurl users need to call this method and parse the JSON * data returned by Yelp to see what has happened. * * @input: outWebResp - string in which Yelp's response is supplied back to caller * * @output: none * *--*/ void yelpCurl::getLastWebResponse( std::string& outWebResp ) { if( m_callbackData.length() ) { outWebResp = m_callbackData; } } /*++ * @method: yelpCurl::getProxyServerIp * * @description: method to get proxy server IP address * * @input: none * * @output: proxy server IP address * *--*/ std::string& yelpCurl::getProxyServerIp() { return m_proxyServerIp; } /*++ * @method: yelpCurl::getProxyServerPort * * @description: method to get proxy server port * * @input: none * * @output: proxy server port * *--*/ std::string& yelpCurl::getProxyServerPort() { return m_proxyServerPort; } /*++ * @method: yelpCurl::getProxyUserName * * @description: method to get proxy user name * * @input: none * * @output: proxy server user name * *--*/ std::string& yelpCurl::getProxyUserName() { return m_proxyUserName; } /*++ * @method: yelpCurl::getProxyPassword * * @description: method to get proxy server password * * @input: none * * @output: proxy server password * *--*/ std::string& yelpCurl::getProxyPassword() { return m_proxyPassword; } /*++ * @method: yelpCurl::setProxyServerIp * * @description: method to set proxy server IP address * * @input: proxyServerIp * * @output: none * *--*/ void yelpCurl::setProxyServerIp( std::string& proxyServerIp ) { if( proxyServerIp.length() ) { m_proxyServerIp = proxyServerIp; /* * Reset the flag so that next cURL http request * would set proxy details again into cURL. */ m_curlProxyParamsSet = false; } } /*++ * @method: yelpCurl::setProxyServerPort * * @description: method to set proxy server port * * @input: proxyServerPort * * @output: none * *--*/ void yelpCurl::setProxyServerPort( std::string& proxyServerPort ) { if( proxyServerPort.length() ) { m_proxyServerPort = proxyServerPort; /* * Reset the flag so that next cURL http request * would set proxy details again into cURL. */ m_curlProxyParamsSet = false; } } /*++ * @method: yelpCurl::setProxyUserName * * @description: method to set proxy server username * * @input: proxyUserName * * @output: none * *--*/ void yelpCurl::setProxyUserName( std::string& proxyUserName ) { if( proxyUserName.length() ) { m_proxyUserName = proxyUserName; /* * Reset the flag so that next cURL http request * would set proxy details again into cURL. */ m_curlProxyParamsSet = false; } } /*++ * @method: yelpCurl::setProxyPassword * * @description: method to set proxy server password * * @input: proxyPassword * * @output: none * *--*/ void yelpCurl::setProxyPassword( std::string& proxyPassword ) { if( proxyPassword.length() ) { m_proxyPassword = proxyPassword; /* * Reset the flag so that next cURL http request * would set proxy details again into cURL. */ m_curlProxyParamsSet = false; } } /*++ * @method: yelpCurl::prepareCurlProxy * * @description: method to set proxy details into cURL. this is an internal method. * yelpCurl users should not use this method, instead use setProxyXxx * methods to set proxy server information. * * @input: none * * @output: none * * @remarks: internal method * *--*/ void yelpCurl::prepareCurlProxy() { if( !m_curlProxyParamsSet && m_proxyUserName.length() && m_proxyPassword.length() ) { /* Reset existing proxy details in cURL */ curl_easy_setopt( m_curlHandle, CURLOPT_PROXY, NULL ); curl_easy_setopt( m_curlHandle, CURLOPT_PROXYUSERPWD, NULL ); /* Prepare username and password for proxy server */ std::string proxyIpPort( "" ); std::string proxyUserPass( "" ); utilMakeCurlParams( proxyUserPass, getProxyUserName(), getProxyPassword() ); utilMakeCurlParams( proxyIpPort, getProxyServerIp(), getProxyServerPort() ); /* Set proxy details in cURL */ curl_easy_setopt( m_curlHandle, CURLOPT_PROXY, proxyIpPort.c_str() ); curl_easy_setopt( m_curlHandle, CURLOPT_PROXYUSERPWD, proxyUserPass.c_str() ); curl_easy_setopt( m_curlHandle, CURLOPT_PROXYAUTH, (long)CURLAUTH_ANY ); /* Set the flag to true indicating that proxy info is set in cURL */ m_curlProxyParamsSet = true; } } /*++ * @method: yelpCurl::prepareCurlCallback * * @description: method to set callback details into cURL. this is an internal method. * yelpCurl users should not use this method. * * @input: none * * @output: none * * @remarks: internal method * *--*/ void yelpCurl::prepareCurlCallback() { if( !m_curlCallbackParamsSet ) { /* Set buffer to get error */ curl_easy_setopt( m_curlHandle, CURLOPT_ERRORBUFFER, m_errorBuffer ); /* Set callback function to get response */ curl_easy_setopt( m_curlHandle, CURLOPT_WRITEFUNCTION, curlCallback ); curl_easy_setopt( m_curlHandle, CURLOPT_WRITEDATA, this ); /* Set the flag to true indicating that callback info is set in cURL */ m_curlCallbackParamsSet = true; } } /*++ * @method: yelpCurl::prepareStandardParams * * @description: method to set standard params into cURL. this is an internal method. * yelpCurl users should not use this method. * * @input: none * * @output: none * * @remarks: internal method * *--*/ void yelpCurl::prepareStandardParams() { /* Clear callback and error buffers */ clearCurlCallbackBuffers(); /* Prepare proxy */ prepareCurlProxy(); /* Prepare cURL callback data and error buffer */ prepareCurlCallback(); } /*++ * @method: yelpCurl::curlCallback * * @description: static method to get http response back from cURL. * this is an internal method, users of yelpCurl need not * use this. * * @input: as per cURL convention. * * @output: size of data stored in our buffer * * @remarks: internal method * *--*/ int yelpCurl::curlCallback( char* data, size_t size, size_t nmemb, yelpCurl* pYelpCurlObj ) { int writtenSize = 0; if( ( NULL != pYelpCurlObj ) && ( NULL != data ) ) { /* Save http response in yelpCurl object's buffer */ writtenSize = pYelpCurlObj->saveLastWebResponse( data, ( size*nmemb ) ); } return writtenSize; } /*++ * @method: yelpCurl::saveLastWebResponse * * @description: method to save http responses. this is an internal method * and yelpCurl users need not use this. * * @input: data - character buffer from cURL, * size - size of character buffer * * @output: size of data stored in our buffer * * @remaks: internal method * *--*/ int yelpCurl::saveLastWebResponse( char*& data, size_t size ) { int bytesWritten = 0; if( data && size ) { /* Append data in our internal buffer */ m_callbackData.append( data, size ); bytesWritten = (int)size; } return bytesWritten; } /*++ * @method: yelpCurl::performGet * * @description: method to send http GET request. this is an internal method. * yelpCurl users should not use this method. * * @input: getUrl - Yelp query URL * * @output: none * * @remarks: internal method * *--*/ bool yelpCurl::performGet( const std::string& getUrl ) { /* Prepare cURL params */ prepareStandardParams(); /* Set http request and url */ curl_easy_setopt( m_curlHandle, CURLOPT_HTTPGET, 1 ); curl_easy_setopt( m_curlHandle, CURLOPT_URL, getUrl.c_str() ); /* Send http request */ if( CURLE_OK == curl_easy_perform( m_curlHandle ) ) { return true; } return false; } /*++ * @method: yelpCurl::getYelpWebServiceId * * @description: method to get Yelp web service id * * @input: none * * @output: Yelp web service id * *--*/ std::string& yelpCurl::getYelpWebServiceId() { return m_yelpWebSvcId; } /*++ * @method: yelpCurl::setYelpWebServiceId * * @description: method to set Yelp web service id * * @input: Yelp web service id * * @output: none * *--*/ void yelpCurl::setYelpWebServiceId( std::string& yelpWebSvcId ) { if( yelpWebSvcId.length() ) { m_yelpWebSvcId = yelpWebSvcId; } } /*++ * @method: yelpCurl::reviewSearchByMapBoundingBox * * @description: method to do review search by map bounding box. * * @input: searchTerm - Search term (ex: "coffee") * searchParams - Search params. Only following members of yelpGenericParams * struct are needed to contain valid values: * yelpGenericParams::tl_lat, * yelpGenericParams::tl_long, * yelpGenericParams::br_lat, * yelpGenericParams::br_long, * yelpGenericParams::limit * * @output: true if GET is success, otherwise false. This method does not check http * response by Yelp. * * @remarks: If this method returns true, then use yelpCurl::getLastWebResponse() to * get Yelp's JSON response. * If this method returns false, then use yelpCurl::getLastCurlError() to * get cURL's response. * *--*/ bool yelpCurl::reviewSearchByMapBoundingBox( std::string& searchTerm, yelpGenericParams& searchParams ) { bool retVal = false; /* Check if cURL is initialized and if we have correct YWSID */ if( isCurlInit() && m_yelpWebSvcId.length() && searchTerm.length() ) { std::string srchQuery( "" ); std::string dummyStr2( "" ); char dummyStr[yelpCurlDefaults::YELPCURL_DEFAULT_BUFFSIZE]; /* Build search query URL */ srchQuery = yelpUrls::YELP_BUSINESS_REVIEW_SEARCH_URL; utilTrimSpaces( searchTerm, dummyStr2 ); srchQuery.append( dummyStr2.c_str() ); srchQuery.append( yelpCurlDefaults::YELPCURL_TLLAT.c_str() ); memset( dummyStr, 0, yelpCurlDefaults::YELPCURL_DEFAULT_BUFFSIZE ); sprintf( dummyStr, "%f", searchParams.tl_lat ); srchQuery.append( dummyStr ); srchQuery.append( yelpCurlDefaults::YELPCURL_TLLONG.c_str() ); memset( dummyStr, 0, yelpCurlDefaults::YELPCURL_DEFAULT_BUFFSIZE ); sprintf( dummyStr, "%f", searchParams.tl_long ); srchQuery.append( dummyStr ); srchQuery.append( yelpCurlDefaults::YELPCURL_BRLAT.c_str() ); memset( dummyStr, 0, yelpCurlDefaults::YELPCURL_DEFAULT_BUFFSIZE ); sprintf( dummyStr, "%f", searchParams.br_lat ); srchQuery.append( dummyStr ); srchQuery.append( yelpCurlDefaults::YELPCURL_BRLONG.c_str() ); memset( dummyStr, 0, yelpCurlDefaults::YELPCURL_DEFAULT_BUFFSIZE ); sprintf( dummyStr, "%f", searchParams.br_long ); srchQuery.append( dummyStr ); srchQuery.append( yelpCurlDefaults::YELPCURL_LIMIT.c_str() ); memset( dummyStr, 0, yelpCurlDefaults::YELPCURL_DEFAULT_BUFFSIZE ); sprintf( dummyStr, "%d", searchParams.limit ); srchQuery.append( dummyStr ); srchQuery.append( yelpCurlDefaults::YELPCURL_YWSID.c_str() ); srchQuery.append( m_yelpWebSvcId.c_str() ); /* Perform HTTP GET */ retVal = performGet( srchQuery ); } return retVal; } /*++ * @method: yelpCurl::reviewSearchByGeoPoint * * @description: method to do review search by geo point and radius * * @input: searchTerm - Search term (ex: "coffee") * searchParams - Search params. Only following members of yelpGenericParams * struct are needed to contain valid values: * yelpGenericParams::lat, * yelpGenericParams::longt, * yelpGenericParams::radius, * yelpGenericParams::limit * * @output: true if GET is success, otherwise false. This method does not check http * response by Yelp. * * @remarks: If this method returns true, then use yelpCurl::getLastWebResponse() to * get Yelp's JSON response. * If this method returns false, then use yelpCurl::getLastCurlError() to * get cURL's response. * *--*/ bool yelpCurl::reviewSearchByGeoPoint( std::string& searchTerm, yelpGenericParams& searchParams ) { bool retVal = false; /* Check if cURL is initialized and if we have correct YWSID */ if( isCurlInit() && m_yelpWebSvcId.length() && searchTerm.length() ) { std::string srchQuery( "" ); std::string dummyStr2( "" ); char dummyStr[yelpCurlDefaults::YELPCURL_DEFAULT_BUFFSIZE]; /* Build search query */ srchQuery = yelpUrls::YELP_BUSINESS_REVIEW_SEARCH_URL; utilTrimSpaces( searchTerm, dummyStr2 ); srchQuery.append( dummyStr2.c_str() ); srchQuery.append( yelpCurlDefaults::YELPCURL_LAT.c_str() ); memset( dummyStr, 0, yelpCurlDefaults::YELPCURL_DEFAULT_BUFFSIZE ); sprintf( dummyStr, "%f", searchParams.lat ); srchQuery.append( dummyStr ); srchQuery.append( yelpCurlDefaults::YELPCURL_LONG.c_str() ); memset( dummyStr, 0, yelpCurlDefaults::YELPCURL_DEFAULT_BUFFSIZE ); sprintf( dummyStr, "%f", searchParams.longt ); srchQuery.append( dummyStr ); srchQuery.append( yelpCurlDefaults::YELPCURL_RADIUS.c_str() ); memset( dummyStr, 0, yelpCurlDefaults::YELPCURL_DEFAULT_BUFFSIZE ); sprintf( dummyStr, "%f", searchParams.radius ); srchQuery.append( dummyStr ); srchQuery.append( yelpCurlDefaults::YELPCURL_LIMIT.c_str() ); memset( dummyStr, 0, yelpCurlDefaults::YELPCURL_DEFAULT_BUFFSIZE ); sprintf( dummyStr, "%d", searchParams.limit ); srchQuery.append( dummyStr ); srchQuery.append( yelpCurlDefaults::YELPCURL_YWSID.c_str() ); srchQuery.append( m_yelpWebSvcId.c_str() ); /* Perform HTTP GET */ retVal = performGet( srchQuery ); } return retVal; } /*++ * @method: yelpCurl::reviewSearchByNieghborhood * * @description: method to do review search by neighborhood location. * * @input: searchTerm - Search term (ex: "coffee") * searchLocation - Search location (ex: "MG Road Bangalore India") * * @output: true if GET is success, otherwise false. This method does not check http * response by Yelp. * * @remarks: If this method returns true, then use yelpCurl::getLastWebResponse() to * get Yelp's JSON response. * If this method returns false, then use yelpCurl::getLastCurlError() to * get cURL's response. * *--*/ bool yelpCurl::reviewSearchByNieghborhood( std::string& searchTerm, std::string& searchLocation ) { bool retVal = false; /* Check if cURL is initialized and if we have correct YWSID */ if( isCurlInit() && m_yelpWebSvcId.length() && searchTerm.length() && searchLocation.length() ) { std::string srchQuery( "" ); std::string dummyStr( "" ); /* Build search query */ srchQuery = yelpUrls::YELP_BUSINESS_REVIEW_SEARCH_URL; utilTrimSpaces( searchTerm, dummyStr ); srchQuery.append( dummyStr.c_str() ); dummyStr = ""; utilTrimSpaces( searchLocation, dummyStr ); srchQuery.append( yelpCurlDefaults::YELPCURL_LOCATION.c_str() ); srchQuery.append( dummyStr.c_str() ); srchQuery.append( yelpCurlDefaults::YELPCURL_YWSID.c_str() ); srchQuery.append( m_yelpWebSvcId.c_str() ); /* Perform HTTP GET */ retVal = performGet( srchQuery ); } return retVal; } /*++ * @method: yelpCurl::searchPhoneNumber * * @description: method to search by phone number * * @input: phoneNum - Phone number * * @output: true if GET is success, otherwise false. This method does not check http * response by Yelp. * * @remarks: If this method returns true, then use yelpCurl::getLastWebResponse() to * get Yelp's JSON response. * If this method returns false, then use yelpCurl::getLastCurlError() to * get cURL's response. * *--*/ bool yelpCurl::searchPhoneNumber( std::string& phoneNum ) { bool retVal = false; /* Check if cURL is initialized and if we have correct YWSID */ if( isCurlInit() && m_yelpWebSvcId.length() && phoneNum.length() ) { std::string srchQuery( "" ); /* Build query URL */ srchQuery = yelpUrls::YELP_PHONE_SEARCH_URL; srchQuery.append( phoneNum.c_str() ); srchQuery.append( yelpCurlDefaults::YELPCURL_YWSID.c_str() ); srchQuery.append( m_yelpWebSvcId.c_str() ); /* Perform HTTP GET */ retVal = performGet( srchQuery ); } return retVal; } /*++ * @method: yelpCurl::searchNeighborhoodByGeoCode * * @description: method to search neighborhood by geo code * * @input: searchParams - Search params. Only following members of yelpGenericParams * struct are needed to contain valid values: * yelpGenericParams::lat, * yelpGenericParams::longt * * @output: true if GET is success, otherwise false. This method does not check http * response by Yelp. * * @remarks: If this method returns true, then use yelpCurl::getLastWebResponse() to * get Yelp's JSON response. * If this method returns false, then use yelpCurl::getLastCurlError() to * get cURL's response. * *--*/ bool yelpCurl::searchNeighborhoodByGeoCode( yelpGenericParams& searchParams ) { bool retVal = false; /* Check if cURL is initialized and if we have correct YWSID */ if( isCurlInit() && m_yelpWebSvcId.length() ) { std::string srchQuery( "" ); char dummyStr[yelpCurlDefaults::YELPCURL_DEFAULT_BUFFSIZE]; /* Build query URL */ srchQuery = yelpUrls::YELP_NEIGHBORHOOD_SEARCH_URL; srchQuery.append( yelpCurlDefaults::YELPCURL_LAT2.c_str() ); memset( dummyStr, 0, yelpCurlDefaults::YELPCURL_DEFAULT_BUFFSIZE ); sprintf( dummyStr, "%f", searchParams.lat ); srchQuery.append( dummyStr ); srchQuery.append( yelpCurlDefaults::YELPCURL_LONG.c_str() ); memset( dummyStr, 0, yelpCurlDefaults::YELPCURL_DEFAULT_BUFFSIZE ); sprintf( dummyStr, "%f", searchParams.longt ); srchQuery.append( dummyStr ); srchQuery.append( yelpCurlDefaults::YELPCURL_YWSID.c_str() ); srchQuery.append( m_yelpWebSvcId.c_str() ); /* Perform HTTP GET */ retVal = performGet( srchQuery ); } return retVal; } /*++ * @method: yelpCurl::searchNeighborhoodByLocation * * @description: method to search neighborhood by location/address * * @input: searchLocation - Location string (ex: "MG Road Bangalore" ) * * @output: true if GET is success, otherwise false. This method does not check http * response by Yelp. * * @remarks: If this method returns true, then use yelpCurl::getLastWebResponse() to * get Yelp's JSON response. * If this method returns false, then use yelpCurl::getLastCurlError() to * get cURL's response. * *--*/ bool yelpCurl::searchNeighborhoodByLocation( std::string& searchLocation ) { bool retVal = false; /* Check if cURL is initialized and if we have correct YWSID */ if( isCurlInit() && m_yelpWebSvcId.length() ) { std::string srchQuery( "" ); std::string dummyStr( "" ); /* Build query URL */ srchQuery = yelpUrls::YELP_NEIGHBORHOOD_SEARCH_URL; utilTrimSpaces( searchLocation, dummyStr ); srchQuery.append( yelpCurlDefaults::YELPCURL_LOCATION2.c_str() ); srchQuery.append( dummyStr.c_str() ); srchQuery.append( yelpCurlDefaults::YELPCURL_YWSID.c_str() ); srchQuery.append( m_yelpWebSvcId.c_str() ); /* Perform HTTP GET */ retVal = performGet( srchQuery ); } return retVal; } /*++ * @method: utilMakeCurlParams * * @description: utility function to build parameter strings in the format * required by cURL ("param1:param2"). yelpCurl users should * not use this function. * * @input: inParam1 - first parameter, * inParam2 - second parameter * * @output: outStr - built parameter * * @remarks: internal method * *--*/ void utilMakeCurlParams( std::string& outStr, std::string& inParam1, std::string& inParam2 ) { outStr = inParam1; outStr.append( yelpCurlDefaults::YELPCURL_COLON.c_str() ); outStr.append( inParam2.c_str() ); } /*++ * @method: utilTrimSpaces * * @description: utility function to replace space (' ') with %20 * * @input: inStr - input string, * outStr - output string with space replaced by %20 * * @output: outStr - built parameter * * @remarks: internal method * *--*/ void utilTrimSpaces( std::string& inStr, std::string& outStr ) { for( int i = 0; i < inStr.length(); i++ ) { if( ' ' == inStr[i] ) { outStr.append( yelpCurlDefaults::YELPCURL_SPACE.c_str() ); } else { outStr.append( 1, inStr[i] ); } } }
[ "[email protected]@94aee722-be17-374c-8e63-df07a9a60fe6" ]
[ [ [ 1, 853 ] ] ]
924e4445b18bb7316fc93b257c704be121a126dd
5506729a4934330023f745c3c5497619bddbae1d
/vst2.x/P4P1Synth/source/Filter.cpp
a5e494eb740294129f2de4a311c2feb58b92acf9
[]
no_license
berak/vst2.0
9e6d1d7246567f367d8ba36cf6f76422f010739e
9d8f51ad3233b9375f7768be528525c15a2ba7a1
refs/heads/master
2020-03-27T05:42:19.762167
2011-02-18T13:35:09
2011-02-18T13:35:09
1,918,997
4
3
null
null
null
null
UTF-8
C++
false
false
21,245
cpp
#include "Filter.h" #include <string.h> #include <stdlib.h> #include <stdio.h> #include <math.h> const float Pi = 3.141592653f; namespace FilterBessel { struct Filter { float State0,State1,State2,State3; float A0,A1,A2,A3,A4; float B0,B1,B2,B3,B4; void calc( float q, float Frequency, float Samplerate ) { float K,K2,K4; K = tan(Pi * Frequency / Samplerate); K2 = K*K; // speed improvement K4 = K2*K2; // speed improvement A0 = ((((105*K + 105)*K + 45)*K + 10)*K + 1); A1 = -( ((420*K + 210)*K2 - 20)*K - 4)*q; A2 = -( (630*K2 - 90)*K2 + 6)*q; A3 = -( ((420*K - 210)*K2 + 20)*K - 4)*q; A4 = -((((105*K - 105)*K + 45)*K - 10)*K + 1)*q; A1 = A1/A0; A2 = A2/A0; A3 = A3/A0; A4 = A4/A0; B0 = 105*K4; B1 = 420*K4; B2 = 630*K4; B3 = 420*K4; B4 = 105*K4; } float value( float Input ) { float Output = B0*Input + State0; State0 = B1*Input + A1*Output + State1; State1 = B2*Input + A2*Output + State2; State2 = B3*Input + A3*Output + State3; State3 = B4*Input + A4*Output; return Output; } } filtor; void set( float q, float freq, float sampleFreq ) { filtor.calc( q, freq, sampleFreq ); } float process( float sound ) { return filtor.value(sound); } } namespace FilterFormant { // Public source code by [email protected] // Simple example of implementation of formant filter // Vowelnum can be 0,1,2,3,4 <=> A,E,I,O,U // Good for spectral rich input like saw or square //-------------------------------------------------------------VOWEL COEFFICIENTS const double coeff[5][11] = { { 8.11044e-06, 8.943665402, -36.83889529, 92.01697887, -154.337906, 181.6233289, -151.8651235, 89.09614114, -35.10298511, 8.388101016, -0.923313471 ///A }, { 4.36215e-06, 8.90438318, -36.55179099, 91.05750846, -152.422234, 179.1170248, ///E -149.6496211,87.78352223, -34.60687431, 8.282228154, -0.914150747 }, { 3.33819e-06, 8.893102966, -36.49532826, 90.96543286, -152.4545478, 179.4835618, -150.315433, 88.43409371, -34.98612086, 8.407803364, -0.932568035 ///I }, { 1.13572e-06, 8.994734087, -37.2084849, 93.22900521, -156.6929844, 184.596544, ///O -154.3755513, 90.49663749, -35.58964535, 8.478996281, -0.929252233 }, { 4.09431e-07, 8.997322763, -37.20218544, 93.11385476, -156.2530937, 183.7080141, ///U -153.2631681, 89.59539726, -35.12454591, 8.338655623, -0.910251753 } }; struct TheFilter { //--------------------------------------------------------------------------------- double memory[10]; int vowelnum; TheFilter() : vowelnum(0) { memset(memory,0,10*sizeof(double)); } //--------------------------------------------------------------------------------- void voc(int v) { if ( v>=0 && v<5 ) vowelnum = v; } float value(float in) { return formant_filter(in, vowelnum); } float formant_filter(float in, int vowelnum) { double res = ( coeff[vowelnum][0] * in + coeff[vowelnum][1] * memory[0] + coeff[vowelnum][2] * memory[1] + coeff[vowelnum][3] * memory[2] + coeff[vowelnum][4] * memory[3] + coeff[vowelnum][5] * memory[4] + coeff[vowelnum][6] * memory[5] + coeff[vowelnum][7] * memory[6] + coeff[vowelnum][8] * memory[7] + coeff[vowelnum][9] * memory[8] + coeff[vowelnum][10] * memory[9] ); memory[9]= memory[8]; memory[8]= memory[7]; memory[7]= memory[6]; memory[6]= memory[5]; memory[5]= memory[4]; memory[4]= memory[3]; memory[3]= memory[2]; memory[2]= memory[1]; memory[1]= memory[0]; memory[0]=(double) res; return (float)res; } } filtor; void set( int vnum ) { filtor.voc(vnum); } float process( float sound ) { return filtor.value(sound); } } namespace Filter4Pole { struct TheFilter { double coef[9]; double d[4]; double omega; //peak freq double g; //peak mag TheFilter() : omega(0.5) , g(0.5) { memset(coef,0,9*sizeof(double)); memset(d,0,4*sizeof(double)); calc(omega,g); } void calc( double f, double r, bool LP=true ) { // calculating coefficients: if ( f < 0.001 ) f = 0.001; omega = f; g = (1.0 - r); double k,p,q,a; double a0,a1,a2,a3,a4; k=(4.0*g-3.0)/(g+1.0); p=1.0-0.25*k;p*=p; if ( LP ) { a=1.0/(tan(0.5*omega)*(1.0+p)); p=1.0+a; q=1.0-a; a0=1.0/(k+p*p*p*p); a1=4.0*(k+p*p*p*q); a2=6.0*(k+p*p*q*q); a3=4.0*(k+p*q*q*q); a4= (k+q*q*q*q); p=a0*(k+1.0); coef[0]=p; coef[1]=4.0*p; coef[2]=6.0*p; coef[3]=4.0*p; coef[4]=p; coef[5]=-a1*a0; coef[6]=-a2*a0; coef[7]=-a3*a0; coef[8]=-a4*a0; } else { // HP: a=tan(0.5*omega)/(1.0+p); p=a+1.0; q=a-1.0; a0=1.0/(p*p*p*p+k); a1=4.0*(p*p*p*q-k); a2=6.0*(p*p*q*q+k); a3=4.0*(p*q*q*q-k); a4= (q*q*q*q+k); p=a0*(k+1.0); coef[0]=p; coef[1]=-4.0*p; coef[2]=6.0*p; coef[3]=-4.0*p; coef[4]=p; coef[5]=-a1*a0; coef[6]=-a2*a0; coef[7]=-a3*a0; coef[8]=-a4*a0; } } double value( double sound ) { // per sample: double out=0.3 * (coef[0]*sound+d[0]); if ( out > 1.0 ) out = 1.0; if ( out < -1.0 ) out = -1.0; d[0]=coef[1]*sound+coef[5]*out+d[1]; d[1]=coef[2]*sound+coef[6]*out+d[2]; d[2]=coef[3]*sound+coef[7]*out+d[3]; d[3]=coef[4]*sound+coef[8]*out; return out; } } filtor; void set( float q, float freq, float sampleFreq ) { filtor.calc( freq, q, true ); } float process( float sound ) { return filtor.value(sound); } } namespace FilterBP { // wot, - no pi ? // // 2nd order latfir bandpass, orig. from 'sox': // y(t) = A * x(t) - B * y(t-1) - C * y(t-2); // class Filter { enum { kCMax = 8000, // max. centerfreq. kSRate = 44100 // est. samplefreq. }; protected: float A, B, C, v0, v1, v2, om; public: Filter() { om=2*Pi*kCMax/kSRate; stop(); } void stop() { v0=v1=v2=0.0f; calc(0.0f,0.0f); } void calc( float c, float w ) { float center = om*c*c; float width = om*(1-w*w); C = expf(-width); float D = 1+C; // helper B = -4*C/D*cosf(center); A = sqrtf((D*D-B*B)*(1-C)/D); // 'noizy' version } inline float value( float in ) { v0 = A * in - B * v1 - C * v2; v2 = v1; v1 = v0; return v0; } } bpFilter; void set( float q, float freq, float sampleFreq ) { if ( freq < 0.03f ) freq = 0.03f; if ( q < 0.0001f ) q = 0.0001f; if ( q > 1.0f ) q = 1.0f; bpFilter.calc( freq, q ); } float process( float sound ) { return bpFilter.value(sound); } } namespace FilterLP { const int FILTER_SECTIONS = 2; /* 2 filter sections for 24 db/oct filter */ // // hmm, the original calloc thing seemd to break vc2009.. // iir.coef = (float *) calloc(4 * iir.length + 1, sizeof(float)); // so history & coef got fixed sized arrays. // struct FILTER { unsigned int length; /* size of filter */ float history[ FILTER_SECTIONS * 2 ]; /* pointer to history in filter */ float coef[ FILTER_SECTIONS * 4 + 1 ]; /* pointer to coefficients of filter */ }; struct BIQUAD { double a0, a1, a2; /* numerator coefficients */ double b0, b1, b2; /* denominator coefficients */ } ; /* * -------------------------------------------------------------------- * * main() * * Example main function to show how to update filter coefficients. * We create a 4th order filter (24 db/oct roloff), consisting * of two second order sections. * -------------------------------------------------------------------- */ class TheFiltor { BIQUAD ProtoCoef[FILTER_SECTIONS]; /* Filter prototype coefficients, 1 for each section */ FILTER iir; float *coef; public: double fs, fc; /* Sampling frequency, cutoff frequency */ double Q; /* Resonance > 1.0 < 1000 */ double k; /* Set overall filter gain */ TheFiltor() { Q = 1; /* Resonance */ fc = 5000; /* Filter cutoff (Hz) */ fs = 44100; /* Sampling frequency (Hz) */ k = 1.0; /* Set overall filter gain */ /* * Setup filter s-domain coefficients */ /* Section 1 */ ProtoCoef[0].a0 = 1.0; ProtoCoef[0].a1 = 0; ProtoCoef[0].a2 = 0; ProtoCoef[0].b0 = 1.0; ProtoCoef[0].b1 = 0.765367; ProtoCoef[0].b2 = 1.0; /* Section 2 */ ProtoCoef[1].a0 = 1.0; ProtoCoef[1].a1 = 0; ProtoCoef[1].a2 = 0; ProtoCoef[1].b0 = 1.0; ProtoCoef[1].b1 = 1.847759; ProtoCoef[1].b2 = 1.0; iir.length = FILTER_SECTIONS; /* Number of filter sections */ calcCoeff(); } float value( float v ) { return iir_filter( v, &(iir) ); } void calcCoeff() { /* * Compute z-domain coefficients for each biquad section * for new Cutoff Frequency and Resonance */ unsigned nInd; double a0, a1, a2, b0, b1, b2; k = 1.0; coef = iir.coef + 1; /* Skip k, or gain */ for (nInd = 0; nInd < iir.length; nInd++) { a0 = ProtoCoef[nInd].a0; a1 = ProtoCoef[nInd].a1; a2 = ProtoCoef[nInd].a2; b0 = ProtoCoef[nInd].b0; b1 = ProtoCoef[nInd].b1 / Q; /* Divide by resonance or Q */ b2 = ProtoCoef[nInd].b2; szxform(&a0, &a1, &a2, &b0, &b1, &b2, fc, fs, &k, coef); coef += 4; /* Point to next filter section */ } /* Update overall filter gain in coef array */ iir.coef[0] = k; } private: /* * -------------------------------------------------------------------- * * iir_filter - Perform IIR filtering sample by sample on floats * * Implements cascaded direct form II second order sections. * Requires FILTER structure for history and coefficients. * The length in the filter structure specifies the number of sections. * The size of the history array is 2*iir->length. * The size of the coefficient array is 4*iir->length + 1 because * the first coefficient is the overall scale factor for the filter. * Returns one output sample for each input sample * * float iir_filter(float input,FILTER *iir) * * float input new float input sample * FILTER *iir pointer to FILTER structure * * Returns float value giving the current output. * -------------------------------------------------------------------- */ float iir_filter(float input,FILTER *iir) { unsigned int i; float *hist1_ptr,*hist2_ptr,*coef_ptr; float output,new_hist,history1,history2; coef_ptr = iir->coef; /* coefficient pointer */ hist1_ptr = iir->history; /* first history */ hist2_ptr = hist1_ptr + 1; /* next history */ /* 1st number of coefficients array is overall input scale factor, * or filter gain */ output = input * (*coef_ptr++); for (i = 0 ; i < iir->length; i++) { history1 = *hist1_ptr; /* history values */ history2 = *hist2_ptr; output = output - history1 * (*coef_ptr++); new_hist = output - history2 * (*coef_ptr++); /* poles */ output = new_hist + history1 * (*coef_ptr++); output = output + history2 * (*coef_ptr++); /* zeros */ *hist2_ptr++ = *hist1_ptr; *hist1_ptr++ = new_hist; hist1_ptr++; hist2_ptr++; } return(output); } /* * ---------------------------------------------------------- * bilinear.c * * Perform bilinear transformation on s-domain coefficients * of 2nd order biquad section. * First design an analog filter and use s-domain coefficients * as input to szxform() to convert them to z-domain. * * Here's the butterworth polinomials for 2nd, 4th and 6th order sections. * When we construct a 24 db/oct filter, we take to 2nd order * sections and compute the coefficients separately for each section. * * n Polinomials * -------------------------------------------------------------------- * 2 s^2 + 1.4142s +1 * 4 (s^2 + 0.765367s + 1) (s^2 + 1.847759s + 1) * 6 (s^2 + 0.5176387s + 1) (s^2 + 1.414214 + 1) (s^2 + 1.931852s + 1) * * Where n is a filter order. * For n=4, or two second order sections, we have following equasions for each * 2nd order stage: * * (1 / (s^2 + (1/Q) * 0.765367s + 1)) * (1 / (s^2 + (1/Q) * 1.847759s + 1)) * * Where Q is filter quality factor in the range of * 1 to 1000. The overall filter Q is a product of all * 2nd order stages. For example, the 6th order filter * (3 stages, or biquads) with individual Q of 2 will * have filter Q = 2 * 2 * 2 = 8. * * The nominator part is just 1. * The denominator coefficients for stage 1 of filter are: * b2 = 1; b1 = 0.765367; b0 = 1; * numerator is * a2 = 0; a1 = 0; a0 = 1; * * The denominator coefficients for stage 1 of filter are: * b2 = 1; b1 = 1.847759; b0 = 1; * numerator is * a2 = 0; a1 = 0; a0 = 1; * * These coefficients are used directly by the szxform() * and bilinear() functions. For all stages the numerator * is the same and the only thing that is different between * different stages is 1st order coefficient. The rest of * coefficients are the same for any stage and equal to 1. * * Any filter could be constructed using this approach. * * References: * Van Valkenburg, "Analog Filter Design" * Oxford University Press 1982 * ISBN 0-19-510734-9 * * C Language Algorithms for Digital Signal Processing * Paul Embree, Bruce Kimble * Prentice Hall, 1991 * ISBN 0-13-133406-9 * * Digital Filter Designer's Handbook * With C++ Algorithms * Britton Rorabaugh * McGraw Hill, 1997 * ISBN 0-07-053806-9 * ---------------------------------------------------------- */ /* * ---------------------------------------------------------- * Pre-warp the coefficients of a numerator or denominator. * Note that a0 is assumed to be 1, so there is no wrapping * of it. * ---------------------------------------------------------- */ void prewarp( double *a0, double *a1, double *a2, double fc, double fs) { double wp, pi; pi = 4.0 * atan(1.0); wp = 2.0 * fs * tan(pi * fc / fs); *a2 = (*a2) / (wp * wp); *a1 = (*a1) / wp; } /* * ---------------------------------------------------------- * bilinear() * * Transform the numerator and denominator coefficients * of s-domain biquad section into corresponding * z-domain coefficients. * * Store the 4 IIR coefficients in array pointed by coef * in following order: * beta1, beta2 (denominator) * alpha1, alpha2 (numerator) * * Arguments: * a0-a2 - s-domain numerator coefficients * b0-b2 - s-domain denominator coefficients * k - filter gain factor. initially set to 1 * and modified by each biquad section in such * a way, as to make it the coefficient by * which to multiply the overall filter gain * in order to achieve a desired overall filter gain, * specified in initial value of k. * fs - sampling rate (Hz) * coef - array of z-domain coefficients to be filled in. * * Return: * On return, set coef z-domain coefficients * ---------------------------------------------------------- */ void bilinear( double a0, double a1, double a2, /* numerator coefficients */ double b0, double b1, double b2, /* denominator coefficients */ double *k, /* overall gain factor */ double fs, /* sampling rate */ float *coef /* pointer to 4 iir coefficients */ ) { double ad, bd; /* alpha (Numerator in s-domain) */ ad = 4. * a2 * fs * fs + 2. * a1 * fs + a0; /* beta (Denominator in s-domain) */ bd = 4. * b2 * fs * fs + 2. * b1* fs + b0; /* update gain constant for this section */ *k *= ad/bd; /* Denominator */ *coef++ = (2. * b0 - 8. * b2 * fs * fs) / bd; /* beta1 */ *coef++ = (4. * b2 * fs * fs - 2. * b1 * fs + b0) / bd; /* beta2 */ /* Nominator */ *coef++ = (2. * a0 - 8. * a2 * fs * fs) / ad; /* alpha1 */ *coef = (4. * a2 * fs * fs - 2. * a1 * fs + a0) / ad; /* alpha2 */ } /* * ---------------------------------------------------------- * Transform from s to z domain using bilinear transform * with prewarp. * * Arguments: * For argument description look at bilinear() * * coef - pointer to array of floating point coefficients, * corresponding to output of bilinear transofrm * (z domain). * * Note: frequencies are in Hz. * ---------------------------------------------------------- */ void szxform( double *a0, double *a1, double *a2, /* numerator coefficients */ double *b0, double *b1, double *b2, /* denominator coefficients */ double fc, /* Filter cutoff frequency */ double fs, /* sampling rate */ double *k, /* overall gain factor */ float *coef) /* pointer to 4 iir coefficients */ { /* Calculate a1 and a2 and overwrite the original values */ prewarp(a0, a1, a2, fc, fs); prewarp(b0, b1, b2, fc, fs); bilinear(*a0, *a1, *a2, *b0, *b1, *b2, k, fs, coef); } } filtor; void set( float q, float freq, float sampleFreq ) { if ( freq < 33.0f ) freq = 33.0f; if ( q < 0.0001f ) q = 0.0001f; if ( q > 10.0f ) q = 10.0f; filtor.Q = q; filtor.fc = freq; filtor.fs = sampleFreq; filtor.calcCoeff(); } float process( float sound ) { return filtor.value(sound); } } // // cl /nologo /D TEST_PLOT filter.cpp // #ifdef TEST_PLOT #include <stdio.h> #include <stdlib.h> #include <math.h> #define myPI 3.1415926535897932384626433832795 #define FP double #define DWORD unsigned long #define CUTOFF 5000 #define SAMPLERATE 44100 // take enough samples to test the 20 herz frequency 2 times #define TESTSAMPLES (SAMPLERATE/20) * 2 int main(int argc, char **argv) { DWORD freq; DWORD spos; double sIn; double sOut; double tIn; double tOut; double dB; DWORD tmp; double cut = 123.0; double res = 1.0; if ( argc > 1 ) cut = atof(argv[1]); if ( argc > 2 ) res = atof(argv[2]); // define the test filter Filter4Pole::TheFilter filter; printf(" freq dB 9dB 6dB 3dB 0dB\n"); printf(" | | | | \n"); // test frequencies 20 - 20020 with 100 herz steps for (freq=20; freq<20020; freq+=100) { // (re)initialize the filter filter.calc(cut,res); // let the filter do it's thing here tIn = tOut = 0; for (spos=0; spos<TESTSAMPLES; spos++) { sIn = sin((2 * myPI * spos * freq) / SAMPLERATE); sOut = filter.value(sIn); if ((sOut>1) || (sOut<-1)) { // If filter is no good, stop the test //printf("Error! Clipping!\n"); //return(1); } if (sIn >0) tIn += sIn; if (sIn <0) tIn -= sIn; if (sOut>0) tOut += sOut; if (sOut<0) tOut -= sOut; } // analyse the results dB = 20*log(tIn/tOut); printf("%5d %5.1f ", freq, dB); tmp = (DWORD)(60.0/pow(2.0, (dB/3.0))); if ( tmp > 59 ) tmp = 59; while (tmp--) putchar('#'); putchar('\n'); } return 0; } #endif // TEST_PLOT
[ [ [ 1, 777 ] ] ]
52c40291dbc48e52398fbc8f5827040495afbf17
d5f525c995dd321375a19a8634a391255f0e5b6f
/graphic_front_end/motor/demo.cpp
729e36cc92acd90e982451bd69326269277dabcc
[]
no_license
shangdawei/cortex-simulator
bac4b8f19be3e2df622ad26e573330642ec97bae
d343b66a88a5b78d5851a3ee5dc2a4888ff00b20
refs/heads/master
2016-09-05T19:45:32.930832
2009-03-19T06:07:47
2009-03-19T06:07:47
42,106,205
1
1
null
null
null
null
UTF-8
C++
false
false
3,042
cpp
// demo.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "demo.h" #include "MainFrm.h" #include "demoDoc.h" #include "demoView.h" #include <windows.h> #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CDemoApp BEGIN_MESSAGE_MAP(CDemoApp, CWinApp) //{{AFX_MSG_MAP(CDemoApp) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG_MAP // Standard file based document commands ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew) ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CDemoApp construction CDemoApp::CDemoApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } ///////////////////////////////////////////////////////////////////////////// // The one and only CDemoApp object CDemoApp theApp; ///////////////////////////////////////////////////////////////////////////// // CDemoApp initialization BOOL CDemoApp::InitInstance() { STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); ZeroMemory( &pi, sizeof(pi) ); AfxEnableControlContainer(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need. #ifdef _AFXDLL Enable3dControls(); // Call this when using MFC in a shared DLL #else Enable3dControlsStatic(); // Call this when linking to MFC statically #endif // Change the registry key under which our settings are stored. // TODO: You should modify this string to be something appropriate // such as the name of your company or organization. SetRegistryKey(_T("Local AppWizard-Generated Applications")); LoadStdProfileSettings(); // Load standard INI file options (including MRU) // Register the application's document templates. Document templates // serve as the connection between documents, frame windows and views. CSingleDocTemplate* pDocTemplate; pDocTemplate = new CSingleDocTemplate( IDR_MAINFRAME, RUNTIME_CLASS(CDemoDoc), RUNTIME_CLASS(CMainFrame), // main SDI frame window RUNTIME_CLASS(CDemoView)); AddDocTemplate(pDocTemplate); // Parse command line for standard shell commands, DDE, file open CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); // Dispatch commands specified on the command line if (!ProcessShellCommand(cmdInfo)) return FALSE; // The one and only window has been initialized, so show and update it. m_pMainWnd->ShowWindow(SW_SHOW); m_pMainWnd->UpdateWindow(); m_pMainWnd->SetWindowText("Demo"); return TRUE; }
[ "yihengw@3e89f612-834b-0410-bb31-dbad55e6f342" ]
[ [ [ 1, 102 ] ] ]
358fa1c256dca2c535174f79ea98eb164bf5d275
915d454b5f3099ea8d12f291fd79dab0688f9b6c
/TheCodeForTheProject/MazeWindow/MazeWindow/MazeWindow.cpp
a5a6aab258e8c97f00b5f017df37e3594dd488dc
[]
no_license
johnballantyne/mazegeneration483w
e60593bbbeac2fe4589bace2076c1d8620b8b5d5
dddbbb8b9e919ba2c7b3977e230c7afd545073cd
refs/heads/master
2021-01-23T14:03:59.843199
2009-12-14T01:56:57
2009-12-14T01:56:57
39,958,368
0
0
null
null
null
null
UTF-8
C++
false
false
446
cpp
// MazeWindow.cpp : main project file. #include "stdafx.h" #include "MazeForm.h" using namespace MazeWindow; [STAThreadAttribute] int main(array<System::String ^> ^args) { // Enabling Windows XP visual effects before any controls are created Application::EnableVisualStyles(); Application::SetCompatibleTextRenderingDefault(false); // Create the main window and run it Application::Run(gcnew MazeForm()); return 0; }
[ "vash7ehstampede@f1cf40a4-bd93-11de-8784-f7ad4773dbab" ]
[ [ [ 1, 18 ] ] ]
5b7b6761bec917cfae1ff539e23b82d42d2222b2
a0bc9908be9d42d58af7a1a8f8398c2f7dcfa561
/SlonEngine/src/Physics/PhysicsTransform.cpp
57a8e00e826535b7f4cde1338255b57f13b0f1ad
[]
no_license
BackupTheBerlios/slon
e0ca1137a84e8415798b5323bc7fd8f71fe1a9c6
dc10b00c8499b5b3966492e3d2260fa658fee2f3
refs/heads/master
2016-08-05T09:45:23.467442
2011-10-28T16:19:31
2011-10-28T16:19:31
39,895,039
0
0
null
null
null
null
UTF-8
C++
false
false
3,599
cpp
#include "stdafx.h" #include "Database/Archive.h" #include "Log/Formatters.h" #include "Log/LogVisitor.h" #include "Physics/RigidBody.h" #include "Physics/DynamicsWorld.h" #include "Physics/PhysicsTransform.h" #include "Realm/Location.h" #include "Utility/functor_slot.hpp" namespace slon { namespace physics { PhysicsTransform::PhysicsTransform(const collision_object_ptr& collisionObject_) : absolute(false) { setCollisionObject(collisionObject_); } const char* PhysicsTransform::serialize(database::OArchive& ar) const { // serialize base class Transform::serialize(ar); // serialize data ar.writeSerializable(collisionObject.get()); ar.writeChunk("absolute", &absolute); return "PhysicsTransform"; } void PhysicsTransform::deserialize(database::IArchive& ar) { // deserialize base class Transform::deserialize(ar); // deserialize data collisionObject = ar.readSerializable<physics::CollisionObject>(); if (collisionObject) { setCollisionObject(collisionObject); } ar.readChunk("absolute", &absolute); } const math::Matrix4f& PhysicsTransform::getTransform() const { return transform; } const math::Matrix4f& PhysicsTransform::getInverseTransform() const { invTransform = math::invert(transform); return invTransform; } void PhysicsTransform::setCollisionObject(const collision_object_ptr& collisionObject_) { collisionObject = collisionObject_; if (collisionObject) { transformConnection.reset( collisionObject->getTransformSignal(), make_slot<void (const math::RigidTransformr&)>(boost::bind(&PhysicsTransform::setWorldTransform, this, _1)) ); transform = collisionObject->getTransform(); } else { transformConnection.reset(); } } void PhysicsTransform::setWorldTransform(const math::RigidTransformr& transform_) { #ifdef SLON_ENGINE_USE_DOUBLE_PRECISION_PHYSICS // copy if using double precision physics transform = math::RigidTransformf(transform_); #else transform = transform_; #endif ++modifiedCount; update(false); } void PhysicsTransform::accept(log::LogVisitor& visitor) const { visitor << "PhysicsTransform"; if ( getName() != "" ) { visitor << " '" << getName() << "'"; } visitor << "\n{\n" << log::indent() << "collisionObject ="; if (collisionObject) { if ( collisionObject->getName() != "" ) { visitor << "'" << collisionObject->getName() << "'"; } else { visitor << "unnamed(" << collisionObject << ")"; } } else { visitor << "0"; } visitor << "\n" << "transform =" << log::detailed(getTransform(), true) << "localToWorld =" << log::detailed(getLocalToWorld(), true); visitor.visitGroup(*this); visitor << log::unindent() << "}\n"; } void PhysicsTransform::accept(realm::EventVisitor& ev) { if ( !ev.getPhysicsToggle() ) { return; } if ( realm::Location* location = ev.getLocation() ) { if ( physics::DynamicsWorld* world = location->getDynamicsWorld() ) { if (ev.getType() == realm::EventVisitor::WORLD_ADD) { world->addRigidBody( static_cast<RigidBody*>(collisionObject.get()) ); } else if (ev.getType() == realm::EventVisitor::WORLD_REMOVE) { world->removeRigidBody( static_cast<RigidBody*>(collisionObject.get()) ); } } } } } // namespace physics } // namespace slon
[ "devnull@localhost" ]
[ [ [ 1, 129 ] ] ]
c02c017746602d9381caf04d79962cae9de5e299
847cccd728e768dc801d541a2d1169ef562311cd
/externalLibs/DbgLib/DbgLib/MemLeakDetector.cpp
847363267de9fd9168739e7b7f8025e194137c94
[]
no_license
aadarshasubedi/Ocerus
1bea105de9c78b741f3de445601f7dee07987b96
4920b99a89f52f991125c9ecfa7353925ea9603c
refs/heads/master
2021-01-17T17:50:00.472657
2011-03-25T13:26:12
2011-03-25T13:26:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,001
cpp
#include "stdafx.h" #include "DebugHelp.h" #include "MemLeakDetector.h" #include "Utils.h" #if defined(PLATFORM_WINDOWS) #pragma warning(disable: 4748) #endif #if defined(PLATFORM_WINDOWS) // we have to define _CRTBLD in order to include dbgint.h and mtdll.h #define _CRTBLD #ifdef _MT // required for synchronization with _mlock/_munlock #include <..\crt\src\mtdll.h> #endif // #ifdef _MT // required for internal crt heap structures #include <..\crt\src\dbgint.h> #undef _CRTBLD // macros for lock the heap (only when compiling with _MT) #ifdef _MT #define LOCK_HEAP _mlock(_HEAP_LOCK); #define UNLOCK_HEAP { _munlock(_HEAP_LOCK); } #else #define LOCK_HEAP #define UNLOCK_HEAP #endif #else // PLATFORM_WINDOWS #include <malloc.h> #define LOCK_HEAP #define UNLOCK_HEAP // static class members namespace DbgLib { CMemLeakDetector::MALLOCHOOKFUNC CMemLeakDetector::m_OldMallocFunc; // backup of the malloc function before hooking CMemLeakDetector::REALLOCHOOKFUNC CMemLeakDetector::m_OldReallocFunc; // backup of the realloc function before hooking CMemLeakDetector::FREEHOOKFUNC CMemLeakDetector::m_OldFreeFunc; // backup of the free function before hooking } // install our malloc hook initialization function #if defined(_DEBUG) && defined(AUTO_ENABLE_MEMLEAKDETECTOR) void (*__malloc_initialize_hook) (void) = DbgLib::CMemLeakDetector::InitHooks; #endif #endif // PLATFORM_WINDOWS namespace DbgLib { // Put the leak detector in the library initialization segment so we can trace memory allocs as soon as possible // Otherwise we could miss leaks caused by global/static objects. #if defined(PLATFORM_WINDOWS) #pragma warning(disable : 4073) #pragma init_seg(lib) #endif CMemLeakDetector g_MemLeakDetector; #if defined(PLATFORM_WINDOWS) #pragma warning(default : 4073) #endif ////////////////////////////////////////////////////////////////////////// CMemLeakDetector::CMemLeakDetector() { m_HooksEnabled = false; #if defined(PLATFORM_WINDOWS) m_Reporter = new CDefaultLeakReporter(true, true); m_CacheModuleInfo = true; #if defined(AUTO_ENABLE_MEMLEAKDETECTOR) Enable(); #endif #endif } CMemLeakDetector::~CMemLeakDetector() { #if defined(AUTO_ENABLE_MEMLEAKDETECTOR) // report leaks Disable(); ReportLeaks(); #endif #if defined(PLATFORM_WINDOWS) for(std::size_t i = 0; i < m_ModuleInfoVector.size(); ++i) _free_dbg(m_ModuleInfoVector[i].m_ModuleName, _CRT_BLOCK); #endif delete m_Reporter; } ////////////////////////////////////////////////////////////////////////// void CMemLeakDetector::TrackAllocInfo(uintx p_AllocID, uintx p_Size) { AllocInfo& ainfo = m_AllocInfoMap[p_AllocID]; #if defined(PLATFORM_UNIX) ainfo.m_Size = p_Size; #endif ainfo.m_CallstackSize = CDebugHelp::DoStackWalk(ainfo.m_Callstack, AllocInfo::MaxCallstackDepth); #if defined(PLATFORM_WINDOWS) // determine the names of all modules referenced in our callstack to load the symbol information // later on when reporting a leak for(uintx i = 0; i < ainfo.m_CallstackSize; ++i) { ainfo.m_ModuleReference[i] = -1; if(m_CacheModuleInfo) { // determine the module handle for the current callstack address MEMORY_BASIC_INFORMATION mbi; VirtualQuery(reinterpret_cast<LPCVOID>(static_cast<size_t>(ainfo.m_Callstack[i])), &mbi, sizeof(mbi)); HMODULE hModule = static_cast<HMODULE>(mbi.AllocationBase); // check if we already have that module in our vector for(uintx curModInfo = 0; curModInfo < m_ModuleInfoVector.size(); ++curModInfo) { if(m_ModuleInfoVector[curModInfo].m_hModule == hModule) ainfo.m_ModuleReference[i] = curModInfo; } // if we haven't got that module - determine it's name if(ainfo.m_ModuleReference[i] == -1) { TCHAR moduleName[MAX_PATH]; DWORD moduleNameSize = MAX_PATH; if((moduleNameSize = GetModuleFileName(hModule, moduleName, moduleNameSize)) != 0) { ModuleInfo modInfo; modInfo.m_hModule = hModule; modInfo.m_ModuleName = static_cast<tchar*>(_malloc_dbg(++moduleNameSize * sizeof(tchar), _CRT_BLOCK, __FILE__, __LINE__)); _tcscpy_s(modInfo.m_ModuleName, moduleNameSize, moduleName); m_ModuleInfoVector.push_back(modInfo); ainfo.m_ModuleReference[i] = static_cast<intx>(m_ModuleInfoVector.size() - 1); } } } } #else // set all module refs to -1 for(uintx i = 0; i < ainfo.m_CallstackSize; ++i) ainfo.m_ModuleReference[i] = -1; #endif } ////////////////////////////////////////////////////////////////////////// void CMemLeakDetector::RemoveAllocInfo(uintx p_AllocID) { m_AllocInfoMap.erase(p_AllocID); } ////////////////////////////////////////////////////////////////////////// void CMemLeakDetector::Enable() { if(m_HooksEnabled) return; #if defined(PLATFORM_WINDOWS) m_OldHook = _CrtSetAllocHook(CrtAllocHook); #else #if defined(_DEBUG) SaveHooks(); InstallHooks(); #endif #endif m_HooksEnabled = true; } ////////////////////////////////////////////////////////////////////////// void CMemLeakDetector::Disable() { if(!m_HooksEnabled) return; #if defined(PLATFORM_WINDOWS) _CrtSetAllocHook(m_OldHook); m_OldHook = NULL; #else #if defined(_DEBUG) RestoreHooks(); #endif #endif m_HooksEnabled = false; } ////////////////////////////////////////////////////////////////////////// void CMemLeakDetector::SetReporter(IMemLeakReporter* p_Reporter) { delete m_Reporter; m_Reporter = p_Reporter; } ////////////////////////////////////////////////////////////////////////// void CMemLeakDetector::ClearAllocInfo() { m_AllocInfoMap.clear(); #if defined(PLATFORM_WINDOWS) for(std::size_t i = 0; i < m_ModuleInfoVector.size(); ++i) _free_dbg(m_ModuleInfoVector[i].m_ModuleName, _CRT_BLOCK); m_ModuleInfoVector.clear(); #endif } ////////////////////////////////////////////////////////////////////////// void CMemLeakDetector::SetModuleInfoCaching(bool p_Enable) { #if defined(PLATFORM_WINDOWS) m_CacheModuleInfo = p_Enable; #else UNREFERENCED_PARAMETER(p_Enable); #endif } ////////////////////////////////////////////////////////////////////////// void CMemLeakDetector::ReportLeaks() { #ifdef _DEBUG // hooks must be disabled for reporting assert(!m_HooksEnabled); if(m_AllocInfoMap.size() > 0) { // start reporting m_Reporter->WriteHeader(static_cast<uintx>(m_AllocInfoMap.size())); // we'r accessing heap-internal structures so synchronize via heap lock LOCK_HEAP // We employ a simple trick here to get a pointer to the first allocated // block: just allocate a new block and get the new block's memory header. // This works because the most recently allocated block is always placed at // the head of the allocated list. We can then walk the list from head to // tail. For each block still in out allocation list search for the entry // in the crt list. #if defined(PLATFORM_WINDOWS) char *pHeap = new char; _CrtMemBlockHeader *pHeader = pHdr(pHeap)->pBlockHeaderNext; delete(pHeap); #endif // search through all alloc entries for(AllocInfoMap::iterator iter = m_AllocInfoMap.begin(); iter != m_AllocInfoMap.end(); ++iter) { AllocInfo& info = (*iter).second; uintx request = (*iter).first; #if defined(PLATFORM_WINDOWS) // search for entry in the crt list _CrtMemBlockHeader *pNext = pHeader; while(pNext && pNext->lRequest != request) pNext = pNext->pBlockHeaderNext; // write memory leak infos if(pNext && pNext->lRequest == request) m_Reporter->WriteLeak(request, pbData(pNext), static_cast<uintx>(pNext->nDataSize), info.m_CallstackSize, info.m_Callstack, info.m_ModuleReference, &m_ModuleInfoVector[0]); else m_Reporter->WriteLeak(request, NULL, 0, info.m_CallstackSize, info.m_Callstack, info.m_ModuleReference, &m_ModuleInfoVector[0]); #else // restore old malloc functions //RestoreHooks(); m_Reporter->WriteLeak(request, reinterpret_cast<void*>(request), info.m_Size, info.m_CallstackSize, info.m_Callstack, info.m_ModuleReference, NULL); // set hooking functions //SaveHooks(); //InstallHooks(); #endif } UNLOCK_HEAP // finished reporting m_Reporter->WriteFooter(); } #endif // _DEBUG } #if defined(PLATFORM_WINDOWS) ////////////////////////////////////////////////////////////////////////// int CMemLeakDetector::CrtAllocHook(int allocType, void *userData, size_t size, int blockType, long requestNumber, const unsigned char *filename, int lineNumber) { #ifdef _DEBUG UNREFERENCED_PARAMETER(size); UNREFERENCED_PARAMETER(filename); UNREFERENCED_PARAMETER(lineNumber); bool trackAllocation = true; // do not memory tracking on crt blocks or if detection is disabled for this thread if(blockType == _CRT_BLOCK) trackAllocation = false; // get the current debug flag bits, only track debug allocations // INFO: The _CrtSetDbgFlag does NOT store its flags thread local! // Therefore if one thread deactivates memory tracking, an allocation in another thread could not be tracked. // This MFC default usage behavior and must be implemented, otherwise many MFC memory leak will be reported. // The function does not affect applications without MFC, because this flag is not used by applications without MFC. int debugFlags = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); if(!(debugFlags & _CRTDBG_ALLOC_MEM_DF)) trackAllocation = false; // prevent the current thread from re-entering on allocs/reallocs/frees // that we or the CRT do internally to record the data we collect. if(trackAllocation) { // handle the allocation request switch(allocType) { case _HOOK_ALLOC: g_MemLeakDetector.TrackAllocInfo(requestNumber, 0); break; case _HOOK_FREE: g_MemLeakDetector.RemoveAllocInfo(pHdr(userData)->lRequest); break; case _HOOK_REALLOC: g_MemLeakDetector.RemoveAllocInfo(pHdr(userData)->lRequest); g_MemLeakDetector.TrackAllocInfo(requestNumber, 0); break; } } if(g_MemLeakDetector.m_OldHook) return g_MemLeakDetector.m_OldHook(blockType, userData, size, blockType, requestNumber, filename, lineNumber); #endif // _DEBUG return TRUE; } #else // PLATFORM_WINDOWS ////////////////////////////////////////////////////////////////////////// void CMemLeakDetector::InitHooks() { g_MemLeakDetector.m_Reporter = new CDefaultLeakReporter(true, true); g_MemLeakDetector.Enable(); } ////////////////////////////////////////////////////////////////////////// void* CMemLeakDetector::MallocHook(size_t p_Size, const void* p_Caller) { void *result; // Restore all old hooks RestoreHooks(); // Call recursively result = malloc(p_Size); // Save underlying hooks SaveHooks(); // might call malloc, so protect it too. if(result) g_MemLeakDetector.TrackAllocInfo((uintx)result, (uintx)p_Size); // Install our own hooks InstallHooks(); return result; } ////////////////////////////////////////////////////////////////////////// void* CMemLeakDetector::ReallocHook(void* p_MemPtr, size_t p_Size, const void* p_Caller) { void *result; // Restore all old hooks RestoreHooks(); // Call recursively result = realloc(p_MemPtr, p_Size); // Save underlying hooks SaveHooks(); // might call malloc, so protect it too. if(p_MemPtr) g_MemLeakDetector.RemoveAllocInfo((uintx)p_MemPtr); if(result) g_MemLeakDetector.TrackAllocInfo((uintx)result, (uintx)p_Size); // Install our own hooks InstallHooks(); return result; } ////////////////////////////////////////////////////////////////////////// void CMemLeakDetector::FreeHook(void* p_MemPtr, const void* p_Caller) { // Restore all old hooks RestoreHooks(); // Call recursively free(p_MemPtr); // Save underlying hooks SaveHooks(); // might call free, so protect it too. if(p_MemPtr) g_MemLeakDetector.RemoveAllocInfo((uintx)p_MemPtr); // install our own hooks InstallHooks(); } ////////////////////////////////////////////////////////////////////////// void CMemLeakDetector::InstallHooks() { __malloc_hook = CMemLeakDetector::MallocHook; __realloc_hook = CMemLeakDetector::ReallocHook; __free_hook = CMemLeakDetector::FreeHook; } ////////////////////////////////////////////////////////////////////////// void CMemLeakDetector::SaveHooks() { CMemLeakDetector::m_OldMallocFunc = __malloc_hook; CMemLeakDetector::m_OldReallocFunc = __realloc_hook; CMemLeakDetector::m_OldFreeFunc = __free_hook; } ////////////////////////////////////////////////////////////////////////// void CMemLeakDetector::RestoreHooks() { __malloc_hook = CMemLeakDetector::m_OldMallocFunc; __realloc_hook = CMemLeakDetector::m_OldReallocFunc; __free_hook = CMemLeakDetector::m_OldFreeFunc; } #endif // PLATFORM_WINDOWS ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// CDefaultLeakReporter::CDefaultLeakReporter(bool p_ShowDataBytes, bool p_ShowCallstack, uintx p_MaxLeaksToReport) : m_SymbolResolver(NULL), m_MaxLeaksToReport(p_MaxLeaksToReport), m_ShowDataBytes(p_ShowDataBytes), m_ShowCallstack(p_ShowCallstack) { // fill callstack ignore table #if defined(PLATFORM_WINDOWS) m_IgnoreCallstackFrames.push_back(_T("malloc_dbg")); m_IgnoreCallstackFrames.push_back(_T("malloc")); m_IgnoreCallstackFrames.push_back(_T("realloc_dbg")); m_IgnoreCallstackFrames.push_back(_T("realloc")); m_IgnoreCallstackFrames.push_back(_T("_heap_alloc_dbg")); m_IgnoreCallstackFrames.push_back(_T("_nh_malloc_dbg")); m_IgnoreCallstackFrames.push_back(_T("_malloc_dbg")); m_IgnoreCallstackFrames.push_back(_T("operator new")); m_IgnoreCallstackFrames.push_back(_T("operator new[]")); m_IgnoreCallstackFrames.push_back(_T("DbgLib::CDebugHelp::DoStackWalk")); m_IgnoreCallstackFrames.push_back(_T("DbgLib::CMemLeakDetector::TrackAllocInfo")); m_IgnoreCallstackFrames.push_back(_T("DbgLib::CMemLeakDetector::CrtAllocHook")); #else m_IgnoreCallstackFrames.push_back(_T("*DbgLib*CDebugHelp*DoStackWalk*")); m_IgnoreCallstackFrames.push_back(_T("*DbgLib*CMemLeakDetector*TrackAllocInfo*")); m_IgnoreCallstackFrames.push_back(_T("*DbgLib*CMemLeakDetector*MallocHook*")); m_IgnoreCallstackFrames.push_back(_T("*DbgLib*CMemLeakDetector*ReallocHook*")); m_IgnoreCallstackFrames.push_back(_T("*(calloc+0x*")); m_IgnoreCallstackFrames.push_back(_T("*(malloc+0x*")); #endif } CDefaultLeakReporter::~CDefaultLeakReporter() { delete m_SymbolResolver; } ////////////////////////////////////////////////////////////////////////// void CDefaultLeakReporter::WriteHeader(uintx p_LeaksFound) { assert(m_SymbolResolver == NULL); m_SymbolResolver = new CSymbolResolver(CSymbolResolver::GetDefaultSymbolSearchPath().c_str()); // write leaks to stream tostringstream outStream; outStream << _T("Detected ") << p_LeaksFound << (" memory leaks!") << std::endl; // check how much to dump if(m_MaxLeaksToReport > 0 && m_MaxLeaksToReport < p_LeaksFound) outStream << _T("Dumping the first ") << m_MaxLeaksToReport << _T(" leaks."); // write to debug output WriteDebugString(_T("----------------------------------------------------------------------------------------------------\n")); WriteDebugString(outStream.str().c_str()); } ////////////////////////////////////////////////////////////////////////// void CDefaultLeakReporter::WriteFooter() { WriteDebugString(_T("----------------------------------------------------------------------------------------------------\n")); delete m_SymbolResolver; m_SymbolResolver = NULL; } ////////////////////////////////////////////////////////////////////////// void CDefaultLeakReporter::WriteLeak(uintx p_Request, void* p_Data, uintx p_DataSize, uintx p_StackSize, uintx* p_Callstack, intx* p_ModRefs, CMemLeakDetector::ModuleInfo* p_ModuleInfo) { tostringstream leakInfoStream; leakInfoStream << _T("- Memleak: {") << std::dec << p_Request << _T("} at 0x") << Internal::Hex(digits_intx) << reinterpret_cast<size_t>(p_Data) << _T(", ") << std::dec << p_DataSize << _T(" bytes"); if(m_ShowDataBytes) { // print data buffer in ASCII leakInfoStream << _T(" <"); for(uintx i = 0; i < m_MaxDataBytes && i < p_DataSize; ++i) { tchar c = static_cast<tchar>(static_cast<byte*>(p_Data)[i]); if(c < 32) c = _T('.'); leakInfoStream << c; } leakInfoStream << _T(">"); // print data buffer in HEX leakInfoStream << _T(" { ") << Internal::Hex(2); for(uintx i = 0; i < m_MaxDataBytes && i < p_DataSize; ++i) leakInfoStream << static_cast<uintx>(static_cast<byte*>(p_Data)[i]) << _T(" "); leakInfoStream << _T("}"); } WriteDebugString(leakInfoStream.str().c_str()); // show callstack for(uintx i = 0; i < p_StackSize; ++i) { // get module name const tchar* moduleName = NULL; ModuleHandle hModule = NULL; if(p_ModRefs[i] != -1) { moduleName = p_ModuleInfo[p_ModRefs[i]].m_ModuleName; hModule = p_ModuleInfo[p_ModRefs[i]].m_hModule; } // resolve debug symbols tstring symFunc; tstring symFile; uintx symLine; m_SymbolResolver->ResolveSymbol(p_Callstack[i], hModule, moduleName, symFunc, symFile, symLine); // set unknown symbols if(symFunc.empty()) symFunc = _T("Unknown Function"); if(symFile.empty()) symFile = _T("Unknown File"); // ignore some functions bool ignore = false; for(uintx curEntry = 0; curEntry < m_IgnoreCallstackFrames.size(); ++curEntry) { if(Internal::WildMatch(m_IgnoreCallstackFrames[curEntry].c_str(), symFunc.c_str())) { ignore = true; break; } } if(!ignore) { // print symbols tostringstream stackInfoStream; stackInfoStream << _T(" ") << symFile << _T("(") << std::dec << symLine << _T(") : ") << symFunc << _T(" 0x") << Internal::Hex(digits_intx) << p_Callstack[i] << _T(" "); // write module name if(moduleName) { stackInfoStream.fill(_T(' ')); if(stackInfoStream.tellp() < 140) stackInfoStream << std::setw(140 - stackInfoStream.tellp()) << _T(" ") << std::setw(1); stackInfoStream << _T("(") << moduleName << _T(")"); } // write to debug output WriteDebugString(stackInfoStream.str().c_str()); } } } ////////////////////////////////////////////////////////////////////////// void CDefaultLeakReporter::WriteDebugString(const tchar* p_Msg) { #if defined(PLATFORM_WINDOWS) OutputDebugString(p_Msg); OutputDebugString(_T("\n")); #else #if defined(_UNICODE) fwprintf(stderr, p_Msg); fwprintf(stderr, _T("\n")); #else fprintf(stderr, "%s", p_Msg); fprintf(stderr, _T("\n")); #endif #endif } }
[ [ [ 1, 614 ] ] ]
66ab6584061ef721917f5ef35a771269f90adb02
b546f33f58d2fad0c6fd1bb431532ab6124c118a
/T42.h
b330a9f85534c768a24dc07a0936474268767a1e
[ "MIT" ]
permissive
hacker/T42
cdcc02f91d52262374f1e0b6f286e387bfb9b582
025f8c9b1a478eed9dcb9e0ac13b9e26e955860a
refs/heads/master
2021-01-20T11:59:58.800561
2005-08-06T13:59:18
2005-08-06T13:59:18
892,107
2
0
null
null
null
null
UTF-8
C++
false
false
2,079
h
// T42.h : main header file for the T42 application // #ifndef __AFXWIN_H__ #error include 'stdafx.h' before including this file for PCH #endif #include "resource.h" // main symbols ///////////////////////////////////////////////////////////////////////////// // CT42App: // See T42.cpp for the implementation of this class // class CT42Dlg; class CT42App : public CWinApp { public: void FlushT42CallsLog(); CString m_HelpFile; UINT m_T42TalkPort; UINT m_T42LinesBusy; BOOL m_bAwayOnScreenSaver; BOOL UpdateT42Call(CT42CallLogEntry& entry); CT42Dlg* m_pT42Dlg; BOOL DelT42Call(CTime& time); BOOL AddT42Call(CT42CallLogEntry& entry); LONG m_nT42Calls; LONG GetT42Calls(); BOOL GetT42Call(LONG call,CT42CallLogEntry& entry); LONG m_t42Call; BOOL CloseT42CallsLog(); BOOL OpenT42CallsLog(); CString m_t42CallsFile; CT42CallLog m_T42Calls; CString m_T42SGreeting; CTimeSpan m_T42STimeLimit; UINT m_T42SWinLimit; UINT m_T42SBytesLimit; COLORREF m_crT42LocalBG; COLORREF m_crT42RemoteBG; CHARFORMAT m_fmtT42System; CHARFORMAT m_fmtT42Remote; CHARFORMAT m_fmtT42Local; void Options(CWnd* pParent=NULL); void StopSound(LPCTSTR snd); BOOL StartSound(LPCTSTR snd,BOOL bLoop = FALSE); void Initialize(); CString m_sndTeapotWhistle; CString m_sndBoilingTeapot; CString m_sndTeaDrop; CString m_sndT42Wake; BOOL m_bT42PromptLoop; CString m_sndT42Prompt; CString m_sndT42Bell; BOOL m_bt42AutosaveLayout; UINT m_maxT42Callers; CStringList m_t42Callers; BOOL LastCaller(LPCTSTR caller); void LoadSettings(); void SaveSettings(); UINT m_maxT42Callees; BOOL LastCallee(LPCTSTR callee); CStringList m_t42Callees; CDocTemplate* m_pTemplate; CT42App(); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CT42App) public: virtual BOOL InitInstance(); //}}AFX_VIRTUAL // Implementation //{{AFX_MSG(CT42App) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; /////////////////////////////////////////////////////////////////////////////
[ [ [ 1, 83 ] ] ]
367e2f13c43345ea5a025bb8149b6fa1d87caed7
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/tags/techdemo2/engine/ui/include/JournalWindow.h
ad1ff3675a1b8873f11b172c5277db8a0cda6f30
[ "ClArtistic", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
jacmoe/dsa-hl-svn
55b05b6f28b0b8b216eac7b0f9eedf650d116f85
97798e1f54df9d5785fb206c7165cd011c611560
refs/heads/master
2021-04-22T12:07:43.389214
2009-11-27T22:01:03
2009-11-27T22:01:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,192
h
/* This source file is part of Rastullahs Lockenpracht. * Copyright (C) 2003-2005 Team Pantheon. http://www.team-pantheon.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the Clarified Artistic License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not you can get it here * http://www.jpaulmorrison.com/fbp/artistic2.htm. */ #ifndef __JOURNALWINDOW_H__ #define __JOURNALWINDOW_H__ #include "UiPrerequisites.h" #include "CeGuiWindow.h" #include "QuestListener.h" namespace rl { class JournalWindow : public CeGuiWindow, public QuestListener { public: JournalWindow(); virtual ~JournalWindow(); virtual void questStateChanged(QuestEvent* anEvent); virtual void questPartsDoneChanged(QuestEvent* anEvent); virtual void questKnownChanged(QuestEvent* anEvent); virtual void questSubquestAdded(QuestEvent* anEvent); virtual void journalEntryAdded(JournalEvent* anEvent); private: CEGUI::Listbox* mQuests; CEGUI::StaticText* mQuestTitle; CEGUI::StaticText* mQuestState; CEGUI::MultiLineEditbox* mQuestDescription; CEGUI::Listbox* mJournalEntries; CEGUI::StaticText* mJournalEntryTitle; CEGUI::MultiLineEditbox* mJournalEntryText; CeGuiString mSelectionBrush; CeGuiString mSelectionImageset; CEGUI::colour mSelectionColour; void updateQuests(); void selectQuest(CEGUI::ListboxItem* item); bool updateQuestSelection(); void addQuest(Quest* quest, int level = 0); void updateJournal(); void selectJournalEntry(CEGUI::ListboxItem* item); bool updateJournalEntrySelection(); void addJournalEntry(JournalEntry* entry); }; } #endif //__JOURNALWINDOW_H__
[ "tanis@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 64 ] ] ]
a01e9ecf22f21a8618bfefd94a54e57755779b4e
5f0b8d4a0817a46a9ae18a057a62c2442c0eb17e
/Include/theme/Default/ButtonTheme.h
12192df9de08617629c3d0d255b6c3bbf23154c9
[ "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
2,685
h
/* * 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. */ #ifndef BUTTONTHEME_H #define BUTTONTHEME_H #include "./ComponentTheme.h" #include "../../util/GradientColor.h" #include "../../border/BevelBorder.h" #include "../../event/PropertyListener.h" #include "../../event/KeyListener.h" namespace ui { namespace theme { namespace defaulttheme { class ButtonTheme : public ComponentTheme, public event::PropertyListener, public event::KeyListener { public: ButtonTheme(); void installTheme(Component *comp); void deinstallTheme(Component *comp); void paint(Graphics& g,const Component *comp) const; const util::Dimension getPreferredSize(const Component *comp) const; private: void propertyChanged(const event::PropertyEvent &e); void keyPressed(const event::KeyEvent &e); void keyReleased(const event::KeyEvent &e); void keyTyped(const event::KeyEvent &e); util::GradientColor backgroundRaised; util::GradientColor backgroundLowered; util::Color foreground; util::Color focus; border::BevelBorder borderRaised; border::BevelBorder borderLowered; }; } } } #endif
[ "bs@bram.(none)" ]
[ [ [ 1, 70 ] ] ]
27bc8f3f397be666523a1bb3ec87c1dd22e5267c
974a20e0f85d6ac74c6d7e16be463565c637d135
/trunk/packages/dMath/dQuaternion.cpp
9c6cf755fe3d84856b73573fc5edd3eb2064b8aa
[]
no_license
Naddiseo/Newton-Dynamics-fork
cb0b8429943b9faca9a83126280aa4f2e6944f7f
91ac59c9687258c3e653f592c32a57b61dc62fb6
refs/heads/master
2021-01-15T13:45:04.651163
2011-11-12T04:02:33
2011-11-12T04:02:33
2,759,246
0
0
null
null
null
null
UTF-8
C++
false
false
4,791
cpp
/* Copyright (c) <2009> <Newton Game Dynamics> * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely */ #include "dStdAfxMath.h" #include "dMathDefines.h" #include "dVector.h" #include "dMatrix.h" #include "dQuaternion.h" dQuaternion::dQuaternion (const dMatrix &matrix) { enum QUAT_INDEX { X_INDEX=0, Y_INDEX=1, Z_INDEX=2 }; static QUAT_INDEX QIndex [] = {Y_INDEX, Z_INDEX, X_INDEX}; dFloat *ptr; dFloat trace; QUAT_INDEX i; QUAT_INDEX j; QUAT_INDEX k; trace = matrix[0][0] + matrix[1][1] + matrix[2][2]; _ASSERTE (((matrix[0] * matrix[1]) % matrix[2]) > 0.0f); if (trace > dFloat(0.0f)) { trace = dSqrt (trace + dFloat(1.0f)); m_q0 = dFloat (0.5f) * trace; trace = dFloat (0.5f) / trace; m_q1 = (matrix[1][2] - matrix[2][1]) * trace; m_q2 = (matrix[2][0] - matrix[0][2]) * trace; m_q3 = (matrix[0][1] - matrix[1][0]) * trace; } else { i = X_INDEX; if (matrix[Y_INDEX][Y_INDEX] > matrix[X_INDEX][X_INDEX]) { i = Y_INDEX; } if (matrix[Z_INDEX][Z_INDEX] > matrix[i][i]) { i = Z_INDEX; } j = QIndex [i]; k = QIndex [j]; trace = dFloat(1.0f) + matrix[i][i] - matrix[j][j] - matrix[k][k]; trace = dSqrt (trace); ptr = &m_q1; ptr[i] = dFloat (0.5f) * trace; trace = dFloat (0.5f) / trace; m_q0 = (matrix[j][k] - matrix[k][j]) * trace; ptr[j] = (matrix[i][j] + matrix[j][i]) * trace; ptr[k] = (matrix[i][k] + matrix[k][i]) * trace; } #if _DEBUG dMatrix tmp (*this, matrix.m_posit); dMatrix unitMatrix (tmp * matrix.Inverse()); for (int i = 0; i < 4; i ++) { dFloat err = dAbs (unitMatrix[i][i] - dFloat(1.0f)); _ASSERTE (err < dFloat (1.0e-3f)); } dFloat err = dAbs (DotProduct(*this) - dFloat(1.0f)); _ASSERTE (err < dFloat(1.0e-3f)); #endif } dQuaternion::dQuaternion (const dVector &unitAxis, dFloat Angle) { dFloat sinAng; Angle *= dFloat (0.5f); m_q0 = dCos (Angle); sinAng = dSin (Angle); #ifdef _DEBUG if (dAbs (Angle) > dFloat(1.0e-6f)) { _ASSERTE (dAbs (dFloat(1.0f) - unitAxis % unitAxis) < dFloat(1.0e-3f)); } #endif m_q1 = unitAxis.m_x * sinAng; m_q2 = unitAxis.m_y * sinAng; m_q3 = unitAxis.m_z * sinAng; } dVector dQuaternion::CalcAverageOmega (const dQuaternion &QB, dFloat dt) const { dFloat dirMag; dFloat dirMag2; dFloat omegaMag; dFloat dirMagInv; dQuaternion dq (Inverse() * QB); dVector omegaDir (dq.m_q1, dq.m_q2, dq.m_q3); dirMag2 = omegaDir % omegaDir; if (dirMag2 < dFloat(dFloat (1.0e-5f) * dFloat (1.0e-5f))) { return dVector (dFloat(0.0f), dFloat(0.0f), dFloat(0.0f), dFloat(0.0f)); } dirMagInv = dFloat (1.0f) / dSqrt (dirMag2); dirMag = dirMag2 * dirMagInv; omegaMag = dFloat(2.0f) * dAtan2 (dirMag, dq.m_q0) / dt; return omegaDir.Scale (dirMagInv * omegaMag); } dQuaternion dQuaternion::Slerp (const dQuaternion &QB, dFloat t) const { dFloat dot; dFloat ang; dFloat Sclp; dFloat Sclq; dFloat den; dFloat sinAng; dQuaternion Q; dot = DotProduct (QB); _ASSERTE (dot >= 0.0f); if ((dot + dFloat(1.0f)) > dFloat(1.0e-5f)) { if (dot < dFloat(0.995f)) { ang = dAcos (dot); sinAng = dSin (ang); den = dFloat(1.0f) / sinAng; Sclp = dSin ((dFloat(1.0f) - t ) * ang) * den; Sclq = dSin (t * ang) * den; } else { Sclp = dFloat(1.0f) - t; Sclq = t; } Q.m_q0 = m_q0 * Sclp + QB.m_q0 * Sclq; Q.m_q1 = m_q1 * Sclp + QB.m_q1 * Sclq; Q.m_q2 = m_q2 * Sclp + QB.m_q2 * Sclq; Q.m_q3 = m_q3 * Sclp + QB.m_q3 * Sclq; } else { Q.m_q0 = m_q3; Q.m_q1 = -m_q2; Q.m_q2 = m_q1; Q.m_q3 = m_q0; Sclp = dSin ((dFloat(1.0f) - t) * dFloat (3.141592f *0.5f)); Sclq = dSin (t * dFloat (3.141592f * 0.5f)); Q.m_q0 = m_q0 * Sclp + Q.m_q0 * Sclq; Q.m_q1 = m_q1 * Sclp + Q.m_q1 * Sclq; Q.m_q2 = m_q2 * Sclp + Q.m_q2 * Sclq; Q.m_q3 = m_q3 * Sclp + Q.m_q3 * Sclq; } dot = Q.DotProduct (Q); if ((dot) < (1.0f - 1.0e-4f) ) { dot = dFloat(1.0f) / dSqrt (dot); //dot = dgRsqrt (dot); Q.m_q0 *= dot; Q.m_q1 *= dot; Q.m_q2 *= dot; Q.m_q3 *= dot; } return Q; } dVector dQuaternion::RotateVector (const dVector& point) const { dMatrix matrix (*this, dVector (0.0f, 0.0f, 0.0f, 1.0f)); return matrix.RotateVector(point); } dVector dQuaternion::UnrotateVector (const dVector& point) const { dMatrix matrix (*this, dVector (0.0f, 0.0f, 0.0f, 1.0f)); return matrix.UnrotateVector(point); }
[ "[email protected]@b7a2f1d6-d59d-a8fe-1e9e-8d4888b32692" ]
[ [ [ 1, 202 ] ] ]
1011d152515ddefa94a4726426fe9a8f70035531
38664d844d9fad34e88160f6ebf86c043db9f1c5
/branches/initialize/cwf/render.hpp
82e15334cc56f3485bdd93c13fc7c3c4d846d1a6
[]
no_license
cnsuhao/jezzitest
84074b938b3e06ae820842dac62dae116d5fdaba
9b5f6cf40750511350e5456349ead8346cabb56e
refs/heads/master
2021-05-28T23:08:59.663581
2010-11-25T13:44:57
2010-11-25T13:44:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,355
hpp
#ifndef CWF_RENDER_HPP_ #define CWF_RENDER_HPP_ #include "cwf/http.hpp" namespace cwf { class HostInfo { public: // server name // address // document root // config // const std::string & config(const std::string &) const; const std::string & name() const; const std::string & document_root() const; }; class RequestInfo { public: // ip, ... }; enum RenderResult { RR_FAILED, RR_SUCCEEDED, RR_ASYNC, }; class ResponsePipe { public: virtual bool Write(const char *buf, std::size_t len) = 0; // error detail virtual bool Close() = 0; // need ? }; typedef bool(*RenderFunction)(const HostInfo *, const RequestInfo * , const http::HttpRequest *, http::HttpResponse *, ResponsePipe *); RenderResult NullRender(const HostInfo *, const RequestInfo * , const http::HttpRequest *, http::HttpResponse *, ResponsePipe *); RenderResult ServerErrorRender(const HostInfo *, const RequestInfo * , const http::HttpRequest *, http::HttpResponse *, ResponsePipe *); RenderResult StaticRender(const HostInfo *, const RequestInfo * , const http::HttpRequest *, http::HttpResponse *, ResponsePipe *); RenderResult TemplateRender(const HostInfo *, const RequestInfo * , const http::HttpRequest *, http::HttpResponse *, ResponsePipe *); } #endif // CWF_RENDER_HPP_
[ "ken.shao@ba8f1dc9-3c1c-0410-9eed-0f8a660c14bd" ]
[ [ [ 1, 52 ] ] ]
57a10968f7fb2625a041cda581c45e311e2ff8d5
c0bd82eb640d8594f2d2b76262566288676b8395
/src/game/AIInterface.cpp
f8a995549ace8cc95ec74e0dd26cf6cdbfc3248d
[ "FSFUL" ]
permissive
vata/solution
4c6551b9253d8f23ad5e72f4a96fc80e55e583c9
774fca057d12a906128f9231831ae2e10a947da6
refs/heads/master
2021-01-10T02:08:50.032837
2007-11-13T22:01:17
2007-11-13T22:01:17
45,352,930
0
1
null
null
null
null
UTF-8
C++
false
false
130,765
cpp
// Copyright (C) 2004 WoW Daemon // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "StdAfx.h" AIInterface::AIInterface() { m_canMove = true; m_destinationX = m_destinationY = m_destinationZ = 0; m_nextPosX = m_nextPosY = m_nextPosZ = 0; UnitToFollow = NULL; FollowDistance = 0.0f; m_fallowAngle = M_PI/2; m_timeToMove = 0; m_timeMoved = 0; m_moveTimer = 0; m_nWaypoints = 0; m_WayPointsShowing = false; m_WayPointsShowBackwards = false; m_currentWaypoint = 0; m_moveBackward = false; m_moveType = 0; m_moveRun = false; m_moveSprint = false; m_moveFly = false; m_creatureState = STOPPED; m_canCallForHelp = false; m_hasCalledForHelp = false; m_fleeTimer = 0; m_FleeDuration = 0; m_canFlee = false; m_hasFleed = false; m_canRangedAttack = false; m_FleeHealth = m_CallForHelpHealth = 0.0f; m_AIState = STATE_IDLE; m_updateAssist = false; m_updateTargets = false; m_updateAssistTimer = 1; m_updateTargetsTimer = TARGET_UPDATE_INTERVAL; m_hasOnEnterCombatSpells = m_hasOnLeaveCombatSpells = m_hasOnDamageTakenSpells = m_hasOnTargetCastSpellSpells = m_hasOnTargetParryedSpells = m_hasOnTargetDodgedSpells = m_hasOnTargetBlockedSpells = m_hasOnTargetCritHitSpells = m_hasOnTargetDiedSpells = m_hasOnUnitParryedSpells = m_hasOnUnitDodgedSpells = m_hasOnUnitBlockedSpells = m_hasOnUnitCritHitSpells = m_hasOnUnitDiedSpells = m_hasOnAssistTargetDiedSpells = m_hasOnFollowOwnerSpells = m_hasCooldownOnEnterCombatSpells = m_hasCooldownOnLeaveCombatSpells = m_hasCooldownOnDamageTakenSpells = m_hasCooldownOnTargetCastSpellSpells = m_hasCooldownOnTargetParryedSpells = m_hasCooldownOnTargetDodgedSpells = m_hasCooldownOnTargetBlockedSpells = m_hasCooldownOnTargetCritHitSpells = m_hasCooldownOnTargetDiedSpells = m_hasCooldownOnUnitParryedSpells = m_hasCooldownOnUnitDodgedSpells = m_hasCooldownOnUnitBlockedSpells = m_hasCooldownOnUnitCritHitSpells = m_hasCooldownOnUnitDiedSpells = m_hasCooldownOnAssistTargetDiedSpells = m_hasCooldownOnFollowOwnerSpells = false; m_nextSpell = NULL; m_nextTarget = NULL; m_Unit = NULL; m_PetOwner = NULL; m_aiCurrentAgent = AGENT_NULL; m_moveSpeed = 0.0f; UnitToFear = NULL; firstLeaveCombat = true; m_outOfCombatRange = 2500; tauntedBy = NULL; isTaunted = false; m_AllowedToEnterCombat = true; m_DefaultSpell = m_DefaultMeleeSpell = NULL; m_totalMoveTime = 0; m_lastFollowX = m_lastFollowY = 0; m_FearTimer = 0; m_WanderTimer = 0; m_totemspelltime = 0; m_totemspelltimer = 0; m_formationFollowAngle = 0.0f; m_formationFollowDistance = 0.0f; m_formationLinkTarget = 0; m_formationLinkSqlId = 0; } void AIInterface::Init(Unit *un, AIType at, MovementType mt) { ASSERT(at != AITYPE_PET); m_AIType = at; m_MovementType = mt; m_AIState = STATE_IDLE; m_MovementState = MOVEMENTSTATE_STOP; m_Unit = un; m_moveSpeed = m_Unit->m_runSpeed*0.001f; if(!m_DefaultMeleeSpell) { m_DefaultMeleeSpell = new AI_Spell; m_DefaultMeleeSpell->entryId = 0; m_DefaultMeleeSpell->spellType = 0; m_DefaultMeleeSpell->agent = AGENT_MELEE; m_DefaultSpell = m_DefaultMeleeSpell; } m_sourceX = un->GetPositionX(); m_sourceY = un->GetPositionY(); m_sourceZ = un->GetPositionZ(); m_guardTimer = getMSTime(); } AIInterface::~AIInterface() { // cleanup all spell maps CleanupSpellMap(&m_OnEnterCombatSpells); CleanupSpellMap(&m_OnLeaveCombatSpells); CleanupSpellMap(&m_OnDamageTakenSpells); CleanupSpellMap(&m_OnTargetCastSpellSpells); CleanupSpellMap(&m_OnTargetParryedSpells); CleanupSpellMap(&m_OnTargetDodgedSpells); CleanupSpellMap(&m_OnTargetBlockedSpells); CleanupSpellMap(&m_OnTargetCritHitSpells); CleanupSpellMap(&m_OnTargetDiedSpells); CleanupSpellMap(&m_OnUnitParryedSpells); CleanupSpellMap(&m_OnUnitDodgedSpells); CleanupSpellMap(&m_OnUnitCritHitSpells); CleanupSpellMap(&m_OnUnitBlockedSpells); CleanupSpellMap(&m_OnUnitDiedSpells); CleanupSpellMap(&m_OnAssistTargetDiedSpells); CleanupSpellMap(&m_OnFollowOwnerSpells); if(m_DefaultMeleeSpell) delete m_DefaultMeleeSpell; #ifndef PRECACHE_LOAD for(WayPointMap::iterator iter = m_waypoints.begin(); iter != m_waypoints.end(); ++iter) { delete iter->second; } #endif m_waypoints.clear(); } void AIInterface::Init(Unit *un, AIType at, MovementType mt, Unit *owner) { ASSERT(at == AITYPE_PET || at == AITYPE_TOTEM); m_AIType = at; m_MovementType = mt; m_AIState = STATE_IDLE; m_MovementState = MOVEMENTSTATE_STOP; m_Unit = un; m_PetOwner = owner; m_moveSpeed = m_Unit->m_runSpeed*0.001f; if(!m_DefaultMeleeSpell) { m_DefaultMeleeSpell = new AI_Spell; m_DefaultMeleeSpell->agent = AGENT_MELEE; m_DefaultSpell = m_DefaultMeleeSpell; } m_sourceX = un->GetPositionX(); m_sourceY = un->GetPositionY(); m_sourceZ = un->GetPositionZ(); } void AIInterface::HandleEvent(uint32 event, Unit* pUnit, uint32 misc1) { if(!pUnit) return; if(m_AIState != STATE_EVADE) { switch(event) { case EVENT_ENTERCOMBAT: { CALL_SCRIPT_EVENT(m_Unit, OnCombatStart)(pUnit); // Stop the emote m_Unit->SetUInt32Value(UNIT_NPC_EMOTESTATE, 0); m_returnX = m_Unit->GetPositionX(); m_returnY = m_Unit->GetPositionY(); m_returnZ = m_Unit->GetPositionZ(); m_moveRun = true; //run to the target if(m_AIState != STATE_ATTACKING) StopMovement(0); m_AIState = STATE_ATTACKING; m_nextSpell = getSpellByEvent(event); m_nextTarget = FindTargetForSpell(m_nextSpell); firstLeaveCombat = true; if(pUnit) { m_Unit->SetUInt64Value(UNIT_FIELD_TARGET, pUnit->GetGUID()); } }break; case EVENT_LEAVECOMBAT: { // restart emote if(m_Unit->GetBaseUInt32Value(UNIT_NPC_EMOTESTATE) != 0) m_Unit->SetUInt32Value(UNIT_NPC_EMOTESTATE, m_Unit->GetBaseUInt32Value(UNIT_NPC_EMOTESTATE)); if(m_AIType == AITYPE_PET) { m_AIState = STATE_FOLLOWING; UnitToFollow = m_PetOwner; FollowDistance = 3.0f; m_lastFollowX = m_lastFollowY = 0; ((Pet*)m_Unit)->SetPetAction(PET_ACTION_FOLLOW); HandleEvent(EVENT_FOLLOWOWNER, 0, 0); } else { CALL_SCRIPT_EVENT(m_Unit, OnCombatStop)(UnitToFollow); m_AIState = STATE_EVADE; m_Unit->setAttackTarget(NULL); UnitToFollow = NULL; FollowDistance = 0.0f; m_lastFollowX = m_lastFollowY = 0; } m_aiTargets.clear(); m_fleeTimer = 0; m_hasFleed = false; m_hasCalledForHelp = false; m_nextSpell = NULL; m_nextTarget = NULL; m_Unit->SetUInt64Value(UNIT_FIELD_TARGET, 0); resetSpellCounter(); firstLeaveCombat = false; // Scan for a new target before moving back on waypoint path Unit * Target = FindTarget(); if(Target != NULL) AttackReaction(Target, 1, 0, 0); else firstLeaveCombat = true; /*SpellEntry* spell = getSpellEntry(2054); Affect* aff = new Affect(spell, 6000, m_Unit->GetGUID()); aff->SetHealPerTick(uint16(m_Unit->GetUInt32Value(UNIT_FIELD_MAXHEALTH)/4), 2000); m_Unit->AddAffect(aff);*/ }break; case EVENT_DAMAGETAKEN: { CALL_SCRIPT_EVENT(m_Unit, OnDamageTaken)(pUnit, misc1); if(!modThreatByPtr(pUnit, misc1)) { m_aiTargets.insert(TargetMap::value_type(pUnit, misc1)); } m_nextSpell = getSpellByEvent(event); m_nextTarget = FindTargetForSpell(m_nextSpell); }break; case EVENT_TARGETCASTSPELL: { CALL_SCRIPT_EVENT(m_Unit, OnCastSpell)(0); //fixme m_nextSpell = getSpellByEvent(event); m_nextTarget = FindTargetForSpell(m_nextSpell); }break; case EVENT_TARGETPARRYED: { CALL_SCRIPT_EVENT(m_Unit, OnTargetParried)(pUnit); m_nextSpell = getSpellByEvent(event); m_nextTarget = FindTargetForSpell(m_nextSpell); }break; case EVENT_TARGETDODGED: { CALL_SCRIPT_EVENT(m_Unit, OnTargetDodged)(pUnit); m_nextSpell = getSpellByEvent(event); m_nextTarget = FindTargetForSpell(m_nextSpell); }break; case EVENT_TARGETBLOCKED: { CALL_SCRIPT_EVENT(m_Unit, OnTargetBlocked)(pUnit,misc1); m_nextSpell = getSpellByEvent(event); m_nextTarget = FindTargetForSpell(m_nextSpell); }break; case EVENT_TARGETCRITHIT: { CALL_SCRIPT_EVENT(m_Unit, OnTargetCritHit)(pUnit,(float)misc1); m_nextSpell = getSpellByEvent(event); m_nextTarget = FindTargetForSpell(m_nextSpell); }break; case EVENT_TARGETDIED: { CALL_SCRIPT_EVENT(m_Unit, OnTargetDied)(pUnit); m_nextSpell = getSpellByEvent(event); m_nextTarget = FindTargetForSpell(m_nextSpell); }break; case EVENT_UNITPARRYED: { CALL_SCRIPT_EVENT(m_Unit, OnParried)(pUnit); m_nextSpell = getSpellByEvent(event); m_nextTarget = FindTargetForSpell(m_nextSpell); }break; case EVENT_UNITDODGED: { CALL_SCRIPT_EVENT(m_Unit, OnDodged)(pUnit); m_nextSpell = getSpellByEvent(event); m_nextTarget = FindTargetForSpell(m_nextSpell); }break; case EVENT_UNITBLOCKED: { CALL_SCRIPT_EVENT(m_Unit, OnBlocked)(pUnit, misc1); m_nextSpell = getSpellByEvent(event); m_nextTarget = FindTargetForSpell(m_nextSpell); }break; case EVENT_UNITCRITHIT: { CALL_SCRIPT_EVENT(m_Unit, OnCritHit)(pUnit, (float)misc1); m_nextSpell = getSpellByEvent(event); m_nextTarget = FindTargetForSpell(m_nextSpell); }break; case EVENT_ASSISTTARGETDIED: { CALL_SCRIPT_EVENT(m_Unit, OnAssistTargetDied)(pUnit); m_nextSpell = getSpellByEvent(event); m_nextTarget = FindTargetForSpell(m_nextSpell); }break; case EVENT_FOLLOWOWNER: { m_AIState = STATE_FOLLOWING; if(m_Unit->GetGUIDHigh() == HIGHGUID_PET) ((Pet*)m_Unit)->SetPetAction(PET_ACTION_FOLLOW); UnitToFollow = m_PetOwner; m_lastFollowX = m_lastFollowY = 0; FollowDistance = 4.0f; m_aiTargets.clear(); m_fleeTimer = 0; m_hasFleed = false; m_hasCalledForHelp = false; m_nextSpell = NULL; m_nextTarget = NULL; m_Unit->SetUInt64Value(UNIT_FIELD_TARGET, 0); resetSpellCounter(); }break; case EVENT_PET_ATTACK: { m_AIState = STATE_ATTACKING; m_Unit->GetAIInterface()->AttackReaction(pUnit,1,0); }break; case EVENT_FEAR: { CALL_SCRIPT_EVENT(m_Unit, OnFear)(pUnit, 0); m_AIState = STATE_FEAR; StopMovement(1); UnitToFollow = NULL; m_lastFollowX = m_lastFollowY = 0; FollowDistance = 0.0f; m_aiTargets.clear(); m_fleeTimer = 0; m_hasFleed = false; m_hasCalledForHelp = false; m_moveRun = true; // update speed m_Unit->m_runSpeed /= 2; getMoveFlags(); m_nextSpell = NULL; m_nextTarget = NULL; m_Unit->SetUInt64Value(UNIT_FIELD_TARGET, 0); //m_Unit->setAttackTarget(NULL); resetSpellCounter(); }break; case EVENT_UNFEAR: { // update speed m_Unit->m_runSpeed *= 2; getMoveFlags(); }break; case EVENT_WANDER: { //CALL_SCRIPT_EVENT(m_Unit, OnWander)(pUnit, 0); FIXME m_AIState = STATE_WANDER; StopMovement(1); UnitToFollow = NULL; m_lastFollowX = m_lastFollowY = 0; FollowDistance = 0.0f; m_aiTargets.clear(); m_fleeTimer = 0; m_hasFleed = false; m_hasCalledForHelp = false; m_moveRun = true; // update speed m_Unit->m_runSpeed /= 2; getMoveFlags(); m_nextSpell = NULL; m_nextTarget = NULL; m_Unit->SetUInt64Value(UNIT_FIELD_TARGET, 0); //m_Unit->setAttackTarget(NULL); resetSpellCounter(); }break; case EVENT_UNWANDER: { // update speed m_Unit->m_runSpeed *= 2; getMoveFlags(); }break; default: { }break; } } if(event != EVENT_UNITDIED) m_Unit->setAttackTarget(m_nextTarget); //Should be able to do this stuff even when evading switch(event) { case EVENT_UNITDIED: { CALL_SCRIPT_EVENT(m_Unit, OnDied)(pUnit); m_AIState = STATE_IDLE; StopMovement(0); m_aiTargets.clear(); UnitToFollow = NULL; m_lastFollowX = m_lastFollowY = 0; UnitToFear = NULL; FollowDistance = 0.0f; m_fleeTimer = 0; m_hasFleed = false; m_hasCalledForHelp = false; m_nextSpell = NULL; m_nextTarget = NULL; //reset waypoint to 0 m_currentWaypoint = 0; m_Unit->SetUInt64Value(UNIT_FIELD_TARGET, 0); // There isn't any need to do any attacker checks here, as // they should all be taken care of in DealDamage resetSpellCounter(); //BURLEXFIXME: check state, and follow owner again if appropriate if(m_AIType == AITYPE_PET) { SetUnitToFollow(m_PetOwner); SetFollowDistance(3.0f); HandleEvent(EVENT_FOLLOWOWNER, m_Unit, 0); } }break; } } void AIInterface::Update(uint32 p_time) { if(m_AIType == AITYPE_TOTEM) { assert(m_DefaultSpell != 0 && totemspell != 0); if(p_time >= m_totemspelltimer) { // these will *almost always* be AoE, so no need to find a target here. SpellCastTargets targets(m_Unit->GetGUID()); Spell * pSpell = new Spell(m_Unit, totemspell, true, 0); pSpell->prepare(&targets); // need proper cooldown time! m_totemspelltimer = m_totemspelltime; } else { m_totemspelltimer -= p_time; } return; } _UpdateTimer(p_time); _UpdateTargets(); if(m_Unit->isAlive() && m_AIState != STATE_IDLE && m_AIState != STATE_FOLLOWING && m_AIState != STATE_FEAR && m_AIState != STATE_WANDER && m_AIState != STATE_SCRIPTMOVE) { if(m_AIType == AITYPE_PET ) { Pet * pPet = static_cast<Pet*>(m_Unit); if(pPet->GetPetAction() == PET_ACTION_ATTACK || pPet->GetPetState() != PET_STATE_PASSIVE) { // todo: some check for autocast here /*if(m_DefaultSpell && !m_nextSpell) m_nextSpell = m_DefaultSpell;*/ if(m_DefaultSpell && !m_nextSpell) { if(m_DefaultSpell->agent == AGENT_SPELL) { // Check cooldown on this spell if(pPet->GetSpellCooldown(m_DefaultSpell->spellId) == 0) { // We're fine to cast. m_nextSpell = m_DefaultSpell; } else { // Waiting for cooldown to expire.... } } } _UpdateCombat(p_time); } } else { _UpdateCombat(p_time); } } _UpdateMovement(p_time); if(m_AIState == STATE_EVADE) { if(m_creatureState != MOVING) { if(m_AIType == AITYPE_PET && m_PetOwner != NULL) { m_returnX = m_PetOwner->GetPositionX()+(3*(cosf(m_fallowAngle+m_PetOwner->GetOrientation()))); m_returnY = m_PetOwner->GetPositionY()+(3*(sinf(m_fallowAngle+m_PetOwner->GetOrientation()))); m_returnZ = m_PetOwner->GetPositionZ(); } if(m_returnX != 0.0f && m_returnY != 0.0f && m_returnZ != 0.0f) { //return to last position before attacking MoveTo(m_returnX,m_returnY,m_returnZ,m_Unit->GetOrientation()); } } //else //{ if(m_returnX !=0.0f && m_returnY != 0.0f) { if(m_Unit->GetDistanceSq(m_returnX,m_returnY,m_returnZ) < 4.0f/*2.0*/) { m_AIState = STATE_IDLE; m_returnX = m_returnY = m_returnZ = 0.0f; if(hasWaypoints()) { if(m_moveBackward) { if(m_currentWaypoint != m_nWaypoints-1) m_currentWaypoint++; } else { if(m_currentWaypoint != 0) m_currentWaypoint--; } } // Set health to full if they at there last location before attacking if(m_Unit->GetMapId() > 1 && m_Unit->GetMapId() != 530) m_Unit->SetUInt32Value(UNIT_FIELD_HEALTH,m_Unit->GetUInt32Value(UNIT_FIELD_MAXHEALTH)); } } //} } if(m_fleeTimer) { if(m_fleeTimer > p_time) { m_fleeTimer -= p_time; _CalcDestinationAndMove(m_nextTarget, 5.0f); } else { m_fleeTimer = 0; m_nextTarget = FindTargetForSpell(m_nextSpell); } } //Pet Dismiss after a certian ditance away if(m_AIType == AITYPE_PET && m_PetOwner != NULL) { float dist = m_Unit->GetDistanceSq(m_PetOwner); if(dist > 8100.0f/*90.0f*/) //90 yard away we Dismissed { DismissPet(); return; } } } void AIInterface::_UpdateTimer(uint32 p_time) { if(m_updateAssistTimer > p_time) { m_updateAssistTimer -= p_time; }else { m_updateAssist = true; m_updateAssistTimer = TARGET_UPDATE_INTERVAL * 2 - m_updateAssistTimer - p_time; } if(m_updateTargetsTimer > p_time) { m_updateTargetsTimer -= p_time; }else { m_updateTargets = true; m_updateTargetsTimer = TARGET_UPDATE_INTERVAL * 2 - m_updateTargetsTimer - p_time; } _UpdateCooldownTimers(p_time); } void AIInterface::_UpdateCooldownTimers(uint32 p_time) { _UpdateCooldownTimer(&m_hasCooldownOnEnterCombatSpells, &m_OnEnterCombatSpells, p_time); _UpdateCooldownTimer(&m_hasCooldownOnLeaveCombatSpells, &m_OnLeaveCombatSpells, p_time); _UpdateCooldownTimer(&m_hasCooldownOnDamageTakenSpells, &m_OnDamageTakenSpells, p_time); _UpdateCooldownTimer(&m_hasCooldownOnTargetCastSpellSpells, &m_OnTargetCastSpellSpells, p_time); _UpdateCooldownTimer(&m_hasCooldownOnTargetParryedSpells, &m_OnTargetParryedSpells, p_time); _UpdateCooldownTimer(&m_hasCooldownOnTargetDodgedSpells, &m_OnTargetDodgedSpells, p_time); _UpdateCooldownTimer(&m_hasCooldownOnTargetBlockedSpells, &m_OnTargetBlockedSpells, p_time); _UpdateCooldownTimer(&m_hasCooldownOnTargetCritHitSpells, &m_OnTargetCritHitSpells, p_time); _UpdateCooldownTimer(&m_hasCooldownOnTargetDiedSpells, &m_OnTargetDiedSpells, p_time); _UpdateCooldownTimer(&m_hasCooldownOnUnitParryedSpells, &m_OnUnitParryedSpells, p_time); _UpdateCooldownTimer(&m_hasCooldownOnUnitDodgedSpells, &m_OnUnitDodgedSpells, p_time); _UpdateCooldownTimer(&m_hasCooldownOnUnitBlockedSpells, &m_OnUnitBlockedSpells, p_time); _UpdateCooldownTimer(&m_hasCooldownOnUnitCritHitSpells, &m_OnUnitCritHitSpells, p_time); _UpdateCooldownTimer(&m_hasCooldownOnUnitDiedSpells, &m_OnUnitDiedSpells, p_time); _UpdateCooldownTimer(&m_hasCooldownOnAssistTargetDiedSpells, &m_OnAssistTargetDiedSpells, p_time); _UpdateCooldownTimer(&m_hasCooldownOnFollowOwnerSpells, &m_OnFollowOwnerSpells, p_time); } void AIInterface::_UpdateTargets() { if(!m_Unit->GetCreatureName() || m_Unit->GetCreatureName()->Type == CRITTER) return; AssistTargetSet::iterator i, i2; TargetMap::iterator itr, itr2; // Find new Assist Targets and remove old ones if(m_AIState == STATE_FLEEING) { FindFriends(100.0f/*10.0*/); } else if(m_AIState != STATE_IDLE && m_AIState != STATE_SCRIPTIDLE) { FindFriends(16.0f/*4.0f*/); } if(m_updateAssist) { m_updateAssist = false; //modified for vs2005 compatibility for(i = m_assistTargets.begin(); i != m_assistTargets.end();) { i2 = i; ++i; if(m_Unit->GetDistanceSq((*i2)) > 2500.0f/*50.0f*/ || !(*i2)->isAlive() || !(*i2)->isInCombat()) { m_assistTargets.erase(i2); } } } if(m_updateTargets) { m_updateTargets = false; //modified for vs2005 compatibility for(itr = m_aiTargets.begin(); itr != m_aiTargets.end();) { itr2 = itr; ++itr; //if(!itr->target) // we shouldnt get to here, i'm guessing. //continue; if(!itr2->first->isAlive() || m_Unit->GetDistanceSq(itr2->first) >= 6400.0f/*80.0f*/) { m_aiTargets.erase(itr2); } } if(m_aiTargets.size() == 0 && m_AIState != STATE_IDLE && m_AIState != STATE_FOLLOWING && m_AIState != STATE_EVADE && m_AIState != STATE_FEAR && m_AIState != STATE_WANDER && m_AIState != STATE_SCRIPTIDLE) { if(firstLeaveCombat) { Unit* target = FindTarget(); if(target) { AttackReaction(target, 1, 0); }else { firstLeaveCombat = false; } } /*else { HandleEvent(EVENT_LEAVECOMBAT, m_Unit, 0); }*/ } else if(m_aiTargets.size() == 0 && m_AIType == AITYPE_PET && static_cast<Pet*>(m_Unit)->GetPetState() == PET_STATE_AGGRESSIVE) { Unit* target = FindTarget(); if(target) AttackReaction(target, 1, 0); } } // Find new Targets when we are ooc if((m_AIState == STATE_IDLE || m_AIState == STATE_SCRIPTIDLE) && m_assistTargets.size() == 0) { Unit* target = FindTarget(); if(target) { AttackReaction(target, 1, 0); } } } ///==================================================================== /// Desc: Updates Combat Status of m_Unit ///==================================================================== void AIInterface::_UpdateCombat(uint32 p_time) { uint16 agent = m_aiCurrentAgent; /*if(m_AIType == AITYPE_PET) // pets - default spell { if(m_DefaultSpell != NULL) { if(m_DefaultSpell != m_nextSpell) { m_nextSpell = m_DefaultSpell; } } }*/ // no need to do this anymore // If creature is very far from spawn point return to spawnpoint // If at instance dont return -- this is wrong ... (mmcs) instance creatures always returns to spawnpoint, dunno how do you got this ideia. if(m_AIType != AITYPE_PET && (m_Unit->GetDistanceSq(m_returnX,m_returnY,m_returnZ) > m_outOfCombatRange/*oocr*/) && m_AIState != STATE_EVADE && m_AIState != STATE_SCRIPTMOVE) { HandleEvent(EVENT_LEAVECOMBAT, m_Unit, 0); } else if(!m_nextTarget && m_AIState != STATE_FOLLOWING && m_AIState != STATE_SCRIPTMOVE) { m_nextTarget = FindTargetForSpell(m_nextSpell); if(!m_nextTarget) { if(m_Unit->GetMapMgr()) { if(m_Unit->GetMapMgr()->GetMapInfo()) { if(m_Unit->GetMapMgr()->GetMapInfo()->type == 0) { HandleEvent(EVENT_LEAVECOMBAT, m_Unit, 0); } else m_AIState = STATE_IDLE; } else HandleEvent(EVENT_LEAVECOMBAT, m_Unit, 0); } else { HandleEvent(EVENT_LEAVECOMBAT, m_Unit, 0); } } } bool cansee; if(m_nextTarget) cansee=((Creature*)m_Unit)->CanSee(m_nextTarget); else cansee=false; if(cansee && m_nextTarget && m_nextTarget->isAlive() && m_AIState != STATE_EVADE && !m_Unit->isCasting()) { if(agent == AGENT_NULL) { if(m_canFlee && !m_hasFleed && ((m_Unit->GetUInt32Value(UNIT_FIELD_HEALTH) / m_Unit->GetUInt32Value(UNIT_FIELD_MAXHEALTH)) < m_FleeHealth )) agent = AGENT_FLEE; else if(m_canCallForHelp && !m_hasCalledForHelp && (m_CallForHelpHealth > (m_Unit->GetUInt32Value(UNIT_FIELD_HEALTH) / (m_Unit->GetUInt32Value(UNIT_FIELD_MAXHEALTH) > 0 ? m_Unit->GetUInt32Value(UNIT_FIELD_MAXHEALTH) : 1)))) agent = AGENT_CALLFORHELP; else if(m_nextSpell) { if(m_nextSpell->agent != AGENT_NULL) { agent = m_nextSpell->agent; } else { agent = AGENT_MELEE; } } else { agent = AGENT_MELEE; } } if(agent == AGENT_RANGED || agent == AGENT_MELEE) { if(m_canRangedAttack) { agent = AGENT_MELEE; if(m_nextTarget->GetTypeId() == TYPEID_PLAYER) { float dist = m_Unit->GetDistanceSq(m_nextTarget); if(((Player*)m_nextTarget)->m_currentMovement == MOVE_ROOT || dist >= 64.0f) { agent = AGENT_RANGED; } } else if(m_nextTarget->m_canMove == false || m_Unit->GetDistanceSq(m_nextTarget) >= 64.0f) { agent = AGENT_RANGED; } } else { agent = AGENT_MELEE; } } switch(agent) { case AGENT_MELEE: { float combatReach[2]; // Calculate Combat Reach float distance = m_Unit->CalcDistance(m_nextTarget); combatReach[0] = 0.0f; combatReach[1] = _CalcCombatRange(m_nextTarget, false); if(distance >= combatReach[0] && distance <= combatReach[1]) // Target is in Range -> Attack { if(UnitToFollow != NULL) { UnitToFollow = NULL; //we shouldn't be following any one m_lastFollowX = m_lastFollowY = 0; m_Unit->setAttackTarget(NULL); // remove ourselves from any target that might have been followed } FollowDistance = 0.0f; m_moveRun = false; //FIXME: offhand shit if(m_Unit->isAttackReady(false) && !m_fleeTimer) { m_creatureState = ATTACKING; bool infront = m_Unit->isInFront(m_nextTarget); if(!infront) // set InFront { //prevent mob from rotating while stunned if(!m_Unit->IsStunned ()) { setInFront(m_nextTarget); infront = true; } } if(infront) { m_Unit->setAttackTimer(0, false); m_Unit->Strike(m_nextTarget, (agent==AGENT_MELEE)?0:2,NULL,0,0,0); } } } else // Target out of Range -> Run to it { //calculate next move float dist = 1.0f; dist = combatReach[1]-1.15f; m_moveRun = true; _CalcDestinationAndMove(m_nextTarget, dist); } }break; case AGENT_RANGED: { float combatReach[2]; // Calculate Combat Reach float distance = m_Unit->CalcDistance(m_nextTarget); combatReach[0] = 8.0f; combatReach[1] = 30.0f; if(distance >= combatReach[0] && distance <= combatReach[1]) // Target is in Range -> Attack { if(UnitToFollow != NULL) { UnitToFollow = NULL; //we shouldn't be following any one m_lastFollowX = m_lastFollowY = 0; m_Unit->setAttackTarget(NULL); // remove ourselves from any target that might have been followed } FollowDistance = 0.0f; m_moveRun = false; //FIXME: offhand shit if(m_Unit->isAttackReady(false) && !m_fleeTimer) { m_creatureState = ATTACKING; bool infront = m_Unit->isInFront(m_nextTarget); if(!infront) // set InFront { //prevent mob from rotating while stunned if(!m_Unit->IsStunned ()) { setInFront(m_nextTarget); infront = true; } } if(infront) { m_Unit->setAttackTimer(0, false); SpellEntry *info = sSpellStore.LookupEntry(SPELL_RANGED_BOW); if(info) { Spell *sp = new Spell(m_Unit, info, false, NULL); SpellCastTargets targets; targets.m_unitTarget = m_nextTarget->GetGUID(); sp->prepare(&targets); //Lets make spell handle this //m_Unit->Strike(m_nextTarget, (agent==AGENT_MELEE)?0:2,NULL,0,0,0); } } } } else // Target out of Range -> Run to it { //calculate next move float dist = 1.0f; if(distance < combatReach[0])// Target is too near dist = 9.0f; else dist = 20.0f; m_moveRun = true; _CalcDestinationAndMove(m_nextTarget, dist); } }break; case AGENT_SPELL: { if(!m_nextSpell || !m_nextTarget) return; // this shouldnt happen float distance = m_Unit->GetDistanceSq(m_nextTarget); if((distance <= powf(m_nextSpell->maxrange,2) && distance >= powf(m_nextSpell->minrange,2)) || m_nextSpell->maxrange == 0) // Target is in Range -> Attack { uint32 spellId = m_nextSpell->spellId; SpellEntry* spellInfo = getSpellEntry(spellId); SpellCastTargets targets = setSpellTargets(spellInfo, m_nextTarget); CastSpell(m_Unit, spellInfo, targets); increaseProcCounter(m_nextSpell->procEvent, m_nextSpell); m_nextSpell = NULL; if(m_AIType == AITYPE_PET) // Add cooldown ((Pet*)m_Unit)->AddSpellCooldown(spellId); } else // Target out of Range -> Run to it { //calculate next move m_moveRun = true; _CalcDestinationAndMove(m_nextTarget, m_nextSpell->maxrange - 5.0f); /*Destination* dst = _CalcDestination(m_nextTarget, dist); MoveTo(dst->x, dst->y, dst->z,0); delete dst;*/ } }break; case AGENT_FLEE: { //float dist = 5.0f; m_moveRun = false; if(m_fleeTimer == 0) m_fleeTimer = m_FleeDuration; /*Destination* dst = _CalcDestination(m_nextTarget, dist); MoveTo(dst->x, dst->y, dst->z,0); delete dst;*/ _CalcDestinationAndMove(m_nextTarget, 5.0f); if(!m_hasFleed) // to avoid lua excuting spam CALL_SCRIPT_EVENT(m_Unit, OnFlee)(m_nextTarget); m_AIState = STATE_FLEEING; m_nextTarget = m_Unit; m_Unit->SetUInt64Value(UNIT_FIELD_TARGET, 0); m_Unit->setAttackTarget(0); m_Unit->clearAttackers(true); // Send message //char msg[200]; //sprintf(msg, "\%s attempts to run away in fear!"); WorldPacket data(SMSG_MESSAGECHAT, 100); string msg = "%s attempts to run away in fear!"; data << (uint8)CHAT_MSG_MONSTER_EMOTE; data << (uint32)LANG_UNIVERSAL; data << (uint32)(m_Unit->GetCreatureName()->Name.size() + 1); data << m_Unit->GetCreatureName()->Name; data << (uint64)0; data << (uint32)(msg.size() + 1); data << msg; data << uint8(0); m_Unit->SendMessageToSet(&data, false); //m_Unit->SendChatMessage(CHAT_MSG_MONSTER_EMOTE, LANG_UNIVERSAL, msg); //sChatHandler.FillMessageData(&data, CHAT_MSG_MONSTER_EMOTE, LANG_UNIVERSAL, msg, m_Unit->GetGUID()); m_hasFleed = true; }break; case AGENT_CALLFORHELP: { FindFriends(400.0f/*20.0f*/); m_hasCalledForHelp = true; // We only want to call for Help once in a Fight. CALL_SCRIPT_EVENT(m_Unit, OnCallForHelp)(); }break; } } else if(!m_nextTarget || !m_nextTarget->isAlive() || !cansee) { m_nextTarget = NULL; m_Unit->SetUInt64Value(UNIT_FIELD_TARGET, 0); // no more target //m_Unit->setAttackTarget(NULL); } } void AIInterface::DismissPet() { //BURLEXFIXME /* if(m_AIType != AITYPE_PET) return; if(!m_PetOwner) return; if(m_PetOwner->GetTypeId() != TYPEID_PLAYER) return; if(m_Unit->GetUInt32Value(UNIT_CREATED_BY_SPELL) == 0) ((Player*)m_PetOwner)->SetFreePetNo(false, (int)m_Unit->GetUInt32Value(UNIT_FIELD_PETNUMBER)); ((Player*)m_PetOwner)->SetPet(NULL); ((Player*)m_PetOwner)->SetPetName(""); //FIXME:Check hunter pet or not //FIXME:Check enslaved creature m_PetOwner->SetUInt64Value(UNIT_FIELD_SUMMON, 0); WorldPacket data; data.Initialize(SMSG_PET_SPELLS); data << (uint64)0; ((Player*)m_PetOwner)->GetSession()->SendPacket(&data); sEventMgr.RemoveEvents(((Creature*)m_Unit)); if(m_Unit->IsInWorld()) { m_Unit->RemoveFromWorld(); } //setup an event to delete the Creature sEventMgr.AddEvent(((Creature*)this->m_Unit), &Creature::DeleteMe, EVENT_DELETE_TIMER, 1, 1);*/ } void AIInterface::AttackReaction(Unit* pUnit, uint32 damage_dealt, uint32 state, uint32 spellId) { if(pUnit->GetTypeId() == TYPEID_PLAYER && m_Unit->GetMapMgr() && m_Unit->GetMapMgr()->GetUpdaterThread() && m_Unit->GetTypeId() == TYPEID_UNIT && !m_Unit->_Activated && UINT32_LOPART(m_Unit->GetGUIDHigh()) != HIGHGUID_PET) { // we must be in an active cell to be attacked.. m_Unit->GetMapMgr()->GetUpdaterThread()->AddObject<Creature>(static_cast<Creature*>(m_Unit)); m_Unit->_Activated = true; } else { m_Unit->_Activated = false; } if(m_AIState == STATE_EVADE || m_fleeTimer != 0 || !pUnit || m_Unit->IsPacified() || m_Unit->IsStunned() || !m_Unit->isAlive()) { return; } if(m_Unit == pUnit) { return; } bool state_reduced = false; if(state >= 0xFF) { state -= 0xFF; state_reduced = true; } // this isn't right if we're dealing damage.. we dont want to add threat for when we're attacking someone? or do we? //modThreatByGUID(pUnit->GetGUID(), _CalcThreat(damage_dealt, spellId, pUnit)); if(m_AIState == STATE_IDLE || m_AIState == STATE_FOLLOWING) { WipeTargetList(); HandleEvent(EVENT_ENTERCOMBAT, pUnit, 0); if(pUnit->GetTypeId() == TYPEID_PLAYER) { // Show attack animation icon //((Player*)pUnit)->SetFlag(UNIT_FIELD_FLAGS, U_FIELD_FLAG_ATTACK_ANIMATION); // if(((Player*)pUnit)->GetUInt64Value(PLAYER_SELECTION) == 0) // ((Player*)pUnit)->SetUInt64Value(PLAYER_SELECTION, m_Unit->GetGUID()); //Disabled by Phantomas -> this is wrong we should not set player selection } //these 2 are done already in deal damage //right before this func is called //there should be a way not to do this twice.... // no need to do this /*if(pUnit != m_Unit) // this shouldnt happen { pUnit->AddAttacker(m_Unit); m_Unit->m_AttackTarget = pUnit; } else { char msg[100]; sprintf(msg, "AI: Tried to add self to attacker set "I64FMT, m_Unit->GetGUID()); sWorld.SendIRCMessage(msg); sLog.outString(msg); }*/ } switch(state) { case 1: // Target dodged { HandleEvent(EVENT_TARGETDODGED, pUnit, 0); }break; case 2: // Target blocked { HandleEvent(EVENT_TARGETBLOCKED, pUnit, 0); }break; case 3: // Target parryed { HandleEvent(EVENT_TARGETPARRYED, pUnit, 0); }break; case 5: // Unit critted { HandleEvent(EVENT_UNITCRITHIT, pUnit, 0); }break; } if(!state_reduced) { HandleEvent(EVENT_DAMAGETAKEN, pUnit, _CalcThreat(damage_dealt, spellId, pUnit)); } //burlex: WHAT the fuck is this for??!!!?!! /*// check for a Pet/Summon owner and add him to Targetlist if(pUnit->GetUInt64Value(UNIT_FIELD_SUMMONEDBY)) { Unit* petOwner = NULL; petOwner = sObjHolder.GetObject<Player>(pUnit->GetUInt64Value(UNIT_FIELD_SUMMONEDBY)); if(!petOwner) { petOwner = sObjHolder.GetObject<Creature>(pUnit->GetUInt64Value(UNIT_FIELD_SUMMONEDBY)); } if(!petOwner) { return; } AttackReaction(petOwner, 1, 0); }*/ } bool AIInterface::HealReaction(Unit* caster, Unit* victim, uint32 amount) { if(!caster || !victim) { printf("!!!BAD POINTER IN AIInterface::HealReaction!!!\n"); return false; } int casterInList = 0, victimInList = 0; if(m_aiTargets.find(caster) != m_aiTargets.end()) casterInList = 1; if(m_aiTargets.find(victim) != m_aiTargets.end()) victimInList = 1; /*for(i = m_aiTargets.begin(); i != m_aiTargets.end(); i++) { if(casterInList && victimInList) { // no need to check the rest, just break that break; } if(i->target == victim) { victimInList = true; } if(i->target == caster) { casterInList = true; } }*/ if(!victimInList && !casterInList) // none of the Casters is in the Creatures Threat list { return false; } if(!casterInList && victimInList) // caster is not yet in Combat but victim is { // get caster into combat if he's hostile if(isHostile(m_Unit, caster)) { //AI_Target trgt; //trgt.target = caster; //trgt.threat = amount; //m_aiTargets.push_back(trgt); m_aiTargets.insert(TargetMap::value_type(caster, amount)); return true; } return false; } else if(casterInList && victimInList) // both are in combat already { // mod threat for caster modThreatByPtr(caster, amount); return true; } else // caster is in Combat already but victim is not { modThreatByPtr(caster, amount); // both are players so they might be in the same group if(caster->GetTypeId() == TYPEID_PLAYER && victim->GetTypeId() == TYPEID_PLAYER) { if(((Player*)caster)->GetGroup() == ((Player*)victim)->GetGroup()) { // get victim into combat since they are both // in the same party if(isHostile(m_Unit, victim)) { m_aiTargets.insert(TargetMap::value_type(victim, 1)); return true; } return false; } } } return false; } void AIInterface::OnDeath(Object* pKiller) { if(pKiller->GetTypeId() == TYPEID_PLAYER || pKiller->GetTypeId() == TYPEID_UNIT) HandleEvent(EVENT_UNITDIED, static_cast<Unit*>(pKiller), 0); else HandleEvent(EVENT_UNITDIED, m_Unit, 0); } Unit* AIInterface::FindTarget() {// find nearest hostile Target to attack if( !m_AllowedToEnterCombat ) return NULL; CreatureInfo* ci = m_Unit->GetCreatureName(); if(!ci) return NULL; Unit* target = NULL; Unit* critterTarget = NULL; float distance = 999999.0f; // that should do it.. :p std::set<Object*>::iterator itr, it2; Object *pObj; Unit *pUnit; float dist; for( itr = m_Unit->GetInRangeOppFactsSetBegin(); itr != m_Unit->GetInRangeOppFactsSetEnd(); ) { it2 = itr; ++itr; pObj = (*it2); if(pObj->GetTypeId() == TYPEID_PLAYER) { if(static_cast<Player*>(pObj)->GetTaxiState()) // skip players on taxi continue; } else if(pObj->GetTypeId() != TYPEID_UNIT) continue; pUnit = static_cast<Unit*>(pObj); if(pUnit->m_invisible) // skip invisible units continue; if(!pUnit->isAlive() || m_Unit == pUnit /* wtf? */ || m_Unit->GetUInt64Value(UNIT_FIELD_CREATEDBY) == pUnit->GetGUID()) continue; dist = m_Unit->GetDistanceSq(pUnit); if(!pUnit->m_faction || !pUnit->m_factionDBC) continue; if(pUnit->m_faction->FactionId == 28)// only Attack a critter if there is no other Enemy in range { if(dist < 225.0f) // was 10 critterTarget = pUnit; continue; } if(dist > distance) // we want to find the CLOSEST target continue; if(dist <= _CalcAggroRange(pUnit) ) { distance = dist; target = pUnit; } } if( !target ) { target = critterTarget; } if( target ) { AttackReaction(target, 1, 0); if(target->GetUInt32Value(UNIT_FIELD_CREATEDBY) != 0) { Unit* target2 = sObjHolder.GetObject<Player>(target->GetUInt32Value(UNIT_FIELD_CREATEDBY)); if(!target2) { target2 = sObjHolder.GetObject<Player>(target->GetUInt32Value(UNIT_FIELD_CREATEDBY)); } if(target2) { AttackReaction(target2, 1, 0); } } } return target; } Unit* AIInterface::FindTargetForSpell(AI_Spell *sp) { if(!sp) { m_Unit->SetUInt64Value(UNIT_FIELD_TARGET, 0); return NULL; } TargetMap::iterator itr, itr2; if(sp->spellType == STYPE_HEAL) { uint32 cur = m_Unit->GetUInt32Value(UNIT_FIELD_HEALTH); uint32 max = m_Unit->GetUInt32Value(UNIT_FIELD_MAXHEALTH); float healthPercent = float(long2float(cur) / long2float(max)); if(healthPercent <= sp->floatMisc1) // Heal ourselves cause we got too low HP { m_Unit->SetUInt64Value(UNIT_FIELD_TARGET, 0); return m_Unit; } for(AssistTargetSet::iterator i = m_assistTargets.begin(); i != m_assistTargets.end(); i++) { if(!(*i)->isAlive()) { continue; } cur = (*i)->GetUInt32Value(UNIT_FIELD_HEALTH); max = (*i)->GetUInt32Value(UNIT_FIELD_MAXHEALTH); healthPercent = float(long2float(cur) / long2float(max)); if(healthPercent <= sp->floatMisc1) // Heal ourselves cause we got too low HP { m_Unit->SetUInt64Value(UNIT_FIELD_TARGET, (*i)->GetGUID()); return (*i); // heal Assist Target which has low HP } } } if(sp->spellType == STYPE_BUFF) { m_Unit->SetUInt64Value(UNIT_FIELD_TARGET, 0); return m_Unit; } Unit* target = NULL; uint32 threat = 0; //modified for vs2005 compatibility if(GetIsTaunted()) { m_Unit->SetUInt64Value(UNIT_FIELD_TARGET, tauntedBy->GetGUID()); return tauntedBy; } for (itr = m_aiTargets.begin(); itr != m_aiTargets.end();) // Find Target and Cleanup Targetlist { itr2 = itr; ++itr; uint32 curThreat = 1; if((itr2->second + itr2->first->GetThreatModifyer()) > 0) // threat may be < 0 due to some modifyers. { curThreat = (itr2->second + itr2->first->GetThreatModifyer()); } if(curThreat > threat) { if(itr2->first->isAlive()) { target = itr2->first; threat = curThreat; } else { m_aiTargets.erase(itr2); } } } if(target) { m_Unit->SetUInt64Value(UNIT_FIELD_TARGET, target->GetGUID()); return target; } return NULL; } bool AIInterface::FindFriends(float dist) { bool result = false; TargetMap::iterator it; std::set<Object*>::iterator itr; Unit *pUnit; for( itr = m_Unit->GetInRangeSetBegin(); itr != m_Unit->GetInRangeSetEnd(); itr++ ) { if((*itr)->GetTypeId() != TYPEID_UNIT) continue; pUnit = static_cast<Unit*>((*itr)); if(!pUnit->isAlive()) continue; if(isCombatSupport(m_Unit, pUnit) && (pUnit->GetAIInterface()->getAIState() == STATE_IDLE || pUnit->GetAIInterface()->getAIState() == STATE_SCRIPTIDLE))//Not sure { if(m_Unit->GetDistanceSq(pUnit) < dist) { if(m_assistTargets.count(pUnit) > 0) // already have him break; result = true; //addAssistTargets(pUnit); m_assistTargets.insert(pUnit); for(it = m_aiTargets.begin(); it != m_aiTargets.end(); ++it) { ((Unit*)(*itr))->GetAIInterface()->AttackReaction(it->first, 1, 0); } } } } // check if we're a civillan, in which case summon guards on a despawn timer /*if(m_Unit->GetCreatureName() && m_Unit->GetCreatureName()->Civilian && getMSTime() > m_guardTimer && m_Unit->GetMapId() < 2) { switch(m_Unit->GetCreatureName()->Family) { case UNDEAD: case HUMANOID: break; default: return result; break; } m_Unit->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "Guards, help me!"); uint32 guardid = 1423; if(m_Unit->m_factionDBC->factionGroupReputationFrame == 67) // horde guardid = 3296; // ogri CreatureSpawnTemplate * pSpawnTemplate = objmgr.GetCreatureSpawnTemplate(guardid); if(pSpawnTemplate != 0) { Creature *pCreature = sObjHolder.Create<Creature>(); // FIXME: Summon hardcoded stormwind guard/ogrimmar grunt float x = m_Unit->GetPositionX() + (float)( (float)(rand() % 150 + 100) / 1000.0f ); float y = m_Unit->GetPositionY() + (float)( (float)(rand() % 150 + 100) / 1000.0f ); float z = m_Unit->GetPositionZ(); float adt_z = m_Unit->GetMapMgr()->GetLandHeight(x, y); if(fabs(z - adt_z) < 3) z = adt_z; pCreature->Create(pSpawnTemplate, m_Unit->GetMapId(), x, y, z, 0); pCreature->SetInstanceID(m_Unit->GetInstanceID()); pCreature->SetZoneId(m_Unit->GetZoneId()); pCreature->AddToWorld(); // set despawn timer // at 5mins sEventMgr.AddEvent(pCreature, &Creature::Despawn, EVENT_CREATURE_SAFE_DELETE, 60*5*1000, 1); for(it = m_aiTargets.begin(); it != m_aiTargets.end(); ++it) { pCreature->GetAIInterface()->AttackReaction(it->first, 1, 0); } } m_guardTimer = getMSTime() + 15000; }*/ return result; } float AIInterface::_CalcAggroRange(Unit* target) { //float baseAR = 15.0f; // Base Aggro Range // -8 -7 -6 -5 -4 -3 -2 -1 0 +1 +2 +3 +4 +5 +6 +7 +8 //float baseAR[17] = {29.0f, 27.5f, 26.0f, 24.5f, 23.0f, 21.5f, 20.0f, 18.5f, 17.0f, 15.5f, 14.0f, 12.5f, 11.0f, 9.5f, 8.0f, 6.5f, 5.0f}; float baseAR[17] = {19.0f, 18.5f, 18.0f, 17.5f, 17.0f, 16.5f, 16.0f, 15.5f, 15.0f, 14.5f, 12.0f, 10.5f, 8.5f, 7.5f, 6.5f, 6.5f, 5.0f}; // Lvl Diff -8 -7 -6 -5 -4 -3 -2 -1 +0 +1 +2 +3 +4 +5 +6 +7 +8 // Arr Pos 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 int8 lvlDiff = target->getLevel() - m_Unit->getLevel(); uint8 realLvlDiff = lvlDiff; if(lvlDiff > 8) { lvlDiff = 8; } if(lvlDiff < -8) { lvlDiff = -8; } if(!((Creature*)m_Unit)->CanSee(target)) return 0; float AggroRange = baseAR[lvlDiff + 8]; if(realLvlDiff > 8) { AggroRange += AggroRange * ((lvlDiff - 8) * 5 / 100); } // Multiply by elite value if(m_Unit->GetCreatureName()->Rank > 0) AggroRange *= (m_Unit->GetCreatureName()->Rank) * 2; if(AggroRange > 40.0f) // cap at 40.0f { AggroRange = 40.0f; } /* //printf("aggro range: %f , stealthlvl: %d , detectlvl: %d\n",AggroRange,target->GetStealthLevel(),m_Unit->m_stealthDetectBonus); if(! ((Creature*)m_Unit)->CanSee(target)) { AggroRange =0; // AggroRange *= ( 100.0f - (target->m_stealthLevel - m_Unit->m_stealthDetectBonus)* 20.0f ) / 100.0f; } */ // SPELL_AURA_MOD_DETECT_RANGE int32 modDetectRange = target->getDetectRangeMod(m_Unit->GetGUID()); AggroRange += modDetectRange; if(AggroRange < 3.0f) { AggroRange = 3.0f; } if(AggroRange > 40.0f) // cap at 40.0f { AggroRange = 40.0f; } return powf(AggroRange, 2); } void AIInterface::_CalcDestinationAndMove(Unit *target, float dist) { if(!m_canMove || m_Unit->IsStunned()) { StopMovement(0); //Just Stop return; } if(target->GetTypeId() == TYPEID_UNIT || target->GetTypeId() == TYPEID_PLAYER) { float angle = m_Unit->calcAngle(m_Unit->GetPositionX(), m_Unit->GetPositionY(), target->GetPositionX(), target->GetPositionY()) * M_PI / 180.0f; float x = dist * cosf(angle); float y = dist * sinf(angle); m_nextPosX = target->GetPositionX() - x; m_nextPosY = target->GetPositionY() - y; m_nextPosZ = target->GetPositionZ(); } else { target = NULL; m_nextPosX = m_Unit->GetPositionX(); m_nextPosY = m_Unit->GetPositionY(); m_nextPosZ = m_Unit->GetPositionZ(); } float dx = m_nextPosX - m_Unit->GetPositionX(); float dy = m_nextPosY - m_Unit->GetPositionY(); if(dy != 0.0f) { float angle = atan2(dx, dy); m_Unit->SetOrientation(angle); } if(m_creatureState != MOVING) UpdateMove(); } float AIInterface::_CalcCombatRange(Unit* target, bool ranged) { if(!target) { return 0; } float range = 0.0f; float rang = 1.5f; if(ranged) { rang = 5.0f; } // float targetreach = target->GetFloatValue(UNIT_FIELD_COMBATREACH); float selfreach = m_Unit->GetFloatValue(UNIT_FIELD_COMBATREACH); float targetradius = target->GetFloatValue(UNIT_FIELD_BOUNDINGRADIUS); float selfradius = m_Unit->GetFloatValue(UNIT_FIELD_BOUNDINGRADIUS); float targetscale = target->GetFloatValue(OBJECT_FIELD_SCALE_X); float selfscale = m_Unit->GetFloatValue(OBJECT_FIELD_SCALE_X); range = (((powf(targetradius,2)*targetscale) + selfreach) + ((powf(selfradius,2)*selfscale) + rang)); return range; } float AIInterface::_CalcDistanceFromHome() { if (m_AIType == AITYPE_PET) { return m_Unit->GetDistanceSq(m_PetOwner); } else if(m_Unit->GetTypeId() == TYPEID_UNIT) { if(m_returnX !=0.0f && m_returnY != 0.0f) { return m_Unit->GetDistanceSq(m_returnX,m_returnY,m_returnZ); } } return 0.0f; } void AIInterface::SendMoveToPacket(float toX, float toY, float toZ, float toO, uint32 time, uint32 MoveFlags) { //this should NEVER be called directly !!!!!! //use MoveTo() /* Move Flags 0x00000000 - Walk 0x00000100 - Run 0x00000300 - Fly */ WorldPacket data(SMSG_MONSTER_MOVE, 50); // 50 bytes should be more than enough data << m_Unit->GetNewGUID(); data << m_Unit->GetPositionX() << m_Unit->GetPositionY() << m_Unit->GetPositionZ(); data << getMSTime(); // Check if we have an orientation if(toO != 0.0f) { data << uint8(4); data << toO; } else { data << uint8(0); } data << MoveFlags; data << time; data << uint32(1); // 1 waypoint data << toX << toY << toZ; /*WorldPacket data; uint8 DontMove = 0; data.Initialize( SMSG_MONSTER_MOVE ); data << m_Unit->GetNewGUID(); data << m_Unit->GetPositionX() << m_Unit->GetPositionY() << m_Unit->GetPositionZ(); data << getMSTime(); data << uint8(DontMove); if(DontMove != 1) { //data << uint32(run ? 0x00000100 : 0x00000000); data << uint32(MoveFlags); data << time; //if(toO != 0.0f) //{ //data << uint32(2); //} //else //{ data << uint32(1); //Number of Waypoints //} data << toX << toY << toZ; //if(toO != 0.0f) //{ //data << toO; //} }*/ if(m_Unit->GetTypeId() == TYPEID_PLAYER) m_Unit->SendMessageToSet( &data, true ); else m_Unit->SendMessageToSet( &data, false ); } /* void AIInterface::SendMoveToSplinesPacket(std::list<Waypoint> wp, bool run) { if(!m_canMove) { return; } WorldPacket data; uint8 DontMove = 0; uint32 travelTime = 0; for(std::list<Waypoint>::iterator i = wp.begin(); i != wp.end(); i++) { travelTime += i->time; } data.Initialize( SMSG_MONSTER_MOVE ); data << m_Unit->GetNewGUID(); data << m_Unit->GetPositionX() << m_Unit->GetPositionY() << m_Unit->GetPositionZ(); data << getMSTime(); data << uint8(DontMove); data << uint32(run ? 0x00000100 : 0x00000000); data << travelTime; data << (uint32)wp.size(); for(std::list<Waypoint>::iterator i = wp.begin(); i != wp.end(); i++) { data << i->x; data << i->y; data << i->z; } m_Unit->SendMessageToSet( &data, false ); } */ bool AIInterface::StopMovement(uint32 time) { m_moveTimer = time; //set pause after stopping m_creatureState = STOPPED; m_destinationX = m_destinationY = m_destinationZ = 0; m_nextPosX = m_nextPosY = m_nextPosZ = 0; m_timeMoved = 0; m_timeToMove = 0; /*WorldPacket data; uint8 DontMove = 1; data.Initialize( SMSG_MONSTER_MOVE ); data << m_Unit->GetNewGUID(); data << m_Unit->GetPositionX() << m_Unit->GetPositionY() << m_Unit->GetPositionZ(); data << getMSTime(); data << uint8(DontMove);*/ WorldPacket data(26); data.SetOpcode(SMSG_MONSTER_MOVE); data << m_Unit->GetNewGUID(); data << m_Unit->GetPositionX() << m_Unit->GetPositionY() << m_Unit->GetPositionZ(); data << getMSTime(); data << uint8(1); // "DontMove = 1" m_Unit->SendMessageToSet( &data, false ); return true; } void AIInterface::MoveTo(float x, float y, float z, float o) { m_sourceX = m_Unit->GetPositionX(); m_sourceY = m_Unit->GetPositionY(); m_sourceZ = m_Unit->GetPositionZ(); if(!m_canMove || m_Unit->IsStunned()) { StopMovement(0); //Just Stop return; } m_nextPosX = x; m_nextPosY = y; m_nextPosZ = z; if(m_creatureState != MOVING) UpdateMove(); } bool AIInterface::IsFlying() { if(m_moveFly) return true; /*float z = m_Unit->GetMapMgr()->GetLandHeight(m_Unit->GetPositionX(), m_Unit->GetPositionY()); if(z) { if(m_Unit->GetPositionZ() >= (z + 1.0f)) //not on ground? Oo { return true; } } return false;*/ if(m_Unit->GetTypeId() == TYPEID_PLAYER) return ((Player*)m_Unit)->FlyCheat; return false; } uint32 AIInterface::getMoveFlags() { uint32 MoveFlags = 0; if(m_moveFly == true) //Fly { m_moveSpeed = m_Unit->m_flySpeed*0.001f; MoveFlags = 0x300; } else if(m_moveSprint == true) //Sprint { m_moveSpeed = (m_Unit->m_runSpeed+5.0f)*0.001f; MoveFlags = 0x100; } else if(m_moveRun == true) //Run { m_moveSpeed = m_Unit->m_runSpeed*0.001f; MoveFlags = 0x100; } else //Walk { m_moveSpeed = m_Unit->m_walkSpeed*0.001f; MoveFlags = 0x000; } return MoveFlags; } void AIInterface::UpdateMove() { //this should NEVER be called directly !!!!!! //use MoveTo() // burlex: not sure what to do on this one.. :/ float distance = m_Unit->CalcDistance(m_nextPosX,m_nextPosY,m_nextPosZ); if(distance < 1.0f) return; //we don't want little movements here and there m_destinationX = m_nextPosX; m_destinationY = m_nextPosY; m_destinationZ = m_nextPosZ; if(m_moveFly != true) { if(m_Unit->GetMapMgr()) { float adt_Z = m_Unit->GetMapMgr()->GetLandHeight(m_destinationX, m_destinationY); if(fabsf(adt_Z - m_destinationZ) < 1.5) m_destinationZ = adt_Z; } } m_nextPosX = m_nextPosY = m_nextPosZ = 0; uint32 moveTime = (uint32) (distance / m_moveSpeed); m_totalMoveTime = moveTime; if(m_Unit->GetTypeId() == TYPEID_UNIT) { Creature *creature = static_cast<Creature*>(m_Unit); // check if we're returning to our respawn location. if so, reset back to default // orientation if(creature->respawn_cord[0] == m_destinationX && creature->respawn_cord[1] == m_destinationY) { creature->SetOrientation(creature->respawn_cord[3]); } else { // Calculate the angle to our next position float dx = (float)m_destinationX - m_Unit->GetPositionX(); float dy = (float)m_destinationY - m_Unit->GetPositionY(); if(dy != 0.0f) { float angle = atan2(dy, dx); m_Unit->SetOrientation(angle); } } } SendMoveToPacket(m_destinationX, m_destinationY, m_destinationZ, m_Unit->GetOrientation(), moveTime, getMoveFlags()); m_timeToMove = moveTime; m_timeMoved = 0; if(m_moveTimer == 0) { m_moveTimer = UNIT_MOVEMENT_INTERPOLATE_INTERVAL; // update every few msecs } m_creatureState = MOVING; } void AIInterface::SendCurrentMove(Player* plyr/*uint64 guid*/) { if(m_destinationX == 0.0f && m_destinationY == 0.0f && m_destinationZ == 0.0f) return; //invalid move ByteBuffer *splineBuf = new ByteBuffer(20*4); *splineBuf << uint32(getMSTime()); // spline flags *splineBuf << uint32((m_totalMoveTime - m_timeToMove)+m_moveTimer); //Time Passed (start Position) //should be generated/save *splineBuf << uint32(m_totalMoveTime); //Total Time //should be generated/save *splineBuf << uint32(0); //Unknown *splineBuf << uint32(4); //Spline Count // lets try this *splineBuf << m_sourceX << m_sourceY << m_sourceZ; *splineBuf << m_Unit->GetPositionX() << m_Unit->GetPositionY() << m_Unit->GetPositionZ(); *splineBuf << m_destinationX << m_destinationY << m_destinationZ; *splineBuf << m_destinationX << m_destinationY << m_destinationZ; *splineBuf << m_destinationX << m_destinationY << m_destinationZ; plyr->AddSplinePacket(m_Unit->GetGUID(), splineBuf); //This should only be called by Players AddInRangeObject() ONLY //using guid cuz when i atempted to use pointer the player was deleted when this event was called some times //Player* plyr = World::GetPlayer(guid); //if(!plyr) return; /*if(m_destinationX == 0.0f && m_destinationY == 0.0f && m_destinationZ == 0.0f) return; //invalid move uint32 moveTime = m_timeToMove-m_timeMoved; //uint32 moveTime = (m_timeToMove-m_timeMoved)+m_moveTimer; WorldPacket data(50); data.SetOpcode( SMSG_MONSTER_MOVE ); data << m_Unit->GetNewGUID(); data << m_Unit->GetPositionX() << m_Unit->GetPositionY() << m_Unit->GetPositionZ(); data << getMSTime(); data << uint8(0); data << getMoveFlags(); //float distance = m_Unit->CalcDistance(m_destinationX, m_destinationY, m_destinationZ); //uint32 moveTime = (uint32) (distance / m_moveSpeed); data << moveTime; data << uint32(1); //Number of Waypoints data << m_destinationX << m_destinationY << m_destinationZ; plyr->GetSession()->SendPacket(&data);*/ } bool AIInterface::setInFront(Unit* target) // not the best way to do it, though { //angle the object has to face float angle = m_Unit->calcAngle(m_Unit->GetPositionX(), m_Unit->GetPositionY(), target->GetPositionX(), target->GetPositionY() ); //Change angle slowly 2000ms to turn 180 deg around if(angle > 180) angle += 90; else angle -= 90; //angle < 180 m_Unit->getEasyAngle(angle); //Convert to Blizzards Format float orientation = angle / (360 / float(2 * M_PI)); //Update Orentation Server Side m_Unit->SetPosition(m_Unit->GetPositionX(), m_Unit->GetPositionY(), m_Unit->GetPositionZ(), orientation); //Update Orentation Client Side //bool Send = m_Unit->isInFront(target); //return true; return m_Unit->isInFront(target); } bool AIInterface::addWayPoint(WayPoint* wp) { if(!wp) return false; if(wp->id <= 0) return false; //not valid id if(m_waypoints.find( wp->id ) == m_waypoints.end( )) { //m_waypoints[wp->id] = wp; m_waypoints.insert(WayPointMap::value_type(wp->id, wp)); m_nWaypoints = m_waypoints.size(); return true; } return false; } void AIInterface::setWaypointMap(HM_NAMESPACE::hash_map<uint32, WayPoint*> wpm) { m_waypoints = wpm; m_nWaypoints = m_waypoints.size(); } void AIInterface::changeWayPointID(uint32 oldwpid, uint32 newwpid) { if(newwpid <= 0) return; //not valid id if(newwpid > m_waypoints.size()) return; //not valid id if(newwpid == oldwpid) return; //same spot //already wp with that id ? WayPoint* originalwp = getWayPoint(newwpid); if(!originalwp) return; WayPoint* oldwp = getWayPoint(oldwpid); if(!oldwp) return; // uint32 startsize = m_waypoints.size(); //we have valid wps in the positions WayPoint* wpnext = NULL; WayPoint* wp = NULL; uint32 i = 0; uint32 endat = 0; //reorder freeing newwpid's spot if((oldwpid+1 == newwpid) || (newwpid+1 == oldwpid)) { //within 1 place of eachother just swap oldwp->id = newwpid; originalwp->id = oldwpid; m_waypoints[newwpid] = oldwp; m_waypoints[oldwpid] = originalwp; } // 4 2 else if(oldwpid > newwpid) // move others up { //2 4 2 endat = (oldwpid-newwpid); for(i = 0; i < endat;i++) { // 2 wpnext = getWayPoint(newwpid+i+1); //waypoint 3 if(i == 0) { //First move oldwp->id = newwpid; m_waypoints[newwpid] = oldwp; //position 2 originalwp->id = newwpid+1; m_waypoints[newwpid+1] = originalwp; //position 3 } else //i > 0 { if(wp) { wp->id = newwpid+1+i; m_waypoints[newwpid+1+i] = wp; } } wp = wpnext; } } // 2 4 else if(oldwpid < newwpid) //move others down { //2 4 2 endat = (newwpid-oldwpid); for(i = 0; i < endat;i++) { // 2 wp = getWayPoint(oldwpid+i+1); //waypoint 3 if(wp) { wp->id = oldwpid+i; m_waypoints[oldwpid+i] = wp; //position 2 } if(i == endat-1) { oldwp->id = newwpid; m_waypoints[newwpid] = oldwp; //position 4 } } } //SaveAll to db saveWayPoints(0); } void AIInterface::deleteWayPoint(uint32 wpid, bool save) { if(wpid <= 0) return; //not valid id if(wpid > m_waypoints.size()) return; //not valid id uint32 startsize = m_waypoints.size(); //Delete Waypoint WayPointMap::iterator iter = m_waypoints.find( wpid ); if( iter != m_waypoints.end() ) { delete iter->second; m_waypoints.erase( iter ); } WayPoint* wp = NULL; //Reorginise the rest if(wpid <= m_waypoints.size()) //non existant wp { uint32 i = 0; for(i = 0; i < startsize-wpid;i++) { wp = m_waypoints[wpid+i+1]; if(wp) { wp->id = wpid+i; m_waypoints[wpid+i] = wp; } } m_waypoints.erase( wpid+i ); } m_nWaypoints = m_waypoints.size(); //SaveAll to db if(save) saveWayPoints(0); } bool AIInterface::showWayPoints(uint32 wpid, Player* pPlayer, bool Backwards) { // if(wpid < 0) return false; //not valid id if(wpid > m_waypoints.size()) return false; //not valid id //wpid of 0 == all WayPointMap::const_iterator itr; if((m_WayPointsShowing == true) && (wpid == 0)) return false; m_WayPointsShowing = true; WayPoint* wp = NULL; for (itr = m_waypoints.begin(); itr != m_waypoints.end(); itr++) { if( (itr->second->id == wpid) || (wpid == 0) ) { wp = itr->second; //Create Creature* pWayPoint = new Creature(HIGHGUID_WAYPOINT ,wp->id); pWayPoint->CreateWayPoint(wp->id,pPlayer->GetMapId(),wp->x,wp->y,wp->z,0); pWayPoint->SetUInt32Value(OBJECT_FIELD_ENTRY, 300000); pWayPoint->SetFloatValue(OBJECT_FIELD_SCALE_X, 0.5f); if(Backwards) { uint32 DisplayID = (wp->backwardskinid == 0)? GetUnit()->GetUInt32Value(UNIT_FIELD_NATIVEDISPLAYID) : wp->backwardskinid; pWayPoint->SetUInt32Value(UNIT_FIELD_DISPLAYID, DisplayID); pWayPoint->SetUInt32Value(UNIT_NPC_EMOTESTATE, wp->backwardemoteid); } else { uint32 DisplayID = (wp->forwardskinid == 0)? GetUnit()->GetUInt32Value(UNIT_FIELD_NATIVEDISPLAYID) : wp->forwardskinid; pWayPoint->SetUInt32Value(UNIT_FIELD_DISPLAYID, DisplayID); pWayPoint->SetUInt32Value(UNIT_NPC_EMOTESTATE, wp->forwardemoteid); } pWayPoint->SetUInt32Value(UNIT_FIELD_LEVEL, wp->id); pWayPoint->SetUInt32Value(UNIT_NPC_FLAGS, 0); pWayPoint->SetUInt32Value(UNIT_FIELD_AURA+32, 8326); //invisable & deathworld look pWayPoint->SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE , pPlayer->GetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE)); pWayPoint->SetUInt32Value(UNIT_FIELD_HEALTH, 1); pWayPoint->SetUInt32Value(UNIT_FIELD_MAXHEALTH, 1); //Create on client ByteBuffer buf(2500); uint32 count = pWayPoint->BuildCreateUpdateBlockForPlayer(&buf, pPlayer); pPlayer->PushUpdateData(&buf, count); //root the object WorldPacket data1; data1.Initialize(SMSG_FORCE_MOVE_ROOT); data1 << pWayPoint->GetNewGUID(); pPlayer->GetSession()->SendPacket( &data1 ); //Cleanup //delete data; delete pWayPoint; if(wpid != 0) return true; } } return true; } bool AIInterface::hideWayPoints(uint32 wpid, Player* pPlayer) { // if(wpid < 0) return false; //not valid id if(wpid > m_waypoints.size()) return false; //not valid id //wpid of 0 == all if(m_WayPointsShowing != true) return false; m_WayPointsShowing = false; WayPointMap::const_iterator itr; // slightly better way to do this uint64 guid; for (itr = m_waypoints.begin(); itr != m_waypoints.end(); itr++) { if( (itr->second->id == wpid) || (wpid == 0) ) { // avoid C4293 guid = ((uint64)HIGHGUID_WAYPOINT << 32) | itr->second->id; WoWGuid wowguid(guid); pPlayer->PushOutOfRange(wowguid); if(wpid != 0) return true; } } return true; } bool AIInterface::saveWayPoints(uint32 wpid) { // if(wpid < 0) return false; //not valid id if(wpid > m_waypoints.size()) return false; //not valid id if(!GetUnit()) return false; if(GetUnit()->GetTypeId() != TYPEID_UNIT) return false; //wpid of 0 == all std::stringstream ss; if(wpid == 0) { //Delete ss << "DELETE FROM creature_waypoints WHERE creatureid = " << ((Creature*)GetUnit())->GetSQL_id() << "\0"; sDatabase.Query( ss.str().c_str() ); } WayPointMap::const_iterator itr; WayPoint* wp = NULL; for (itr = m_waypoints.begin(); itr != m_waypoints.end(); itr++) { if(itr == m_waypoints.end()) break; if(!itr->second) continue; if( (itr->second->id == wpid) || (wpid == 0) ) { wp = itr->second; if(wpid != 0) { //Delete ss.str(""); ss << "DELETE FROM creature_waypoints WHERE creatureid = " << ((Creature*)GetUnit())->GetSQL_id() << " and waypointid = " << wp->id << "\0"; sDatabase.Query( ss.str().c_str() ); } //Save ss.str(""); ss << "INSERT INTO creature_waypoints "; ss << "(creatureid,waypointid,x,y,z,waittime,flags,forwardemoteoneshot,forwardemoteid,backwardemoteoneshot,backwardemoteid,forwardskinid,backwardskinid) VALUES ("; ss << ((Creature*)GetUnit())->GetSQL_id() << ", "; ss << wp->id << ", "; ss << wp->x << ", "; ss << wp->y << ", "; ss << wp->z << ", "; ss << wp->waittime << ", "; ss << wp->flags << ", "; ss << wp->forwardemoteoneshot << ", "; ss << wp->forwardemoteid << ", "; ss << wp->backwardemoteoneshot << ", "; ss << wp->backwardemoteid << ", "; ss << wp->forwardskinid << ", "; ss << wp->backwardskinid << ")\0"; sDatabase.Query( ss.str().c_str() ); if(wpid != 0) return true; } } return false; } WayPoint* AIInterface::getWayPoint(uint32 wpid) { // if(wpid < 0) return NULL; //not valid id if(wpid > m_waypoints.size()) return NULL; //not valid id WayPointMap::const_iterator itr = m_waypoints.find( wpid ); if( itr != m_waypoints.end( ) ) return itr->second; return NULL; } void AIInterface::_UpdateMovement(uint32 p_time) { if(!m_Unit->isAlive()) { StopMovement(0); return; } uint32 timediff = 0; if(m_moveTimer > 0) { if(p_time >= m_moveTimer) { timediff = p_time - m_moveTimer; m_moveTimer = 0; } else m_moveTimer -= p_time; } if(m_timeToMove > 0) { m_timeMoved = m_timeToMove <= p_time + m_timeMoved ? m_timeToMove : p_time + m_timeMoved; } if(m_creatureState == MOVING) { if(!m_moveTimer) { if(m_timeMoved == m_timeToMove) //reached destination { if(m_moveType == MOVEMENTTYPE_WANTEDWP)//We reached wanted wp stop now m_moveType = MOVEMENTTYPE_DONTMOVEWP; float wayO = 0.0f; if((m_nWaypoints != 0) && (m_AIState == STATE_IDLE || m_AIState == STATE_SCRIPTMOVE)) //if we attacking don't use wps { WayPoint* wp = getWayPoint(getCurrentWaypoint()); if(wp) { CALL_SCRIPT_EVENT(m_Unit, OnReachWP)(wp->id, !m_moveBackward); //Lets face to correct orientation wayO = wp->o; m_moveTimer = wp->waittime; //wait before next move if(!m_moveBackward) { if(wp->forwardemoteoneshot) { GetUnit()->Emote(EmoteType(wp->forwardemoteid)); } else { if(GetUnit()->GetUInt32Value(UNIT_NPC_EMOTESTATE) != wp->forwardemoteid) { GetUnit()->SetUInt32Value(UNIT_NPC_EMOTESTATE, wp->forwardemoteid); } } } else { if(wp->backwardemoteoneshot) { GetUnit()->Emote(EmoteType(wp->backwardemoteid)); } else { if(GetUnit()->GetUInt32Value(UNIT_NPC_EMOTESTATE) != wp->backwardemoteid) { GetUnit()->SetUInt32Value(UNIT_NPC_EMOTESTATE, wp->backwardemoteid); } } } } else m_moveTimer = sRand.randInt(m_moveRun ? 5000 : 10000); // wait before next move } m_creatureState = STOPPED; m_moveSprint = false; //if(m_fleeTimer != 0) // m_moveTimer = 0; /*float dx = m_destinationX - m_Unit->GetPositionX(); float dy = m_destinationY - m_Unit->GetPositionY(); if(dy != 0.0f) m_Unit->SetPosition(m_destinationX, m_destinationY, m_destinationZ, atanf(dy/dx), true); else*/ if(m_MovementType = MOVEMENTTYPE_DONTMOVEWP) m_Unit->SetPosition(m_destinationX, m_destinationY, m_destinationZ, wayO, true); else m_Unit->SetPosition(m_destinationX, m_destinationY, m_destinationZ, m_Unit->GetOrientation(), true); m_destinationX = m_destinationY = m_destinationZ = 0; m_timeMoved = 0; m_timeToMove = 0; } else { //Move Server Side Update float q = (float)m_timeMoved / (float)m_timeToMove; float x = m_Unit->GetPositionX() + (m_destinationX - m_Unit->GetPositionX()) * q; float y = m_Unit->GetPositionY() + (m_destinationY - m_Unit->GetPositionY()) * q; float z = m_Unit->GetPositionZ() + (m_destinationZ - m_Unit->GetPositionZ()) * q; if(m_moveFly != true) { if(m_Unit->GetMapMgr()) { float adt_Z = m_Unit->GetMapMgr()->GetLandHeight(x, y); if(fabsf(adt_Z - z) < 1.5) z = adt_Z; } } /*float dx = m_destinationX - m_Unit->GetPositionX(); float dy = m_destinationY - m_Unit->GetPositionY(); if(dy != 0.0f) m_Unit->SetPosition(x, y, z, atanf(dy/dx)); else*/ m_Unit->SetPosition(x, y, z, m_Unit->GetOrientation()); m_timeToMove -= m_timeMoved; m_timeMoved = 0; m_moveTimer = (UNIT_MOVEMENT_INTERPOLATE_INTERVAL < m_timeToMove) ? UNIT_MOVEMENT_INTERPOLATE_INTERVAL : m_timeToMove; } //**** Movement related stuff that should be done after a move update (Keeps Client and Server Synced) ****// //**** Process the Pending Move ****// if(m_nextPosX != 0.0f && m_nextPosY != 0.0f) { UpdateMove(); } } } else if(m_creatureState == STOPPED && (m_AIState == STATE_IDLE || m_AIState == STATE_SCRIPTMOVE) && !m_moveTimer && !m_timeToMove && UnitToFollow == NULL) //creature is stopped and out of Combat { if(sWorld.getAllowMovement() == false) //is creature movement enabled? return; if(m_Unit->GetUInt32Value(UNIT_FIELD_DISPLAYID) == 5233) //if Spirit Healer don't move return; // do we have a formation? if(m_formationLinkSqlId != 0) { if(!m_formationLinkTarget) { // haven't found our target yet Creature * c = static_cast<Creature*>(m_Unit); if(!c->haslinkupevent) { // register linkup event c->haslinkupevent = true; sEventMgr.AddEvent(c, &Creature::FormationLinkUp, m_formationLinkSqlId, EVENT_CREATURE_FORMATION_LINKUP, 1000, 0); } } else { // we've got a formation target, set unittofollow to this UnitToFollow = m_formationLinkTarget; FollowDistance = m_formationFollowDistance; m_fallowAngle = m_formationFollowAngle; } } if(UnitToFollow == 0) { // no formation, use waypoints int destpoint = -1; // If creature has no waypoints just wander aimlessly around spawnpoint if(m_nWaypoints==0) //no waypoints { /* if(m_moveRandom) { if((rand()%10)==0) { float wanderDistance = rand()%4 + 2; float wanderX = ((wanderDistance*rand()) / RAND_MAX) - wanderDistance / 2; float wanderY = ((wanderDistance*rand()) / RAND_MAX) - wanderDistance / 2; float wanderZ = 0; // FIX ME ( i dont know how to get apropriate Z coord, maybe use client height map data) if(m_Unit->CalcDistance(m_Unit->GetPositionX(), m_Unit->GetPositionY(), m_Unit->GetPositionZ(), ((Creature*)m_Unit)->respawn_cord[0], ((Creature*)m_Unit)->respawn_cord[1], ((Creature*)m_Unit)->respawn_cord[2])>15) { //return home MoveTo(((Creature*)m_Unit)->respawn_cord[0],((Creature*)m_Unit)->respawn_cord[1],((Creature*)m_Unit)->respawn_cord[2],false); } else { MoveTo(m_Unit->GetPositionX() + wanderX, m_Unit->GetPositionY() + wanderY, m_Unit->GetPositionZ() + wanderZ,false); } } } */ return; } else //we do have waypoints { if(m_moveType == MOVEMENTTYPE_RANDOMWP) //is random move on if so move to a random waypoint { if(m_nWaypoints > 1) destpoint = sRand.randInt(m_nWaypoints); } else if (m_moveType == MOVEMENTTYPE_CIRCLEWP) //random move is not on lets follow the path in circles { // 1 -> 10 then 1 -> 10 m_currentWaypoint++; if (m_currentWaypoint > m_nWaypoints) m_currentWaypoint = 1; //Happens when you delete last wp seems to continue ticking destpoint = m_currentWaypoint; m_moveBackward = false; } else if(m_moveType == MOVEMENTTYPE_WANTEDWP)//Move to wanted wp { if(m_currentWaypoint) { if(m_nWaypoints > 0) { destpoint = m_currentWaypoint; } else destpoint = -1; } } else if(m_moveType != MOVEMENTTYPE_QUEST && m_moveType != MOVEMENTTYPE_DONTMOVEWP)//4 Unused { // 1 -> 10 then 10 -> 1 if (m_currentWaypoint > m_nWaypoints) m_currentWaypoint = 1; //Happens when you delete last wp seems to continue ticking if (m_currentWaypoint == m_nWaypoints) // Are we on the last waypoint? if so walk back m_moveBackward = true; if (m_currentWaypoint == 1) // Are we on the first waypoint? if so lets goto the second waypoint m_moveBackward = false; if (!m_moveBackward) // going 1..n destpoint = ++m_currentWaypoint; else // going n..1 destpoint = --m_currentWaypoint; } if(destpoint != -1) { WayPoint* wp = getWayPoint(destpoint); if(wp) { if(!m_moveBackward) { if((wp->forwardskinid != 0) && (GetUnit()->GetUInt32Value(UNIT_FIELD_DISPLAYID) != wp->forwardskinid)) { GetUnit()->SetUInt32Value(UNIT_FIELD_DISPLAYID, wp->forwardskinid); } } else { if((wp->backwardskinid != 0) && (GetUnit()->GetUInt32Value(UNIT_FIELD_DISPLAYID) != wp->backwardskinid)) { GetUnit()->SetUInt32Value(UNIT_FIELD_DISPLAYID, wp->backwardskinid); } } m_moveFly = (wp->flags == 768) ? 1 : 0; m_moveRun = (wp->flags == 256) ? 1 : 0; MoveTo(wp->x, wp->y, wp->z, 0); } } } } } //Fear Code if(m_AIState == STATE_FEAR && UnitToFear != NULL && m_creatureState == STOPPED) { if(getMSTime() > m_FearTimer) // Wait at point for x ms ;) { float Fx; float Fy; float Fz; // Calculate new angle to target. float Fo = m_Unit->calcRadAngle(UnitToFear->GetPositionX(), UnitToFear->GetPositionY(), m_Unit->GetPositionX(), m_Unit->GetPositionY()); Fx = m_Unit->GetPositionX() + 10*cosf(Fo); Fy = m_Unit->GetPositionY() + 10*sinf(Fo); // Check if this point is in water. float wl = m_Unit->GetMapMgr()->GetWaterHeight(Fx, Fy); uint8 wt = m_Unit->GetMapMgr()->GetWaterType(Fx, Fy); Fz = m_Unit->GetMapMgr()->GetLandHeight(Fx, Fy); if(!(fabs(m_Unit->GetPositionZ() - Fz) > 4 || Fz < (wl-2))/* && wt & 0x1*/) { MoveTo(Fx, Fy, Fz, Fo); } m_FearTimer = m_totalMoveTime + getMSTime() + 200; } } if(m_AIState == STATE_WANDER && m_creatureState == STOPPED) { float wanderO = sRand.randInt(6); float wanderX = m_Unit->GetPositionX() + cosf(wanderO); float wanderY = m_Unit->GetPositionY() + sinf(wanderO); float wanderZ; // Check if this point is in water. float wl = m_Unit->GetMapMgr()->GetWaterHeight(wanderX, wanderY); uint8 wt = m_Unit->GetMapMgr()->GetWaterType(wanderX, wanderY); wanderZ = m_Unit->GetMapMgr()->GetLandHeight(wanderX, wanderY); if(!(fabs(m_Unit->GetPositionZ() - wanderZ) > 4 || wanderZ < (wl-2))/* && wt & 0x1*/) { MoveTo(wanderX,wanderY,wanderZ,wanderO); } } //Unit Follow Code if(UnitToFollow != NULL && (m_AIState == STATE_IDLE || m_AIState == STATE_FOLLOWING)) { float dist = m_Unit->GetDistanceSq(UnitToFollow); // re-calculate orientation based on target's movement if(m_lastFollowX != UnitToFollow->GetPositionX() || m_lastFollowY != UnitToFollow->GetPositionY()) { float dx = UnitToFollow->GetPositionX() - m_Unit->GetPositionX(); float dy = UnitToFollow->GetPositionY() - m_Unit->GetPositionY(); if(dy != 0.0f) { float angle = atan2(dx,dy); m_Unit->SetOrientation(angle); } m_lastFollowX = UnitToFollow->GetPositionX(); m_lastFollowY = UnitToFollow->GetPositionY(); } if (dist > powf(FollowDistance,2)) //if out of range { m_AIState = STATE_FOLLOWING; if(dist > 25.0f) //25 yard away lets run else we will loose the them m_moveRun = true; else m_moveRun = false; if(m_AIType == AITYPE_PET || UnitToFollow == m_formationLinkTarget) //Unit is Pet/formation { if(dist > 900.0f/*30*/) m_moveSprint = true; // estimate position based on orientation /*float delta_x = -(sinf(UnitToFollow->GetOrientation()) * 5); float delta_y = -(cosf(UnitToFollow->GetOrientation()) * 5); delta_x += UnitToFollow->GetPositionX(); delta_y += UnitToFollow->GetPositionY();*/ float delta_x = UnitToFollow->GetPositionX(); float delta_y = UnitToFollow->GetPositionY(); float d = 3; if(m_formationLinkTarget) d = m_formationFollowDistance; MoveTo(delta_x+(d*(cosf(m_fallowAngle+UnitToFollow->GetOrientation()))), delta_y+(d*(sinf(m_fallowAngle+UnitToFollow->GetOrientation()))), UnitToFollow->GetPositionZ(),UnitToFollow->GetOrientation()); } else { _CalcDestinationAndMove(UnitToFollow, FollowDistance); /*Destination* dst = _CalcDestination(UnitToFollow, FollowDistance); MoveTo(dst->x, dst->y, dst->z,0); delete dst;*/ } } } } void AIInterface::CastSpell(Unit* caster, SpellEntry *spellInfo, SpellCastTargets targets) { // check for spell id //printf("Spell: %u cast by "I64FMT"\n", spellInfo->Id, caster->GetGUID()); // Stop movement while casting. /*int32 CastTime = GetCastTime(spellInfo->CastingTimeIndex); if(CastTime > 0) StopMovement(CastTime);*/ m_AIState = STATE_CASTING; Spell *spell = new Spell(caster, spellInfo, false, NULL); spell->prepare(&targets); } SpellEntry *AIInterface::getSpellEntry(uint32 spellId) { SpellEntry *spellInfo = sSpellStore.LookupEntry(spellId ); if(!spellInfo) { sLog.outError("WORLD: unknown spell id %i\n", spellId); return NULL; } return spellInfo; } SpellCastTargets AIInterface::setSpellTargets(SpellEntry *spellInfo, Unit* target) { SpellCastTargets targets; targets.m_unitTarget = 0; targets.m_itemTarget = 0; targets.m_srcX = 0; targets.m_srcY = 0; targets.m_srcZ = 0; targets.m_destX = 0; targets.m_destY = 0; targets.m_destZ = 0; if(m_nextSpell->spelltargetType == TTYPE_SINGLETARGET) { targets.m_targetMask = 2; targets.m_unitTarget = target->GetGUID(); } else if(m_nextSpell->spelltargetType == TTYPE_SOURCE) { targets.m_targetMask = 32; targets.m_srcX = m_Unit->GetPositionX(); targets.m_srcY = m_Unit->GetPositionY(); targets.m_srcZ = m_Unit->GetPositionZ(); } else if(m_nextSpell->spelltargetType == TTYPE_DESTINATION) { targets.m_targetMask = 64; targets.m_destX = target->GetPositionX(); targets.m_destY = target->GetPositionY(); targets.m_destZ = target->GetPositionZ(); } return targets; } AI_Spell *AIInterface::getSpellByEvent(uint32 event) { SpellMap::iterator i; switch(event) { case EVENT_ENTERCOMBAT: { if(!m_hasOnEnterCombatSpells) // has Spells for that Event -- used to reduce iterations { break; } for(i = m_OnEnterCombatSpells.begin();i != m_OnEnterCombatSpells.end(); i++) { if(i->second->procCount == 0 || i->second->procCounter < i->second->procCount) // procCount for that spell isnt expired yet { if(i->second->spellCooldownTimer == 0) // there is no Cooldown for that Spell { if(Rand(i->second->procChance)) // proc this Spell { return i->second; } } } } }break; case EVENT_LEAVECOMBAT: { if(!m_hasOnLeaveCombatSpells) // has Spells for that Event -- used to reduce iterations { break; } for(i = m_OnLeaveCombatSpells.begin();i != m_OnLeaveCombatSpells.end(); i++) { if(i->second->procCount == 0 || i->second->procCounter < i->second->procCount) // procCount for that spell isnt expired yet { if(i->second->spellCooldownTimer == 0) // there is no Cooldown for that Spell { if(Rand(i->second->procChance)) // proc this Spell { return i->second; } } } } }break; case EVENT_DAMAGETAKEN: { if(!m_hasOnDamageTakenSpells) // has Spells for that Event -- used to reduce iterations { break; } for(i = m_OnDamageTakenSpells.begin();i != m_OnDamageTakenSpells.end(); i++) { if(i->second->procCount == 0 || i->second->procCounter < i->second->procCount) // procCount for that spell isnt expired yet { if(i->second->spellCooldownTimer == 0) // there is no Cooldown for that Spell { if(Rand(i->second->procChance)) // proc this Spell { return i->second; } } } } }break; case EVENT_TARGETCASTSPELL: { if(!m_hasOnTargetCastSpellSpells) // has Spells for that Event -- used to reduce iterations { break; } for(i = m_OnTargetCastSpellSpells.begin();i != m_OnTargetCastSpellSpells.end(); i++) { if(i->second->procCount == 0 || i->second->procCounter < i->second->procCount) // procCount for that spell isnt expired yet { if(i->second->spellCooldownTimer == 0) // there is no Cooldown for that Spell { if(Rand(i->second->procChance)) // proc this Spell { return i->second; } } } } }break; case EVENT_TARGETPARRYED: { if(!m_hasOnTargetParryedSpells) // has Spells for that Event -- used to reduce iterations { break; } for(i = m_OnTargetParryedSpells.begin();i != m_OnTargetParryedSpells.end(); i++) { if(i->second->procCount == 0 || i->second->procCounter < i->second->procCount) // procCount for that spell isnt expired yet { if(i->second->spellCooldownTimer == 0) // there is no Cooldown for that Spell { if(Rand(i->second->procChance)) // proc this Spell { return i->second; } } } } }break; case EVENT_TARGETDODGED: { if(!m_hasOnTargetDodgedSpells) // has Spells for that Event -- used to reduce iterations { break; } for(i = m_OnTargetDodgedSpells.begin();i != m_OnTargetDodgedSpells.end(); i++) { if(i->second->procCount == 0 || i->second->procCounter < i->second->procCount) // procCount for that spell isnt expired yet { if(i->second->spellCooldownTimer == 0) // there is no Cooldown for that Spell { if(Rand(i->second->procChance)) // proc this Spell { return i->second; } } } } }break; case EVENT_TARGETBLOCKED: { if(!m_hasOnTargetBlockedSpells) // has Spells for that Event -- used to reduce iterations { break; } for(i = m_OnTargetBlockedSpells.begin();i != m_OnTargetBlockedSpells.end(); i++) { if(i->second->procCount == 0 || i->second->procCounter < i->second->procCount) // procCount for that spell isnt expired yet { if(i->second->spellCooldownTimer == 0) // there is no Cooldown for that Spell { if(Rand(i->second->procChance)) // proc this Spell { return i->second; } } } } }break; case EVENT_TARGETCRITHIT: { if(!m_hasOnTargetCritHitSpells) // has Spells for that Event -- used to reduce iterations { break; } for(i = m_OnTargetCritHitSpells.begin();i != m_OnTargetCritHitSpells.end(); i++) { if(i->second->procCount == 0 || i->second->procCounter < i->second->procCount) // procCount for that spell isnt expired yet { if(i->second->spellCooldownTimer == 0) // there is no Cooldown for that Spell { if(Rand(i->second->procChance)) // proc this Spell { i->second->spellCooldownTimer = 500; return i->second; } } } } }break; case EVENT_TARGETDIED: { if(!m_hasOnTargetDiedSpells) // has Spells for that Event -- used to reduce iterations { break; } for(i = m_OnTargetDiedSpells.begin();i != m_OnTargetDiedSpells.end(); i++) { if(i->second->procCount == 0 || i->second->procCounter < i->second->procCount) // procCount for that spell isnt expired yet { if(i->second->spellCooldownTimer == 0) // there is no Cooldown for that Spell { if(Rand(i->second->procChance)) // proc this Spell { return i->second; } } } } }break; case EVENT_UNITPARRYED: { if(!m_hasOnUnitParryedSpells) // has Spells for that Event -- used to reduce iterations { break; } for(i = m_OnUnitParryedSpells.begin();i != m_OnUnitParryedSpells.end(); i++) { if(i->second->procCount == 0 || i->second->procCounter < i->second->procCount) // procCount for that spell isnt expired yet { if(i->second->spellCooldownTimer == 0) // there is no Cooldown for that Spell { if(Rand(i->second->procChance)) // proc this Spell { return i->second; } } } } }break; case EVENT_UNITDODGED: { if(!m_hasOnUnitDodgedSpells) // has Spells for that Event -- used to reduce iterations { break; } for(i = m_OnUnitDodgedSpells.begin();i != m_OnUnitDodgedSpells.end(); i++) { if(i->second->procCount == 0 || i->second->procCounter < i->second->procCount) // procCount for that spell isnt expired yet { if(i->second->spellCooldownTimer == 0) // there is no Cooldown for that Spell { if(Rand(i->second->procChance)) // proc this Spell { return i->second; } } } } }break; case EVENT_UNITBLOCKED: { if(!m_hasOnUnitBlockedSpells) // has Spells for that Event -- used to reduce iterations { break; } for(i = m_OnUnitBlockedSpells.begin();i != m_OnUnitBlockedSpells.end(); i++) { if(i->second->procCount == 0 || i->second->procCounter < i->second->procCount) // procCount for that spell isnt expired yet { if(i->second->spellCooldownTimer == 0) // there is no Cooldown for that Spell { if(Rand(i->second->procChance)) // proc this Spell { return i->second; } } } } }break; case EVENT_UNITCRITHIT: { if(!m_hasOnUnitCritHitSpells) // has Spells for that Event -- used to reduce iterations { break; } for(i = m_OnUnitCritHitSpells.begin();i != m_OnUnitCritHitSpells.end(); i++) { if(i->second->procCount == 0 || i->second->procCounter < i->second->procCount) // procCount for that spell isnt expired yet { if(i->second->spellCooldownTimer == 0) // there is no Cooldown for that Spell { if(Rand(i->second->procChance)) // proc this Spell { return i->second; } } } } }break; case EVENT_UNITDIED: { if(!m_hasOnUnitDiedSpells) // has Spells for that Event -- used to reduce iterations { break; } for(i = m_OnUnitDiedSpells.begin();i != m_OnUnitDiedSpells.end(); i++) { if(i->second->procCount == 0 || i->second->procCounter < i->second->procCount) // procCount for that spell isnt expired yet { if(i->second->spellCooldownTimer == 0) // there is no Cooldown for that Spell { if(Rand(i->second->procChance)) // proc this Spell { return i->second; } } } } }break; case EVENT_ASSISTTARGETDIED: { if(!m_hasOnAssistTargetDiedSpells) // has Spells for that Event -- used to reduce iterations { break; } for(i = m_OnAssistTargetDiedSpells.begin();i != m_OnAssistTargetDiedSpells.end(); i++) { if(i->second->procCount == 0 || i->second->procCounter < i->second->procCount) // procCount for that spell isnt expired yet { if(i->second->spellCooldownTimer == 0) // there is no Cooldown for that Spell { if(Rand(i->second->procChance)) // proc this Spell { return i->second; } } } } }break; case EVENT_FOLLOWOWNER: { if(!m_hasOnFollowOwnerSpells) // has Spells for that Event -- used to reduce iterations { break; } for(i = m_OnFollowOwnerSpells.begin();i != m_OnFollowOwnerSpells.end(); i++) { if(i->second->procCount == 0 || i->second->procCounter < i->second->procCount) // procCount for that spell isnt expired yet { if(i->second->spellCooldownTimer == 0) // there is no Cooldown for that Spell { if(Rand(i->second->procChance)) // proc this Spell { return i->second; } } } } }break; } /*AI_Spell *sp = new AI_Spell; sp->agent = AGENT_MELEE; // warning... LEAKY:D return sp;*/ return m_DefaultSpell; } void AIInterface::resetSpellCounter() { SpellMap::iterator i; if(m_hasCooldownOnEnterCombatSpells == true) { m_hasCooldownOnEnterCombatSpells = false; for(i = m_OnEnterCombatSpells.begin();i != m_OnEnterCombatSpells.end(); i++) { i->second->spellCooldownTimer = 0; } } if(m_hasCooldownOnLeaveCombatSpells == true) { m_hasCooldownOnLeaveCombatSpells = false; for(i = m_OnLeaveCombatSpells.begin();i != m_OnLeaveCombatSpells.end(); i++) { i->second->spellCooldownTimer = 0; } } if(m_hasCooldownOnDamageTakenSpells == true) { m_hasCooldownOnDamageTakenSpells = false; for(i = m_OnDamageTakenSpells.begin();i != m_OnDamageTakenSpells.end(); i++) { i->second->spellCooldownTimer = 0; } } if(m_hasCooldownOnTargetCastSpellSpells == true) { m_hasCooldownOnTargetCastSpellSpells = false; for(i = m_OnTargetCastSpellSpells.begin();i != m_OnTargetCastSpellSpells.end(); i++) { i->second->spellCooldownTimer = 0; } } if(m_hasCooldownOnTargetParryedSpells == true) { m_hasCooldownOnTargetParryedSpells = false; for(i = m_OnTargetParryedSpells.begin();i != m_OnTargetParryedSpells.end(); i++) { i->second->spellCooldownTimer = 0; } } if(m_hasCooldownOnTargetDodgedSpells == true) { m_hasCooldownOnTargetDodgedSpells = false; for(i = m_OnTargetDodgedSpells.begin();i != m_OnTargetDodgedSpells.end(); i++) { i->second->spellCooldownTimer = 0; } } if(m_hasCooldownOnTargetBlockedSpells == true) { m_hasCooldownOnTargetBlockedSpells = false; for(i = m_OnTargetBlockedSpells.begin();i != m_OnTargetBlockedSpells.end(); i++) { i->second->spellCooldownTimer = 0; } } if(m_hasCooldownOnTargetCritHitSpells == true) { m_hasCooldownOnTargetCritHitSpells = false; for(i = m_OnTargetCritHitSpells.begin();i != m_OnTargetCritHitSpells.end(); i++) { i->second->spellCooldownTimer = 0; } } if(m_hasCooldownOnTargetDiedSpells == true) { m_hasCooldownOnTargetDiedSpells = false; for(i = m_OnTargetDiedSpells.begin();i != m_OnTargetDiedSpells.end(); i++) { i->second->spellCooldownTimer = 0; } } if(m_hasCooldownOnUnitParryedSpells == true) { m_hasCooldownOnUnitParryedSpells = false; for(i = m_OnUnitParryedSpells.begin();i != m_OnUnitParryedSpells.end(); i++) { i->second->spellCooldownTimer = 0; } } if(m_hasCooldownOnUnitDodgedSpells == true) { m_hasCooldownOnUnitDodgedSpells = false; for(i = m_OnUnitDodgedSpells.begin();i != m_OnUnitDodgedSpells.end(); i++) { i->second->spellCooldownTimer = 0; } } if(m_hasCooldownOnUnitBlockedSpells == true) { m_hasCooldownOnUnitBlockedSpells = false; for(i = m_OnUnitBlockedSpells.begin();i != m_OnUnitBlockedSpells.end(); i++) { i->second->spellCooldownTimer = 0; } } if(m_hasCooldownOnUnitCritHitSpells == true) { m_hasCooldownOnUnitCritHitSpells = false; for(i = m_OnUnitCritHitSpells.begin();i != m_OnUnitCritHitSpells.end(); i++) { i->second->spellCooldownTimer = 0; } } if(m_hasCooldownOnUnitDiedSpells == true) { m_hasCooldownOnUnitDiedSpells = false; for(i = m_OnUnitDiedSpells.begin();i != m_OnUnitDiedSpells.end(); i++) { i->second->spellCooldownTimer = 0; } } if(m_hasCooldownOnAssistTargetDiedSpells == true) { m_hasCooldownOnAssistTargetDiedSpells = false; for(i = m_OnAssistTargetDiedSpells.begin();i != m_OnAssistTargetDiedSpells.end(); i++) { i->second->spellCooldownTimer = 0; } } if(m_hasCooldownOnFollowOwnerSpells == true) { m_hasCooldownOnFollowOwnerSpells = false; for(i = m_OnFollowOwnerSpells.begin();i != m_OnFollowOwnerSpells.end(); i++) { i->second->spellCooldownTimer = 0; } } } void AIInterface::increaseProcCounter(uint32 event, AI_Spell *sp) { SpellMap::iterator i; switch(event) { case EVENT_ENTERCOMBAT: { i = m_OnEnterCombatSpells.find(sp->spellId); if(i != m_OnEnterCombatSpells.end()) { i->second->spellCooldownTimer = i->second->spellCooldown; if(i->second->spellCooldown > 0) m_hasCooldownOnEnterCombatSpells = true; i->second->procCounter++; } }break; case EVENT_LEAVECOMBAT: { i = m_OnLeaveCombatSpells.find(sp->spellId); if(i != m_OnLeaveCombatSpells.end()) { i->second->spellCooldownTimer = i->second->spellCooldown; if(i->second->spellCooldown > 0) m_hasCooldownOnLeaveCombatSpells = true; i->second->procCounter++; } }break; case EVENT_DAMAGETAKEN: { i = m_OnDamageTakenSpells.find(sp->spellId); if(i != m_OnDamageTakenSpells.end()) { i->second->spellCooldownTimer = i->second->spellCooldown; if(i->second->spellCooldown > 0) m_hasCooldownOnDamageTakenSpells = true; i->second->procCounter++; } }break; case EVENT_TARGETCASTSPELL: { i = m_OnTargetCastSpellSpells.find(sp->spellId); if(i != m_OnTargetCastSpellSpells.end()) { i->second->spellCooldownTimer = i->second->spellCooldown; if(i->second->spellCooldown > 0) m_hasCooldownOnTargetCastSpellSpells = true; i->second->procCounter++; } }break; case EVENT_TARGETPARRYED: { i = m_OnTargetParryedSpells.find(sp->spellId); if(i != m_OnTargetParryedSpells.end()) { i->second->spellCooldownTimer = i->second->spellCooldown; if(i->second->spellCooldown > 0) m_hasCooldownOnTargetParryedSpells = true; i->second->procCounter++; } }break; case EVENT_TARGETDODGED: { i = m_OnTargetDodgedSpells.find(sp->spellId); if(i != m_OnTargetDodgedSpells.end()) { i->second->spellCooldownTimer = i->second->spellCooldown; if(i->second->spellCooldown > 0) m_hasCooldownOnTargetDodgedSpells = true; i->second->procCounter++; } }break; case EVENT_TARGETBLOCKED: { i = m_OnTargetBlockedSpells.find(sp->spellId); if(i != m_OnTargetBlockedSpells.end()) { i->second->spellCooldownTimer = i->second->spellCooldown; if(i->second->spellCooldown > 0) m_hasCooldownOnTargetBlockedSpells = true; i->second->procCounter++; } }break; case EVENT_TARGETCRITHIT: { i = m_OnTargetCritHitSpells.find(sp->spellId); if(i != m_OnTargetCritHitSpells.end()) { i->second->spellCooldownTimer = i->second->spellCooldown; if(i->second->spellCooldown > 0) m_hasCooldownOnTargetCritHitSpells = true; i->second->procCounter++; } }break; case EVENT_TARGETDIED: { i = m_OnTargetDiedSpells.find(sp->spellId); if(i != m_OnTargetDiedSpells.end()) { i->second->spellCooldownTimer = i->second->spellCooldown; if(i->second->spellCooldown > 0) m_hasCooldownOnTargetDiedSpells = true; i->second->procCounter++; } }break; case EVENT_UNITPARRYED: { i = m_OnUnitParryedSpells.find(sp->spellId); if(i != m_OnUnitParryedSpells.end()) { i->second->spellCooldownTimer = i->second->spellCooldown; if(i->second->spellCooldown > 0) m_hasCooldownOnUnitParryedSpells = true; i->second->procCounter++; } }break; case EVENT_UNITDODGED: { i = m_OnUnitDodgedSpells.find(sp->spellId); if(i != m_OnUnitDodgedSpells.end()) { i->second->spellCooldownTimer = i->second->spellCooldown; if(i->second->spellCooldown > 0) m_hasCooldownOnUnitDodgedSpells = true; i->second->procCounter++; } }break; case EVENT_UNITBLOCKED: { i = m_OnUnitBlockedSpells.find(sp->spellId); if(i != m_OnUnitBlockedSpells.end()) { i->second->spellCooldownTimer = i->second->spellCooldown; if(i->second->spellCooldown > 0) m_hasCooldownOnUnitBlockedSpells = true; i->second->procCounter++; } }break; case EVENT_UNITCRITHIT: { i = m_OnUnitCritHitSpells.find(sp->spellId); if(i != m_OnUnitCritHitSpells.end()) { i->second->spellCooldownTimer = i->second->spellCooldown; if(i->second->spellCooldown > 0) m_hasCooldownOnUnitCritHitSpells = true; i->second->procCounter++; } }break; case EVENT_UNITDIED: { i = m_OnUnitDiedSpells.find(sp->spellId); if(i != m_OnUnitDiedSpells.end()) { i->second->spellCooldownTimer = i->second->spellCooldown; if(i->second->spellCooldown > 0) m_hasCooldownOnUnitDiedSpells = true; i->second->procCounter++; } }break; case EVENT_ASSISTTARGETDIED: { i = m_OnAssistTargetDiedSpells.find(sp->spellId); if(i != m_OnAssistTargetDiedSpells.end()) { i->second->spellCooldownTimer = i->second->spellCooldown; if(i->second->spellCooldown > 0) m_hasCooldownOnAssistTargetDiedSpells = true; i->second->procCounter++; } }break; case EVENT_FOLLOWOWNER: { i = m_OnFollowOwnerSpells.find(sp->spellId); if(i != m_OnFollowOwnerSpells.end()) { i->second->spellCooldownTimer = i->second->spellCooldown; if(i->second->spellCooldown > 0) m_hasCooldownOnFollowOwnerSpells = true; i->second->procCounter++; } }break; } } void AIInterface::addSpellToList(AI_Spell *sp) { switch(sp->procEvent) { case EVENT_ENTERCOMBAT: { m_OnEnterCombatSpells.insert(SpellMap::value_type(sp->spellId, sp)); m_hasOnEnterCombatSpells = true; }break; case EVENT_LEAVECOMBAT: { m_OnLeaveCombatSpells.insert(SpellMap::value_type(sp->spellId, sp)); m_hasOnLeaveCombatSpells = true; }break; case EVENT_DAMAGETAKEN: { m_OnDamageTakenSpells.insert(SpellMap::value_type(sp->spellId, sp)); m_hasOnDamageTakenSpells = true; }break; case EVENT_TARGETCASTSPELL: { m_OnTargetCastSpellSpells.insert(SpellMap::value_type(sp->spellId, sp)); m_hasOnTargetCastSpellSpells = true; }break; case EVENT_TARGETPARRYED: { m_OnTargetParryedSpells.insert(SpellMap::value_type(sp->spellId, sp)); m_hasOnTargetParryedSpells = true; }break; case EVENT_TARGETDODGED: { m_OnTargetDodgedSpells.insert(SpellMap::value_type(sp->spellId, sp)); m_hasOnTargetDodgedSpells = true; }break; case EVENT_TARGETBLOCKED: { m_OnTargetBlockedSpells.insert(SpellMap::value_type(sp->spellId, sp)); m_hasOnTargetBlockedSpells = true; }break; case EVENT_TARGETCRITHIT: { m_OnTargetCritHitSpells.insert(SpellMap::value_type(sp->spellId, sp)); m_hasOnTargetCritHitSpells = true; }break; case EVENT_TARGETDIED: { m_OnTargetDiedSpells.insert(SpellMap::value_type(sp->spellId, sp)); m_hasOnTargetDiedSpells = true; }break; case EVENT_UNITPARRYED: { m_OnUnitParryedSpells.insert(SpellMap::value_type(sp->spellId, sp)); m_hasOnUnitParryedSpells = true; }break; case EVENT_UNITDODGED: { m_OnUnitDodgedSpells.insert(SpellMap::value_type(sp->spellId, sp)); m_hasOnUnitDodgedSpells = true; }break; case EVENT_UNITBLOCKED: { m_OnUnitBlockedSpells.insert(SpellMap::value_type(sp->spellId, sp)); m_hasOnUnitBlockedSpells = true; }break; case EVENT_UNITCRITHIT: { m_OnUnitCritHitSpells.insert(SpellMap::value_type(sp->spellId, sp)); m_hasOnUnitCritHitSpells = true; }break; case EVENT_UNITDIED: { m_OnUnitDiedSpells.insert(SpellMap::value_type(sp->spellId, sp)); m_hasOnUnitDiedSpells = true; }break; case EVENT_ASSISTTARGETDIED: { m_OnAssistTargetDiedSpells.insert(SpellMap::value_type(sp->spellId, sp)); m_hasOnAssistTargetDiedSpells = true; }break; case EVENT_FOLLOWOWNER: { m_OnFollowOwnerSpells.insert(SpellMap::value_type(sp->spellId, sp)); m_hasOnFollowOwnerSpells = true; }break; } m_Unit->m_SpellList.insert(sp->spellId); // add to list } uint32 AIInterface::getThreatByGUID(uint64 guid) { /*std::list<AI_Target>::iterator i; for(i = m_aiTargets.begin(); i != m_aiTargets.end(); i++) { if(i->target->GetGUID() == guid) { return i->threat; } }*/ Unit *obj = World::GetUnit(guid); if(obj) return getThreatByPtr(obj); return 0; } uint32 AIInterface::getThreatByPtr(Unit* obj) { TargetMap::iterator it = m_aiTargets.find(obj); if(it != m_aiTargets.end()) { return it->second; } return 0; } bool AIInterface::modThreatByGUID(uint64 guid, int32 mod) { if (!m_aiTargets.size()) return false; /*std::list<AI_Target>::iterator i; for(i = m_aiTargets.begin(); i != m_aiTargets.end(); i++) { if(i->target && i->target->GetGUID() == guid) { i->threat += mod; return true; } }*/ Unit *obj = World::GetUnit(guid); if(obj) return modThreatByPtr(obj, mod); return false; } bool AIInterface::modThreatByPtr(Unit* obj, int32 mod) { TargetMap::iterator it = m_aiTargets.find(obj); if(it != m_aiTargets.end()) { it->second += mod; return true; } return false; } void AIInterface::addAssistTargets(Unit* Friend) { // stop adding stuff that gives errors on linux! m_assistTargets.insert(Friend); } void AIInterface::WipeHateList() { for(TargetMap::iterator itr = m_aiTargets.begin(); itr != m_aiTargets.end(); ++itr) itr->second = 0; } void AIInterface::WipeTargetList() { m_nextTarget = NULL; m_Unit->SetUInt64Value(UNIT_FIELD_TARGET, 0); m_nextSpell = NULL; m_aiTargets.clear(); } bool AIInterface::taunt(Unit* caster, bool apply) { if(apply) { if(!caster) { isTaunted = false; return false; } isTaunted = true; tauntedBy = caster; } else { isTaunted = false; tauntedBy = NULL; } return true; } Unit* AIInterface::getTauntedBy() { if(GetIsTaunted()) { return tauntedBy; } else { return NULL; } } bool AIInterface::GetIsTaunted() { if(isTaunted) { if(!tauntedBy) { isTaunted = false; tauntedBy = NULL; } if(!tauntedBy->isAlive()) { isTaunted = false; tauntedBy = NULL; } } return isTaunted; } void AIInterface::CheckTarget(Unit* target) { if(target == UnitToFollow) // fix for crash here { UnitToFollow = NULL; m_lastFollowX = m_lastFollowY = 0; } if (target == m_nextTarget) // no need to cast on these.. mem addresses are still the same { m_nextTarget = NULL; m_Unit->SetUInt64Value(UNIT_FIELD_TARGET, 0); m_nextSpell = NULL; } if(target == UnitToFear) UnitToFear = NULL; AssistTargetSet::iterator itr = m_assistTargets.find(target); if(itr != m_assistTargets.end()) m_assistTargets.erase(itr); if (!m_aiTargets.size()) return; TargetMap::iterator it2 = m_aiTargets.find(target); if(it2 != m_aiTargets.end()) { m_aiTargets.erase(it2); } } uint32 AIInterface::_CalcThreat(uint32 damage, uint32 spellId, Unit* Attacker) { int32 mod = 0; if(spellId != 0) { mod = objmgr.GetAIThreatToSpellId(spellId); if(mod == 0) { mod = damage; } } else { mod = damage; } // modify mod by Affects mod += (mod * Attacker->GetGeneratedThreatModifyer() / 100); return mod; } void AIInterface::WipeReferences() { m_nextSpell = 0; m_nextTarget = 0; m_aiTargets.clear(); m_Unit->SetUInt64Value(UNIT_FIELD_TARGET, 0); UnitToFear = 0; UnitToFollow = 0; tauntedBy = 0; }
[ [ [ 1, 3695 ] ] ]
a171d01b332dcf82c2cf1d56864be900cecea1eb
2ff4099407bd04ffc49489f22bd62996ad0d0edd
/Project/Code/src/VirtualTrackball.cpp
42c52579547e457f367cdaeb569de6fe8e7d7552
[]
no_license
willemfrishert/imagebasedrendering
13687840a8e5b37a38cc91c3c5b8135f9c1881f2
1cb9ed13b820b791a0aa2c80564dc33fefdc47a2
refs/heads/master
2016-09-10T15:23:42.506289
2007-06-04T11:52:13
2007-06-04T11:52:13
32,184,690
0
1
null
null
null
null
UTF-8
C++
false
false
2,969
cpp
#include <cmath> #include <iostream> #include "Vector3.h" #include "Matrix4.h" #include "Quaternion.h" #include "VirtualTrackball.h" //#include "Utilities.h" #define RADIUS 1 VirtualTrackball::VirtualTrackball(void) { reset(); } VirtualTrackball::VirtualTrackball(int winWidth, int winHeight): m_iWidth(winWidth), m_iHeight(winHeight) { } VirtualTrackball::~VirtualTrackball(void) { } Vector3<float> VirtualTrackball::MapOnSphere(const Vector3<float>& mappingPoint, float radius) { // Assuming a sphere of radius = 1 Vector3<float> mapped(mappingPoint); float sqrX = mappingPoint.x() * mappingPoint.x(); float sqrY = mappingPoint.y() * mappingPoint.y(); //float z = sqrt( 1.0 - sqrX - sqrY ); float z = sqrt( sqrX + sqrY ); // Inside shpere if( z < radius * 0.70710678118654752440) { z = sqrt( (radius * radius) - ( z * z)); } // Assume a hyperbolic sheet else { float t = radius / 1.41421356237309504880f; z = t*t / z; } mapped.setZ( z ); return mapped; } void VirtualTrackball::MapCoords(float& x, float& y, const Vector3<float>& original) { x = (2 * original.x() - m_iWidth) / m_iWidth; y = (m_iHeight - 2 * original.y()) / m_iHeight; } void VirtualTrackball::MouseDown(const Vector3<float>& startPoint) { float mapCoordsX, mapCoordsY; MapCoords(mapCoordsX, mapCoordsY, startPoint); Vector3<float> normalizedPoint(mapCoordsX, mapCoordsY, 0); Vector3<float> curMappedPoint = MapOnSphere( normalizedPoint , RADIUS); m_LastMappedPoint = curMappedPoint; } void VirtualTrackball::MouseUp(const Vector3<float>& endPoint) { float mapCoordsX, mapCoordsY; MapCoords(mapCoordsX, mapCoordsY, endPoint); Vector3<float> normalizedPoint(mapCoordsX, mapCoordsY, 0); Vector3<float> curMappedPoint = MapOnSphere( normalizedPoint , RADIUS); m_LastMappedPoint = curMappedPoint; } void VirtualTrackball::MouseMove(const Vector3<float>& curPoint) { float mapCoordsX, mapCoordsY; MapCoords(mapCoordsX, mapCoordsY, curPoint); Vector3<float> normalizedPoint(mapCoordsX, mapCoordsY, 0); Vector3<float> curMappedPoint = MapOnSphere( normalizedPoint , RADIUS); // Cross product: find the axis of rotation Vector3<float> rotationAxis = m_LastMappedPoint ^ curMappedPoint; // Angle float theta = rotationAxis.Norm() * m_dResolution; m_lastQuat.ComputeQuaternion(theta, rotationAxis); m_curQuat = m_lastQuat * m_curQuat; m_curQuat.ToMatrix(m_rotMatrix); m_LastMappedPoint = curMappedPoint; } void VirtualTrackball::getRotationMatrix(float* mat) { return m_rotMatrix.getGLMatrix( mat ); } Matrix4 VirtualTrackball::getRotationMatrix() { return m_rotMatrix; } void VirtualTrackball::SetWindowRect(const int winWidth, const int winHeight) { m_iWidth = winWidth; m_iHeight = winHeight; } void VirtualTrackball::SetResolution(const float resolution) { m_dResolution = resolution; }
[ "jpjorge@15324175-3028-0410-9899-2d1205849c9d" ]
[ [ [ 1, 129 ] ] ]
9f6e3f54a4939729d1fa627d1c89817631610dfd
cd792ab53157b029b2daf91c895fb50e1386a757
/GS_Login_Emulator/gs_server.cpp
9005639498097a75af42349609d95f3029da536e
[]
no_license
DevSlashNull/gsloginserver
0d0067fce3f9f4d547fd7bcd10ca2ceff5b75914
134a1ea4ecd604c8a1ed1ba5386a90dc982dcfb7
refs/heads/master
2020-12-25T21:00:56.616983
2011-01-20T13:49:06
2011-01-20T13:49:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,330
cpp
#include "gs_server.h" #include "log.h" #include "md5.h" #include "database.h" #include "client.h" #include "config.h" #include "gpcm.h" #include "gpsp.h" #include "bf2.available.h" #include <iostream> #include <fstream> #include <csignal> #include <sstream> #include <cstdlib> using namespace std; #ifdef WIN32 #define MILLISLEEP( x ) Sleep( x ) #else #define MILLISLEEP( x ) usleep( ( x ) * 1000 ) #endif CGSServer* gGSServer = NULL; string gCFGFile; void SignalCatcher( int s ) { cout << "[!!!] caught signal " << s << ", exiting!" << endl; exit( EXIT_SUCCESS ); } int main( int argc, char** argv ) { // cout -> gs_login.log ofstream logfile( "gs_log.log" ); CLog log( cout, logfile ); cout << "[GS_SERVER] starting up" << endl; gCFGFile = "gs_server.cfg"; if( argc > 1 && argv[1] ) gCFGFile = argv[1]; CConfig CFG( gCFGFile ); #ifdef WIN32 WSADATA wsadata; if( WSAStartup( MAKEWORD(2, 2), &wsadata ) != 0 ) { cout << "[WINSOCK] error starting winsock" << endl; return EXIT_FAILURE; } #endif signal( SIGINT, SignalCatcher ); #ifndef WIN32 // disable SIGPIPE since some systems like OS X don't define MSG_NOSIGNAL signal( SIGPIPE, SIG_IGN ); #endif gGSServer = new CGSServer( &CFG ); while( true ) { if( gGSServer->Update(50000) ) break; } #ifdef WIN32 WSACleanup( ); #endif delete gGSServer; cout << "[GS_SERVER] shutting down" << endl; logfile.close(); return EXIT_SUCCESS; } CGSServer :: CGSServer( CConfig* CFG ) : m_Exiting(false) { if( CFG->GetString("db_type", "sqlite3") == "sqlite3" ) m_DB = new CSQLite3( CFG->GetString("db_sqlite3_file", "gs_login_server.db3") ); else m_DB = new CMySQL( CFG->GetString("db_mysql_server", string()), CFG->GetString("db_mysql_database", "gs_login_server"), CFG->GetString("db_mysql_user", string()), CFG->GetString("db_mysql_password", string()), CFG->GetInt("db_mysql_port", 0) ); if( m_DB->HasError() ) m_Exiting = true; else { m_GPCM = new CGPCM( this ); m_GPSP = new CGPSP( this ); m_BF2Available = new CBF2Available( this ); } } CGSServer :: ~CGSServer( ) { delete m_DB; delete m_GPCM; delete m_GPSP; delete m_BF2Available; } bool CGSServer :: Update( long usecBlock ) { if( m_Exiting ) return true; unsigned int NumFDs = 0; // take every socket we own and throw it in one select statement so we can block on all sockets int nfds = 0; fd_set fd; fd_set send_fd; FD_ZERO( &fd ); FD_ZERO( &send_fd ); NumFDs += m_GPCM->SetFD( &fd, &send_fd, &nfds ); NumFDs += m_GPSP->SetFD( &fd, &send_fd, &nfds ); NumFDs += m_BF2Available->SetFD( &fd, &send_fd, &nfds ); struct timeval tv; tv.tv_sec = 0; tv.tv_usec = usecBlock; struct timeval send_tv; send_tv.tv_sec = 0; send_tv.tv_usec = 0; #ifdef WIN32 select( 1, &fd, NULL, NULL, &tv ); select( 1, NULL, &send_fd, NULL, &send_tv ); #else select( nfds + 1, &fd, NULL, NULL, &tv ); select( nfds + 1, NULL, &send_fd, NULL, &send_tv ); #endif if( NumFDs == 0 ) MILLISLEEP( 50 ); m_GPCM->Update(&fd, &send_fd); m_GPSP->Update(&fd, &send_fd); m_BF2Available->Update(&fd, &send_fd); MILLISLEEP( usecBlock - tv.tv_usec ); return false; }
[ "[email protected]@ba25c47e-de5b-bb52-df15-9bdbbe628eaa", "[email protected]@ba25c47e-de5b-bb52-df15-9bdbbe628eaa" ]
[ [ [ 1, 14 ], [ 16, 23 ], [ 26, 70 ], [ 72, 86 ], [ 89, 89 ], [ 92, 92 ], [ 95, 99 ], [ 103, 107 ], [ 112, 153 ], [ 156, 158 ] ], [ [ 15, 15 ], [ 24, 25 ], [ 71, 71 ], [ 87, 88 ], [ 90, 91 ], [ 93, 94 ], [ 100, 102 ], [ 108, 111 ], [ 154, 155 ] ] ]
2eab35614c3686f365a9a3dfced132471eec0672
138a353006eb1376668037fcdfbafc05450aa413
/source/ogre/OgreNewt/boost/mpl/set/aux_/tag.hpp
88c0139dd3a7b2b889666dc611c5cfa5c15d4b87
[]
no_license
sonicma7/choreopower
107ed0a5f2eb5fa9e47378702469b77554e44746
1480a8f9512531665695b46dcfdde3f689888053
refs/heads/master
2020-05-16T20:53:11.590126
2009-11-18T03:10:12
2009-11-18T03:10:12
32,246,184
0
0
null
null
null
null
UTF-8
C++
false
false
677
hpp
#ifndef BOOST_MPL_SET_AUX_TAG_HPP_INCLUDED #define BOOST_MPL_SET_AUX_TAG_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2003-2004 // Copyright David Abrahams 2003-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) // // See http://www.boost.org/libs/mpl for documentation. // $Source: /cvsroot/ogre/ogreaddons/ogrenewt/OgreNewt_Main/inc/boost/mpl/set/aux_/tag.hpp,v $ // $Date: 2006/04/17 23:49:41 $ // $Revision: 1.1 $ namespace boost { namespace mpl { namespace aux { struct set_tag; }}} #endif // BOOST_MPL_SET_AUX_TAG_HPP_INCLUDED
[ "Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e" ]
[ [ [ 1, 24 ] ] ]
c771bf3f9a0ec617cad119c3f6edb6ec2f992ff4
a47e4026ab8f791518d0319c5f3ec8c5a8afec2e
/Terrain/main.cpp
0aa1d444b4657397fb3c56493e374431caa8954c
[]
no_license
bobbyrward/horrible-terrain-demo
715064fd020a620751b0c99f0a324300dd4e387e
55c9add73f5179b4272538950ec8a713dbed88b2
refs/heads/master
2016-09-06T08:29:53.623401
2009-10-28T19:20:24
2009-10-28T19:20:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,751
cpp
#include "stdafx.h" #include "application.h" #include "camera.h" #include "logging.h" #include "terrain.h" #include "limits.h" class TestApp : public d3ddfw::Application<TestApp> { public: typedef d3ddfw::Application<TestApp> Base; public: BEGIN_EVENT_MAP(TestApp) EVENT_WM_LBUTTONDOWN(onLeftMouseDown) EVENT_WM_LBUTTONUP(onLeftMouseUp) EVENT_WM_MOUSEMOVE(onMouseMove) EVENT_WM_KEYUP(onKeyDown) EVENT_CHAIN(Base) END_EVENT_MAP() public: TestApp() : Base(L"Test D3DDFW") , trackingMouse_(false) , lastMouseX_(0) , lastMouseY_(0) , mouseDeltaX_(0) , mouseDeltaY_(0) { } bool getDisplayFormat(d3ddfw::DisplayFormat &format) { // Look for a windowed format(width=0, height=0 since not fullscreen) // with atleast 5 bits per color channel, no alpha nessecary // with atleast 15 bit depth with no stencil nessecary //return d3ddfw::findAdapterMode(d3d_, format, false, 0, 0, 5, 0, 15, 0); // Go fullscreen. Use current resolution return d3ddfw::findAdapterMode(d3d_, format, true, 0, 0, 5, 0, 15, 0); } bool initialize() { //if(!terrain_.loadHeightmap("Terrain-512x512.raw", 512, 512, 1.f, 0.1f)) { if(!terrain_.loadHeightmap("output.raw", 512, 512, 5.f, 0.75f)) { return false; } D3DXVECTOR3 bbMin, bbMax; terrain_.getTerrainBB(&bbMin, &bbMax); camera_.pos_.x = bbMin.x + (bbMax.x - bbMin.x) / 2.f; camera_.pos_.z = bbMin.z + (bbMax.z - bbMin.z) / 2.f; camera_.pos_.y = 5.f + terrain_.getHeightAt(camera_.pos_.x, camera_.pos_.z); if(!Base::initialize()) { return false; } return true; } void update(float elapsedTime) { camera_.adjustPitch(mouseDeltaY_ * -0.01f); camera_.adjustYaw(mouseDeltaX_ * -0.01f); mouseDeltaX_ = 0; mouseDeltaY_ = 0; float movementNudge = 100.f; if(GetAsyncKeyState('W')) camera_.forward( movementNudge * elapsedTime); if(GetAsyncKeyState('S')) camera_.forward(-movementNudge * elapsedTime); if(GetAsyncKeyState('A')) camera_.strafe(-movementNudge * elapsedTime); if(GetAsyncKeyState('D')) camera_.strafe( movementNudge * elapsedTime); if(GetAsyncKeyState('R')) camera_.rise( movementNudge * elapsedTime); if(GetAsyncKeyState('F')) camera_.rise(-movementNudge * elapsedTime); if(GetAsyncKeyState(VK_TAB)) device_->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME); D3DXVECTOR3 const& tSize = terrain_.getTerrainSize(); D3DXVECTOR3 bbMin, bbMax; terrain_.getTerrainBB(&bbMin, &bbMax); if(camera_.pos_.x > bbMax.x) { camera_.pos_.x = bbMax.x; } if(camera_.pos_.x < bbMin.x) { camera_.pos_.x = bbMin.x; } if(camera_.pos_.z > bbMax.z) { camera_.pos_.z = bbMax.z; } if(camera_.pos_.z < bbMin.z) { camera_.pos_.z = bbMin.z; } camera_.pos_.y = 5.f + terrain_.getHeightAt(camera_.pos_.x, camera_.pos_.z); static boost::wformat statsFormatter( L"\nPos: (%0.2f, %0.2f, %0.2f)" L"\nLook: (%0.2f, %0.2f, %0.2f)" L"\nUp: (%0.2f, %0.2f, %0.2f)" L"\nRight: (%0.2f, %0.2f, %0.2f)" ); cameraString_ = boost::str(boost::wformat(statsFormatter) % camera_.pos_.x % camera_.pos_.y % camera_.pos_.z % camera_.look_.x % camera_.look_.y % camera_.look_.z % camera_.up_.x % camera_.up_.y % camera_.up_.z % camera_.right_.x % camera_.right_.y % camera_.right_.z ); } void render() { device_->Clear( 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0,0,255), 1.0f, 0 ); if(SUCCEEDED(device_->BeginScene())) { camera_.realize(device_); terrain_.render(device_); // font_->Begin(); statsString_ += cameraString_; font_.DrawText(statsString_, 5, 5, DT_NOCLIP, D3DCOLOR_XRGB(0,0,0)); // font_->End(); device_->EndScene(); } } bool restoredUnmanagedResources() { D3DXMATRIX mView; D3DXMATRIX mProj; RECT rc={0}; GetClientRect(windowHandle(), &rc); D3DXMatrixPerspectiveFovLH( &mProj, D3DX_PI/4, rc.right/(float)rc.bottom, 1.0f, 1000.0f ); device_->SetTransform( D3DTS_PROJECTION, &mProj ); // Turn off culling, so we see the front and back of the triangle device_->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE ); if(!terrain_.restoreUnmanagedResources(device_)) { return false; } D3DXMATRIX m; D3DXMatrixIdentity(&m); device_->SetTransform(D3DTS_WORLD, &m); return Base::restoreUnmanagedResources(); } void destroyUnmanagedResources() { terrain_.destroyUnmanagedResources(device_); Base::destroyUnmanagedResources(); } LRESULT onLeftMouseDown(UINT x, UINT y) { SetCapture(); trackingMouse_ = true; mouseDeltaX_ = 0; mouseDeltaY_ = 0; lastMouseX_ = x; lastMouseY_ = y; return 0; } LRESULT onLeftMouseUp(UINT x, UINT y) { trackingMouse_ = false; mouseDeltaX_ = 0; mouseDeltaY_ = 0; ReleaseCapture(); return 0; } LRESULT onMouseMove(UINT x, UINT y) { if(trackingMouse_) { mouseDeltaX_ = (int)x - lastMouseX_; mouseDeltaY_ = (int)y - lastMouseY_; lastMouseX_ = x; lastMouseY_ = y; } return Base::onMouseMove(x, y); } LRESULT onKeyDown(WPARAM vkey) { switch(vkey) { case VK_ESCAPE: DestroyWindow(); break; } return DefWindowProc(); } private: d3ddfw::Camera camera_; bool trackingMouse_; UINT lastMouseX_; UINT lastMouseY_; int mouseDeltaX_; int mouseDeltaY_; d3ddfw::Terrain terrain_; std::wstring cameraString_; }; INT WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, INT) { TestApp test; test.run(); return 0; }
[ [ [ 1, 222 ] ] ]
eef572744b437347b49680cafc9cf184644da1bf
485c5413e1a4769516c549ed7f5cd4e835751187
/Source/ImacDemo/[backUp]main.h
cf79941d0ff3d79c5a52fee91c1070c199a49bb4
[]
no_license
FranckLetellier/rvstereogram
44d0a78c47288ec0d9fc88efac5c34088af88d41
c494b87ee8ebb00cf806214bc547ecbec9ad0ca0
refs/heads/master
2021-05-29T12:00:15.042441
2010-03-25T13:06:10
2010-03-25T13:06:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
895
h
/************************************* * * ImacDemo Project * * Created : 30/10/09 * Authors : Franck Letellier * Baptiste Malaga * Fabien Kapala * **************************************/ #include <GL/glew.h> #include <GL/glut.h> #include <GL/glu.h> #include <iostream> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif //Forward class declaration class AbstractCamera; class CubeMapObject; // Origine de la fenetre static const unsigned int windowx = 100; static const unsigned int windowy = 100; // Dimensions de la fenetre static unsigned int windowwidth = 1024; static unsigned int windowheight = 768; //Timer variables static unsigned int timebase; static unsigned int time; static unsigned int frames = 0; AbstractCamera *cam; //Value that could be stored into a XML CubeMapObject *cubeMap; GLenum err;
[ [ [ 1, 50 ] ] ]
0ff0694a8ad45cb1ef8d01e2139061b664ee121f
14ad15a09c39347ecc9733c1547bdccefc75893f
/strutils.cpp
b2ea59441de5962eda7e7c2fc6d36389da171948
[]
no_license
begoon/serialcom
649ea1e3d2bea084349558c63e2f1a09c55a38a9
ea2ac76672a3ab43e19724c15c2d9c4ccf0b6970
refs/heads/master
2021-01-10T19:53:20.109320
2009-06-06T13:56:49
2009-06-06T13:56:49
32,339,549
1
0
null
null
null
null
UTF-8
C++
false
false
2,282
cpp
#include "strutils.h" AnsiString hexPack(const AnsiString& str) { AnsiString raw; for (int i = 1; i <= str.Length(); ++i) if (isxdigit(str[i])) raw += str[i]; int sz = raw.Length() / 2; char* result = new char[ sz + 1 ]; HexToBin(raw.LowerCase().c_str(), result, sz); AnsiString _result = AnsiString(result, sz); delete[] result; return _result; } AnsiString smartHexPack(const AnsiString& str) { AnsiString _str(str); AnsiString result = ""; while (_str.Length()) { int start = _str.Pos("<"); int end = _str.Pos(">"); if (!start || !end || start > end || (end - start - 1)&1) { result += _str; break; } result += _str.SubString(1, start-1) + hexPack(_str.SubString(start+1, end-start-1)); _str.Delete(1, end); } return result; } AnsiString hexDump(const AnsiString& str, const AnsiString& delimiter = "") { AnsiString result = ""; for (int i = 1; i <= str.Length(); ++i) result += IntToHex((int)(unsigned char)str[ i ], 2) + delimiter; return result; } AnsiString smartHexDump(const AnsiString& str) { AnsiString result = ""; enum { shdChar, shdDump }; int mode = shdChar; for (int i = 1; i <= str.Length(); ++i) { switch (mode) { case shdChar: if (!isprint(str[i]) || str[i]=='<' || str[i]=='>') { result += AnsiString("<") + hexDump(str[i]); mode = shdDump; } else result += str[i]; break; case shdDump: if (!isprint(str[i]) || str[i]=='<' || str[i]=='>') result += hexDump(str[i]); else { result += AnsiString(">") + str[i]; mode = shdChar; } } } if (mode == shdDump) result += ">"; return result; } AnsiString expandLeft(const AnsiString& str, char ch, int sz) { return str.Length() < sz ? AnsiString::StringOfChar(ch, sz - str.Length()) + str : str; } AnsiString expandRight(const AnsiString& str, char ch, int sz) { return str.Length() < sz ? str + AnsiString::StringOfChar(ch, sz - str.Length()) : str; }
[ "Alexander Demin@localhost" ]
[ [ [ 1, 92 ] ] ]
0aed89c846f0f57ce05308151f0166c7af7e2d1d
6e563096253fe45a51956dde69e96c73c5ed3c18
/dhnetsdk/netsdk/RenderManager.cpp
612df44275ddeb9c820d4dadf67d146f79f84f65
[]
no_license
15831944/phoebemail
0931b76a5c52324669f902176c8477e3bd69f9b1
e10140c36153aa00d0251f94bde576c16cab61bd
refs/heads/master
2023-03-16T00:47:40.484758
2010-10-11T02:31:02
2010-10-11T02:31:02
null
0
0
null
null
null
null
GB18030
C++
false
false
2,582
cpp
#include "RenderManager.h" #include "VideoRender.h" CRenderManager::CRenderManager(CManager *pManager) : m_pManager(pManager) { // InitializeCriticalSection(&m_csRenders); } CRenderManager::~CRenderManager() { // DeleteCriticalSection(&m_csRenders); } BOOL CRenderManager::Init() { return TRUE; } BOOL CRenderManager::Uninit() { // EnterCriticalSection(&m_csRenders); m_csRenders.Lock(); list<RenderResource *>::iterator it = m_renders.begin(); while (it != m_renders.end()) { if ((*it) && (*it)->render) { delete (*it)->render; } if (*it) { delete (*it); } it++; } m_renders.clear(); // LeaveCriticalSection(&m_csRenders); m_csRenders.UnLock(); return TRUE; } CVideoRender* CRenderManager::GetRender(HWND hwnd) { if (!hwnd) { return 0; } CVideoRender* result = NULL; // EnterCriticalSection(&m_csRenders); m_csRenders.Lock(); list<RenderResource *>::iterator it = m_renders.begin(); //查找空闲render资源 it = m_renders.begin(); for (; it != m_renders.end(); it++) { if ((*it) && (*it)->bAvailable) { (*it)->bAvailable = FALSE; (*it)->hwindow = hwnd; int nRet = (*it)->render->ChangeHwnd(hwnd); if (nRet >= 0) { result = (*it)->render; break; } else { //changeHwnd失败,这个。。。 } } } if (NULL == result) { //否则创建新的render RenderResource* newresource = 0; CVideoRender* newrender = 0; newrender = new CVideoRender(hwnd); if (!newrender) { goto e_clearup; } newresource = new RenderResource; if (!newresource) { goto e_clearup; } newresource->render = newrender; newresource->bAvailable = FALSE; newresource->hwindow = hwnd; m_renders.push_back(newresource); result = newrender; } // LeaveCriticalSection(&m_csRenders); m_csRenders.UnLock(); return result; e_clearup: // LeaveCriticalSection(&m_csRenders); m_csRenders.UnLock(); return (CVideoRender*)-1; } void CRenderManager::ReleaseRender(CVideoRender* rls_render) { if (!rls_render) { return; } // EnterCriticalSection(&m_csRenders); m_csRenders.Lock(); list<RenderResource *>::iterator it = m_renders.begin(); for (; it != m_renders.end(); it++) { if(*it) { if ((*it)->render == rls_render) { //正常render,更改空闲标志 (*it)->bAvailable = TRUE; break; } } } // LeaveCriticalSection(&m_csRenders); m_csRenders.UnLock(); return; }
[ "guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd" ]
[ [ [ 1, 149 ] ] ]
ce6bd7282dd0c28da9345e3f88eec65497cf6a29
e1f7c2f6dd66916fe5b562d9dd4c0a5925197ec4
/Engine/Project/include/AGInputs.h
56b7e8aa12425b1fed217a7f7eadc4d82176d5d0
[]
no_license
OtterOrder/agengineproject
de990ad91885b54a0c63adf66ff2ecc113e0109d
0b92a590af4142369e2946f692d5f30a06d32135
refs/heads/master
2020-05-27T07:44:25.593878
2011-05-01T14:52:05
2011-05-01T14:52:05
32,115,301
0
0
null
null
null
null
UTF-8
C++
false
false
341
h
#pragma once #include "AGUtilities.h" //------------------------------------------------------------------------------------------------------------------------------ class AGInputs { public: DefineVectorIterator(AGInputs, Iterator); private: public: AGInputs (); virtual ~AGInputs (); virtual void Update () =0; };
[ "alban.chagnoleau@fe70d4ac-e33c-11de-8d18-5b59c22968bc" ]
[ [ [ 1, 18 ] ] ]
467366302bedaee988c5afaf792c0dcbf0c87158
de13bb58f0b0a0c5b7a533bb7a4ef8f255cbf35a
/Grapplon/ParticleSystemManager.cpp
dcce8d520d50622c9c8dbe91d0a0351855539d89
[]
no_license
TimToxopeus/grapplon
96a34cc1fcefc2582c8702600727f5748ee894a9
f63c258357fe4b993e854089e7222c14a00ed731
refs/heads/master
2016-09-06T15:05:15.328601
2008-06-05T11:24:14
2008-06-05T11:24:14
41,954,511
0
0
null
null
null
null
UTF-8
C++
false
false
8,118
cpp
#include "ParticleSystemManager.h" #include "Tokenizer.h" #include "LogManager.h" #include <map> #include "GameSettings.h" CParticleSystemManager *CParticleSystemManager::m_pInstanceNear = 0; CParticleSystemManager *CParticleSystemManager::m_pInstanceFar = 0; CParticleSystemManager::CParticleSystemManager(float depth) { CLogManager::Instance()->LogMessage( "Initializing Particle System manager." ); m_eType = PARTICLESYSTEM; SetDepth( depth ); } CParticleSystemManager::~CParticleSystemManager() { CLogManager::Instance()->LogMessage( "Terminating Particle System manager." ); } void CParticleSystemManager::Update(float fTime) { std::vector<CParticleEmitter *> vDelete; for ( unsigned int i = 0; i<m_vEmitters.size(); i++ ) { m_vEmitters[i]->Update( fTime ); if ( !m_vEmitters[i]->IsAlive() ) { vDelete.push_back( m_vEmitters[i] ); m_vEmitters.erase( m_vEmitters.begin() + i ); } } for ( unsigned int i = 0; i<vDelete.size(); i++ ) { delete vDelete[i]; } vDelete.clear(); } void CParticleSystemManager::Render() { for ( unsigned int i = 0; i<m_vEmitters.size(); i++ ) { m_vEmitters[i]->Render(); } } std::string CParticleSystemManager::ReadLine( FILE *pFile ) { if ( !pFile || feof(pFile) ) return "<<<EOF>>>"; char input[1024]; fgets( input, 1024, pFile ); if ( feof(pFile) ) return ""; int len = strlen(input); if ( len > 0 ) input[len - 1] = 0; // Cut off the \n return std::string(input); } CParticleEmitter *CParticleSystemManager::LoadEmitter( std::string szEmitterScript ) { if ( !SETS->PARTICLES_ON ) return NULL; FILE *pFile = fopen( szEmitterScript.c_str(), "rt" ); if ( !pFile ) return NULL; std::string in = ReadLine( pFile ); while ( in != "<<<EOF>>>" && in != "[emitter]" ) in = ReadLine( pFile ); EmitterType eType = NONE; float fTypeParameter = 0.0f; unsigned int iMaxParticles = 50; unsigned int iLifespan = 6000; unsigned int iSpawnrate = 10; float fRadius = 0.0f; CTokenizer tokenizer; std::vector<std::string> tokens; std::map<std::string, int> vParticles; std::map<std::string,int>::iterator particleIt; while ( in != "<<<EOF>>>" && in != "" ) { tokens = tokenizer.GetTokens( in, " ,;:\"" ); if ( tokens.size() > 0 ) { if ( tokens[0] == "direction" ) { if ( tokens[2] == "arc" ) { eType = ARC; fTypeParameter = (float)atof(tokens[3].c_str()); } else if ( tokens[2] == "line" ) { eType = LINE; fTypeParameter = (float)atof(tokens[3].c_str()); } else { eType = NONE; fTypeParameter = 0.0f; } } else if ( tokens[0] == "maxparticles" ) iMaxParticles = atoi(tokens[2].c_str()); else if ( tokens[0] == "lifespan" ) iLifespan = atoi(tokens[2].c_str()); else if ( tokens[0] == "spawnrate" ) iSpawnrate = atoi(tokens[2].c_str()); else if ( tokens[0] == "radius" ) fRadius = (float)atof(tokens[2].c_str()); else if ( tokens[0] == "particles" ) { int particles = (tokens.size() - 2) / 2; for ( int i = 0; i<particles * 2; i+=2 ) { std::string name = tokens[i + 2]; int chance = atoi(tokens[i + 3].c_str()); vParticles[name] = chance; } } } in = ReadLine( pFile ); } fclose( pFile ); CParticleEmitter *pEmitter = new CParticleEmitter( eType, fTypeParameter, iMaxParticles, iLifespan, iSpawnrate, fRadius ); for ( particleIt = vParticles.begin(); particleIt != vParticles.end(); particleIt++ ) { std::string name = (*particleIt).first; int chance = (*particleIt).second; CParticle *pParticle = ReadParticle( szEmitterScript, name, pEmitter ); pEmitter->AddToFactory( pParticle, chance ); } m_vEmitters.push_back( pEmitter ); return pEmitter; } CParticle *CParticleSystemManager::ReadParticle(std::string szEmitterScript, std::string szParticleName, CParticleEmitter *pEmitter) { FILE *pFile = fopen( szEmitterScript.c_str(), "rt" ); if ( !pFile ) return NULL; CTokenizer tokenizer; std::vector<std::string> tokens; std::string in = ReadLine( pFile ); bool bInparticle = false; CParticle *pParticle = NULL; std::string szSpriteScript = ""; Vector colour1, colour2; unsigned int iLifespan = 1500; unsigned int iSize = 2; std::vector<std::string> vBehaviours; while ( in != "<<<EOF>>>" ) { tokens = tokenizer.GetTokens( in, " ,;:\"" ); if ( tokens.size() == 0 ) { in = ReadLine( pFile ); bInparticle = false; continue; } if ( tokens[0] == "[emitter]" ) bInparticle = false; else if ( tokens[0] == "[particle]" ) bInparticle = true; else if ( tokens[0] == "[behaviour]" ) bInparticle = false; if ( bInparticle ) { if ( tokens[0] == "name" && tokens[2] == szParticleName ) { // Read until the next blank line in = ReadLine( pFile ); while ( in != "" && in != "<<<EOF>>>" ) { tokens = tokenizer.GetTokens(in); if ( tokens[0] == "colour1" ) colour2 = colour1 = Vector((float)atof(tokens[2].c_str()), (float)atof(tokens[3].c_str()), (float)atof(tokens[4].c_str())); else if ( tokens[0] == "colour2" ) colour2 = Vector((float)atof(tokens[2].c_str()), (float)atof(tokens[3].c_str()), (float)atof(tokens[4].c_str())); else if ( tokens[0] == "lifespan" ) iLifespan = atoi(tokens[2].c_str()); else if ( tokens[0] == "size" ) iSize = atoi(tokens[2].c_str()); else if ( tokens[0] == "sprite" ) szSpriteScript = tokens[2]; else if ( tokens[0] == "behave" ) { for ( unsigned int i = 2; i<tokens.size(); i++ ) vBehaviours.push_back( tokens[i] ); } in = ReadLine( pFile ); } pParticle = new CParticle(pEmitter, szSpriteScript); pParticle->m_colour1 = colour1; pParticle->m_colour2 = colour2; pParticle->m_iLifespan = iLifespan; pParticle->m_szName = szParticleName; pParticle->m_iSize = iSize; fclose( pFile ); break; } } in = ReadLine( pFile ); } fclose( pFile ); if ( pParticle ) { for ( unsigned int i = 0; i<vBehaviours.size(); i++ ) { CParticleBehaviour behaviour = pEmitter->GetBehaviour(vBehaviours[i]); if ( behaviour.m_szName == "NULL" ) { behaviour = ReadParticleBehaviour( szEmitterScript, vBehaviours[i] ); pEmitter->AddBehaviour( vBehaviours[i], behaviour ); } pParticle->m_vBehaviourStyles.push_back( behaviour ); } } return pParticle; } CParticleBehaviour CParticleSystemManager::ReadParticleBehaviour( std::string szEmitterScript, std::string szParticleBehaviourName ) { FILE *pFile = fopen( szEmitterScript.c_str(), "rt" ); if ( !pFile ) return CParticleBehaviour( "NULL", 0.0f, 0.0f ); CTokenizer tokenizer; std::vector<std::string> tokens; std::string in = ReadLine( pFile ); bool bInBehaviour = false; float fEffect, fVelocity; while ( in != "<<<EOF>>>" ) { tokens = tokenizer.GetTokens( in, " ,;:\"" ); if ( tokens.size() == 0 ) { in = ReadLine( pFile ); bInBehaviour = false; continue; } if ( tokens[0] == "[emitter]" ) bInBehaviour = false; else if ( tokens[0] == "[particle]" ) bInBehaviour = false; else if ( tokens[0] == "[behaviour]" ) bInBehaviour = true; if ( bInBehaviour ) { if ( tokens[0] == "name" && tokens[2] == szParticleBehaviourName ) { // Read until the next blank line in = ReadLine( pFile ); while ( in != "" && in != "<<<EOF>>>" ) { tokens = tokenizer.GetTokens(in); if ( tokens[0] == "velocity" ) fVelocity = (float)atof( tokens[2].c_str() ); else if ( tokens[0] == "move" ) fEffect = (float)atof( tokens[2].c_str() ); in = ReadLine( pFile ); } fclose( pFile ); return CParticleBehaviour( szParticleBehaviourName, fEffect, fVelocity ); } } in = ReadLine( pFile ); } fclose( pFile ); return CParticleBehaviour( "NULL", 0.0f, 0.0f ); }
[ "Tim.Toxopeus@290fe64d-754b-0410-ab79-69b6bb713112" ]
[ [ [ 1, 303 ] ] ]
ad601d4df558a1f3757f39c790abf94445d5c56b
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/spirit/phoenix/example/fundamental/sample2.cpp
db2d25594c58da4478c53c299e720f8e86092e1b
[ "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
997
cpp
/*============================================================================= Phoenix V1.2.1 Copyright (c) 2001-2003 Joel de Guzman 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) ==============================================================================*/ #include <vector> #include <algorithm> #include <iostream> #include <boost/spirit/phoenix/operators.hpp> #include <boost/spirit/phoenix/primitives.hpp> using namespace std; using namespace phoenix; int main() { int init[] = { 2, 10, 4, 5, 1, 6, 8, 3, 9, 7 }; vector<int> c(init, init + 10); typedef vector<int>::iterator iterator; // Find the first odd number in container c iterator it = find_if(c.begin(), c.end(), arg1 % 2 == 1); if (it != c.end()) cout << *it; // if found, print the result return 0; }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 31 ] ] ]